From 57efbc791fe83a28c204ea5479b99765325c1377 Mon Sep 17 00:00:00 2001 From: Timo Klerx <1579185+TKlerx@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:00:10 +0100 Subject: [PATCH 1/2] M6: Preserve variable prototype actions in .fig exports --- ROADMAP.md | 1 + contributors/people.toml | 4 + crates/format/src/fig/assets_tests.rs | 100 ++++++++++++++++ crates/format/src/fig/export.rs | 12 +- crates/format/src/fig/export/prototype.rs | 132 ++++++++++++++++++++-- crates/format/src/fig/kiwi.rs | 2 +- docs/file-format-parity.md | 6 +- 7 files changed, 243 insertions(+), 14 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index dc6204b44..1f4018855 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Experimental `.fig` export preserves set-variable, set-variable-mode and conditional prototype actions (#2210). | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | diff --git a/contributors/people.toml b/contributors/people.toml index c6924df5f..4b11ae582 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -115,3 +115,7 @@ display_name = "Hamza0101" [people.ashokram-si] real_name = "Ashok Ram" + +[people.TKlerx] +real_name = "Timo Klerx" +sync_github_name = true diff --git a/crates/format/src/fig/assets_tests.rs b/crates/format/src/fig/assets_tests.rs index 4e77ab4a3..f0a7cf5ab 100644 --- a/crates/format/src/fig/assets_tests.rs +++ b/crates/format/src/fig/assets_tests.rs @@ -1245,3 +1245,103 @@ fn a_scaled_instance_keeps_reset_lists_above_a_changed_style_link() { same_after_round_trip(&doc, "explicit list values above a changed style link"); } } + +#[test] +fn checkbox_variable_and_conditional_actions_round_trip() { + use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp}; + + let mut doc = Document::new("Checkbox"); + let page = doc.first_page().unwrap(); + doc.variables.collections.push(Collection { + id: "demo".into(), + name: "Demo".into(), + modes: vec![Mode { id: "default".into(), name: "Default".into() }], + extends: None, + }); + doc.variables.variables = vec![ + var("checked", "checked", "demo", VariableType::Boolean, &[("default", VariableValue::Boolean(false))]), + var("status", "status", "demo", VariableType::String, &[("default", VariableValue::String("Unchecked".into()))]), + ]; + let frame = doc.create(page, NodeKind::Frame, "Checkbox demo", 0.0, 0.0, 320.0, 180.0).unwrap(); + let toggle = doc.create(frame, NodeKind::Frame, "Toggle checkbox", 24.0, 24.0, 44.0, 44.0).unwrap(); + let mark = doc.create(toggle, NodeKind::Rectangle, "Checked indicator", 12.0, 12.0, 20.0, 20.0).unwrap(); + let label = doc.create(frame, NodeKind::Text(TextData::new("Unchecked")), "Status", 84.0, 36.0, 120.0, 20.0).unwrap(); + doc.node_mut(mark).unwrap().bound.insert("visible".into(), "checked".into()); + doc.node_mut(label).unwrap().bound.insert("characters".into(), "status".into()); + let set_status = |value| Action::SetVariable { variable: "status".into(), value: json!(value), expr: None }; + doc.node_mut(toggle).unwrap().interactions.push(Interaction { + trigger: Trigger::OnClick, + actions: vec![ + Action::SetVariable { variable: "checked".into(), value: Value::Null, expr: Some(Expr::op(ExprOp::Not, vec![Expr::var("checked")])) }, + Action::Conditional { + blocks: vec![ + ConditionalBlock { condition: Some(Expr::var("checked")), actions: vec![set_status("Checked")] }, + ConditionalBlock { condition: None, actions: vec![set_status("Unchecked")] }, + ], + }, + ], + transition: Transition::Instant, + duration_ms: 300, + easing: Easing::EaseOut, + delay_ms: 0, + }); + + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let (mut back, warnings) = import(&bytes, "Checkbox").unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let toggle = back.nodes().find(|n| n.name == "Toggle checkbox").unwrap(); + let [interaction] = toggle.interactions.as_slice() else { panic!("missing checkbox interaction") }; + assert_eq!(interaction.trigger, Trigger::OnClick); + let [Action::SetVariable { variable, expr: Some(expr), .. }, Action::Conditional { blocks }] = interaction.actions.as_slice() else { + panic!("wrong action order: {:?}", interaction.actions); + }; + let checked = back.nodes().find(|n| n.name == "Checked indicator").unwrap().bound["visible"].clone(); + let status = back.nodes().find(|n| n.name == "Status").unwrap().bound["characters"].clone(); + assert_eq!(variable, &checked); + assert_eq!(expr, &Expr::op(ExprOp::Not, vec![Expr::var(&checked)])); + assert_eq!(blocks.len(), 2); + assert_eq!(blocks[0].condition, Some(Expr::var(&checked))); + assert_eq!(blocks[1].condition, None); + let (expr, blocks) = (expr.clone(), blocks.clone()); + let modes = BTreeMap::new(); + for (is_checked, expected) in [(true, "Checked"), (false, "Unchecked")] { + let value = expr.eval(&back.variables, &modes).unwrap(); + assert_eq!(value, VariableValue::Boolean(is_checked)); + let checked = back.variables.variables.iter_mut().find(|v| v.id == checked).unwrap(); + *checked.values.values_mut().next().unwrap() = value; + let branch = ConditionalBlock::choose(&blocks, &back.variables, &modes).unwrap(); + assert_eq!(branch, &[Action::SetVariable { variable: status.clone(), value: json!(expected), expr: None }]); + } +} + +#[test] +fn overdeep_conditional_is_omitted_without_losing_the_export() { + use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp, MAX_EXPR_DEPTH}; + + let mut doc = Document::new("Depth"); + let frame = doc.create(doc.first_page().unwrap(), NodeKind::Frame, "Trigger", 0.0, 0.0, 100.0, 100.0).unwrap(); + let condition = (0..MAX_EXPR_DEPTH).fold(Expr::Value(VariableValue::Boolean(true)), |inner, _| Expr::op(ExprOp::Not, vec![inner])); + doc.node_mut(frame).unwrap().interactions.push(Interaction { + trigger: Trigger::OnClick, + actions: vec![ + Action::Conditional { + blocks: vec![ + ConditionalBlock { condition: Some(condition), actions: vec![Action::Back] }, + ConditionalBlock { condition: None, actions: vec![Action::CloseOverlay] }, + ], + }, + Action::Back, + ], + transition: Transition::Instant, + duration_ms: 300, + easing: Easing::EaseOut, + delay_ms: 0, + }); + + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.iter().any(|w| w.contains("nesting")), "{warnings:?}"); + let (back, _) = import(&bytes, "Depth").unwrap(); + let frame = back.nodes().find(|n| n.name == "Trigger").unwrap(); + assert_eq!(frame.interactions[0].actions, vec![Action::Back]); +} diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index f00de3606..5dcac9f9f 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -114,12 +114,12 @@ enum ImageType PNG=0 JPEG=1 SVG=2 PDF=3 enum ExportConstraintType CONTENT_SCALE=0 CONTENT_WIDTH=1 CONTENT_HEIGHT=2 enum ComponentPropType BOOL=0 TEXT=1 INSTANCE_SWAP=3 VARIANT=4 enum VariableField MISSING=0 CORNER_RADIUS=1 PARAGRAPH_SPACING=2 PARAGRAPH_INDENT=3 STROKE_WEIGHT=4 STACK_SPACING=5 STACK_PADDING_LEFT=6 STACK_PADDING_TOP=7 STACK_PADDING_RIGHT=8 STACK_PADDING_BOTTOM=9 VISIBLE=10 TEXT_DATA=11 WIDTH=12 HEIGHT=13 RECTANGLE_TOP_LEFT_CORNER_RADIUS=14 RECTANGLE_TOP_RIGHT_CORNER_RADIUS=15 RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS=16 RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS=17 BORDER_TOP_WEIGHT=18 BORDER_BOTTOM_WEIGHT=19 BORDER_LEFT_WEIGHT=20 BORDER_RIGHT_WEIGHT=21 STACK_COUNTER_SPACING=23 MIN_WIDTH=24 MAX_WIDTH=25 MIN_HEIGHT=26 MAX_HEIGHT=27 FONT_FAMILY=28 FONT_STYLE=29 OPACITY=31 FONT_SIZE=32 LETTER_SPACING=34 LINE_HEIGHT=36 OVERRIDDEN_SYMBOL_ID=37 -enum VariableDataType BOOLEAN=0 FLOAT=1 STRING=2 ALIAS=3 COLOR=4 SYMBOL_ID=7 TEXT_DATA=9 PROP_REF=13 +enum VariableDataType BOOLEAN=0 FLOAT=1 STRING=2 ALIAS=3 COLOR=4 EXPRESSION=5 SYMBOL_ID=7 TEXT_DATA=9 PROP_REF=13 enum VariableScope ALL_SCOPES=0 TEXT_CONTENT=1 CORNER_RADIUS=2 WIDTH_HEIGHT=3 GAP=4 ALL_FILLS=5 FRAME_FILL=6 SHAPE_FILL=7 TEXT_FILL=8 STROKE=9 STROKE_FLOAT=10 EFFECT_FLOAT=11 EFFECT_COLOR=12 OPACITY=13 FONT_STYLE=14 FONT_FAMILY=15 FONT_SIZE=16 LINE_HEIGHT=17 LETTER_SPACING=18 PARAGRAPH_SPACING=19 PARAGRAPH_INDENT=20 enum StyleType NONE=0 FILL=1 STROKE=2 TEXT=3 EFFECT=4 EXPORT=5 GRID=6 enum InteractionType ON_CLICK=0 DRAG=9 ON_HOVER=4 ON_PRESS=7 MOUSE_IN=2 MOUSE_OUT=3 MOUSE_DOWN=5 MOUSE_UP=6 AFTER_TIMEOUT=1 ON_KEY_DOWN=10 enum TriggerDevice KEYBOARD=0 UNKNOWN_CONTROLLER=1 -enum ConnectionType NONE=0 INTERNAL_NODE=1 URL=2 BACK=3 CLOSE=4 +enum ConnectionType NONE=0 INTERNAL_NODE=1 URL=2 BACK=3 CLOSE=4 SET_VARIABLE=5 CONDITIONAL=7 SET_VARIABLE_MODE=8 enum NavigationType NAVIGATE=0 OVERLAY=1 SWAP=2 SWAP_STATE=3 SCROLL_TO=4 enum TransitionType INSTANT_TRANSITION=0 DISSOLVE=1 SMART_ANIMATE=24 SLIDE_FROM_LEFT=3 SLIDE_FROM_RIGHT=4 SLIDE_FROM_TOP=5 SLIDE_FROM_BOTTOM=6 PUSH_FROM_LEFT=7 PUSH_FROM_RIGHT=8 PUSH_FROM_TOP=9 PUSH_FROM_BOTTOM=10 MOVE_FROM_LEFT=11 MOVE_FROM_RIGHT=12 MOVE_FROM_TOP=13 MOVE_FROM_BOTTOM=14 SLIDE_OUT_TO_LEFT=15 SLIDE_OUT_TO_RIGHT=16 SLIDE_OUT_TO_TOP=17 SLIDE_OUT_TO_BOTTOM=18 MOVE_OUT_TO_LEFT=19 MOVE_OUT_TO_RIGHT=20 MOVE_OUT_TO_TOP=21 MOVE_OUT_TO_BOTTOM=22 enum EasingType IN_CUBIC=0 OUT_CUBIC=1 INOUT_CUBIC=2 LINEAR=3 IN_BACK_CUBIC=4 OUT_BACK_CUBIC=5 INOUT_BACK_CUBIC=6 CUSTOM_CUBIC=7 GENTLE_SPRING=9 @@ -167,7 +167,9 @@ message VariantPropSpec GUID propDefId=1, string value=2 message StateGroupPropertyValueOrder string property=1, string[] values=2 message PropRefValue GUID defId=1 message SymbolId GUID guid=1 -message VariableAnyValue bool boolValue=1, string textValue=2, float floatValue=3, VariableID alias=4, Color colorValue=5, SymbolId symbolIdValue=8, TextData textDataValue=10, PropRefValue propRefValue=13 +message VariableAnyValue bool boolValue=1, string textValue=2, float floatValue=3, VariableID alias=4, Color colorValue=5, Expression expressionValue=6, SymbolId symbolIdValue=8, TextData textDataValue=10, PropRefValue propRefValue=13 +enum ExpressionFunction ADDITION=0 SUBTRACTION=1 MULTIPLY=3 DIVIDE=4 EQUALS=5 NOT_EQUAL=6 LESS_THAN=7 LESS_THAN_OR_EQUAL=8 GREATER_THAN=9 GREATER_THAN_OR_EQUAL=10 AND=11 OR=12 NOT=13 VAR_MODE_LOOKUP=16 NEGATE=17 +message Expression ExpressionFunction expressionFunction=1, VariableData[] expressionArguments=2 message VariableData VariableAnyValue value=1, VariableDataType dataType=2, VariableResolvedDataType resolvedDataType=3 message VariableDataMapEntry uint nodeField=1, VariableData variableData=2, VariableField variableField=3 message VariableDataMap VariableDataMapEntry[] entries=1 @@ -178,7 +180,9 @@ message VariableDataValuesEntry GUID modeID=1, VariableData variableData=2 message VariableDataValues VariableDataValuesEntry[] entries=1 message KeyTrigger int[] keyCodes=1, TriggerDevice triggerDevice=2 message PrototypeEvent InteractionType interactionType=1, float transitionTimeout=6, KeyTrigger keyTrigger=4 -message PrototypeAction GUID transitionNodeID=1, TransitionType transitionType=2, float transitionDuration=3, EasingType easingType=4, float[] easingFunction=12, ConnectionType connectionType=7, Vector overlayRelativePosition=9, NavigationType navigationType=10, string connectionURL=8, bool transitionPreserveScroll=11 +message PrototypeVariableTarget VariableID id=1 +message ConditionalActions PrototypeAction[] actions=1, VariableData condition=2 +message PrototypeAction GUID transitionNodeID=1, TransitionType transitionType=2, float transitionDuration=3, EasingType easingType=4, float[] easingFunction=12, ConnectionType connectionType=7, Vector overlayRelativePosition=9, NavigationType navigationType=10, string connectionURL=8, bool transitionPreserveScroll=11, PrototypeVariableTarget targetVariable=19, VariableData targetVariableData=20, ConditionalActions[] conditionalActions=24, VariableSetID targetVariableSetID=27, GUID targetVariableModeID=28 message PrototypeInteraction PrototypeEvent event=2, PrototypeAction[] actions=3 message PrototypeStartingPoint string name=1, string position=3 message OverlayBackgroundAppearance OverlayBackgroundType backgroundType=1, Color backgroundColor=2 diff --git a/crates/format/src/fig/export/prototype.rs b/crates/format/src/fig/export/prototype.rs index 3b0fcc122..4d86f776e 100644 --- a/crates/format/src/fig/export/prototype.rs +++ b/crates/format/src/fig/export/prototype.rs @@ -1,7 +1,10 @@ +use figcraft_doc::proto::{Expr, ExprOp, MAX_ACTION_DEPTH}; +use figcraft_doc::{VariableType, VariableValue}; + use super::common::key_codes; use super::{ - Action, Direction, Easing, Exporter, Fields, Interaction, Kv, Node, NodeId, Overflow, OverlayPosition, ScrollPosition, Transition, Trigger, arr, - b, color, e, fl, int, o, position, s, + AUX, Action, Direction, Easing, Exporter, Fields, Interaction, Kv, LAYERS, Node, NodeId, Overflow, OverlayPosition, ScrollPosition, Transition, + Trigger, arr, b, color, e, fl, guid, int, o, position, s, }; impl<'d> Exporter<'d> { @@ -73,11 +76,19 @@ impl<'d> Exporter<'d> { event.push(("transitionTimeout", fl(it.delay_secs()))); } event.insert(0, ("interactionType", e(ty))); - let actions: Vec = it.actions.iter().filter_map(|a| self.action(a, it)).collect(); + let actions: Vec = it.actions.iter().filter_map(|a| self.action(a, it, 0)).collect(); (!actions.is_empty()).then(|| o(vec![("event", o(event)), ("actions", arr(actions))])) } - fn action(&mut self, a: &Action, it: &Interaction) -> Option> { + fn action(&mut self, a: &Action, it: &Interaction, depth: usize) -> Option> { + let encoded = self.encode_action(a, it, depth); + if encoded.is_none() && matches!(a, Action::SetVariable { .. } | Action::SetVariableMode { .. } | Action::Conditional { .. }) { + self.warn("variable or conditional prototype actions with unsupported values, references or nesting were left out"); + } + encoded + } + + fn encode_action(&mut self, a: &Action, it: &Interaction, depth: usize) -> Option> { let node = |x: &mut Self, dest: &NodeId, nav: &'static str| -> Option> { let Some(g) = x.guid_of(*dest) else { x.warn("prototype actions whose destination isn't written were left out"); @@ -88,6 +99,10 @@ impl<'d> Exporter<'d> { Some(o(f)) }; let plain = |ty: &'static str| Some(o(vec![("connectionType", e(ty))])); + // Message → layer → interaction → action uses three Kiwi levels. Each + // conditional adds two, an expression operator adds three, and the deepest + // condition (an alias with a GUID) uses five levels below its action. + let expression_levels = (super::super::kiwi::MAX_DEPTH - 8 - 2 * depth) / 3; match a { Action::Navigate { dest, preserve_scroll } => { let mut act = node(self, dest, "NAVIGATE")?; @@ -120,13 +135,97 @@ impl<'d> Exporter<'d> { Action::Back => plain("BACK"), Action::CloseOverlay => plain("CLOSE"), Action::OpenUrl { url, .. } => Some(o(vec![("connectionType", e("URL")), ("connectionURL", s(url))])), - Action::SetVariable { .. } | Action::SetVariableMode { .. } | Action::Conditional { .. } => { - self.warn("variable and conditional prototype actions were left out"); - None + Action::SetVariable { variable, value, expr } => { + let target = self.doc.variables.get_by_id(variable)?; + let id = self.var_ids.get(variable.as_str())?; + let data = match expr { + Some(expr) => self.expression(expr, expression_levels)?, + None => { + let literal = match target.kind { + VariableType::Boolean => VariableValue::Boolean(value.as_bool()?), + VariableType::Number => VariableValue::Number(value.as_f64()?), + VariableType::String => VariableValue::String(value.as_str()?.to_owned()), + VariableType::Color => VariableValue::Color(super::Color::parse_css(value.as_str()?)?), + }; + literal_data(&literal)? + } + }; + Some(o(vec![ + ("connectionType", e("SET_VARIABLE")), + ("targetVariable", o(vec![("id", o(vec![("guid", guid(LAYERS, *id))]))])), + ("targetVariableData", data), + ])) } + Action::SetVariableMode { collection, mode } => { + let set = self.set_ids.get(collection.as_str())?; + let mode = self.mode_ids.get(&(collection.as_str(), mode.as_str()))?; + Some(o(vec![ + ("connectionType", e("SET_VARIABLE_MODE")), + ("targetVariableSetID", o(vec![("guid", guid(LAYERS, *set))])), + ("targetVariableModeID", guid(AUX, *mode)), + ])) + } + Action::Conditional { blocks } if depth < MAX_ACTION_DEPTH => { + let mut encoded = Vec::new(); + for block in blocks { + // Dropping an unreadable condition would turn this branch into an else. + let mut fields = Vec::new(); + if let Some(condition) = &block.condition { + fields.push(("condition", self.expression(condition, expression_levels)?)); + } + let actions = block.actions.iter().map(|action| self.action(action, it, depth + 1)).collect::>>()?; + fields.push(("actions", arr(actions))); + encoded.push(o(fields)); + } + Some(o(vec![("connectionType", e("CONDITIONAL")), ("conditionalActions", arr(encoded))])) + } + Action::Conditional { .. } => None, } } + fn expression(&self, expr: &Expr, levels: usize) -> Option> { + match expr { + Expr::Value(VariableValue::Alias(id)) => self.expression_alias(id), + Expr::Value(literal) => literal_data(literal), + Expr::Op { op, args } if levels > 0 && (1..=64).contains(&args.len()) => { + let args = args.iter().map(|arg| self.expression(arg, levels - 1)).collect::>>()?; + let (function, resolved) = match op { + ExprOp::Add => { + let string = args.iter().any(|arg| arg.get("resolvedDataType").and_then(Kv::str) == Some("STRING")); + ("ADDITION", if string { "STRING" } else { "FLOAT" }) + } + ExprOp::Subtract => ("SUBTRACTION", "FLOAT"), + ExprOp::Multiply => ("MULTIPLY", "FLOAT"), + ExprOp::Divide => ("DIVIDE", "FLOAT"), + ExprOp::Negate => ("NEGATE", "FLOAT"), + ExprOp::Equals => ("EQUALS", "BOOLEAN"), + ExprOp::NotEqual => ("NOT_EQUAL", "BOOLEAN"), + ExprOp::Less => ("LESS_THAN", "BOOLEAN"), + ExprOp::LessOrEqual => ("LESS_THAN_OR_EQUAL", "BOOLEAN"), + ExprOp::Greater => ("GREATER_THAN", "BOOLEAN"), + ExprOp::GreaterOrEqual => ("GREATER_THAN_OR_EQUAL", "BOOLEAN"), + ExprOp::And => ("AND", "BOOLEAN"), + ExprOp::Or => ("OR", "BOOLEAN"), + ExprOp::Not => ("NOT", "BOOLEAN"), + }; + Some(expression_data(function, resolved, args)) + } + Expr::InMode { variable, mode } if levels > 0 => { + let var = self.doc.variables.get_by_id(variable)?; + let mode = self.mode_ids.get(&(var.collection.as_str(), mode.as_str()))?; + let args = vec![self.expression_alias(variable)?, variable_data("STRING", "STRING", ("textValue", s(&format!("{AUX}:{mode}"))))]; + Some(expression_data("VAR_MODE_LOOKUP", super::common::resolved_type(var.kind), args)) + } + Expr::Mode { .. } | Expr::Op { .. } | Expr::InMode { .. } => None, + } + } + + fn expression_alias(&self, variable: &str) -> Option> { + let var = self.doc.variables.get_by_id(variable)?; + let local = self.var_ids.get(variable)?; + Some(variable_data("ALIAS", super::common::resolved_type(var.kind), ("alias", o(vec![("guid", guid(LAYERS, *local))])))) + } + /// An interaction's transition on one of its actions. fn transition(&mut self, it: &Interaction, f: &mut Fields) { let side_from = |d: Direction, l: &'static str, r: &'static str, t: &'static str, bo: &'static str| match d { @@ -175,3 +274,22 @@ impl<'d> Exporter<'d> { } } } + +fn variable_data(kind: &'static str, resolved: &'static str, value: (&'static str, Kv<'static>)) -> Kv<'static> { + o(vec![("dataType", e(kind)), ("resolvedDataType", e(resolved)), ("value", o(vec![value]))]) +} + +fn literal_data(value: &VariableValue) -> Option> { + let (kind, field) = match value { + VariableValue::Boolean(v) => ("BOOLEAN", ("boolValue", b(*v))), + VariableValue::Number(v) if v.is_finite() => ("FLOAT", ("floatValue", fl(*v))), + VariableValue::String(v) => ("STRING", ("textValue", s(&v.replace('\0', "")))), + VariableValue::Color(v) => ("COLOR", ("colorValue", color(*v))), + _ => return None, + }; + Some(variable_data(kind, kind, field)) +} + +fn expression_data(function: &'static str, resolved: &'static str, args: Vec>) -> Kv<'static> { + variable_data("EXPRESSION", resolved, ("expressionValue", o(vec![("expressionFunction", e(function)), ("expressionArguments", arr(args))]))) +} diff --git a/crates/format/src/fig/kiwi.rs b/crates/format/src/fig/kiwi.rs index 382311b40..d83a59a66 100644 --- a/crates/format/src/fig/kiwi.rs +++ b/crates/format/src/fig/kiwi.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; use std::fmt; /// Deepest struct/message nesting decoded. -const MAX_DEPTH: usize = 64; +pub(super) const MAX_DEPTH: usize = 64; /// Most values decoded from one message (every scalar, array element and field counts): at least /// [`MIN_VALUES`], and [`VALUES_PER_PACKED_BYTE`] per byte of the file's compressed canvas up to /// [`MAX_VALUES`], so a large real file decodes while a small one can't expand into a huge tree, diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index dd04fdf75..03c8dc2eb 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -129,7 +129,8 @@ scales and empty-style clears; they have not been checked in other software. with the area it paints); prototype interactions (clicks, hovers, presses, drags, mouse triggers, delays, keys with modifiers and controller buttons; navigate, overlays with their position, outside-click setting and - background, swap, change to, scroll to, back, close, open link; transitions and easing, custom + background, swap, change to, scroll to, back, close, open link, set variable, set variable mode + and conditional branches; transitions and easing, custom curves included), scrolling and fixed layers, flow starting points. - **Left out, with a warning each:** colour calculations that resolve to nothing (an operand missing, or more than 32 variables to read), variable bindings the format has no field for (component @@ -141,7 +142,8 @@ scales and empty-style clears; they have not been checked in other software. 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), image adjustments, glass settings other than frost, springs other than Gentle (written as ease - out), set-variable, set-variable-mode and conditional actions, scroll-to offsets, text decoration + out), prototype actions with unsupported values, references or nesting (including expressions + that read the current mode of a collection), scroll-to offsets, text decoration looks, variable font axes, text on a path, nested list levels, list spacing, hanging punctuation, leading trim, OpenType features, per-layer operations inside boolean groups, different stroke ends on lines, the Dash cap (no public name for it). Not written at all: stroke outlines of dashed and per-side strokes and of inside or From d928da29bad36e4903083b9ede7122cbc304c5c2 Mon Sep 17 00:00:00 2001 From: Timo Klerx <1579185+TKlerx@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:16:46 +0100 Subject: [PATCH 2/2] M6: Test prototype expression export depth limits --- crates/format/src/fig/assets_tests.rs | 45 +++++++++++++++++++++++ crates/format/src/fig/export/prototype.rs | 8 ++++ 2 files changed, 53 insertions(+) diff --git a/crates/format/src/fig/assets_tests.rs b/crates/format/src/fig/assets_tests.rs index f0a7cf5ab..1fdb82a40 100644 --- a/crates/format/src/fig/assets_tests.rs +++ b/crates/format/src/fig/assets_tests.rs @@ -1246,6 +1246,7 @@ fn a_scaled_instance_keeps_reset_lists_above_a_changed_style_link() { } } +/// The checkbox toggles the imported variable before choosing its status branch. #[test] fn checkbox_variable_and_conditional_actions_round_trip() { use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp}; @@ -1315,6 +1316,7 @@ fn checkbox_variable_and_conditional_actions_round_trip() { } } +/// An unrepresentable condition leaves other actions in the interaction intact. #[test] fn overdeep_conditional_is_omitted_without_losing_the_export() { use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp, MAX_EXPR_DEPTH}; @@ -1345,3 +1347,46 @@ fn overdeep_conditional_is_omitted_without_losing_the_export() { let frame = back.nodes().find(|n| n.name == "Trigger").unwrap(); assert_eq!(frame.interactions[0].actions, vec![Action::Back]); } + +/// The longest conditions with a variable-reference leaf survive at each tested nesting level. +#[test] +fn conditional_expression_depth_boundary_round_trips() { + use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp}; + + let conditional = |condition, action| Action::Conditional { blocks: vec![ConditionalBlock { condition, actions: vec![action] }] }; + let nested_action = |depth, operators, variable: String| { + let flag = Expr::var(variable); + let condition = (0..operators).fold(flag.clone(), |inner, _| Expr::op(ExprOp::Not, vec![inner])); + (0..depth).fold(conditional(Some(condition), Action::Back), |inner, _| conditional(Some(flag.clone()), inner)) + }; + + // The deepest alias is at Kiwi depth 8 + 2 × conditional depth + 3 × operator count. + for (depth, operators) in [(0, 18), (1, 18), (15, 8)] { + let mut doc = Document::new("Depth boundary"); + let page = doc.first_page().unwrap(); + doc.variables.collections.push(Collection { + id: "demo".into(), + name: "Demo".into(), + modes: vec![Mode { id: "default".into(), name: "Default".into() }], + extends: None, + }); + doc.variables.variables.push(var("checked", "checked", "demo", VariableType::Boolean, &[("default", VariableValue::Boolean(true))])); + let frame = doc.create(page, NodeKind::Frame, "Trigger", 0.0, 0.0, 100.0, 100.0).unwrap(); + doc.node_mut(frame).unwrap().interactions.push(Interaction { + trigger: Trigger::OnClick, + actions: vec![nested_action(depth, operators, "checked".into())], + transition: Transition::Instant, + duration_ms: 300, + easing: Easing::EaseOut, + delay_ms: 0, + }); + + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.is_empty(), "export at conditional depth {depth}: {warnings:?}"); + let (back, warnings) = import(&bytes, "Depth boundary").unwrap(); + assert!(warnings.is_empty(), "import at conditional depth {depth}: {warnings:?}"); + let trigger = back.nodes().find(|node| node.name == "Trigger").unwrap(); + let checked = back.variables.variables.iter().find(|variable| variable.name == "checked").unwrap(); + assert_eq!(trigger.interactions[0].actions, [nested_action(depth, operators, checked.id.clone())], "conditional depth {depth}"); + } +} diff --git a/crates/format/src/fig/export/prototype.rs b/crates/format/src/fig/export/prototype.rs index 4d86f776e..08b3f031a 100644 --- a/crates/format/src/fig/export/prototype.rs +++ b/crates/format/src/fig/export/prototype.rs @@ -46,6 +46,7 @@ impl<'d> Exporter<'d> { } } + /// Encode the trigger and the actions that can be represented in the export. fn interaction(&mut self, it: &Interaction) -> Option> { let mut event: Fields = Vec::new(); let ty = match &it.trigger { @@ -80,6 +81,7 @@ impl<'d> Exporter<'d> { (!actions.is_empty()).then(|| o(vec![("event", o(event)), ("actions", arr(actions))])) } + /// Encode one action and warn when a variable or conditional action must be omitted. fn action(&mut self, a: &Action, it: &Interaction, depth: usize) -> Option> { let encoded = self.encode_action(a, it, depth); if encoded.is_none() && matches!(a, Action::SetVariable { .. } | Action::SetVariableMode { .. } | Action::Conditional { .. }) { @@ -88,6 +90,7 @@ impl<'d> Exporter<'d> { encoded } + /// Map an action to Kiwi, preserving branch order and bounding conditional recursion. fn encode_action(&mut self, a: &Action, it: &Interaction, depth: usize) -> Option> { let node = |x: &mut Self, dest: &NodeId, nav: &'static str| -> Option> { let Some(g) = x.guid_of(*dest) else { @@ -183,6 +186,7 @@ impl<'d> Exporter<'d> { } } + /// Encode an expression within the remaining Kiwi operator nesting budget. fn expression(&self, expr: &Expr, levels: usize) -> Option> { match expr { Expr::Value(VariableValue::Alias(id)) => self.expression_alias(id), @@ -220,6 +224,7 @@ impl<'d> Exporter<'d> { } } + /// Reference an exported variable by GUID and include its resolved type. fn expression_alias(&self, variable: &str) -> Option> { let var = self.doc.variables.get_by_id(variable)?; let local = self.var_ids.get(variable)?; @@ -275,10 +280,12 @@ impl<'d> Exporter<'d> { } } +/// Wrap a literal, alias or expression in the Kiwi variable-data record. fn variable_data(kind: &'static str, resolved: &'static str, value: (&'static str, Kv<'static>)) -> Kv<'static> { o(vec![("dataType", e(kind)), ("resolvedDataType", e(resolved)), ("value", o(vec![value]))]) } +/// Encode a finite, typed literal without variable references. fn literal_data(value: &VariableValue) -> Option> { let (kind, field) = match value { VariableValue::Boolean(v) => ("BOOLEAN", ("boolValue", b(*v))), @@ -290,6 +297,7 @@ fn literal_data(value: &VariableValue) -> Option> { Some(variable_data(kind, kind, field)) } +/// Encode an operator and its ordered arguments with their result type. fn expression_data(function: &'static str, resolved: &'static str, args: Vec>) -> Kv<'static> { variable_data("EXPRESSION", resolved, ("expressionValue", o(vec![("expressionFunction", e(function)), ("expressionArguments", arr(args))]))) }