diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index e35c3f5b..a8901f24 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -678,8 +678,8 @@ fn push_changes(s: &mut Session, p: &Value) -> Result { if !doc.contains(component) { return Err(EngineError::Disabled(cmd.into(), "the main component was deleted (use component.restoreMain)".into())); } - // Copy every overridden layer's values to its source in the main (geometry, swaps, property - // values and slot content stay with the instance). + // Copy every overridden layer's values to its source in the main (geometry, resizing, swaps, + // property values and slot content stay with the instance). let mut pushed = 0; for d in doc.subtree(inst) { let Some(n) = doc.node(d).cloned() else { continue }; @@ -691,7 +691,9 @@ fn push_changes(s: &mut Session, p: &Value) -> Result { let groups: BTreeSet = n .overrides .iter() - .filter(|g| !matches!(g.as_str(), "size" | "position" | "component" | "props" | SLOT) && !(d == inst && g.as_str() == "name")) + .filter(|g| { + !matches!(g.as_str(), "size" | "resizing" | "position" | "component" | "props" | SLOT) && !(d == inst && g.as_str() == "name") + }) .cloned() .collect(); for g in &groups { diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 598be752..78b448c0 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -783,12 +783,14 @@ pub fn apply(cmd: &str, doc: &mut Document, id: NodeId, props: &Map &'static str { "features" | "fontFeatures" | "openTypeFeatures" | "listStyle" | "indentation" | "listSpacing" | "maxLines" | "variationSettings" | "hangingPunctuation" | "hangingList" => "textStyle", "cornerRadius" | "cornerSmoothing" | "topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "corners", - "width" | "height" | "w" | "h" | "sizingH" | "sizingV" => "size", + "width" | "height" | "w" | "h" => "size", + "sizingH" | "sizingV" | "layoutSizingHorizontal" | "layoutSizingVertical" | "minWidth" | "maxWidth" | "minHeight" | "maxHeight" => "resizing", "gap" | "itemSpacing" | "columnGap" | "crossGap" | "counterAxisSpacing" | "rowGap" => "gap", "padding" | "paddingTop" | "paddingRight" | "paddingBottom" | "paddingLeft" | "paddingHorizontal" | "paddingVertical" => "padding", "mainAlign" | "primaryAxisAlignItems" | "crossAlign" | "counterAxisAlignItems" | "contentAlign" | "counterAxisAlignContent" => "alignment", diff --git a/crates/engine/src/components.rs b/crates/engine/src/components.rs index 30f21b8c..ff582b8a 100644 --- a/crates/engine/src/components.rs +++ b/crates/engine/src/components.rs @@ -11,12 +11,12 @@ //! Override groups: `fills`, `strokes`, `effects`, `opacity`, `visible`, `name`, `corners`, //! `characters`, `textStyle` (font, size, spacing, resizing, …), `padding`, `gap` and `alignment` //! (of auto layout: its direction and other settings are the main's), `grids`, `exports`, -//! `interactions`, `component` (a swapped nested instance), `props` (property values of a nested -//! instance) and `slot` (a slot holding the instance's own content). An instance's own export -//! settings and interactions are its own, like its place. `size` and `position` overrides of -//! layers inside an instance are still read and kept, but new ones are refused -//! ([`check_override_edit`]): those layers take their geometry, constraints and resizing from the -//! main; the instance itself resizes. +//! `interactions`, `size` and `resizing` (hug, fill or fixed, with min and max sizes) of layers +//! inside an instance, `component` (a swapped nested instance), `props` (property values of a +//! nested instance) and `slot` (a slot holding the instance's own content). An instance's own +//! export settings, interactions and resizing are its own, like its place. `position` +//! overrides of layers inside an instance are still read and kept, but new ones are refused +//! ([`check_override_edit`]): those layers take their place and constraints from the main. //! //! Switching variants keeps an override where the layer's name path matches and the two variants //! agreed on that property (text layers keep all of theirs); swapping from the Assets panel keeps @@ -58,6 +58,7 @@ pub const OVERRIDE_GROUPS: &[&str] = &[ "exports", "interactions", "size", + "resizing", "position", "component", "props", @@ -388,11 +389,14 @@ pub(crate) fn copy_group(from: &Node, to: &mut Node, g: &str) { "size" => { to.width = from.width; to.height = from.height; - to.child_layout = from.child_layout.clone(); if let (NodeKind::Text(a), NodeKind::Text(b)) = (&from.kind, &mut to.kind) { b.auto_resize = a.auto_resize; } } + "resizing" => { + let (a, b) = (&from.child_layout, &mut to.child_layout); + (b.sizing_h, b.sizing_v, b.min_w, b.max_w, b.min_h, b.max_h) = (a.sizing_h, a.sizing_v, a.min_w, a.max_w, a.min_h, a.max_h); + } "position" => to.transform = from.transform, "component" => { if let (NodeKind::Instance { component: a, .. }, NodeKind::Instance { component: b, .. }) = (&from.kind, &mut to.kind) { @@ -773,6 +777,15 @@ fn sync_instance_depth(doc: &mut Document, inst: NodeId, depth: usize, spare: BT for s in &src { let Some(nid) = map.get(s).copied() else { continue }; let Some(o) = old.get(&nid) else { continue }; + // A frame that kept the size its own resizing gave it: its layers (copied at their main + // layers' places) follow their constraints from its main layer's size. + if o.overrides.contains("resizing") + && !o.overrides.contains("size") + && doc.node(nid).is_some_and(|n| n.kind.is_frame_like() && n.layout.is_none()) + && let Some((mw, mh)) = doc.node(*s).map(|m| (m.width, m.height)) + { + figcraft_layout::apply_constraints(doc, nid, mw, mh); + } if !o.overrides.contains("size") && !o.overrides.contains("position") { continue; } @@ -985,6 +998,9 @@ pub fn diff_groups(a: &Node, b: &Node) -> Vec<&'static str> { if (a.width - b.width).abs() > 1e-6 || (a.height - b.height).abs() > 1e-6 { out.push("size"); } + if resizing(a) != resizing(b) { + out.push("resizing"); + } if a.transform != b.transform { out.push("position"); } @@ -1027,6 +1043,12 @@ pub fn diff_groups(a: &Node, b: &Node) -> Vec<&'static str> { out } +/// The `resizing` group of a layer: how it sizes on each axis, and its min and max sizes. +fn resizing(n: &Node) -> (Sizing, Sizing, [Option; 4]) { + let c = &n.child_layout; + (c.sizing_h, c.sizing_v, [c.min_w, c.max_w, c.min_h, c.max_h]) +} + /// Whether two texts differ in anything but their characters (the `textStyle` group). fn text_style_differs(x: &TextData, y: &TextData) -> bool { x.style != y.style @@ -1107,9 +1129,10 @@ pub fn sync_after_edit(doc: &mut Document, before: &Document, changed: &[NodeId] } let raw = diff_groups(b, n); let mut groups = raw.clone(); - // An instance's own place, export settings and interactions are its own, not overrides. + // An instance's own place, resizing, export settings and interactions are its own, not + // overrides. if top_root { - groups.retain(|g| !matches!(*g, "component" | "props" | "position" | "exports" | "interactions")); + groups.retain(|g| !matches!(*g, "component" | "props" | "position" | "resizing" | "exports" | "interactions")); } if groups.iter().any(|g| matches!(*g, "size" | "position")) { groups.retain(|g| !matches!(*g, "size" | "position") || !geometry_derived(doc, before, id, g)); @@ -1414,7 +1437,7 @@ fn patch_structure(doc: &mut Document, before: &Document, seeds: &[NodeId]) -> b fn child_follows_main(doc: &Document, parent: NodeId, absolute: bool) -> bool { let Some(p) = doc.node(parent) else { return false }; let constrains = p.layout.is_none() || absolute; - let resized = p.overrides.contains("size") + let resized = sized_own(p) || match &p.kind { NodeKind::Instance { component, .. } => { doc.node(*component).is_none_or(|m| (m.width - p.width).abs() > 1e-9 || (m.height - p.height).abs() > 1e-9) @@ -1518,7 +1541,7 @@ fn follows_main_geometry(doc: &Document, id: NodeId) -> bool { chain.windows(2).all(|w| { let (Some(below), Some(a)) = (w.first().and_then(|i| doc.node(*i)), w.get(1).and_then(|i| doc.node(*i))) else { return false }; let constrains = a.layout.is_none() || below.child_layout.absolute; - if a.overrides.contains("size") && constrains { + if sized_own(a) && constrains { return false; } match &a.kind { @@ -1530,6 +1553,12 @@ fn follows_main_geometry(doc: &Document, id: NodeId) -> bool { }) } +/// Whether a layer inside an instance overrides its size or resizing: it may not have its main +/// layer's size, so the layers in it can't take their main layers' places as they are. +fn sized_own(n: &Node) -> bool { + n.overrides.contains("size") || n.overrides.contains("resizing") +} + /// Rebuild every instance of `comps` (and of the components that hold those instances, and so on /// outwards), each outermost instance once, inner components first. fn rebuild_instances(doc: &mut Document, comps: &BTreeSet) { @@ -1665,10 +1694,9 @@ pub fn check_override_edit(before: &Document, after: &Document) -> Result<(), St /// What about layer `id` an edit from `before` to `after` changed that only its main can: the /// auto layout of an instance or a layer in one but its padding, gap and alignment, or the -/// position (rotation too), size, constraints or resizing of a layer inside an instance (the -/// instance itself resizes, and its layers follow; text whose box follows its content still -/// does). `None` when the edit is fine, also when the main changed the same way in this edit (a -/// library update). +/// position (rotation too), constraints or place in auto layout (absolute, grid cell) of a layer +/// inside an instance (its size and resizing are overrides). `None` when the edit is fine, also +/// when the main changed the same way in this edit (a library update). pub fn refused_override(before: &Document, after: &Document, id: NodeId) -> Option<&'static str> { let (n, b) = (after.node(id)?, before.node(id)?); if after.is_remote(id) || n.source != b.source || owning_instance(before, id).is_none() || owning_instance(after, id).is_none() { @@ -1684,8 +1712,12 @@ pub fn refused_override(before: &Document, after: &Document, id: NodeId) -> Opti l }) }; - let size = |x: &Node| (x.width, x.height); - let resized = |x: &Node, y: &Node| (x.width - y.width).abs() > 1e-6 || (x.height - y.height).abs() > 1e-6; + // Child layout settings other than the resizing ones. + let placing = |x: &Node| { + let mut c = x.child_layout.clone(); + (c.sizing_h, c.sizing_v, c.min_w, c.max_w, c.min_h, c.max_h) = (Sizing::Fixed, Sizing::Fixed, None, None, None, None); + c + }; if mode(n) != mode(b) && mode(ma) == mode(mb) { return Some("The auto layout direction"); } @@ -1698,14 +1730,11 @@ pub fn refused_override(before: &Document, after: &Document, id: NodeId) -> Opti if n.transform != b.transform && ma.transform == mb.transform && !geometry_derived(after, before, id, "position") { return Some("A layer's position"); } - if resized(n, b) && size(ma) == size(mb) && !geometry_derived(after, before, id, "size") { - return Some("A layer's size"); - } if n.constraints != b.constraints && ma.constraints == mb.constraints { return Some("A layer's constraints"); } - if n.child_layout != b.child_layout && ma.child_layout == mb.child_layout { - return Some("A layer's resizing"); + if placing(n) != placing(b) && placing(ma) == placing(mb) { + return Some("A layer's place in auto layout"); } None } @@ -1923,6 +1952,7 @@ pub fn rebase_instance(doc: &mut Document, inst: NodeId) { let mut groups: Vec = value_groups(m, n) .into_iter() .filter(|g| !matches!(g.as_str(), "name" | "exports" | "interactions") && !from_variables.contains(&g.as_str())) + .filter(|g| placed_source.is_some() || g != "resizing") .collect(); let named = if placed_source.is_some() { n.name != m.name } else { n.name != default_instance_name(doc, component) }; if named { @@ -1946,7 +1976,8 @@ pub fn rebase_instance(doc: &mut Document, inst: NodeId) { } if let Some(n) = doc.node_mut(inst) { n.source = root_base; - n.overrides.retain(|g| !matches!(g.as_str(), "component" | "props" | "position")); + // A top-level instance's resizing is its own (a nested one's overrides its main layer's). + n.overrides.retain(|g| !matches!(g.as_str(), "component" | "props" | "position") && (placed_source.is_some() || g != "resizing")); n.overrides.extend(root_groups); } } diff --git a/crates/engine/src/components_behaviour_tests.rs b/crates/engine/src/components_behaviour_tests.rs index 325ccdee..15f660e1 100644 --- a/crates/engine/src/components_behaviour_tests.rs +++ b/crates/engine/src/components_behaviour_tests.rs @@ -316,14 +316,6 @@ fn what_instances_cannot_override_is_refused() { ("nudge a layer", "transform.nudge", json!({"ids": ["$"], "dx": 1, "dy": 0}), Layer::Bg, "position"), ("rotate a layer", "node.set", json!({"id": "$", "props": {"rotation": 15}}), Layer::Bg, "position and rotation come with the layer's place"), ("flip a layer", "object.flipH", json!({"ids": ["$"]}), Layer::Bg, "position"), - ( - "resize a layer", - "node.set", - json!({"id": "$", "props": {"width": 50}}), - Layer::Bg, - "not among the overridable properties; the instance resizes", - ), - ("resize a text box", "node.set", json!({"id": "$", "props": {"width": 150}}), Layer::Title, "\"the bounds of any text layers\""), ( "change constraints", "node.set", @@ -331,13 +323,6 @@ fn what_instances_cannot_override_is_refused() { Layer::Bg, "\"any constraints applied to the layers\"", ), - ( - "make a layer fill its auto layout", - "node.set", - json!({"id": "$", "props": {"sizingH": "fill"}}), - Layer::Chip, - "resizing comes with the layer's size", - ), ( "take a layer out of auto layout", "node.set", diff --git a/crates/engine/src/components_tests.rs b/crates/engine/src/components_tests.rs index eb21b20e..209560cd 100644 --- a/crates/engine/src/components_tests.rs +++ b/crates/engine/src/components_tests.rs @@ -67,8 +67,6 @@ fn overrides_survive_main_edits() { ex(&mut s, "node.set", json!({"id": ibg, "props": {"effects": [{"type": "dropShadow"}]}})); ex(&mut s, "text.set", json!({"id": ititle, "characters": "Overridden"})); ex(&mut s, "node.set", json!({"id": idot, "props": {"visible": false}})); - // A layer inside an instance keeps its main's size (the instance itself resizes). - assert!(s.execute("node.set", &json!({"id": idot, "props": {"width": 30}})).is_err()); let ov = node(&s, ibg).overrides; for g in ["fills", "strokes", "effects", "name"] { assert!(ov.contains(g), "{g} in {ov:?}"); diff --git a/crates/engine/src/cursor_tests.rs b/crates/engine/src/cursor_tests.rs index 05a95f66..7a9e0621 100644 --- a/crates/engine/src/cursor_tests.rs +++ b/crates/engine/src/cursor_tests.rs @@ -202,15 +202,16 @@ fn an_edit_an_instance_refuses_shows_not_allowed_and_is_undone() { let before = s.doc().unwrap().world_bounds(inner).unwrap(); assert_eq!((before.x0, before.y0, before.x1, before.y1), (450.0, 50.0, 550.0, 150.0)); ex(&mut s, "select.set", json!({"ids": [inner]})); - // Resizing it by its right edge: only the main component can. - assert!(close(resize(hover(&mut s, (550.0, 100.0), NONE)), 0.0), "the handle still shows its arrow"); + // Resizing it by its right edge: a size of its own (an override). + assert!(close(resize(hover(&mut s, (550.0, 100.0), NONE)), 0.0), "the handle shows its arrow"); s.pointer(&ev(PointerKind::Down, (550.0, 100.0), NONE)).unwrap(); s.pointer(&ev(PointerKind::Move, (570.0, 100.0), NONE)).unwrap(); s.pointer(&ev(PointerKind::Move, (600.0, 100.0), NONE)).unwrap(); - assert_eq!(s.tool.overlay.cursor, Cursor::NotAllowed); + assert_ne!(s.tool.overlay.cursor, Cursor::NotAllowed); s.pointer(&ev(PointerKind::Up, (600.0, 100.0), NONE)).unwrap(); - assert_eq!(s.doc().unwrap().world_bounds(inner).unwrap(), before, "the resize was undone"); - // Moving it: refused too. + let before = s.doc().unwrap().world_bounds(inner).unwrap(); + assert_eq!((before.x0, before.x1), (450.0, 600.0), "the resize stays"); + // Moving it: only the main component can. s.pointer(&ev(PointerKind::Down, (500.0, 100.0), NONE)).unwrap(); s.pointer(&ev(PointerKind::Move, (510.0, 110.0), NONE)).unwrap(); s.pointer(&ev(PointerKind::Move, (520.0, 120.0), NONE)).unwrap(); diff --git a/crates/engine/src/instance_resizing_tests.rs b/crates/engine/src/instance_resizing_tests.rs new file mode 100644 index 00000000..43386af9 --- /dev/null +++ b/crates/engine/src/instance_resizing_tests.rs @@ -0,0 +1,190 @@ +//! Size and resizing overrides of layers inside instances: a layer in an instance can hug, fill or +//! keep a fixed size of its own, and that override is kept through relayout, edits of the main +//! (only the overridden property stays), undo, save and reopen (native and .fig), REST import, +//! detach and reset. + +use base64::Engine; +use serde_json::{Value, json}; + +use crate::Session; +use crate::components::tests::{copy_of, ex, healthy, idv, node}; +use figcraft_doc::*; + +/// A "Field" component: a 240×40 fixed horizontal auto layout frame (no padding or gap) holding +/// "Atom", an auto layout frame hugging its 20×20 "Dot" with a min width of 100; and an instance of +/// it. Returns (component, atom, dot, instance). +fn field(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let f = idv(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 40, "name": "Field"}))); + ex(s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "fixed", "sizingV": "fixed"}})); + let atom = idv(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": f, "name": "Atom"}))); + ex( + s, + "node.set", + json!({"id": atom, "props": {"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug", "minWidth": 100}}), + ); + let dot = idv(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20, "parent": atom, "props": {"name": "Dot"}}))); + let c = idv(&ex(s, "component.create", json!({"ids": [f]}))); + let i = idv(&ex(s, "instance.create", json!({"component": c, "x": 0, "y": 100}))); + (c, atom, dot, i) +} + +fn sizing_h(s: &Session, id: NodeId) -> Sizing { + node(s, id).child_layout.sizing_h +} + +/// The layer named `name` below instance `inst`. +fn named(s: &Session, inst: NodeId, name: &str) -> NodeId { + let doc = s.doc().unwrap(); + doc.subtree(inst).into_iter().find(|d| *d != inst && doc.node(*d).is_some_and(|n| n.name == name)).unwrap() +} + +/// The first instance in the document. +fn instance(s: &Session) -> NodeId { + s.doc().unwrap().nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap().id +} + +fn open(s: &mut Session, bytes: &[u8], name: &str) { + ex(s, "file.open", json!({"data": base64::engine::general_purpose::STANDARD.encode(bytes), "name": name})); +} + +#[test] +fn a_layer_in_an_instance_fills_and_keeps_it_through_main_edits() { + let mut s = Session::new(); + let (c, atom, dot, i) = field(&mut s); + let (ia, idot) = (copy_of(&s, i, atom), copy_of(&s, i, dot)); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width), (Sizing::Hug, 100.0), "hugs its dot, at least 100 wide"); + ex(&mut s, "node.set", json!({"id": ia, "props": {"sizingH": "fill"}})); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width), (Sizing::Fill, 240.0), "fills the instance"); + assert!(node(&s, ia).overrides.contains("resizing"), "{:?}", node(&s, ia).overrides); + // Edits of the main relay the instance out: the override stays, other properties follow. + ex(&mut s, "node.set", json!({"id": dot, "props": {"width": 30, "fill": "#ff0000"}})); + assert_eq!((node(&s, ia).width, node(&s, idot).width), (240.0, 30.0)); + ex(&mut s, "node.set", json!({"id": atom, "props": {"minWidth": 120, "fill": "#00ff00"}})); + assert_eq!(node(&s, atom).width, 120.0); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width, node(&s, ia).child_layout.min_w), (Sizing::Fill, 240.0, Some(100.0))); + assert_eq!(node(&s, ia).fills, node(&s, atom).fills, "the fill isn't overridden: it follows the main"); + // The main fixing its own width is the same property: the instance keeps filling. + ex(&mut s, "node.set", json!({"id": atom, "props": {"width": 80}})); + assert_eq!((sizing_h(&s, atom), sizing_h(&s, ia), node(&s, ia).width), (Sizing::Fixed, Sizing::Fill, 240.0)); + // A structure edit of the main rebuilds the instance: the atom fills what the new layer leaves. + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5, "parent": c})); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width), (Sizing::Fill, 235.0)); + healthy(&s); + // Back to the main's resizing: no override left. + ex(&mut s, "component.resetOverride", json!({"id": ia, "group": "resizing"})); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width), (Sizing::Fixed, node(&s, atom).width)); + assert!(!node(&s, ia).overrides.contains("resizing")); + healthy(&s); +} + +#[test] +fn size_and_resizing_overrides_undo_reset_and_detach() { + let mut s = Session::new(); + let (_, atom, dot, i) = field(&mut s); + let (ia, idot) = (copy_of(&s, i, atom), copy_of(&s, i, dot)); + ex(&mut s, "node.set", json!({"id": ia, "props": {"sizingH": "fill"}})); + ex(&mut s, "edit.undo", json!({})); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width), (Sizing::Hug, 100.0)); + assert!(node(&s, ia).overrides.is_empty()); + // A fixed size of its own: kept when the main resizes the layer. + ex(&mut s, "node.set", json!({"id": idot, "props": {"width": 50, "height": 10}})); + assert!(node(&s, idot).overrides.contains("size")); + ex(&mut s, "node.set", json!({"id": dot, "props": {"width": 30}})); + assert_eq!((node(&s, idot).width, node(&s, idot).height, node(&s, dot).width), (50.0, 10.0, 30.0)); + // A min width of its own. + ex(&mut s, "node.set", json!({"id": ia, "props": {"minWidth": 150}})); + assert_eq!(node(&s, ia).width, 150.0); + ex(&mut s, "node.set", json!({"id": atom, "props": {"minWidth": 90}})); + assert_eq!(node(&s, ia).width, 150.0); + healthy(&s); + // Reset all changes: the main's values again. + ex(&mut s, "component.resetInstance", json!({"ids": [i]})); + assert_eq!((node(&s, ia).width, node(&s, idot).width), (90.0, 30.0)); + assert!(node(&s, ia).overrides.is_empty() && node(&s, idot).overrides.is_empty()); + // Detaching keeps what the instance showed. + ex(&mut s, "node.set", json!({"id": ia, "props": {"sizingH": "fill"}})); + ex(&mut s, "component.detach", json!({"ids": [i]})); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width, node(&s, ia).source), (Sizing::Fill, 240.0, None)); + healthy(&s); +} + +#[test] +fn layers_in_instances_resize_but_keep_their_place() { + let mut s = Session::new(); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 100, "name": "Card"}))); + let title = idv(&ex(&mut s, "text.create", json!({"text": "Hello", "x": 10, "y": 10, "parent": f, "props": {"name": "Title"}}))); + let c = idv(&ex(&mut s, "component.create", json!({"ids": [f]}))); + let i = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 300, "y": 0}))); + let it = copy_of(&s, i, title); + ex(&mut s, "node.set", json!({"id": it, "props": {"width": 150}})); + assert_eq!(node(&s, it).width, 150.0, "a text box resizes"); + assert!(node(&s, it).overrides.contains("size")); + // Its place, rotation and constraints are still the main's. + for props in [json!({"x": 50}), json!({"rotation": 15}), json!({"constraints": {"horizontal": "right"}})] { + assert!(s.execute("node.set", &json!({"id": it, "props": props})).is_err(), "{props} is refused"); + } + // The instance's own resizing is its own, not an override. + ex(&mut s, "node.set", json!({"id": i, "props": {"minWidth": 100}})); + assert!(!node(&s, i).overrides.contains("resizing")); + healthy(&s); +} + +#[test] +fn resizing_overrides_survive_save_and_reopen() { + let mut s = Session::new(); + let (_, atom, dot, i) = field(&mut s); + let (ia, idot) = (copy_of(&s, i, atom), copy_of(&s, i, dot)); + ex(&mut s, "node.set", json!({"id": ia, "props": {"sizingH": "fill"}})); + ex(&mut s, "node.set", json!({"id": idot, "props": {"width": 40}})); + let native = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap(); + let (fig, _) = figcraft_format::fig::export(s.doc().unwrap(), None).unwrap(); + for (bytes, name) in [(native, "field.figcraft"), (fig, "field.fig")] { + let mut s = Session::new(); + open(&mut s, &bytes, name); + let i = instance(&s); + let (ia, idot) = (named(&s, i, "Atom"), named(&s, i, "Dot")); + assert!(node(&s, ia).overrides.contains("resizing"), "{name}: {:?}", node(&s, ia).overrides); + assert!(node(&s, idot).overrides.contains("size"), "{name}: {:?}", node(&s, idot).overrides); + // An edit of the main relays the instance out. + let main = |s: &Session, id: NodeId| node(s, id).source.unwrap(); + let (atom, dot) = (main(&s, ia), main(&s, idot)); + ex(&mut s, "node.set", json!({"id": atom, "props": {"minWidth": 120}})); + ex(&mut s, "node.set", json!({"id": dot, "props": {"width": 30}})); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width, node(&s, idot).width), (Sizing::Fill, 240.0, 40.0), "{name}"); + healthy(&s); + } +} + +#[test] +fn imported_resizing_overrides_survive_relayout() { + let at = |x: f64, y: f64| json!([[1, 0, x], [0, 1, y]]); + let dot = |id: &str| json!({"id": id, "name": "Dot", "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 20, "y": 20}}); + let atom = |id: &str, dot_id: &str, w: f64, more: Value| { + let mut a = json!({"id": id, "name": "Atom", "type": "FRAME", "relativeTransform": at(0.0, 0.0), "size": {"x": w, "y": 20}, + "layoutMode": "HORIZONTAL", "primaryAxisSizingMode": "AUTO", "counterAxisSizingMode": "AUTO", "minWidth": 100, "children": [dot(dot_id)]}); + a.as_object_mut().unwrap().extend(more.as_object().unwrap().clone()); + a + }; + let field = |id: &str, ty: &str, y: f64, kids: Value| { + json!({"id": id, "name": "Field", "type": ty, "relativeTransform": at(0.0, y), "size": {"x": 240, "y": 40}, "layoutMode": "HORIZONTAL", + "primaryAxisSizingMode": "FIXED", "counterAxisSizingMode": "FIXED", "children": kids}) + }; + let mut inst = + field("2:1", "INSTANCE", 100.0, json!([atom("I2:1;1:2", "I2:1;1:3", 240.0, json!({"layoutSizingHorizontal": "FILL", "layoutGrow": 1}))])); + inst["componentId"] = json!("1:1"); + inst["overrides"] = json!([{"id": "I2:1;1:2", "overriddenFields": ["layoutSizingHorizontal", "layoutGrow"]}]); + let file = json!({"name": "Field", "document": {"id": "0:0", "type": "DOCUMENT", "children": [ + {"id": "0:1", "name": "Page", "type": "CANVAS", "children": [field("1:1", "COMPONENT", 0.0, json!([atom("1:2", "1:3", 100.0, json!({}))])), inst]} + ]}, "components": {"1:1": {"key": "k", "name": "Field", "description": ""}}, "styles": {}}); + let mut s = Session::new(); + open(&mut s, file.to_string().as_bytes(), "field.json"); + let i = instance(&s); + let ia = named(&s, i, "Atom"); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width), (Sizing::Fill, 240.0)); + assert!(node(&s, ia).overrides.contains("resizing"), "{:?}", node(&s, ia).overrides); + // The main's first edit relays every instance out from it. + let main_atom = node(&s, ia).source.unwrap(); + ex(&mut s, "node.set", json!({"id": main_atom, "props": {"minWidth": 120}})); + assert_eq!((sizing_h(&s, ia), node(&s, ia).width), (Sizing::Fill, 240.0)); + healthy(&s); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f49d3fc6..a0d87f9c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1623,6 +1623,8 @@ mod import_journal_tests; #[cfg(test)] mod inspect_behaviour_tests; #[cfg(test)] +mod instance_resizing_tests; +#[cfg(test)] mod interaction_rollback_tests; #[cfg(test)] mod invite_links_tests; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index de1705ea..ca9e2682 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -1858,12 +1858,13 @@ impl<'d> Exporter<'d> { let named = set.is_none_or(|s| s.name != n.name); let root_mine: Fields = f.iter().filter(|(k, _)| !OWN.contains(k) && (named || *k != "name")).cloned().collect(); // Each layer below: its id path, the fields that differ from the main's layer, that layer's - // fields, and the component a nested instance was swapped for. + // fields, whether its size is its own (a nested instance, a size override) and the + // component a nested instance was swapped for. struct Row { path: Kv<'static>, changed: Fields, theirs: Fields, - nested: bool, + sized: bool, swap: Option>, } let mut rows: Vec = Vec::new(); @@ -1891,8 +1892,8 @@ impl<'d> Exporter<'d> { (NodeKind::Instance { component, .. }, _) => self.guid_of(*component), _ => None, }; - let nested = matches!(d.kind, NodeKind::Instance { .. }); - rows.push(Row { path: o(vec![("guids", arr(guids))]), changed: changed(mine, &theirs), theirs, nested, swap }); + let sized = matches!(d.kind, NodeKind::Instance { .. }) || d.overrides.contains("size"); + rows.push(Row { path: o(vec![("guids", arr(guids))]), changed: changed(mine, &theirs), 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. @@ -1927,8 +1928,8 @@ impl<'d> Exporter<'d> { let (mut of, mut df): (Fields, Fields) = (vec![("guidPath", r.path.clone())], vec![("guidPath", r.path)]); for (k, v) in r.changed { let follows = follows(k, &v, &r.theirs); - // A nested instance's size is its own to set. - if follows && r.nested && k == "size" { + // A nested instance's size is its own to set, as is a size the layer overrides. + if follows && r.sized && k == "size" { of.push((k, v.clone())); } if follows { &mut df } else { &mut of }.push((k, v)); diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index 5c32c583..230faa7d 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -860,6 +860,8 @@ impl<'a> Mapper<'a> { "wireFrame": own == "FRAME", "wireInstance": own == "INSTANCE", "slotContent": inst.is_some_and(|i| i.slot_content), + // A size the instance gives this layer itself (kept when the instance relays out). + "sizeOverride": entries.iter().any(|e| e.entry == Entry::Override && e.row.get("size").is_some()), }), ); o.insert("type".into(), json!(ty)); diff --git a/crates/format/src/rest/mod.rs b/crates/format/src/rest/mod.rs index 60f1cc9c..953522e1 100644 --- a/crates/format/src/rest/mod.rs +++ b/crates/format/src/rest/mod.rs @@ -481,9 +481,11 @@ impl<'a> Ctx<'a> { let id = self.doc.alloc_id(); let label = kind.label(); let mut n = Node::new(id, kind, text(j, "name").map_or(label, clip_str), w, h); - if self.fig_sources.is_some() && j.get(FIG_SOURCE_FIELD).and_then(|source| source.get("slotOverride")).and_then(Value::as_bool) == Some(true) - { - n.overrides.insert("slot".into()); + // Overrides the .fig names explicitly (the rest are found by comparing with the main). + for (flag, group) in [("slotOverride", "slot"), ("sizeOverride", "size")] { + if self.fig_sources.is_some() && j.get(FIG_SOURCE_FIELD).and_then(|source| source.get(flag)).and_then(Value::as_bool) == Some(true) { + n.overrides.insert(group.into()); + } } n.transform = local(space.world, world); self.common(&mut n, j, parent_mode); @@ -1152,6 +1154,16 @@ fn override_group(field: &str) -> Option<&'static str> { | "textDecorationSkipInk" | "textDecorationColor" => "textStyle", "width" | "height" | "size" => "size", + "layoutSizingHorizontal" + | "layoutSizingVertical" + | "layoutGrow" + | "layoutAlign" + | "primaryAxisSizingMode" + | "counterAxisSizingMode" + | "minWidth" + | "maxWidth" + | "minHeight" + | "maxHeight" => "resizing", "paddingLeft" | "paddingRight" | "paddingTop" | "paddingBottom" | "horizontalPadding" | "verticalPadding" => "padding", "itemSpacing" | "counterAxisSpacing" => "gap", "primaryAxisAlignItems" | "counterAxisAlignItems" => "alignment", diff --git a/crates/ui-egui/locales/cs.toml b/crates/ui-egui/locales/cs.toml index f87bc401..2459d104 100644 --- a/crates/ui-egui/locales/cs.toml +++ b/crates/ui-egui/locales/cs.toml @@ -1087,6 +1087,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "Změnit velikost o velikost posunu" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Přizpůsobit velikost rámců obrazovce zařízení (nebo oknu bez zařízení): omezení a automatické rozvržení se přizpůsobí" "Resize to fit" = "Přizpůsobit velikost obsahu" +"Resizing" = "Změna velikosti" "Resolve" = "Vyřešit" "Resolve change" = "Vyřešit změnu" "Resolved" = "Vyřešené" diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index dd991077..b679feb7 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -1053,6 +1053,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "Um die Schrittweite skalieren" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Passt Rahmen an den Bildschirm des Geräts an (ohne Gerät an das Fenster): ihre Constraints und ihr Auto-Layout reagieren" "Resize to fit" = "Größe an Inhalt anpassen" +"Resizing" = "Größenanpassung" "Resolve" = "Erledigen" "Resolve change" = "Änderung erledigen" "Resolved" = "Erledigt" diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 6d5f0a5a..9ce38a22 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1107,6 +1107,7 @@ name = "English" "Resize by the nudge amount" = "Resize by the nudge amount" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" "Resize to fit" = "Resize to fit" +"Resizing" = "Resizing" "Resolve" = "Resolve" "Resolve change" = "Resolve change" "Resolved" = "Resolved" diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index 1d43c320..2849f4ec 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -1108,6 +1108,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "Redimensionar según el desplazamiento" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Ajusta los marcos a la pantalla del dispositivo (o a la ventana sin dispositivo): sus restricciones y su diseño automático se adaptan" "Resize to fit" = "Ajustar tamaño" +"Resizing" = "Cambio de tamaño" "Resolve" = "Resolver" "Resolve change" = "Resolver cambio" "Resolved" = "Resuelto" diff --git a/crates/ui-egui/locales/fr.toml b/crates/ui-egui/locales/fr.toml index c59c1cae..1c561f15 100644 --- a/crates/ui-egui/locales/fr.toml +++ b/crates/ui-egui/locales/fr.toml @@ -1047,6 +1047,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "Redimensionner du pas de décalage" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Redimensionne les cadres à l’écran de l’appareil (ou à la fenêtre sans appareil) : leurs contraintes et leur mise en page auto s’adaptent" "Resize to fit" = "Redimensionner au contenu" +"Resizing" = "Redimensionnement" "Resolve" = "Résoudre" "Resolve change" = "Résoudre la modification" "Resolved" = "Résolu" diff --git a/crates/ui-egui/locales/id.toml b/crates/ui-egui/locales/id.toml index 2bb41e03..7a0a3c3c 100644 --- a/crates/ui-egui/locales/id.toml +++ b/crates/ui-egui/locales/id.toml @@ -1091,6 +1091,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "Ubah ukuran sebesar jarak geser" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Ubah ukuran frame ke layar perangkat (atau jendela tanpa perangkat): batasan dan auto layout-nya menyesuaikan" "Resize to fit" = "Ubah ukuran agar pas" +"Resizing" = "Pengubahan ukuran" "Resolve" = "Selesaikan" "Resolve change" = "Selesaikan perubahan" "Resolved" = "Terselesaikan" diff --git a/crates/ui-egui/locales/ja.toml b/crates/ui-egui/locales/ja.toml index 84c3d6b3..b09db3bd 100644 --- a/crates/ui-egui/locales/ja.toml +++ b/crates/ui-egui/locales/ja.toml @@ -1097,6 +1097,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "微調整の量でサイズ変更" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "フレームをデバイスの画面(デバイスなしの場合はウィンドウ)に合わせてサイズ変更:制約とオートレイアウトが反応" "Resize to fit" = "サイズを合わせる" +"Resizing" = "サイズ変更" "Resolve" = "解決" "Resolve change" = "変更を解決" "Resolved" = "解決済み" diff --git a/crates/ui-egui/locales/ko.toml b/crates/ui-egui/locales/ko.toml index 0d64aeb1..f2cfcfff 100644 --- a/crates/ui-egui/locales/ko.toml +++ b/crates/ui-egui/locales/ko.toml @@ -1047,6 +1047,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "미세 이동 거리만큼 크기 조정" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "프레임 크기를 기기 화면(기기가 없으면 창)에 맞게 조정: 제약과 자동 레이아웃이 반응함" "Resize to fit" = "크기 맞춤" +"Resizing" = "크기 조정" "Resolve" = "해결" "Resolve change" = "변경 사항 해결" "Resolved" = "해결됨" diff --git a/crates/ui-egui/locales/pt-BR.toml b/crates/ui-egui/locales/pt-BR.toml index 98039666..e9e1300c 100644 --- a/crates/ui-egui/locales/pt-BR.toml +++ b/crates/ui-egui/locales/pt-BR.toml @@ -1046,6 +1046,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "Redimensionar pelo valor do deslocamento" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Redimensiona os quadros para a tela do dispositivo (ou para a janela, sem dispositivo): as restrições e o layout automático deles se adaptam" "Resize to fit" = "Redimensionar para caber" +"Resizing" = "Redimensionamento" "Resolve" = "Resolver" "Resolve change" = "Resolver alteração" "Resolved" = "Resolvido" diff --git a/crates/ui-egui/locales/ru.toml b/crates/ui-egui/locales/ru.toml index 91d0a702..2023b692 100644 --- a/crates/ui-egui/locales/ru.toml +++ b/crates/ui-egui/locales/ru.toml @@ -1089,6 +1089,7 @@ name = "Русский" "Resize by the nudge amount" = "Изменить размер на шаг сдвига" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Менять размер Frame под экран устройства (или окно, если устройство не выбрано): ограничения и автолейаут подстраиваются" "Resize to fit" = "Подогнать размер" +"Resizing" = "Изменение размера" "Resolve" = "Решить" "Resolve change" = "Разрешить изменение" "Resolved" = "Решённые" diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index d4e031e4..51f16508 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -1101,6 +1101,7 @@ name = "Svenska" "Resize by the nudge amount" = "Ändra storlek med knuffavståndet" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Ändra storlek på ramar efter enhetens skärm (eller fönstret utan enhet): deras begränsningar och automatiska layout anpassas" "Resize to fit" = "Anpassa storlek" +"Resizing" = "Storleksändring" "Resolve" = "Lös" "Resolve change" = "Lös ändring" "Resolved" = "Löst" diff --git a/crates/ui-egui/locales/tr.toml b/crates/ui-egui/locales/tr.toml index 7e7996e6..cc002654 100644 --- a/crates/ui-egui/locales/tr.toml +++ b/crates/ui-egui/locales/tr.toml @@ -1091,6 +1091,7 @@ name = "Türkçe" "Resize by the nudge amount" = "Kaydırma miktarı kadar yeniden boyutlandır" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "Çerçeveleri cihazın ekranına (veya cihaz yoksa pencereye) göre yeniden boyutlandır: kısıtlamaları ve otomatik yerleşimleri tepki verir" "Resize to fit" = "Sığacak şekilde yeniden boyutlandır" +"Resizing" = "Yeniden boyutlandırma" "Resolve" = "Çöz" "Resolve change" = "Değişikliği çöz" "Resolved" = "Çözüldü" diff --git a/crates/ui-egui/locales/zh-Hans.toml b/crates/ui-egui/locales/zh-Hans.toml index b95e3b39..702cae7b 100644 --- a/crates/ui-egui/locales/zh-Hans.toml +++ b/crates/ui-egui/locales/zh-Hans.toml @@ -1048,6 +1048,7 @@ status = "draft — needs native review" "Resize by the nudge amount" = "按微移量调整大小" "Resize frames to the device's screen (or the window without a device): their constraints and auto layout respond" = "将画框调整为设备屏幕大小(无设备时为窗口大小):其约束和自动布局随之响应" "Resize to fit" = "调整大小以适应" +"Resizing" = "调整大小" "Resolve" = "解决" "Resolve change" = "解决更改" "Resolved" = "已解决" diff --git a/crates/ui-egui/src/component_panel.rs b/crates/ui-egui/src/component_panel.rs index 719c2588..6c9ff7d4 100644 --- a/crates/ui-egui/src/component_panel.rs +++ b/crates/ui-egui/src/component_panel.rs @@ -503,6 +503,7 @@ fn group_label(g: &str) -> String { "exports" => tr("Export settings"), "interactions" => tr("Interactions"), "size" => tr("Size"), + "resizing" => tr("Resizing"), "position" => tr("Position"), "component" => tr("Swapped instance"), "props" => tr("Instance properties"), diff --git a/crates/ui-egui/src/layout_panel.rs b/crates/ui-egui/src/layout_panel.rs index bb60ebeb..9d3c0dcc 100644 --- a/crates/ui-egui/src/layout_panel.rs +++ b/crates/ui-egui/src/layout_panel.rs @@ -29,8 +29,8 @@ pub fn layout_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[Node let al = common(doc, sel, |n| n.layout.clone()); let has_al = matches!(al, Some(Some(_))); let title = if has_al { tr("Auto layout") } else { tr("Layout") }; - // An instance's auto layout is its main's (only padding, gap and alignment are its own), and - // the layers inside it keep their main's size. + // An instance's auto layout is its main's (only padding, gap and alignment are its own); the + // layers inside it override their size and resizing, not their place in the layout. let in_instance = sel.iter().any(|i| figcraft_engine::components::owning_instance(doc, *i).is_some()); let nested = sel.iter().any(|i| figcraft_engine::components::inside_instance(doc, *i)); let btns: Vec<(Icon, &str)> = if in_instance { @@ -49,7 +49,7 @@ pub fn layout_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[Node if let Some(Some(l)) = &al { ui.add_enabled_ui(!in_instance, |ui| direction(app, ui, &ids, l)).response.on_disabled_hover_text(from_main); } - ui.add_enabled_ui(!nested, |ui| dimensions(app, ui, doc, sel, has_al)).response.on_disabled_hover_text(from_main); + dimensions(app, ui, doc, sel, has_al, nested, from_main); if let Some(Some(l)) = &al { alignment(app, ui, &ids, l); spacing(app, ui, &ids, l); @@ -146,7 +146,8 @@ fn limit(n: &Node, horizontal: bool, is_min: bool) -> Option { } } -fn dimensions(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], has_al: bool) { +/// `nested`: layers inside an instance, whose proportion lock is their main's (`from_main` says so). +fn dimensions(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], has_al: bool, nested: bool, from_main: &str) { let ids = sel.to_vec(); let w_of = |n: &Node| (n.width * 100.0).round() / 100.0; let h_of = |n: &Node| (n.height * 100.0).round() / 100.0; @@ -159,7 +160,13 @@ fn dimensions(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], has let e = crate::variable_ui::number_field_mixed(app, ui, &ids, "height", Id::new("lay_h"), Lead::Text("H"), h, "", col); app.field_of(&ids, "height", e, h_of, |v| json!(v.max(0.0))); let locked = common(doc, sel, |n| n.constrain_proportions).unwrap_or(false); - if icons::button(ui, if locked { Icon::LinkOn } else { Icon::LinkOff }, 24.0, locked, tr("Constrain proportions")).clicked() { + let link = ui + .add_enabled_ui(!nested, |ui| { + icons::button(ui, if locked { Icon::LinkOn } else { Icon::LinkOff }, 24.0, locked, tr("Constrain proportions")) + }) + .inner + .on_disabled_hover_text(from_main); + if link.clicked() { app.set_props(&ids, json!({"constrainProportions": !locked})); } }); diff --git a/docs/components-parity.md b/docs/components-parity.md index 659676fd..1ecd9686 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -14,8 +14,8 @@ accounts). |---|---|---| | Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main | | Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances | -| What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent) | -| What it doesn't: position, rotation, size, constraints and resizing of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out; the instance itself resizes and its layers follow the main's constraints | +| What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | +| What it doesn't: position, rotation, constraints and absolute or grid placement of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out; the instance itself resizes and its layers follow the main's constraints | | Component sets / variants, add variant, switch | done | | | Switching variants keeps overrides where names match and both variants had the same value; text layers keep theirs | done | | | Default variant: the top-left one (new instances, Assets thumbnail, generated code) | done | | @@ -76,6 +76,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | Size and resizing overrides of layers inside instances (#731): a layer in an instance can hug, fill or keep a size of its own (group `resizing`: hug/fill/fixed with min and max; `size`), from the Layout panel, the canvas handles and `node.set`; they were refused, and imported ones were dropped at the first relayout. Kept through main edits of other properties, rebuilds, undo, save, `.fig` and REST import (sizes a `.fig` instance gives its layers and the REST `overrides` fields), `.fig` export and detach; reset per group and with Reset all changes (`instance_resizing_tests`). The row that listed them as not overridable was wrong. Numbers unchanged. | | 2026-10-14 | minor | Variables export in the browser: Export… ▸ Variables JSON / CSS custom properties did nothing in the web build, which has no save dialogs; it now hands the file over as a download (`Services::downloads` / `download`, `variables_export_ui_tests`). Import in the browser still needs a file picker, as do the other exports there. Numbers unchanged. | | 2026-10-13 | minor | Component playground (M3): with an instance, a component or a component set selected, the Inspect tab shows a Playground: a preview of the component and a control for each variant, boolean and text property. What is tried there changes the preview and the code in the Code section, never the file (no undo step, the canvas instance stays as it is); Reset goes back to the component's or the instance's own values. `component.playground {id?, properties?, language?, path?}` gives the same to scripts: the properties with their values, the code, and a PNG on request (`playground_tests`). Left: instance-swap and slot properties in the playground (the command takes an instance swap; the panel has no control for it), a code connect template's snippet with the tried values. Numbers unchanged. | | 2026-10-13 | minor | Variables inside styles (M3): a shared style can bind variables to fields of its value (`style.bind {style, field, variable?}`: a paint style's colours and gradient stops, an effect style's colour, radius, spread and offsets, a grid style's size, count, gutter and offset, a text style's font size, line height, letter spacing, family and style). Every layer using the style shows those fields resolved in its own modes and stays linked when a variable or a mode changes; the style keeps them resolved in the default modes. A style made from a layer keeps that layer's bindings; a new value drops bindings to what is gone. The style editor binds from its property rows (paint colour, shadow colour, blur radius, grid size) and detaches from the variable's chip; the style picker marks styles that use variables. `.fig` export and import carry the bindings on the style, REST layers hand theirs to the style they use. Left: binding text style fields and the other effect and grid fields from the editor (commands only), library variables in the picker, a style's library copy. Numbers unchanged. | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d8e51711..e6591853 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -17,9 +17,9 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| -| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes, shapes with text, connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Not read: connector labels, table cells beyond their own layers, filled areas with their own fills, per-point stroke joins, variables bound to fields the editor can't bind, fixed or content-sized grid tracks, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs`, fuzzed) and by reading back what the export writes; no real-world files yet | read tail 5–10, write: checks against real files 5–15 | +| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes, shapes with text, connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Not read: connector labels, table cells beyond their own layers, filled areas with their own fills, per-point stroke joins, variables bound to fields the editor can't bind, fixed or content-sized grid tracks, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs`, fuzzed) and by reading back what the export writes; no real-world files yet | read tail 5–10, write: checks against real files 5–15 | | `.jam` (FigJam), `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | -| REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout, constraints, grids, components, sets, instances with overrides, component properties, styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | +| REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout, constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`) | — | | Local library files | team libraries in the cloud | yes (enable a `.figcraft` as a library) | yes (publish) | per-asset versions, updates with overrides kept | see [collaboration-parity](collaboration-parity.md) | @@ -162,6 +162,7 @@ each. | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | Instance layers' own size and resizing (#731): a `.fig` import keeps the sizes an instance gives its layers and their hug/fill/fixed and min/max as overrides, a REST import reads the resizing fields of `overrides`, and a `.fig` export writes a layer's own size as an override (it went with the derived layout, which a relayout replaces). Numbers unchanged | | 2026-10-14 | minor | SVG/PDF depth overflow (#208) is checked before bounds and drawing; public checked APIs return the offending root/layer, commands and CLI report it, and no incomplete export replaces an existing file. Tested at depths 255/256/257, with inner roots, hidden branches, masks, raster fallbacks and multiple roots/pages. Numbers unchanged. | | 2026-10-13 | minor | `.fig` export (gap 1): instances write what they change from their main as an override addressed by the main's id (their size, name and paints were lost elsewhere without it), what follows for their layers as derived data, and a scale factor when scaled as a whole; layers of a nested instance swapped for another component keep their overrides; variable collections, modes, variables and their bindings, the modes frames and pages set, shared styles with their links and variable-width strokes are written, and the import reads all of it back (style definitions and unused styles, variable order and scopes, bindings on paint lists, gradient stops, effects and layout grids, page modes, text field bindings, which a `.fig` import used to drop, and width profiles). Opened `.fig` and file JSON documents link nested instances of variants (and any nested instance under a name of its own) to their main's layers; they stayed unlinked, so a second export lost what they changed. Checked by opening written files in other software: resized and scaled instances keep their size and lay their layers out for it, variables with their modes and colour bindings resolve there (a frame set to another mode shows that mode's colours, also inside instances), colour, text, effect and grid styles are listed, and variable-width strokes that are the same on both sides of the path draw with their width; number, string and boolean bindings and bindings on effects, layout guides and gradient stops come across as the values they give but did not show as bound there (their entries now also name the layer field they set, not yet checked there), and strokes wider on one side of the path are written as filled outlines, no longer editable strokes there (the stroke itself is kept as plugin data and our own import puts it back; not yet checked there). Numbers unchanged | | 2026-10-12 | minor | `.fig` export made to open elsewhere (gap 1): the document and its pages say they are visible and opaque (left out, nothing was drawn), the schema in the file uses the format's own names, kinds, field ids and enum values, rectangles are rounded rectangles with four radii, frames and shapes carry their fill outline and plain strokes their stroke outline, text carries its layout settings, font styles use their standard names, line heights that are a share of the font size are raw multipliers, masks keep their type (read back too); the import reads per-side stroke weights whose zero sides are left out. Written files were checked by opening them in other software: layers, fills, gradients, strokes, shadows, vectors, components and text draw as in FigCraft; effects such as glass and noise, images and prototype interactions are still unchecked there, and variables are not written. Numbers unchanged |