mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-30 18:24:11 +01:00
Merge pull request #2212 from TKlerx/codex/2210-fig-prototype-actions
Preserve variable and conditional prototype actions in .fig exports
This commit is contained in:
7 files changed
+364
-26
No files matched your search
@@ -374,6 +374,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| 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-10 | minor | M12, #2226 (step 2 of 4): mind maps in the UI. The Shapes flyout ends in a mind map tool (`tool.mindMap`): a click places a map with the first node's text starting there and types in it. Cmd/Ctrl+Enter adds a child of the selected or edited node (`board.mindMapAdd`), Shift+Cmd/Ctrl+Enter its next sibling (`board.nextSticky` on a node), both typing on; Tab and Shift+Tab walk a node's siblings in the map's order (`select.next`, `select.previous`). The bar over the selection colours a node's text (`board.setColor`) and shows a branch the connector's controls without the line types. Tests: `board_mindmap_tests` (four more), `board_ui_tests` (five more). Breadth ~47% → ~48%, ready ~29% → ~30%. |
|
||||
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
|
||||
| 2026-11-10 | minor | Experimental `.fig` export preserves set-variable, set-variable-mode and conditional prototype actions (#2210). |
|
||||
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
|
||||
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
|
||||
| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. |
|
||||
|
||||
@@ -116,6 +116,10 @@ display_name = "Hamza0101"
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
[people.TKlerx]
|
||||
real_name = "Timo Klerx"
|
||||
sync_github_name = true
|
||||
|
||||
[people.GiovanniBot]
|
||||
sync_github_name = true
|
||||
|
||||
|
||||
@@ -1245,3 +1245,193 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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};
|
||||
|
||||
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 }]);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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};
|
||||
|
||||
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]);
|
||||
}
|
||||
|
||||
/// 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}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_override_conditions_respect_the_kiwi_depth_limit() {
|
||||
use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp};
|
||||
|
||||
let (mut doc, [same, resized, _]) = sized();
|
||||
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))]));
|
||||
for (instance, operators) in [(same, 17), (resized, 18)] {
|
||||
let child = doc.node(instance).unwrap().children[0];
|
||||
let condition = (0..operators).fold(Expr::var("checked"), |inner, _| Expr::op(ExprOp::Not, vec![inner]));
|
||||
doc.node_mut(child).unwrap().interactions.push(Interaction {
|
||||
trigger: Trigger::OnClick,
|
||||
actions: vec![
|
||||
Action::Conditional {
|
||||
blocks: vec![ConditionalBlock {
|
||||
condition: Some(Expr::var("checked")),
|
||||
actions: vec![Action::Conditional {
|
||||
blocks: vec![ConditionalBlock { condition: Some(condition), actions: vec![Action::Back] }],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
Action::Back,
|
||||
],
|
||||
transition: Transition::Instant,
|
||||
duration_ms: 300,
|
||||
easing: Easing::EaseOut,
|
||||
delay_ms: 0,
|
||||
});
|
||||
}
|
||||
|
||||
let (_, warnings) = export(&doc, None).unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains("nesting")), "{warnings:?}");
|
||||
let nodes = written(&doc);
|
||||
for (name, expected) in [("Same", vec!["CONDITIONAL", "BACK"]), ("Resized", vec!["BACK"])] {
|
||||
let rows = named(&nodes, name)["symbolData"]["symbolOverrides"].as_array().unwrap();
|
||||
let actions = rows.iter().find_map(|row| row["prototypeInteractions"][0]["actions"].as_array()).unwrap();
|
||||
assert_eq!(actions.iter().map(|action| action["connectionType"].as_str().unwrap()).collect::<Vec<_>>(), expected);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -170,7 +170,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
|
||||
@@ -181,7 +183,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
|
||||
|
||||
@@ -210,15 +210,11 @@ impl<'d> Exporter<'d> {
|
||||
_ => None,
|
||||
};
|
||||
let sized = matches!(d.kind, NodeKind::Instance { .. }) || d.overrides.contains("size");
|
||||
rows.push(Row {
|
||||
path: o(vec![("guids", arr(guids))]),
|
||||
main_equal_lengths: if scale_candidate.is_some() { main_equal_lengths(&mine, &theirs) } else { Vec::new() },
|
||||
styles: self.changed_list_styles(d, &mine, &theirs),
|
||||
changed: changed(mine, &theirs),
|
||||
theirs,
|
||||
sized,
|
||||
swap,
|
||||
});
|
||||
let main_equal_lengths = if scale_candidate.is_some() { main_equal_lengths(&mine, &theirs) } else { Vec::new() };
|
||||
let styles = self.changed_list_styles(d, &mine, &theirs);
|
||||
let mut changed = changed(mine, &theirs);
|
||||
self.bound_override_interactions(d, &mut changed);
|
||||
rows.push(Row { path: o(vec![("guids", arr(guids))]), main_equal_lengths, styles, changed, theirs, sized, swap });
|
||||
}
|
||||
// An instance scaled as a whole (the Scale tool) is `factor` times its main in every length:
|
||||
// sizes, places and stroke weights, its own and its layers'. A resized one keeps its weights.
|
||||
@@ -248,7 +244,9 @@ impl<'d> Exporter<'d> {
|
||||
if factor.is_some() {
|
||||
of.extend(main_equal_lengths(&root_mine, &root_theirs));
|
||||
}
|
||||
of.extend(changed(root_mine, &root_theirs).into_iter().filter(|(k, v)| *k == "size" || !follows(k, v, &root_theirs)));
|
||||
let mut root_changed = changed(root_mine, &root_theirs);
|
||||
self.bound_override_interactions(n, &mut root_changed);
|
||||
of.extend(root_changed.into_iter().filter(|(k, v)| *k == "size" || !follows(k, v, &root_theirs)));
|
||||
if of.len() > 1 {
|
||||
overrides.push(o(of));
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
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> {
|
||||
/// Interactions, scrolling, flow starts and the overlay settings this layer is opened with.
|
||||
pub(super) fn prototype(&mut self, n: &Node, f: &mut Fields) {
|
||||
self.trigger_size = [n.width, n.height];
|
||||
let list: Vec<Kv> = n.interactions.iter().filter_map(|it| self.interaction(it)).collect();
|
||||
let list = self.prototype_interactions(n, 0);
|
||||
if !list.is_empty() {
|
||||
f.push(("prototypeInteractions", arr(list)));
|
||||
}
|
||||
@@ -43,7 +45,21 @@ impl<'d> Exporter<'d> {
|
||||
}
|
||||
}
|
||||
|
||||
fn interaction(&mut self, it: &Interaction) -> Option<Kv<'static>> {
|
||||
/// Re-encode only interactions that differ from the main and will be written as overrides.
|
||||
pub(super) fn bound_override_interactions(&mut self, n: &Node, fields: &mut Fields) {
|
||||
if let Some((_, value)) = fields.iter_mut().find(|(key, _)| *key == "prototypeInteractions") {
|
||||
// SymbolData and its override NodeChange add two Kiwi levels.
|
||||
*value = arr(self.prototype_interactions(n, 2));
|
||||
}
|
||||
}
|
||||
|
||||
fn prototype_interactions(&mut self, n: &Node, extra_depth: usize) -> Vec<Kv<'static>> {
|
||||
self.trigger_size = [n.width, n.height];
|
||||
n.interactions.iter().filter_map(|it| self.interaction(it, extra_depth)).collect()
|
||||
}
|
||||
|
||||
/// Encode the trigger and the actions that can be represented in the export.
|
||||
fn interaction(&mut self, it: &Interaction, extra_depth: usize) -> Option<Kv<'static>> {
|
||||
let mut event: Fields = Vec::new();
|
||||
let ty = match &it.trigger {
|
||||
Trigger::OnClick => "ON_CLICK",
|
||||
@@ -73,11 +89,21 @@ impl<'d> Exporter<'d> {
|
||||
event.push(("transitionTimeout", fl(it.delay_secs())));
|
||||
}
|
||||
event.insert(0, ("interactionType", e(ty)));
|
||||
let actions: Vec<Kv> = it.actions.iter().filter_map(|a| self.action(a, it)).collect();
|
||||
let actions: Vec<Kv> = it.actions.iter().filter_map(|a| self.action(a, it, 0, extra_depth)).collect();
|
||||
(!actions.is_empty()).then(|| o(vec![("event", o(event)), ("actions", arr(actions))]))
|
||||
}
|
||||
|
||||
fn action(&mut self, a: &Action, it: &Interaction) -> Option<Kv<'static>> {
|
||||
/// Encode one action and warn when a variable or conditional action must be omitted.
|
||||
fn action(&mut self, a: &Action, it: &Interaction, depth: usize, extra_depth: usize) -> Option<Kv<'static>> {
|
||||
let encoded = self.encode_action(a, it, depth, extra_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
|
||||
}
|
||||
|
||||
/// Map an action to Kiwi, preserving branch order and bounding conditional recursion.
|
||||
fn encode_action(&mut self, a: &Action, it: &Interaction, depth: usize, extra_depth: usize) -> Option<Kv<'static>> {
|
||||
let node = |x: &mut Self, dest: &NodeId, nav: &'static str| -> Option<Kv<'static>> {
|
||||
let Some(g) = x.guid_of(*dest) else {
|
||||
x.warn("prototype actions whose destination isn't written were left out");
|
||||
@@ -88,6 +114,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 = (craft_fig::kiwi::MAX_DEPTH - 8 - extra_depth - 2 * depth) / 3;
|
||||
match a {
|
||||
Action::Navigate { dest, preserve_scroll } => {
|
||||
let mut act = node(self, dest, "NAVIGATE")?;
|
||||
@@ -120,13 +150,99 @@ 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, extra_depth)).collect::<Option<Vec<_>>>()?;
|
||||
fields.push(("actions", arr(actions)));
|
||||
encoded.push(o(fields));
|
||||
}
|
||||
Some(o(vec![("connectionType", e("CONDITIONAL")), ("conditionalActions", arr(encoded))]))
|
||||
}
|
||||
Action::Conditional { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode an expression within the remaining Kiwi operator nesting budget.
|
||||
fn expression(&self, expr: &Expr, levels: usize) -> Option<Kv<'static>> {
|
||||
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::<Option<Vec<_>>>()?;
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference an exported variable by GUID and include its resolved type.
|
||||
fn expression_alias(&self, variable: &str) -> Option<Kv<'static>> {
|
||||
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 +291,25 @@ 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<Kv<'static>> {
|
||||
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))
|
||||
}
|
||||
|
||||
/// Encode an operator and its ordered arguments with their result type.
|
||||
fn expression_data(function: &'static str, resolved: &'static str, args: Vec<Kv<'static>>) -> Kv<'static> {
|
||||
variable_data("EXPRESSION", resolved, ("expressionValue", o(vec![("expressionFunction", e(function)), ("expressionArguments", arr(args))])))
|
||||
}
|
||||
@@ -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
|
||||
@@ -140,7 +141,9 @@ 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),
|
||||
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 or references (including expressions
|
||||
that read the current mode of a collection) or nesting beyond the Kiwi limit, which instance
|
||||
overrides reach two levels sooner, scroll-to offsets, text decoration
|
||||
looks, variable font axes, text on a path with more than one line or on a path the format can't hold (written as plain text), the parts of a text's path after the first, text on a path in an instance but not in its main or the other way round (written as the main has it), an instance's text of more than one line on a main on a path (it stays on that path, as an override can't take it off), nested list levels, 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
|
||||
outside strokes on polygons, stars and vectors, glyph outlines of text (a reader lays text out
|
||||
|
||||
Reference in new issue
Block a user