From 3053b771102405096c47b4c99375af0fe48f30b4 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 20:07:14 -0500 Subject: [PATCH 001/268] M3: the Scale tool keeps variable-bound lengths bound on an instance (value x its scale) and bakes them elsewhere (#2090) Cause: scale_node baked the factor into every length, then the command's normalize re-applied the variable bindings of the scaled subtree and wrote each variable's plain value back, so a bound gap or radius snapped back to the unscaled value. Fix: Node gets scale_factor (default 1, not saved at 1, last collab Prop). scale_node makes an instance multiply its factor (clamped 1e-3..1e3) and keep its bindings; apply_bindings_matching draws a bound length at value x the factors of the instance and the instances around it. Any other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. The gesture preview's detach_edited leaves an instance whose factor changed alone. The instance rebuild carries the factor. Verified: scale_bound_values_tests (instance via transform.scale incl. mode switch and rebuild, the K drag and its undo, save and reopen, a plain frame). Only the gap was measured in Figma; radius, stroke weight and font size are assumed to follow it, and main components are unmeasured. Not changed: .fig import setting the factor, list and text-run bindings, the properties panel label, .fig export. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove and measured; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/collab/src/change.rs | 1 + crates/doc/src/node.rs | 11 ++ crates/engine/src/assets/components/sync.rs | 2 + crates/engine/src/cmd/arrange.rs | 14 ++ crates/engine/src/cmd/styles.rs | 56 ++++++++ crates/engine/src/lib.rs | 2 + crates/engine/src/scale_bound_values_tests.rs | 130 ++++++++++++++++++ docs/components-parity.md | 3 +- docs/ui-parity.md | 3 +- 9 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/scale_bound_values_tests.rs diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 442376f37..6ebe9e0e4 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -183,6 +183,7 @@ node_props! { DevResources => dev_resources, Measurements => measurements, Board => board, + ScaleFactor => scale_factor, } /// A document-level property. Lists of entries with ids (styles, comments, variable collections, diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 5b90b3bff..338984638 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -511,6 +511,10 @@ pub struct Node { /// Explicit variable modes (collection → mode) set on this container. #[serde(default, skip_serializing_if = "is_default")] pub var_modes: BTreeMap, + /// An instance's scale factor (the Scale tool): the variables bound on its layers draw at their + /// value times this, and times the factors of the instances around it. 1 on everything else. + #[serde(default = "one64", skip_serializing_if = "is_one64")] + pub scale_factor: f64, /// In a boolean group: how this operand combines with the operands below it (`None`: the /// group's operation). Ignored for the bottom operand and outside boolean groups. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -571,6 +575,9 @@ pub(crate) fn yes() -> bool { fn one() -> f32 { 1.0 } +fn one64() -> f64 { + 1.0 +} fn pass() -> BlendMode { BlendMode::PassThrough } @@ -588,6 +595,9 @@ pub(crate) fn is_default(v: &T) -> bool { fn is_yes(v: &bool) -> bool { *v == yes() } +fn is_one64(v: &f64) -> bool { + *v == 1.0 +} fn is_one(v: &f32) -> bool { *v == one() } @@ -730,6 +740,7 @@ impl Node { styles: StyleRefs::default(), bound: BTreeMap::new(), var_modes: BTreeMap::new(), + scale_factor: 1.0, bool_op: None, constrain_proportions: false, source: None, diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs index 7b34c33c2..90304c8f4 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -350,6 +350,8 @@ fn fresh_root(doc: &Document, root: &mut Node, comp: &Node, inst: NodeId, compon fresh.locked = root.locked; fresh.visible = root.visible; fresh.var_modes = root.var_modes.clone(); + // The scale an instance was given (a nested copy's own factor comes from its main layer). + fresh.scale_factor = root.scale_factor; fresh.is_mask = root.is_mask; fresh.exposed = root.exposed; fresh.guides = root.guides.clone(); diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 88146ea95..a5725521c 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -399,9 +399,17 @@ fn turn_pivot(s: &Session, ids: &[NodeId]) -> Result> { Ok(ds.moved_origin().filter(|_| ds.selection == ids).or_else(|| ds.doc.bounds_of(&roots(&ds.doc, ids)).map(|b| b.center()))) } +/// The range an instance's scale factor stays in (the same range `.fig` files allow). +const MIN_SCALE_FACTOR: f64 = 1e-3; +const MAX_SCALE_FACTOR: f64 = 1e3; + /// Scale a node and everything in it uniformly (the Scale tool): sizes and positions (whatever /// the children's constraints), strokes, effects, radii, auto layout spacing, min/max sizes, /// layout grids, ruler guides, tiled images and text sizes. +/// +/// Variable-bound lengths follow the incumbent (#2090): an instance multiplies its scale factor and +/// keeps its bindings, which draw at the variable's value times the factor; any other layer not +/// inside an instance keeps the scaled value and drops the binding of each length it scaled. pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { let k = if k.is_finite() && k > 0.0 { k } else { return Ok(()) }; let sub = doc.subtree(id); @@ -410,6 +418,7 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { // changed with an ancestor's size for what constraints give, so the next rebuild of the // instance would put them back at their main's size (#922). let in_instance: Vec = sub.iter().enumerate().map(|(depth, i)| depth > 0 && crate::components::inside_instance(doc, *i)).collect(); + let nested: Vec = sub.iter().map(|i| crate::components::inside_instance(doc, *i)).collect(); let tiles = |paints: &mut Vec| { for p in paints { if let figcraft_color::PaintKind::Image(img) = &mut p.kind @@ -422,6 +431,11 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { for (depth, i) in sub.iter().enumerate() { let n = doc.get_mut(*i)?; let (w0, h0, t0) = (n.width, n.height, n.transform); + if matches!(n.kind, NodeKind::Instance { .. }) { + n.scale_factor = (n.scale_factor * k).clamp(MIN_SCALE_FACTOR, MAX_SCALE_FACTOR); + } else if !nested.get(depth).copied().unwrap_or(false) && !n.bound.is_empty() { + n.bound.retain(|field, _| !super::styles::LENGTH_FIELDS.contains(&field.as_str())); + } tiles(&mut n.fills); tiles(&mut n.strokes); let cl = &mut n.child_layout; diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 9ba420c43..7b6947b29 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -1096,6 +1096,10 @@ pub(crate) fn bound_before(doc: &Document, ids: &[NodeId]) -> Vec]) { for old in before { let Some(n) = doc.node(old.id) else { continue }; + // An instance the Scale tool scaled keeps its bindings: they draw at its new scale (#2090). + if n.scale_factor != old.scale_factor { + continue; + } let edited: Vec = n .bound .keys() @@ -1239,6 +1243,55 @@ pub(crate) fn apply_paint_bindings_on_load(doc: &mut Document) { doc.mark_dirty(pending); } +/// The bound fields holding a length: what the Scale tool scales, so what an instance's scale +/// factor multiplies a number variable by (#2090). +pub(crate) const LENGTH_FIELDS: &[&str] = &[ + "width", + "height", + "w", + "h", + "gap", + "itemSpacing", + "columnGap", + "crossGap", + "counterAxisSpacing", + "rowGap", + "padding", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + "paddingHorizontal", + "paddingVertical", + "cornerRadius", + "topLeftRadius", + "topRightRadius", + "bottomRightRadius", + "bottomLeftRadius", + "strokeWeight", + "strokeTopWeight", + "strokeRightWeight", + "strokeBottomWeight", + "strokeLeftWeight", + "minWidth", + "maxWidth", + "minHeight", + "maxHeight", + "fontSize", + "lineHeight", + "letterSpacing", + "paragraphSpacing", + "paragraphIndent", +]; + +/// The scale a layer's lengths are drawn at: the product of the scale factors of the instances it +/// is or sits in. +fn scale_of(doc: &Document, id: NodeId) -> f64 { + let factor = |i: NodeId| doc.node(i).filter(|n| matches!(n.kind, NodeKind::Instance { .. })).map_or(1.0, |n| n.scale_factor); + let k = std::iter::once(id).chain(doc.ancestors(id)).map(factor).product::(); + if k.is_finite() && k > 0.0 { k } else { 1.0 } +} + /// Re-apply the variable bindings whose field passes `include`, on the `only` nodes (every bound /// node when `None`). Auto layout fields wait while their node has no auto layout. fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::BTreeSet>, include: impl Fn(&str) -> bool) { @@ -1253,6 +1306,7 @@ fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::B }; for id in bound { let modes = doc.modes_for(id); + let scale = scale_of(doc, id); let Some(n) = doc.node(id) else { continue }; let binds = n.bound.clone(); let has_layout = n.layout.is_some(); @@ -1300,6 +1354,8 @@ fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::B VariableValue::Number(x) if field == "arcSweep" => json!(x * 3.6), VariableValue::Number(x) if field == "arcInner" => json!(x / 100.0), VariableValue::Number(x) if field == "characters" => json!(trim_num(*x)), + // An instance's scale factor scales the lengths its variables give. + VariableValue::Number(x) if scale != 1.0 && LENGTH_FIELDS.contains(&field.as_str()) => json!(x * scale), VariableValue::Number(x) => json!(x), VariableValue::String(x) => json!(x), VariableValue::Boolean(b) => json!(b), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 302e7053e..8da1c651a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -531,6 +531,8 @@ mod save_disk_changes_tests; #[cfg(test)] mod save_format_tests; #[cfg(test)] +mod scale_bound_values_tests; +#[cfg(test)] mod scale_tool_tests; #[cfg(test)] mod scaled_instance_tests; diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs new file mode 100644 index 000000000..45f5f1644 --- /dev/null +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -0,0 +1,130 @@ +//! The Scale tool and variable-bound lengths (#2090): an instance keeps its bindings and draws them +//! at the variable's value times its scale factor; a plain frame bakes the scaled value and drops +//! the binding of each length it scaled (what the incumbent does, measured for the gap). + +use serde_json::{Value, json}; + +use crate::Session; +use crate::components::tests::{copy_of, ex, healthy, idv, node}; +use figcraft_doc::NodeId; + +/// The scale factor an instance stores (1 when the file has none), read through the saved form. +fn factor(s: &Session, id: NodeId) -> f64 { + serde_json::to_value(node(s, id)).ok().and_then(|v| v.get("scale_factor").and_then(Value::as_f64)).unwrap_or(1.0) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +fn gap(s: &Session, id: NodeId) -> f64 { + node(s, id).layout.map(|l| l.gap).unwrap_or(f64::NAN) +} + +/// Variables Gap = 8 (Dark 12) and Round = 4; a 56 x 24 horizontal auto layout frame holding two +/// 24 x 24 rectangles, its gap bound to Gap and the first rectangle's corner radius to Round. +/// Returns the frame and the first rectangle. +fn bound_row(s: &mut Session) -> (NodeId, NodeId) { + ex(s, "variable.createCollection", json!({"name": "Theme", "modes": ["Light", "Dark"]})); + ex(s, "variable.create", json!({"collection": "Theme", "name": "Gap", "type": "number", "value": 8})); + ex(s, "variable.set", json!({"variable": "Gap", "mode": "Dark", "value": 12})); + ex(s, "variable.create", json!({"collection": "Theme", "name": "Round", "type": "number", "value": 4})); + let f = idv(&ex(s, "frame.create", json!({"x": 100, "y": 0, "width": 56, "height": 24, "name": "Row"}))); + ex(s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 8, "fills": []}})); + let a = idv(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 24, "height": 24, "parent": f}))); + ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 24, "height": 24, "parent": f})); + ex(s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "Gap"})); + ex(s, "variable.bind", json!({"ids": [a], "field": "cornerRadius", "variable": "Round"})); + assert!(near(gap(s, f), 8.0), "{}", gap(s, f)); + assert_eq!(node(s, a).corners.radii, [4.0; 4]); + (f, a) +} + +/// The row as a component with one instance; returns (main, first rectangle in main, instance). +fn row_instance(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let (f, a) = bound_row(s); + let c = idv(&ex(s, "component.create", json!({"ids": [f]}))); + let i = idv(&ex(s, "instance.create", json!({"component": c, "x": 300, "y": 0}))); + (c, a, i) +} + +fn assert_bound_at_half(s: &Session, i: NodeId, a: NodeId, gap_now: f64, why: &str) { + let ia = copy_of(s, i, a); + assert!(near(gap(s, i), gap_now), "{why}: gap {}", gap(s, i)); + assert_eq!(node(s, ia).corners.radii, [2.0; 4], "{why}: radii"); + assert!(node(s, i).bound.contains_key("gap"), "{why}: gap binding kept"); + assert!(node(s, ia).bound.contains_key("cornerRadius"), "{why}: radius binding kept"); + let (n, ni) = (node(s, i), node(s, ia)); + assert!(!n.overrides.contains("gap") && !ni.overrides.contains("corners"), "{why}: {:?} {:?}", n.overrides, ni.overrides); +} + +#[test] +fn a_scaled_instance_draws_bound_gap_and_radius_at_the_factor_and_keeps_the_bindings() { + let mut s = Session::new(); + let (c, a, i) = row_instance(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 0.5})); + assert!(near(factor(&s, i), 0.5), "factor {}", factor(&s, i)); + assert_bound_at_half(&s, i, a, 4.0, "scaled"); + healthy(&s); + ex(&mut s, "variable.setMode", json!({"ids": [i], "collection": "Theme", "mode": "Dark"})); + assert_bound_at_half(&s, i, a, 6.0, "dark"); + ex(&mut s, "node.set", json!({"id": c, "props": {"fills": ["#ff0000"]}})); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 2, "height": 2, "parent": c})); + assert_bound_at_half(&s, i, a, 6.0, "rebuilt"); + assert!(near(factor(&s, i), 0.5), "factor after rebuild {}", factor(&s, i)); + healthy(&s); +} + +#[test] +fn scaling_an_instance_with_the_tool_scales_bound_values_and_undo_takes_them_back() { + use crate::tools::{PointerEvent, PointerKind}; + let mut s = Session::new(); + let (_c, a, i) = row_instance(&mut s); + ex(&mut s, "select.set", json!({"ids": [i]})); + ex(&mut s, "tool.scale", json!({})); + // The bottom right handle of the 56 x 24 box at (300, 0), to half its size about the top left. + for (kind, (x, y)) in + [(PointerKind::Down, (356.0, 24.0)), (PointerKind::Move, (340.0, 18.0)), (PointerKind::Move, (328.0, 12.0)), (PointerKind::Up, (328.0, 12.0))] + { + s.pointer(&PointerEvent::at(kind, x, y, 1.0)).unwrap(); + } + assert!(near(factor(&s, i), 0.5), "factor {}", factor(&s, i)); + assert_bound_at_half(&s, i, a, 4.0, "dragged"); + s.undo().unwrap(); + assert!(near(factor(&s, i), 1.0), "factor after undo {}", factor(&s, i)); + assert!(near(gap(&s, i), 8.0), "gap after undo {}", gap(&s, i)); + assert!(node(&s, i).overrides.is_empty() && node(&s, copy_of(&s, i, a)).overrides.is_empty()); + healthy(&s); +} + +#[test] +fn a_file_with_a_scaled_instance_keeps_its_factor_and_bound_gap_after_save_and_open() { + let mut s = Session::new(); + let (_c, a, i) = row_instance(&mut s); + let plain = serde_json::to_value(node(&s, i)).unwrap(); + assert!(plain.get("scale_factor").is_none(), "an unscaled instance saves no factor: {plain}"); + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 0.5})); + let dir = std::env::temp_dir().join(format!("figcraft-scale-bound-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("scaled.figcraft"); + ex(&mut s, "file.saveAs", json!({"path": path.to_string_lossy()})); + let mut back = Session::empty(); + back.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert!(near(factor(&back, i), 0.5), "factor {}", factor(&back, i)); + assert_bound_at_half(&back, i, a, 4.0, "reopened"); + healthy(&back); +} + +#[test] +fn scaling_a_plain_frame_bakes_its_bound_gap_and_drops_the_binding() { + let mut s = Session::new(); + let (f, a) = bound_row(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [f], "factor": 0.5})); + assert!(near(gap(&s, f), 4.0), "gap {}", gap(&s, f)); + assert!(!node(&s, f).bound.contains_key("gap"), "{:?}", node(&s, f).bound); + assert_eq!(node(&s, a).corners.radii, [2.0; 4]); + assert!(!node(&s, a).bound.contains_key("cornerRadius"), "{:?}", node(&s, a).bound); + assert!(near(factor(&s, f), 1.0)); + healthy(&s); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index d6b1ee5e6..a86a88114 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -68,7 +68,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | | Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values | -| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity) | +| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity); on a scaled instance a bound length draws at the variable's value times the instance's scale factor (#2090) | | Explicit modes per frame, library collections' modes | done | stored variable and collection references resolve by exact id in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker and prototype playback; a collection or variable named like another's id no longer stands in for it there | | Gradient stops and variant properties bound to variables | done | a stop's binding follows it when earlier stops are removed | | Extended collections | done | this file's collections (Extend collection on a collection's row; following its edits at once, chains included) and library collections, including a library's own extended collections (chains through libraries); overrides per mode with reset; follow library updates, variables new to the library collection being an update of their own; modes inherited. Checked with synthetic libraries only ([gaps](gaps.md) #14) | @@ -79,6 +79,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | | 2026-11-05 | minor | M3, #2002: the Local variables window selects several variables, as the Layers panel selects layers. A click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, Escape or a click on the empty space below the rows clears; selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope (all supported properties, hidden from pickers, or only one scope) for the selected local variables, each sent as one `command.batch`, so one undo step; no engine command changed. Renaming and value edits stay single-row. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-02 | minor | M3, #1829: text styles carry paragraph spacing and indent, the list style and the OpenType features ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType features", Create and apply text styles) beside the character properties: `style.create` takes them from the layer (or the selected paragraphs' list) or from a `value` (`paragraphSpacing`, `paragraphIndent`, `listStyle`, `features`), `style.apply` sets them (on a range, the list goes to the paragraphs touched; the rest is the layer's, as in Figma), `style.update` moves them on every linked layer, editing one on a styled text unlinks it as editing its font does, the style editor lists them, and a `.fig` file keeps them with the style (its sample layer). Grade unchanged. | | 2026-11-06 | patch | M3: a glass's light angle bound to a number past ±180 turns round to the same direction (270 is -90), as the angle drawn from it does, instead of stopping at 180. Tests: `effects_tests::a_bound_light_angle_turns_round_instead_of_stopping`. Grade unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index aa0ef25bd..4d3c37a51 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -67,7 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | | +| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each length scaled (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | @@ -187,6 +187,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | | 2026-11-02 | patch | Shortcuts: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides, in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. A documented gesture row: 134 documented, 133 bound. Test: `padding_individual_tests` | | 2026-11-01 | patch | Number fields: dragging the field itself with Alt held scrubs it ("You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option Windows: Alt", Adjust alignment, rotation, position, and dimensions), with the resize cursor and the label's rates (Alt is the enabler there, so it isn't the fine rate); a click with Alt doesn't open the editor. Found by a documentation audit of the ui-parity rows. Test: `field_tests::alt_held_over_a_field_scrubs_it`. Counts unchanged | | 2026-11-02 | patch | M6, #1839: with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it by the nudge amounts (`tool.crosshair`), Enter places the object there (`tool.place`), Escape or a tool change takes it away; the canvas draws the crosshair and `ui.inspect` reports it (`tool.crosshair`), the Keyboard shortcuts panel lists the gesture ("Use the arrow keys to activate the crosshair cursor...", Accessibility at Figma). The board Shapes tool places on it too (its 160 px shape centred, as the tool centres a press), and the view pans by the overshoot when the crosshair is nudged past its edge. Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | From 72e8b4ca940ed67736b217f427ae64187164f984 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 20:13:01 -0500 Subject: [PATCH 002/268] M3: detaching a scaled instance keeps its lengths as drawn and drops their variables (#2090) Measured in Figma: detaching a 0.5x instance whose gap is bound leaves a plain frame with the gap at the scaled value and no variable. component.detach kept the bindings but dropped the factor, so the gap jumped back to the variable's value. Now the detached frame's own layers drop the bindings of their length fields, the instances inside it take its factor on, and its own factor goes back to 1. Test detaching_a_scaled_instance_keeps_its_lengths_and_drops_their_variables (gap 8 before, 4 now). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove, measured and wrote --- crates/engine/src/cmd/arrange.rs | 4 ++-- crates/engine/src/cmd/component/instance.rs | 17 ++++++++++++++++ crates/engine/src/scale_bound_values_tests.rs | 20 +++++++++++++++++++ docs/components-parity.md | 2 +- docs/ui-parity.md | 2 +- 5 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index a5725521c..4aa42f2d8 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -400,8 +400,8 @@ fn turn_pivot(s: &Session, ids: &[NodeId]) -> Result> { } /// The range an instance's scale factor stays in (the same range `.fig` files allow). -const MIN_SCALE_FACTOR: f64 = 1e-3; -const MAX_SCALE_FACTOR: f64 = 1e3; +pub(crate) const MIN_SCALE_FACTOR: f64 = 1e-3; +pub(crate) const MAX_SCALE_FACTOR: f64 = 1e3; /// Scale a node and everything in it uniformly (the Scale tool): sizes and positions (whatever /// the children's constraints), strokes, effects, radii, auto layout spacing, min/max sizes, diff --git a/crates/engine/src/cmd/component/instance.rs b/crates/engine/src/cmd/component/instance.rs index 86af6d54b..3b6f8f17d 100644 --- a/crates/engine/src/cmd/component/instance.rs +++ b/crates/engine/src/cmd/component/instance.rs @@ -36,6 +36,23 @@ pub(super) fn detach(s: &mut Session, p: &Value) -> Result { n.prop_refs.remove("mainComponent"); // No properties left to drive. n.bound.retain(|k, _| !k.starts_with(PROP_BINDING)); + // A scaled instance's lengths stay as drawn (#2090, measured): its own layers keep the + // scaled values and drop their variables, and the instances in it take its scale on. + let k = std::mem::replace(&mut n.scale_factor, 1.0); + if k != 1.0 { + for d in doc.subtree(i) { + let own = !inside_instance(doc, d); + let Some(n) = doc.node_mut(d) else { continue }; + if !own { + continue; + } + if matches!(n.kind, NodeKind::Instance { .. }) { + n.scale_factor = (n.scale_factor * k).clamp(crate::cmd::arrange::MIN_SCALE_FACTOR, crate::cmd::arrange::MAX_SCALE_FACTOR); + } else { + n.bound.retain(|f, _| !crate::cmd::styles::LENGTH_FIELDS.contains(&f.as_str())); + } + } + } for nn in nested { rebase_instance(doc, nn); } diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs index 45f5f1644..567592e28 100644 --- a/crates/engine/src/scale_bound_values_tests.rs +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -128,3 +128,23 @@ fn scaling_a_plain_frame_bakes_its_bound_gap_and_drops_the_binding() { assert!(near(factor(&s, f), 1.0)); healthy(&s); } + +#[test] +fn detaching_a_scaled_instance_keeps_its_lengths_and_drops_their_variables() { + // Measured: detaching a 0.5x instance whose gap is bound leaves a plain frame with the gap + // at the scaled value and no variable. + let mut s = Session::new(); + let (_c, a, i) = row_instance(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 0.5})); + let ia = copy_of(&s, i, a); + ex(&mut s, "component.detach", json!({"ids": [i]})); + assert!(near(gap(&s, i), 4.0), "gap {}", gap(&s, i)); + assert_eq!(node(&s, ia).corners.radii, [2.0; 4]); + assert!(!node(&s, i).bound.contains_key("gap"), "the gap's variable goes"); + assert!(!node(&s, ia).bound.contains_key("cornerRadius"), "the radius's variable goes"); + assert!(near(factor(&s, i), 1.0), "a frame has no scale factor: {}", factor(&s, i)); + // The variables no longer reach it. + ex(&mut s, "variable.set", json!({"variable": "Gap", "mode": "Light", "value": 20})); + assert!(near(gap(&s, i), 4.0), "gap after the variable changed {}", gap(&s, i)); + healthy(&s); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index a86a88114..6dc8514e3 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -79,7 +79,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | | 2026-11-05 | minor | M3, #2002: the Local variables window selects several variables, as the Layers panel selects layers. A click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, Escape or a click on the empty space below the rows clears; selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope (all supported properties, hidden from pickers, or only one scope) for the selected local variables, each sent as one `command.batch`, so one undo step; no engine command changed. Renaming and value edits stay single-row. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-02 | minor | M3, #1829: text styles carry paragraph spacing and indent, the list style and the OpenType features ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType features", Create and apply text styles) beside the character properties: `style.create` takes them from the layer (or the selected paragraphs' list) or from a `value` (`paragraphSpacing`, `paragraphIndent`, `listStyle`, `features`), `style.apply` sets them (on a range, the list goes to the paragraphs touched; the rest is the layer's, as in Figma), `style.update` moves them on every linked layer, editing one on a styled text unlinks it as editing its font does, the style editor lists them, and a `.fig` file keeps them with the style (its sample layer). Grade unchanged. | | 2026-11-06 | patch | M3: a glass's light angle bound to a number past ±180 turns round to the same direction (270 is -90), as the angle drawn from it does, instead of stopping at 180. Tests: `effects_tests::a_bound_light_angle_turns_round_instead_of_stopping`. Grade unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4d3c37a51..7c170f80f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -187,7 +187,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled. Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | | 2026-11-02 | patch | Shortcuts: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides, in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. A documented gesture row: 134 documented, 133 bound. Test: `padding_individual_tests` | | 2026-11-01 | patch | Number fields: dragging the field itself with Alt held scrubs it ("You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option Windows: Alt", Adjust alignment, rotation, position, and dimensions), with the resize cursor and the label's rates (Alt is the enabler there, so it isn't the fine rate); a click with Alt doesn't open the editor. Found by a documentation audit of the ui-parity rows. Test: `field_tests::alt_held_over_a_field_scrubs_it`. Counts unchanged | | 2026-11-02 | patch | M6, #1839: with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it by the nudge amounts (`tool.crosshair`), Enter places the object there (`tool.place`), Escape or a tool change takes it away; the canvas draws the crosshair and `ui.inspect` reports it (`tool.crosshair`), the Keyboard shortcuts panel lists the gesture ("Use the arrow keys to activate the crosshair cursor...", Accessibility at Figma). The board Shapes tool places on it too (its 160 px shape centred, as the tool centres a press), and the view pans by the overshoot when the crosshair is nudged past its edge. Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | From 0636a3e6a041a47f72eb1892f78edbeae69dd844 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 22:59:00 -0500 Subject: [PATCH 003/268] M3: a scaled instance's nested instances and its other conversions keep the lengths as drawn (#2134 review) Scaling a subtree now gives the scale factor only to instances with no instance above them in the subtree (scale_of already multiplies the outer factor, so nested ones drew at k x k and jumped back on rebuild). Detach's baking moved to styles::bake_scale; bake_stale_scales runs it after a library import turns an instance with a missing main into a frame, after cycle-breaking detach, and after Restore main component (by analogy with Detach, not measured in Figma). Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 reviewed; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/assets/components/cycles.rs | 1 + crates/engine/src/assets/library.rs | 5 + crates/engine/src/cmd/arrange.rs | 23 ++++- crates/engine/src/cmd/component/instance.rs | 18 +--- crates/engine/src/cmd/styles.rs | 33 +++++++ crates/engine/src/scale_bound_values_tests.rs | 98 +++++++++++++++++++ 6 files changed, 162 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/assets/components/cycles.rs b/crates/engine/src/assets/components/cycles.rs index 0d9b56f40..1d33b5c80 100644 --- a/crates/engine/src/assets/components/cycles.rs +++ b/crates/engine/src/assets/components/cycles.rs @@ -169,6 +169,7 @@ fn detach_all(doc: &mut Document, top: NodeId) { n.overrides.clear(); n.prop_refs.clear(); } + crate::cmd::styles::bake_stale_scales(doc, top); } /// Break every loop of components containing each other's instances (a file from elsewhere, or diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index d9107ad63..89fe984a9 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -942,6 +942,10 @@ pub fn import(doc: &mut Document, lib: &PublishedLibrary, keys: &[NodeId], updat nodes.push(n); } doc.paste_nodes(&nodes, &map, *u, store, None)?; + // An instance whose main is missing became a plain frame: its lengths stay as drawn (#2090). + if let Some(root) = map.get(u).copied() { + crate::cmd::styles::bake_stale_scales(doc, root); + } } copy_images(doc, src, &hashes); for (u, sub) in &write { @@ -1182,6 +1186,7 @@ fn merge_components( } let Some(root) = remote.get(&r.root).copied() else { continue }; doc.paste_nodes(&nodes, &remote, r.root, store, None)?; + crate::cmd::styles::bake_stale_scales(doc, root); let ids = r.ids.iter().filter_map(|(lib, theirs)| remote.get(theirs).map(|l| (*lib, *l))).collect(); doc.libraries_mut().components.push(ImportedComponent { root, ids, ..r.clone() }); } diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 4aa42f2d8..b6e5362c5 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -419,6 +419,25 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { // instance would put them back at their main's size (#922). let in_instance: Vec = sub.iter().enumerate().map(|(depth, i)| depth > 0 && crate::components::inside_instance(doc, *i)).collect(); let nested: Vec = sub.iter().map(|i| crate::components::inside_instance(doc, *i)).collect(); + // An instance inside another instance of the subtree is covered by the outer factor through + // `scale_of`'s product (#2090); only an instance with no instance above it, up to `id`, takes k. + let covered: Vec = sub + .iter() + .map(|i| { + if *i == id { + return false; + } + for a in doc.ancestors(*i) { + if doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Instance { .. })) { + return true; + } + if a == id { + break; + } + } + false + }) + .collect(); let tiles = |paints: &mut Vec| { for p in paints { if let figcraft_color::PaintKind::Image(img) = &mut p.kind @@ -432,7 +451,9 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { let n = doc.get_mut(*i)?; let (w0, h0, t0) = (n.width, n.height, n.transform); if matches!(n.kind, NodeKind::Instance { .. }) { - n.scale_factor = (n.scale_factor * k).clamp(MIN_SCALE_FACTOR, MAX_SCALE_FACTOR); + if !covered.get(depth).copied().unwrap_or(false) { + n.scale_factor = (n.scale_factor * k).clamp(MIN_SCALE_FACTOR, MAX_SCALE_FACTOR); + } } else if !nested.get(depth).copied().unwrap_or(false) && !n.bound.is_empty() { n.bound.retain(|field, _| !super::styles::LENGTH_FIELDS.contains(&field.as_str())); } diff --git a/crates/engine/src/cmd/component/instance.rs b/crates/engine/src/cmd/component/instance.rs index 3b6f8f17d..f383304c5 100644 --- a/crates/engine/src/cmd/component/instance.rs +++ b/crates/engine/src/cmd/component/instance.rs @@ -38,21 +38,7 @@ pub(super) fn detach(s: &mut Session, p: &Value) -> Result { n.bound.retain(|k, _| !k.starts_with(PROP_BINDING)); // A scaled instance's lengths stay as drawn (#2090, measured): its own layers keep the // scaled values and drop their variables, and the instances in it take its scale on. - let k = std::mem::replace(&mut n.scale_factor, 1.0); - if k != 1.0 { - for d in doc.subtree(i) { - let own = !inside_instance(doc, d); - let Some(n) = doc.node_mut(d) else { continue }; - if !own { - continue; - } - if matches!(n.kind, NodeKind::Instance { .. }) { - n.scale_factor = (n.scale_factor * k).clamp(crate::cmd::arrange::MIN_SCALE_FACTOR, crate::cmd::arrange::MAX_SCALE_FACTOR); - } else { - n.bound.retain(|f, _| !crate::cmd::styles::LENGTH_FIELDS.contains(&f.as_str())); - } - } - } + crate::cmd::styles::bake_scale(doc, i); for nn in nested { rebase_instance(doc, nn); } @@ -381,6 +367,8 @@ pub(super) fn restore_main(s: &mut Session, p: &Value) -> Result { rebase_instance(doc, m); } } + // The instance becomes the main: its lengths stay as drawn (by analogy with Detach, #2090). + crate::cmd::styles::bake_stale_scales(doc, component); s.set_selection(vec![component]); Ok(json!({"id": component})) } diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 7b6947b29..756e5b16d 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -1292,6 +1292,39 @@ fn scale_of(doc: &Document, id: NodeId) -> f64 { if k.is_finite() && k > 0.0 { k } else { 1.0 } } +/// A layer that stops being an instance keeps its lengths as drawn (#2090, measured for Detach): +/// its own layers drop their length variables and the instances in it take its scale on. The +/// layer must no longer be an instance. +pub(crate) fn bake_scale(doc: &mut Document, id: NodeId) { + let Some(n) = doc.node_mut(id) else { return }; + let k = std::mem::replace(&mut n.scale_factor, 1.0); + if k == 1.0 { + return; + } + for d in doc.subtree(id) { + let own = !crate::components::inside_instance(doc, d); + let Some(n) = doc.node_mut(d) else { continue }; + if !own { + continue; + } + if matches!(n.kind, NodeKind::Instance { .. }) { + n.scale_factor = (n.scale_factor * k).clamp(super::arrange::MIN_SCALE_FACTOR, super::arrange::MAX_SCALE_FACTOR); + } else { + n.bound.retain(|f, _| !LENGTH_FIELDS.contains(&f.as_str())); + } + } +} + +/// [`bake_scale`] for every layer under `root` that is no longer an instance but still has a +/// scale factor (a conversion left it behind). +pub(crate) fn bake_stale_scales(doc: &mut Document, root: NodeId) { + for d in doc.subtree(root) { + if doc.node(d).is_some_and(|n| !matches!(n.kind, NodeKind::Instance { .. }) && n.scale_factor != 1.0) { + bake_scale(doc, d); + } + } +} + /// Re-apply the variable bindings whose field passes `include`, on the `only` nodes (every bound /// node when `None`). Auto layout fields wait while their node has no auto layout. fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::BTreeSet>, include: impl Fn(&str) -> bool) { diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs index 567592e28..eb936a042 100644 --- a/crates/engine/src/scale_bound_values_tests.rs +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -148,3 +148,101 @@ fn detaching_a_scaled_instance_keeps_its_lengths_and_drops_their_variables() { assert!(near(gap(&s, i), 4.0), "gap after the variable changed {}", gap(&s, i)); healthy(&s); } + +/// Main A holds an instance of main B (the bound row); returns (A, the instance of B in A, an +/// instance of A, the copy of that B instance inside it). +fn nested_instance(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let (b, _a, _i) = row_instance(s); + let fa = idv(&ex(s, "frame.create", json!({"x": 0, "y": 200, "width": 100, "height": 60, "name": "Holder"}))); + let ib = idv(&ex(s, "instance.create", json!({"component": b, "x": 0, "y": 0, "parent": fa}))); + let a_main = idv(&ex(s, "component.create", json!({"ids": [fa]}))); + let ia = idv(&ex(s, "instance.create", json!({"component": a_main, "x": 500, "y": 0}))); + let inner = copy_of(s, ia, ib); + (a_main, ib, ia, inner) +} + +#[test] +fn an_instance_inside_a_scaled_instance_is_drawn_at_the_outer_factor_once() { + let mut s = Session::new(); + let (a_main, _ib, ia, inner) = nested_instance(&mut s); + assert!(near(gap(&s, inner), 8.0), "{}", gap(&s, inner)); + ex(&mut s, "transform.scale", json!({"ids": [ia], "factor": 0.5})); + assert!(near(factor(&s, ia), 0.5), "outer factor {}", factor(&s, ia)); + assert!(near(gap(&s, inner), 4.0), "the nested copy draws at 0.5 once: gap {}", gap(&s, inner)); + // A change to main A rebuilds the instance: the nested copy is still at 0.5. + ex(&mut s, "node.set", json!({"id": a_main, "props": {"fills": ["#ff0000"]}})); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 2, "height": 2, "parent": a_main})); + let inner = + s.doc().unwrap().subtree(ia).into_iter().find(|d| *d != ia && matches!(node(&s, *d).kind, figcraft_doc::NodeKind::Instance { .. })).unwrap(); + assert!(near(gap(&s, inner), 4.0), "after the main changed: gap {}", gap(&s, inner)); + healthy(&s); +} + +#[test] +fn restoring_the_main_from_a_scaled_instance_keeps_its_lengths_and_drops_their_variables() { + let mut s = Session::new(); + let (c, _a, i) = row_instance(&mut s); + let j = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 600, "y": 0}))); + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 0.5})); + ex(&mut s, "edit.delete", json!({"ids": [c]})); + let r = idv(&ex(&mut s, "component.restoreMain", json!({"id": i}))); + assert_eq!(r, c); + assert!(near(gap(&s, c), 4.0), "the restored main's gap {}", gap(&s, c)); + assert!(!node(&s, c).bound.contains_key("gap"), "the gap's variable goes: {:?}", node(&s, c).bound); + assert!(near(factor(&s, c), 1.0), "a main has no scale factor: {}", factor(&s, c)); + assert!(near(gap(&s, j), 4.0), "another instance re-links and draws the main's gap: {}", gap(&s, j)); + healthy(&s); +} + +#[test] +fn a_library_instance_whose_main_is_missing_lands_as_a_frame_with_the_lengths_as_drawn() { + let dir = std::env::temp_dir().join(format!("figcraft-scale-lib-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let lib_path = dir.join("kit.figcraft").to_string_lossy().to_string(); + let mut lib = Session::new(); + let (b, _a, _i) = row_instance(&mut lib); + let fa = idv(&ex(&mut lib, "frame.create", json!({"x": 0, "y": 200, "width": 100, "height": 60, "name": "Holder"}))); + let ib = idv(&ex(&mut lib, "instance.create", json!({"component": b, "x": 0, "y": 0, "parent": fa}))); + ex(&mut lib, "transform.scale", json!({"ids": [ib], "factor": 0.5})); + ex(&mut lib, "component.create", json!({"ids": [fa]})); + // The row's main goes: the library's instance has no main to bring along. + ex(&mut lib, "edit.delete", json!({"ids": [b]})); + ex(&mut lib, "library.publish", json!({"description": "Kit"})); + ex(&mut lib, "file.saveAs", json!({"path": lib_path})); + let mut s = Session::new(); + let r = ex(&mut s, "library.add", json!({"path": lib_path})); + let lid = r["id"].as_str().unwrap().to_string(); + let placed = idv(&ex(&mut s, "library.place", json!({"library": lid, "component": "Holder", "x": 300, "y": 300}))); + let main = match node(&s, placed).kind { + figcraft_doc::NodeKind::Component { .. } => placed, + figcraft_doc::NodeKind::Instance { component, .. } => component, + _ => panic!("not a component or instance"), + }; + let _ = std::fs::remove_dir_all(&dir); + let doc = s.doc().unwrap(); + let row = doc.subtree(main).into_iter().find(|d| *d != main && node(&s, *d).layout.is_some()).expect("the row frame"); + assert!(matches!(node(&s, row).kind, figcraft_doc::NodeKind::Frame), "{:?}", node(&s, row).kind); + assert!(near(gap(&s, row), 4.0), "gap {}", gap(&s, row)); + assert!(near(factor(&s, row), 1.0), "factor {}", factor(&s, row)); + assert!(!node(&s, row).bound.contains_key("gap"), "binding dropped: {:?}", node(&s, row).bound); +} + +#[test] +fn scaling_a_frame_holding_an_instance_drops_its_own_binding_and_scales_the_instance_once() { + let mut s = Session::new(); + let (c, a, _i) = row_instance(&mut s); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 400, "width": 200, "height": 60, "name": "Outer"}))); + ex(&mut s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 8, "fills": []}})); + let inner = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 0, "y": 0, "parent": f}))); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "Gap"})); + ex(&mut s, "transform.scale", json!({"ids": [f], "factor": 0.5})); + assert!(!node(&s, f).bound.contains_key("gap"), "{:?}", node(&s, f).bound); + assert!(near(gap(&s, f), 4.0), "frame gap {}", gap(&s, f)); + assert!(near(factor(&s, inner), 0.5), "inner factor {}", factor(&s, inner)); + assert_bound_at_half(&s, inner, a, 4.0, "inner"); + // Back to 1: no factor is saved. + ex(&mut s, "transform.scale", json!({"ids": [f], "factor": 2.0})); + let saved = serde_json::to_value(node(&s, inner)).unwrap(); + assert!(saved.get("scale_factor").is_none(), "{saved}"); + healthy(&s); +} From bd86309d9b90c4ccf7ea19ffa3bcb54820b70913 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 23:33:44 -0500 Subject: [PATCH 004/268] M3: the parity status lines carry the #2090 change, and the Scale tool row its limits (#2134 review) Both docs got a 2026-11-09 revision row without their status line. The Scale tool row now lists what is not done yet: .fig import, list and text-run bindings, a layer scaled inside an instance, and a nested instance scaled inside a copy. Docs only. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- docs/components-parity.md | 2 +- docs/ui-parity.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/components-parity.md b/docs/components-parity.md index 6dc8514e3..32783cc52 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7c170f80f..2dbe838b4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -67,7 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each length scaled (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it | +| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each length scaled (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are not multiplied; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | From 572690c0e896055c1f23550ef25069f5c3bbe960 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 00:34:40 -0500 Subject: [PATCH 005/268] M3: the Scale tool row says which bindings a plain layer drops (#2134 review) Effect, layout grid and text-run bindings stay live on a scaled plain layer and draw at the variable's value again; only layer-level lengths drop their binding. Docs only. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2dbe838b4..03e48f937 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -67,7 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each length scaled (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are not multiplied; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt | +| Scale tool (K): handles about an anchor, live factor, panel | done | variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each layer-level length scaled: size, gaps, padding, radii, stroke weights, min and max sizes and the layer's text sizes (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are neither multiplied nor dropped, so on any scaled layer they go back to the variable's value at the next bindings pass; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | From 4fdb02fc5f2c968bca449c8bbd046747827c261c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 01:32:26 -0500 Subject: [PATCH 006/268] M8: a dragged layer moves with its outline: drawn from a sprite while the base stays put (#2033) While a drag only translates plain layers on the threaded render worker, the dragged layers are rendered once into a texture of their own and drawn each frame at the same shift as the selection outline. The base is rendered once without them, from the document the drag started from, and no further render is asked for until the drag ends. On release, cancel or a zoom change the whole document is rendered again and the sprite stays until that image is shown. Trade-offs while dragging: the sprite draws above everything, blends against the background are approximated, and layers outside the conditions keep the old path. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/canvas.rs | 26 ++- crates/ui-egui/src/canvas/drag_sprite.rs | 237 +++++++++++++++++++++++ crates/ui-egui/src/canvas/render.rs | 25 ++- crates/ui-egui/src/canvas_drag_tests.rs | 81 ++++++++ docs/ui-parity.md | 4 +- 5 files changed, 366 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/canvas/drag_sprite.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 251ff25e6..94045a0c8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -15,6 +15,7 @@ use crate::render_worker::{Done, Job, Worker}; use crate::theme::{COMPONENT, Tokens, doc_c32, regular, semibold}; mod builder; +mod drag_sprite; mod input; mod outline; mod overlays; @@ -58,6 +59,10 @@ pub struct CanvasState { /// The request the texture answers ([`crate::render_worker::Done::seq`]). tex_seq: u64, submitted: Option, + /// The dragged layers drawn from a texture of their own while the base render stays put + /// ([`drag_sprite`]), and the gesture (its start document's address) that can't have one. + sprite: Option, + sprite_declined: usize, /// The view of the last render asked for. want_view: Option, /// What the last canvas render had to do (shown by `ui.inspect`). @@ -89,6 +94,19 @@ pub struct CanvasState { wheel_is_mouse: bool, } +#[cfg(test)] +impl CanvasState { + /// The layers the last submitted canvas job leaves out. + pub(crate) fn submitted_skip(&self) -> Option<&[NodeId]> { + self.submitted.as_ref().map(|k| k.skip.as_slice()) + } + + /// Where the drag sprite shows on screen (at one pixel per point), if there is one. + pub(crate) fn sprite_rect(&self, app: &FigApp) -> Option { + drag_sprite::screen_rect(app, 1.0) + } +} + impl Default for CanvasState { fn default() -> Self { Self { @@ -99,6 +117,8 @@ impl Default for CanvasState { tex_coarse: false, tex_seq: 0, submitted: None, + sprite: None, + sprite_declined: 0, want_view: None, render_work: None, preview_latency_ms: None, @@ -260,7 +280,8 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { }) .unwrap_or(t.canvas); let dots = crate::board_bar::dots(app, bg, &t); - request_render(app, worker, ppp, max_texture_side, dots); + request_render(app, worker, &ctx, ppp, max_texture_side, dots); + drag_sprite::drop_orphan(&mut app.canvas); // Every finished render is shown, even when a newer one is already on its way: renders finish // in order, and an edit every frame (a drag) would otherwise never show until it stopped. let shown = app.session.ds().map(|ds| (ds.uid, ds.page)).ok(); @@ -281,6 +302,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { Some(t) => t.set(done.image, filter), None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", done.image, filter)), } + let done_at = done.at; let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0); if done.coarse { app.canvas.preview_latency_ms = latency; @@ -291,6 +313,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_of = Some((done.uid, done.page)); app.canvas.tex_coarse = done.coarse; app.canvas.tex_seq = done.seq; + drag_sprite::arrived(&mut app.canvas, done_at, done.coarse); } let painter = ui.painter_at(rect); painter.rect_filled(rect, CornerRadius::ZERO, bg); @@ -303,6 +326,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { let image_rect = presented_image_rect(tl, v, zoom, ppp, pixel_preview); painter.image(tex.id(), image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } + drag_sprite::draw(app, &painter, ppp); crate::dev_mode::refresh_measurements(app); app.session.tool.labels = overlays(app, &painter, &t); crate::frame_labels::rename_field(app, ui); diff --git a/crates/ui-egui/src/canvas/drag_sprite.rs b/crates/ui-egui/src/canvas/drag_sprite.rs new file mode 100644 index 000000000..8e9035076 --- /dev/null +++ b/crates/ui-egui/src/canvas/drag_sprite.rs @@ -0,0 +1,237 @@ +//! The dragged-subtree sprite (#2033). The selection outline is drawn from the live document every +//! frame, but the canvas shows the last image the render worker finished, so while a layer is +//! dragged the content trails the outline by the render time of every pointer move. When a +//! gesture only translates plain layers ([`crate::selection_cache::moved`]), the layers are +//! rendered once into a texture of their own (the sprite) and drawn each frame at the same +//! shifted place as the outline, while the base render is made once without them +//! ([`figcraft_render::Options::skip`]) from the document the gesture started from, so no render +//! is requested again until the gesture ends. +//! +//! While it drags, the sprite draws above everything (the layers lose their z-order), blends and +//! backdrop effects against what lies under them are approximated, and a layer that doesn't +//! qualify (see [`plan`]) keeps the old way. + +use std::sync::Arc; + +use egui::{Color32, Rect, pos2}; +use figcraft_color::BlendMode; +use figcraft_doc::{Document, NodeId, NodeKind}; +use web_time::Instant; + +use super::{CanvasState, FigApp}; + +/// The sprite is at most this many times the canvas in pixels. +const MAX_AREA_FACTOR: f64 = 4.0; + +pub(super) struct Sprite { + tex: egui::TextureHandle, + /// The dragged layers. + roots: Vec, + /// Where the first of them was, in page units (the final shift is read off its move). + root_at: (f64, f64), + /// The page area the sprite shows when not shifted, and its pixels. + view: figcraft_render::View, + /// The pointer-driven shift (page units) while it drags, then the final one. + delta: (f64, f64), + zoom: f64, + ppp: f32, + /// The address of the document the gesture started from. + base: usize, + /// Page rectangle the layers are clipped to (the clipping frames above them). + clip: Option, + /// The gesture is over (or the plan stopped holding): the sprite stays until the image of the + /// document without a skip, asked for at or after `release`, is on screen. + ending: bool, + release: Option, +} + +impl Sprite { + fn rect(&self, app: &FigApp, ppp: f32) -> Rect { + let tl = app.to_screen(self.view.origin.0 + self.delta.0, self.view.origin.1 + self.delta.1); + let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(self.zoom); + super::presented_image_rect(tl, &self.view, zoom, ppp, false) + } +} + +/// Where the sprite shows on screen now, if there is one (tests compare it with the outline). +#[cfg(test)] +pub(super) fn screen_rect(app: &FigApp, ppp: f32) -> Option { + app.canvas.sprite.as_ref().map(|s| s.rect(app, ppp)) +} + +/// Draw the sprite, above the canvas image. +pub(super) fn draw(app: &FigApp, painter: &egui::Painter, ppp: f32) { + let Some(s) = &app.canvas.sprite else { return }; + let r = s.rect(app, ppp); + let painter = match s.clip { + Some(c) => { + let (a, b) = (app.to_screen(c.x0, c.y0), app.to_screen(c.x1, c.y1)); + painter.with_clip_rect(painter.clip_rect().intersect(Rect::from_two_pos(a, b))) + } + None => painter.clone(), + }; + painter.image(s.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); +} + +/// A finished image of the canvas, asked for at `at`, is on screen: a sprite that is ending goes. +pub(super) fn arrived(c: &mut CanvasState, at: Instant, coarse: bool) { + if !coarse && c.sprite.as_ref().is_some_and(|s| s.ending && s.release.is_some_and(|r| at >= r)) { + c.sprite = None; + } +} + +/// A job without a skip was asked for at `at`: what an ending sprite waits for. +pub(super) fn released_at(c: &mut CanvasState, at: Instant) { + if let Some(s) = c.sprite.as_mut().filter(|s| s.ending) { + s.release = Some(at); + } +} + +/// An ending sprite no job waits on goes (nothing would ever replace it). +pub(super) fn drop_orphan(c: &mut CanvasState) { + if c.sprite.as_ref().is_some_and(|s| s.ending && s.release.is_none()) { + c.sprite = None; + } +} + +/// Bring the sprite in line with the gesture; the document and layers the canvas render is to be +/// made from, with the layers skipped, while it shows them. +pub(super) fn sync(app: &mut FigApp, ctx: &egui::Context, ppp: f32, max_side: u32) -> Option<(Arc, Vec)> { + if cfg!(target_arch = "wasm32") { + return None; + } + let Ok(ds) = app.session.ds() else { + app.canvas.sprite = None; + return None; + }; + let moved = crate::selection_cache::moved(ds); + let zoom = ds.view.zoom; + let view_ok = view_allows(ds); + if let Some(s) = app.canvas.sprite.as_mut().filter(|s| !s.ending) { + if let Some((base, d)) = moved.as_ref().filter(|(b, _)| Arc::as_ptr(b) as usize == s.base) + && zoom.to_bits() == s.zoom.to_bits() + && ppp.to_bits() == s.ppp.to_bits() + && view_ok + { + s.delta = *d; + return Some((base.clone(), s.roots.clone())); + } + // The gesture ended or the plan stopped holding (then not again in this gesture): freeze + // where the layers are now. + if let Some((b, _)) = moved.as_ref().filter(|(b, _)| Arc::as_ptr(b) as usize == s.base) { + app.canvas.sprite_declined = Arc::as_ptr(b) as usize; + } + match ds.doc.world_transform(s.roots[0]).translation() { + t if ds.doc.contains(s.roots[0]) => { + s.delta = (t.x - s.root_at.0, t.y - s.root_at.1); + s.ending = true; + s.release = None; + } + _ => app.canvas.sprite = None, + } + } + let (base, _) = moved?; + let ptr = Arc::as_ptr(&base) as usize; + if app.canvas.sprite_declined == ptr || !view_ok { + return None; + } + let canvas_px = f64::from(app.canvas.rect.width() * ppp) * f64::from(app.canvas.rect.height() * ppp); + match plan(ctx, &base, &ds.selection, zoom, ppp, max_side, canvas_px) { + Some(s) => { + let out = (base, s.roots.clone()); + app.canvas.sprite = Some(s); + Some(out) + } + None => { + app.canvas.sprite_declined = ptr; + None + } + } +} + +/// What the canvas shows that the sprite can't stand in for. +fn view_allows(ds: &figcraft_engine::DocState) -> bool { + !ds.view.outlines + && !ds.view.outlines_selection + && !ds.view.outline_hidden + && ds.focused().is_none() + && ds.view.pixel_preview_scale().is_none() + && !(ds.view.proof_srgb && !ds.doc.color_profile.is_srgb()) +} + +/// Normal, or the pass-through of groups and frames (which draws like it unless the layers in them blend). +fn ordinary(b: BlendMode) -> bool { + matches!(b, BlendMode::Normal | BlendMode::PassThrough) +} + +/// Whether layer `id` can be drawn apart from the rest: it and what it sits in are plain. +fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> bool { + let Some(n) = doc.node(id) else { return false }; + if !n.effects.is_empty() || !ordinary(n.blend) || n.is_mask { + return false; + } + let Some(parent) = n.parent.and_then(|p| doc.node(p)) else { return false }; + if matches!(parent.kind, NodeKind::BooleanOp { .. }) || parent.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.is_mask)) { + return false; + } + let mut at = Some(parent.id); + while let Some(a) = at.and_then(|a| doc.node(a)) { + if matches!(a.kind, NodeKind::Page { .. }) { + break; + } + if !a.effects.is_empty() || !ordinary(a.blend) || a.opacity < 1.0 || a.is_mask { + return false; + } + if a.clip && a.kind.is_frame_like() { + let Some(b) = doc.world_bounds(a.id) else { return false }; + *clip = Some(clip.map_or(b, |c| c.intersect(b))); + } + at = a.parent; + } + true +} + +/// Render the dragged layers of `base` into a sprite, if they qualify: the roots are plain (see +/// [`plain`]), none inside another, and the sprite fits a texture and a few canvases of pixels. +fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, ppp: f32, max_side: u32, canvas_px: f64) -> Option { + if sel.is_empty() || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let mut clip = None; + for id in sel { + if !plain(base, *id, &mut clip) || sel.iter().any(|o| o != id && base.ancestors(*id).contains(o)) { + return None; + } + } + // Bottom to top, as the page draws them. + let page = base.page_of(sel[0])?; + let order = base.subtree(page); + let mut roots: Vec = order.iter().copied().filter(|i| sel.contains(i)).collect(); + if roots.len() != sel.len() { + roots = sel.to_vec(); + } + let bounds = roots.iter().filter_map(|i| base.world_render_bounds(*i)).reduce(|a, b| a.union(b))?; + let scale = zoom * f64::from(ppp); + let (w, h) = ((bounds.width() * scale).ceil(), (bounds.height() * scale).ceil()); + let side = f64::from(max_side); + if !(w >= 1.0 && h >= 1.0 && w <= side && h <= side && w * h <= canvas_px * MAX_AREA_FACTOR) { + return None; + } + let pix = figcraft_render::render_area(base, &roots, bounds, scale)?; + let view = figcraft_render::View { origin: (bounds.x0, bounds.y0), scale, width: pix.width(), height: pix.height() }; + let tex = ctx.load_texture("figcraft-drag-sprite", crate::render_worker::screen_image(&pix, base.color_profile), egui::TextureOptions::LINEAR); + let t = base.world_transform(roots[0]).translation(); + Some(Sprite { + tex, + root_at: (t.x, t.y), + roots, + view, + delta: (0.0, 0.0), + zoom, + ppp, + base: Arc::as_ptr(base) as usize, + clip, + ending: false, + release: None, + }) +} diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs index c6c4702fa..11658708f 100644 --- a/crates/ui-egui/src/canvas/render.rs +++ b/crates/ui-egui/src/canvas/render.rs @@ -10,7 +10,7 @@ pub(super) struct JobKey { outline: bool, outline_extras: figcraft_render::Outline, outlined: Vec, - skip: Vec, + pub(super) skip: Vec, solo: Option, /// Text lays out anew when fonts arrive (system fonts load in the background). fonts: u64, @@ -46,7 +46,16 @@ fn covers(outer: &figcraft_render::View, inner: &figcraft_render::View) -> bool o.x0 <= i.x0 + eps && o.y0 <= i.y0 + eps && o.x1 >= i.x1 - eps && o.y1 >= i.y1 - eps } -pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, max_texture_side: u32, dots: Option) { +pub(super) fn request_render( + app: &mut FigApp, + worker: &mut Worker, + ctx: &egui::Context, + ppp: f32, + max_texture_side: u32, + dots: Option, +) { + // A dragged layer drawn as a sprite: the render is of the document the drag started from, without it. + let sprite = super::drag_sprite::sync(app, ctx, ppp, max_texture_side); let Ok(ds) = app.session.ds() else { return }; let rect = app.canvas.rect; let (mut ox, mut oy) = ds.view.origin(); @@ -60,7 +69,10 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma (ds.view.zoom * f64::from(ppp), (rect.width() * ppp).ceil().max(1.0) as u32, (rect.height() * ppp).ceil().max(1.0) as u32) }; // The edited text is drawn live (an IME composition included); the caret is an overlay. - let doc = app.preedit_view().map(|p| p.doc.clone()).unwrap_or_else(|| ds.doc.clone()); + let (doc, skip) = match sprite { + Some(s) => s, + None => (app.preedit_view().map(|p| p.doc.clone()).unwrap_or_else(|| ds.doc.clone()), vec![]), + }; let outlined = if ds.view.outlines_selection { ds.selection.clone() } else { vec![] }; let proof = ds.view.proof_srgb && !doc.color_profile.is_srgb(); let outline_extras = figcraft_render::Outline { hidden: ds.view.outline_hidden, bounds: ds.view.outline_bounds, light: false }; @@ -81,7 +93,7 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma outline: ds.view.outlines, outline_extras, outlined: outlined.clone(), - skip: vec![], + skip: skip.clone(), solo: ds.focused(), fonts: figcraft_text::layout_generation(), proof, @@ -105,7 +117,7 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma outline: ds.view.outlines, outline_extras, outlined, - skip: vec![], + skip, solo: key.solo, proof, dots, @@ -114,6 +126,9 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma at: web_time::Instant::now(), }; app.canvas.want_view = Some(job.view.clone()); + if job.skip.is_empty() { + super::drag_sprite::released_at(&mut app.canvas, job.at); + } worker.submit(job); app.canvas.submitted = Some(key); } diff --git a/crates/ui-egui/src/canvas_drag_tests.rs b/crates/ui-egui/src/canvas_drag_tests.rs index 9f3b38397..e46ccae9a 100644 --- a/crates/ui-egui/src/canvas_drag_tests.rs +++ b/crates/ui-egui/src/canvas_drag_tests.rs @@ -121,3 +121,84 @@ fn a_drag_released_off_the_window_ends_where_the_pointer_was_last_seen_and_later assert!(!doc.contains(gone), "the delete stays"); assert_eq!(doc.node(text).unwrap().kind.text().unwrap().characters, "B"); } + +/// A frame with a child, selected, and the screen point of an empty spot in it. +fn frame_with_child(effects: bool) -> (Ui, figcraft_doc::NodeId, egui::Pos2) { + let mut s = Session::new(); + let id = |v: serde_json::Value| figcraft_engine::params::id_of(&v["id"]).unwrap(); + let f = id(s.execute("frame.create", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()); + s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 80, "height": 60, "parent": f, "props": {"fill": "#e03030"}})).unwrap(); + if effects { + s.execute("node.set", &json!({"ids": [f], "effects": [{"type": "dropShadow", "color": "#00000066", "offset": [0, 8], "radius": 24}]})) + .unwrap(); + } + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let mut u = Ui::new(s); + settle(&mut u); + let p = u.app.to_screen(350.0, 250.0); + (u, f, p) +} + +fn drag_frames(u: &mut Ui, p: egui::Pos2, n: u32) { + for k in 1..=n { + u.frame(vec![Event::PointerMoved(p + vec2(k as f32 * 7.0, k as f32 * 3.0))]); + } +} + +#[test] +fn dragging_a_plain_frame_draws_its_sprite_with_the_outline() { + let (mut u, f, p) = frame_with_child(false); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite exists"); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[f][..]), "the base render leaves the dragged layer out"); + settle(&mut u); + // The sprite and the outline come from the same shift in the same frame. + for k in 5..9 { + u.frame(vec![Event::PointerMoved(p + vec2(k as f32 * 7.0, k as f32 * 3.0))]); + let ds = u.app.session.ds().unwrap(); + let (base, (dx, dy)) = crate::selection_cache::moved(ds).expect("a plain move"); + let b = figcraft_engine::tools::selection_box(&base, &[f]).unwrap(); + let outline = u.app.to_screen(b[0].x + dx, b[0].y + dy); + let sprite = u.app.canvas.sprite_rect(&u.app).unwrap(); + assert!((sprite.min - outline).length() < 0.6, "sprite {:?} outline {outline:?}", sprite.min); + } + // The base stays put: later moves ask for no new render. + settle(&mut u); + let before = u.app.canvas.submitted_skip().map(<[_]>::to_vec); + u.frame(vec![Event::PointerMoved(p + vec2(90.0, 40.0))]); + assert_eq!(u.app.canvas.submitted_skip().map(<[_]>::to_vec), before); + assert!(!u.app.worker.as_ref().is_some_and(|w| w.in_flight()), "no render for a move"); + u.button(p + vec2(90.0, 40.0), false); + u.frame(vec![]); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the whole document is rendered again"); + settle(&mut u); + u.frame(vec![]); + assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "the sprite goes once that render is shown"); +} + +#[test] +fn a_frame_with_effects_on_itself_keeps_the_old_path() { + let (mut u, _f, p) = frame_with_child(true); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_none()); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); + u.button(p + vec2(30.0, 10.0), false); +} + +#[test] +fn zooming_during_a_drag_ends_the_fast_path() { + let (mut u, _f, p) = frame_with_child(false); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_some()); + let z = u.app.session.ds().unwrap().view.zoom; + u.app.session.ds_mut().unwrap().view.zoom = z * 1.5; + u.frame(vec![Event::PointerMoved(p + vec2(40.0, 12.0))]); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the zoom ended it"); + // Not started again by the next move of the same gesture. + u.frame(vec![Event::PointerMoved(p + vec2(48.0, 15.0))]); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); + u.button(p + vec2(48.0, 15.0), false); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 463be3b47..a70de28ce 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (a dragged layer is drawn from a sprite that moves with its outline (#2033); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -67,6 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | +| A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way | `canvas/drag_sprite.rs` | | Scale tool (K): handles about an anchor, live factor, panel | done | | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | @@ -187,6 +188,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M8, #2033: a dragged layer moves with its outline: the layers a translate-only drag moves are drawn from a sprite (a texture rendered once at the start) at the same shift as the outline, and the base render, made once without them, is not asked for again until the drag ends (see the row "A dragged layer moves with its outline" for the conditions and trade-offs). | | 2026-11-02 | patch | Shortcuts: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides, in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. A documented gesture row: 134 documented, 133 bound. Test: `padding_individual_tests` | | 2026-11-01 | patch | Number fields: dragging the field itself with Alt held scrubs it ("You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option Windows: Alt", Adjust alignment, rotation, position, and dimensions), with the resize cursor and the label's rates (Alt is the enabler there, so it isn't the fine rate); a click with Alt doesn't open the editor. Found by a documentation audit of the ui-parity rows. Test: `field_tests::alt_held_over_a_field_scrubs_it`. Counts unchanged | | 2026-11-02 | patch | M6, #1839: with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it by the nudge amounts (`tool.crosshair`), Enter places the object there (`tool.place`), Escape or a tool change takes it away; the canvas draws the crosshair and `ui.inspect` reports it (`tool.crosshair`), the Keyboard shortcuts panel lists the gesture ("Use the arrow keys to activate the crosshair cursor...", Accessibility at Figma). The board Shapes tool places on it too (its 160 px shape centred, as the tool centres a press), and the view pans by the overshoot when the crosshair is nudged past its edge. Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | From 89c9625ba02b5f306c7e16b4576262ae574c4f82 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 02:39:27 -0500 Subject: [PATCH 007/268] M8: the drag sprite checks every ancestor for booleans and masks, and stays within render_area's scale (#2144 review) `plain` checked the boolean result and mask siblings only at the dragged layer's parent; a layer in a group inside a boolean, or in a group beside a mask, got a sprite that ignored them. Both checks now run at every level, the page included. `render_area` clamps its scale to 64, so a zoom past it declines the sprite instead of drawing it too small. The parity row's file reference moves into the Notes cell. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/canvas/drag_sprite.rs | 56 ++++++++++++++++++++++-- crates/ui-egui/src/canvas_drag_tests.rs | 23 ++++++++++ docs/ui-parity.md | 2 +- 3 files changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag_sprite.rs b/crates/ui-egui/src/canvas/drag_sprite.rs index 8e9035076..d728ea53e 100644 --- a/crates/ui-egui/src/canvas/drag_sprite.rs +++ b/crates/ui-egui/src/canvas/drag_sprite.rs @@ -159,6 +159,9 @@ fn view_allows(ds: &figcraft_engine::DocState) -> bool { && !(ds.view.proof_srgb && !ds.doc.color_profile.is_srgb()) } +/// The largest scale `figcraft_render::render_area` renders at (it clamps to this). +const RENDER_AREA_MAX_SCALE: f64 = 64.0; + /// Normal, or the pass-through of groups and frames (which draws like it unless the layers in them blend). fn ordinary(b: BlendMode) -> bool { matches!(b, BlendMode::Normal | BlendMode::PassThrough) @@ -170,12 +173,16 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> if !n.effects.is_empty() || !ordinary(n.blend) || n.is_mask { return false; } - let Some(parent) = n.parent.and_then(|p| doc.node(p)) else { return false }; - if matches!(parent.kind, NodeKind::BooleanOp { .. }) || parent.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.is_mask)) { + if n.parent.and_then(|p| doc.node(p)).is_none() { return false; } - let mut at = Some(parent.id); + let mut at = n.parent; while let Some(a) = at.and_then(|a| doc.node(a)) { + // At every level, the page included: inside a boolean result, or beside a mask, the layer + // doesn't draw on its own. + if matches!(a.kind, NodeKind::BooleanOp { .. }) || a.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.is_mask)) { + return false; + } if matches!(a.kind, NodeKind::Page { .. }) { break; } @@ -212,6 +219,10 @@ fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, pp } let bounds = roots.iter().filter_map(|i| base.world_render_bounds(*i)).reduce(|a, b| a.union(b))?; let scale = zoom * f64::from(ppp); + // `render_area` renders at most at this scale; past it the sprite would draw smaller than the layers. + if scale > RENDER_AREA_MAX_SCALE { + return None; + } let (w, h) = ((bounds.width() * scale).ceil(), (bounds.height() * scale).ceil()); let side = f64::from(max_side); if !(w >= 1.0 && h >= 1.0 && w <= side && h <= side && w * h <= canvas_px * MAX_AREA_FACTOR) { @@ -235,3 +246,42 @@ fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, pp release: None, }) } + +#[cfg(test)] +mod plain_tests { + use super::plain; + use figcraft_engine::Session; + use serde_json::{Value, json}; + + fn id(v: &Value) -> figcraft_doc::NodeId { + figcraft_engine::params::id_of(&v["id"]).or_else(|| figcraft_engine::params::id_of(&v["ids"][0])).unwrap() + } + + fn rect(s: &mut Session, x: f64) -> figcraft_doc::NodeId { + id(&s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 40, "height": 40})).unwrap()) + } + + #[test] + fn a_layer_in_a_group_inside_a_boolean_is_not_plain() { + let mut s = Session::new(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 20.0), rect(&mut s, 60.0)); + let g = id(&s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + assert!(plain(s.doc().unwrap(), a, &mut None), "in a plain group it is plain"); + s.execute("bool.union", &json!({"ids": [g, c]})).unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.ancestors(a).iter().any(|p| matches!(doc.node(*p).map(|n| &n.kind), Some(figcraft_doc::NodeKind::BooleanOp { .. })))); + assert!(!plain(doc, a, &mut None), "its group sits in a boolean result"); + } + + #[test] + fn a_layer_in_a_group_beside_a_mask_is_not_plain() { + let mut s = Session::new(); + let m = rect(&mut s, 0.0); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 30.0)); + let g = id(&s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + s.execute("object.mask", &json!({"ids": [m, g]})).unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.node(m).is_some_and(|n| n.is_mask), "the bottom layer masks"); + assert!(!plain(doc, a, &mut None), "its group is masked"); + } +} diff --git a/crates/ui-egui/src/canvas_drag_tests.rs b/crates/ui-egui/src/canvas_drag_tests.rs index e46ccae9a..546c56da1 100644 --- a/crates/ui-egui/src/canvas_drag_tests.rs +++ b/crates/ui-egui/src/canvas_drag_tests.rs @@ -187,6 +187,29 @@ fn a_frame_with_effects_on_itself_keeps_the_old_path() { u.button(p + vec2(30.0, 10.0), false); } +#[test] +fn past_the_largest_render_scale_the_drag_keeps_the_old_path() { + // At 8000% a small frame still fits a texture, but `render_area` renders at most at 64x: + // the sprite would draw smaller than the layers, so there is none. + let mut s = Session::new(); + let id = |v: serde_json::Value| figcraft_engine::params::id_of(&v["id"]).unwrap(); + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap()); + s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 2, "height": 2, "parent": f, "props": {"fill": "#e03030"}})).unwrap(); + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let mut u = Ui::new(s); + settle(&mut u); + let v = &mut u.app.session.ds_mut().unwrap().view; + (v.zoom, v.cx, v.cy) = (80.0, 2.0, 2.0); + settle(&mut u); + let p = u.app.to_screen(2.0, 2.0); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert_eq!(u.app.session.ds().unwrap().view.zoom, 80.0); + assert!(u.app.canvas.sprite_rect(&u.app).is_none()); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); + u.button(p + vec2(30.0, 10.0), false); +} + #[test] fn zooming_during_a_drag_ends_the_fast_path() { let (mut u, _f, p) = frame_with_child(false); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a70de28ce..90fcedd74 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -67,7 +67,7 @@ interaction feel not yet compared. | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way | `canvas/drag_sprite.rs` | +| A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way (`canvas/drag_sprite.rs`) | | Scale tool (K): handles about an anchor, live factor, panel | done | | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | From 4cc59a6be17de906bf273c18a1da7ead4407ea5e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 14:47:41 -0500 Subject: [PATCH 008/268] M8: the drag sprite holds its start document, forgets a declined gesture, stays within texture limits and narrows its mask rule (#2144 review) The sprite and the declined-gesture marker held the start document by raw address; they now hold it (Arc / Weak) and compare with ptr_eq. A cancelled drag restores the same document, so a declined gesture no longer declines the next drag of it. The sprite is also dropped when another document or page is on screen, the rendered pixmap is checked against the texture limits, plan declines when the roots are not all on one page, a rounded clipping ancestor or a NaN ancestor opacity makes a layer non-plain, and only the layers above a mask are treated as masked. New tests cover cancel, delete mid-drag, outline views, the sprite size and the rejected ancestor properties. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 triaged and briefed; Sonnet 5.5 verified and wrote at medium --- crates/ui-egui/src/canvas.rs | 6 +- crates/ui-egui/src/canvas/drag_sprite.rs | 147 ++++++++++++++++++----- crates/ui-egui/src/canvas_drag_tests.rs | 77 ++++++++++++ 3 files changed, 194 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 94045a0c8..477b6e046 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -60,9 +60,9 @@ pub struct CanvasState { tex_seq: u64, submitted: Option, /// The dragged layers drawn from a texture of their own while the base render stays put - /// ([`drag_sprite`]), and the gesture (its start document's address) that can't have one. + /// ([`drag_sprite`]), and the gesture (its start document, held weakly) that can't have one. sprite: Option, - sprite_declined: usize, + sprite_declined: Option>, /// The view of the last render asked for. want_view: Option, /// What the last canvas render had to do (shown by `ui.inspect`). @@ -118,7 +118,7 @@ impl Default for CanvasState { tex_seq: 0, submitted: None, sprite: None, - sprite_declined: 0, + sprite_declined: None, want_view: None, render_work: None, preview_latency_ms: None, diff --git a/crates/ui-egui/src/canvas/drag_sprite.rs b/crates/ui-egui/src/canvas/drag_sprite.rs index d728ea53e..8ef80e575 100644 --- a/crates/ui-egui/src/canvas/drag_sprite.rs +++ b/crates/ui-egui/src/canvas/drag_sprite.rs @@ -11,7 +11,7 @@ //! backdrop effects against what lies under them are approximated, and a layer that doesn't //! qualify (see [`plan`]) keeps the old way. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use egui::{Color32, Rect, pos2}; use figcraft_color::BlendMode; @@ -35,8 +35,10 @@ pub(super) struct Sprite { delta: (f64, f64), zoom: f64, ppp: f32, - /// The address of the document the gesture started from. - base: usize, + /// The document the gesture started from (held, so no other document can take its address). + base: Arc, + /// The document and page the sprite belongs to: another one on screen ends it. + of: (u64, NodeId), /// Page rectangle the layers are clipped to (the clipping frames above them). clip: Option, /// The gesture is over (or the plan stopped holding): the sprite stays until the image of the @@ -105,10 +107,16 @@ pub(super) fn sync(app: &mut FigApp, ctx: &egui::Context, ppp: f32, max_side: u3 return None; }; let moved = crate::selection_cache::moved(ds); + if moved.is_none() { + app.canvas.sprite_declined = None; + } + if app.canvas.sprite.as_ref().is_some_and(|s| s.of != (ds.uid, ds.page)) { + app.canvas.sprite = None; + } let zoom = ds.view.zoom; let view_ok = view_allows(ds); if let Some(s) = app.canvas.sprite.as_mut().filter(|s| !s.ending) { - if let Some((base, d)) = moved.as_ref().filter(|(b, _)| Arc::as_ptr(b) as usize == s.base) + if let Some((base, d)) = moved.as_ref().filter(|(b, _)| Arc::ptr_eq(b, &s.base)) && zoom.to_bits() == s.zoom.to_bits() && ppp.to_bits() == s.ppp.to_bits() && view_ok @@ -118,32 +126,32 @@ pub(super) fn sync(app: &mut FigApp, ctx: &egui::Context, ppp: f32, max_side: u3 } // The gesture ended or the plan stopped holding (then not again in this gesture): freeze // where the layers are now. - if let Some((b, _)) = moved.as_ref().filter(|(b, _)| Arc::as_ptr(b) as usize == s.base) { - app.canvas.sprite_declined = Arc::as_ptr(b) as usize; + if let Some((b, _)) = moved.as_ref().filter(|(b, _)| Arc::ptr_eq(b, &s.base)) { + app.canvas.sprite_declined = Some(Arc::downgrade(b)); } - match ds.doc.world_transform(s.roots[0]).translation() { - t if ds.doc.contains(s.roots[0]) => { + match s.roots.first().filter(|r| ds.doc.contains(**r)) { + Some(r) => { + let t = ds.doc.world_transform(*r).translation(); s.delta = (t.x - s.root_at.0, t.y - s.root_at.1); s.ending = true; s.release = None; } - _ => app.canvas.sprite = None, + None => app.canvas.sprite = None, } } let (base, _) = moved?; - let ptr = Arc::as_ptr(&base) as usize; - if app.canvas.sprite_declined == ptr || !view_ok { + if app.canvas.sprite_declined.as_ref().is_some_and(|d| Weak::ptr_eq(d, &Arc::downgrade(&base))) || !view_ok { return None; } let canvas_px = f64::from(app.canvas.rect.width() * ppp) * f64::from(app.canvas.rect.height() * ppp); - match plan(ctx, &base, &ds.selection, zoom, ppp, max_side, canvas_px) { + match plan(ctx, &base, &ds.selection, (ds.uid, ds.page), zoom, ppp, max_side, canvas_px) { Some(s) => { let out = (base, s.roots.clone()); app.canvas.sprite = Some(s); Some(out) } None => { - app.canvas.sprite_declined = ptr; + app.canvas.sprite_declined = Some(Arc::downgrade(&base)); None } } @@ -177,22 +185,29 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> return false; } let mut at = n.parent; + let mut child = id; while let Some(a) = at.and_then(|a| doc.node(a)) { - // At every level, the page included: inside a boolean result, or beside a mask, the layer - // doesn't draw on its own. - if matches!(a.kind, NodeKind::BooleanOp { .. }) || a.children.iter().any(|c| doc.node(*c).is_some_and(|c| c.is_mask)) { + // At every level, the page included: inside a boolean result, or above a mask (a mask + // masks the layers above it in its container), the layer doesn't draw on its own. + let above_a_mask = a.children.iter().take_while(|c| **c != child).any(|c| doc.node(*c).is_some_and(|c| c.is_mask)); + if matches!(a.kind, NodeKind::BooleanOp { .. }) || above_a_mask { return false; } if matches!(a.kind, NodeKind::Page { .. }) { break; } - if !a.effects.is_empty() || !ordinary(a.blend) || a.opacity < 1.0 || a.is_mask { + if !a.effects.is_empty() || !ordinary(a.blend) || a.opacity.is_nan() || a.opacity < 1.0 || a.is_mask { return false; } if a.clip && a.kind.is_frame_like() { + // The sprite is clipped to a rectangle: a rounded frame clips to a shape it can't follow. + if a.corners.radii.iter().any(|r| *r != 0.0) { + return false; + } let Some(b) = doc.world_bounds(a.id) else { return false }; *clip = Some(clip.map_or(b, |c| c.intersect(b))); } + child = a.id; at = a.parent; } true @@ -200,7 +215,17 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> /// Render the dragged layers of `base` into a sprite, if they qualify: the roots are plain (see /// [`plain`]), none inside another, and the sprite fits a texture and a few canvases of pixels. -fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, ppp: f32, max_side: u32, canvas_px: f64) -> Option { +#[allow(clippy::too_many_arguments)] +fn plan( + ctx: &egui::Context, + base: &Arc, + sel: &[NodeId], + of: (u64, NodeId), + zoom: f64, + ppp: f32, + max_side: u32, + canvas_px: f64, +) -> Option { if sel.is_empty() || !zoom.is_finite() || zoom <= 0.0 { return None; } @@ -213,9 +238,10 @@ fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, pp // Bottom to top, as the page draws them. let page = base.page_of(sel[0])?; let order = base.subtree(page); - let mut roots: Vec = order.iter().copied().filter(|i| sel.contains(i)).collect(); + let roots: Vec = order.iter().copied().filter(|i| sel.contains(i)).collect(); + // Not all on the page of the first (or not in the document): the old way, rather than a guessed order. if roots.len() != sel.len() { - roots = sel.to_vec(); + return None; } let bounds = roots.iter().filter_map(|i| base.world_render_bounds(*i)).reduce(|a, b| a.union(b))?; let scale = zoom * f64::from(ppp); @@ -229,22 +255,15 @@ fn plan(ctx: &egui::Context, base: &Arc, sel: &[NodeId], zoom: f64, pp return None; } let pix = figcraft_render::render_area(base, &roots, bounds, scale)?; + // What came back is what the texture is made of: the same limits again. + let (pw, ph) = (f64::from(pix.width()), f64::from(pix.height())); + if !(pw <= side && ph <= side && pw * ph <= canvas_px * MAX_AREA_FACTOR) { + return None; + } let view = figcraft_render::View { origin: (bounds.x0, bounds.y0), scale, width: pix.width(), height: pix.height() }; let tex = ctx.load_texture("figcraft-drag-sprite", crate::render_worker::screen_image(&pix, base.color_profile), egui::TextureOptions::LINEAR); let t = base.world_transform(roots[0]).translation(); - Some(Sprite { - tex, - root_at: (t.x, t.y), - roots, - view, - delta: (0.0, 0.0), - zoom, - ppp, - base: Arc::as_ptr(base) as usize, - clip, - ending: false, - release: None, - }) + Some(Sprite { tex, root_at: (t.x, t.y), roots, view, delta: (0.0, 0.0), zoom, ppp, base: base.clone(), of, clip, ending: false, release: None }) } #[cfg(test)] @@ -284,4 +303,66 @@ mod plain_tests { assert!(doc.node(m).is_some_and(|n| n.is_mask), "the bottom layer masks"); assert!(!plain(doc, a, &mut None), "its group is masked"); } + + fn frame_with_child(s: &mut Session, props: Value) -> (figcraft_doc::NodeId, figcraft_doc::NodeId) { + let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()); + s.execute("node.set", &json!({"id": f, "props": props})).unwrap(); + let c = id(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40, "parent": f})).unwrap()); + (f, c) + } + + #[test] + fn what_the_sprite_cannot_stand_in_for_is_not_plain() { + let mut s = Session::new(); + let (_, c) = frame_with_child(&mut s, json!({"clip": false})); + assert!(plain(s.doc().unwrap(), c, &mut None), "a layer in a plain frame is plain"); + for props in [ + json!({"opacity": 0.5}), + json!({"blend": "multiply"}), + json!({"effects": [{"type": "dropShadow", "color": "#00000066", "offset": [0, 8], "radius": 24}]}), + ] { + let mut s = Session::new(); + let (f, c) = frame_with_child(&mut s, props.clone()); + let n = s.doc().unwrap().node(f).unwrap(); + assert!(n.opacity < 1.0 || !n.effects.is_empty() || n.blend != figcraft_color::BlendMode::PassThrough, "{props} took"); + assert!(!plain(s.doc().unwrap(), c, &mut None), "an ancestor with {props}"); + } + } + + #[test] + fn a_layers_own_opacity_is_drawn_by_the_sprite() { + // `render_area` draws the layer as the page does, its opacity included. + let mut s = Session::new(); + let r = rect(&mut s, 0.0); + s.execute("node.set", &json!({"id": r, "props": {"opacity": 0.5}})).unwrap(); + assert!(s.doc().unwrap().node(r).unwrap().opacity < 1.0); + assert!(plain(s.doc().unwrap(), r, &mut None)); + } + + #[test] + fn only_the_layers_above_a_mask_are_masked() { + // A mask set in place (one layer, no group made): it masks the layers above it in its + // container, as `Document::paint_runs` draws it; the layers below it draw on their own. + let mut s = Session::new(); + let (below, m, above) = (rect(&mut s, 0.0), rect(&mut s, 50.0), rect(&mut s, 100.0)); + s.execute("object.mask", &json!({"ids": [m]})).unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.node(m).is_some_and(|n| n.is_mask), "the middle layer masks in place"); + let parent = |i| doc.node(i).and_then(|n| n.parent); + assert!(parent(below) == parent(m) && parent(above) == parent(m), "one container"); + assert!(!plain(doc, above, &mut None), "above the mask: masked"); + assert!(plain(doc, below, &mut None), "below it nothing is masked"); + } + + #[test] + fn a_rounded_clipping_ancestor_is_not_plain_a_square_one_is_clipped_to() { + let mut s = Session::new(); + let (f, c) = frame_with_child(&mut s, json!({"clip": true})); + let mut clip = None; + assert!(plain(s.doc().unwrap(), c, &mut clip)); + assert_eq!(clip, s.doc().unwrap().world_bounds(f)); + let mut s = Session::new(); + let (_, c) = frame_with_child(&mut s, json!({"clip": true, "cornerRadius": 12})); + assert!(!plain(s.doc().unwrap(), c, &mut None), "a rounded frame clips to a shape the sprite can't follow"); + } } diff --git a/crates/ui-egui/src/canvas_drag_tests.rs b/crates/ui-egui/src/canvas_drag_tests.rs index 546c56da1..65292869f 100644 --- a/crates/ui-egui/src/canvas_drag_tests.rs +++ b/crates/ui-egui/src/canvas_drag_tests.rs @@ -162,6 +162,10 @@ fn dragging_a_plain_frame_draws_its_sprite_with_the_outline() { let outline = u.app.to_screen(b[0].x + dx, b[0].y + dy); let sprite = u.app.canvas.sprite_rect(&u.app).unwrap(); assert!((sprite.min - outline).length() < 0.6, "sprite {:?} outline {outline:?}", sprite.min); + // It is the frame (300 x 200) at the view's zoom, and no move asks the worker for anything. + let zoom = u.app.session.ds().unwrap().view.zoom; + assert!((f64::from(sprite.width()) - 300.0 * zoom).abs() < 1.5 && (f64::from(sprite.height()) - 200.0 * zoom).abs() < 1.5, "{sprite:?}"); + assert!(!u.app.worker.as_ref().is_some_and(|w| w.in_flight()), "no render for a move"); } // The base stays put: later moves ask for no new render. settle(&mut u); @@ -172,6 +176,7 @@ fn dragging_a_plain_frame_draws_its_sprite_with_the_outline() { u.button(p + vec2(90.0, 40.0), false); u.frame(vec![]); assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the whole document is rendered again"); + assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite stays until that render is shown"); settle(&mut u); u.frame(vec![]); assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "the sprite goes once that render is shown"); @@ -225,3 +230,75 @@ fn zooming_during_a_drag_ends_the_fast_path() { assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); u.button(p + vec2(48.0, 15.0), false); } + +/// Drag `u`'s frame four frames, with the sprite up. +fn start_drag(u: &mut Ui, p: egui::Pos2) { + u.button(p, true); + drag_frames(u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite exists"); +} + +#[test] +fn a_cancelled_drag_keeps_its_sprite_until_the_restored_document_shows_and_the_next_drag_has_one() { + let (mut u, _f, p) = frame_with_child(false); + start_drag(&mut u, p); + u.app.session.cancel_interaction().unwrap(); + u.frame(vec![]); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "the restored document is rendered whole"); + assert!(u.app.canvas.sprite_rect(&u.app).is_some(), "the sprite stays until that render is shown"); + u.button(p, false); + settle(&mut u); + u.frame(vec![]); + assert!(u.app.canvas.sprite_rect(&u.app).is_none()); + // The restored document is the one the cancelled drag started from: a new drag of it still gets a sprite. + start_drag(&mut u, p); + u.button(p + vec2(30.0, 10.0), false); +} + +#[test] +fn a_drag_that_declined_the_sprite_does_not_decline_the_next_drag_of_the_same_document() { + let (mut u, _f, p) = frame_with_child(false); + start_drag(&mut u, p); + let z = u.app.session.ds().unwrap().view.zoom; + u.app.session.ds_mut().unwrap().view.zoom = z * 1.5; + u.frame(vec![Event::PointerMoved(p + vec2(40.0, 12.0))]); + u.app.session.cancel_interaction().unwrap(); + u.button(p, false); + settle(&mut u); + u.app.session.ds_mut().unwrap().view.zoom = z; + settle(&mut u); + let p = u.app.to_screen(350.0, 250.0); + start_drag(&mut u, p); + u.button(p + vec2(30.0, 10.0), false); +} + +#[test] +fn deleting_the_dragged_layer_mid_drag_drops_the_sprite_and_renders_normally() { + let (mut u, f, p) = frame_with_child(false); + start_drag(&mut u, p); + u.app.session.cancel_interaction().unwrap(); + u.app.session.execute("edit.delete", &json!({"ids": [f]})).unwrap(); + u.frame(vec![Event::PointerMoved(p + vec2(50.0, 20.0))]); + assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "nothing to show"); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..])); + u.button(p + vec2(50.0, 20.0), false); +} + +#[test] +fn outline_views_keep_the_old_path() { + for flag in 0..3 { + let (mut u, _f, p) = frame_with_child(false); + let v = &mut u.app.session.ds_mut().unwrap().view; + match flag { + 0 => v.outlines = true, + 1 => v.outlines_selection = true, + _ => v.outline_hidden = true, + } + settle(&mut u); + u.button(p, true); + drag_frames(&mut u, p, 4); + assert!(u.app.canvas.sprite_rect(&u.app).is_none(), "flag {flag}"); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[][..]), "flag {flag}"); + u.button(p + vec2(30.0, 10.0), false); + } +} From 1959fc3d71bf90ece9db6cbf329f92950e9fc452 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:44:18 +0800 Subject: [PATCH 009/268] M13: design review commands (engine and MCP) --- crates/doc/src/design_review.rs | 111 ++ crates/doc/src/lib.rs | 6 + crates/engine/src/automation/inspect.rs | 2 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/create.rs | 26 +- crates/engine/src/cmd/props.rs | 2 +- crates/engine/src/design/audit.rs | 1318 +++++++++++++++++++++ crates/engine/src/design/fix.rs | 319 +++++ crates/engine/src/design/mod.rs | 378 ++++++ crates/engine/src/design/rules.rs | 132 +++ crates/engine/src/design/tests.rs | 863 ++++++++++++++ crates/engine/src/inspect_fields_tests.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/prefs.rs | 4 + crates/mcp/src/prompts.rs | 20 +- crates/mcp/src/server.rs | 6 +- crates/mcp/tests/it/protocol.rs | 5 +- 17 files changed, 3183 insertions(+), 12 deletions(-) create mode 100644 crates/doc/src/design_review.rs create mode 100644 crates/engine/src/design/audit.rs create mode 100644 crates/engine/src/design/fix.rs create mode 100644 crates/engine/src/design/mod.rs create mode 100644 crates/engine/src/design/rules.rs create mode 100644 crates/engine/src/design/tests.rs diff --git a/crates/doc/src/design_review.rs b/crates/doc/src/design_review.rs new file mode 100644 index 000000000..c2fce64c8 --- /dev/null +++ b/crates/doc/src/design_review.rs @@ -0,0 +1,111 @@ +//! The design system a file's review follows: how strict it is, the spacing grid, the radii it +//! accepts and the brand accents it knows (`design.configure`). +//! +//! Kept in the document, so a file carries its settings for everyone who opens it, and the audit, +//! the fixer and CI all read the same values. + +use figcraft_color::Color; +use serde::{Deserialize, Serialize}; + +/// How strict `design.audit` is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum DesignPreset { + /// The rules that catch the usual AI-generated tells. + #[default] + Recommended, + /// Recommended plus the judgment calls (too many accent colours, frames without auto layout). + Strict, + /// Only the findings that keep a design usable: contrast, the type floor, gradient text and + /// clipped text. + Accessibility, +} + +impl DesignPreset { + pub const ALL: [Self; 3] = [Self::Recommended, Self::Strict, Self::Accessibility]; + + pub fn id(self) -> &'static str { + match self { + Self::Recommended => "recommended", + Self::Strict => "strict", + Self::Accessibility => "accessibility", + } + } + + pub fn from_id(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "recommended" | "default" => Some(Self::Recommended), + "strict" => Some(Self::Strict), + "accessibility" | "a11y" => Some(Self::Accessibility), + _ => None, + } + } +} + +/// The smallest and largest spacing grid a file may set. +pub const GRID_MIN: f64 = 1.0; +pub const GRID_MAX: f64 = 64.0; + +/// Most radii and brand colours a file keeps. +pub const MAX_RADII: usize = 32; +pub const MAX_BRAND_COLORS: usize = 32; + +/// A file's design review settings. The default is the recommended preset on a 4px grid with the +/// 4px radius scale and no brand palette. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct DesignReview { + pub preset: DesignPreset, + /// The spacing and radius grid in pixels (`0`: 4). A value outside [`GRID_MIN`]..=[`GRID_MAX`] + /// reads as the default. + pub grid: f64, + /// The corner radii the design uses, in pixels. Empty: any multiple of the grid from the grid + /// up, or a pill. + pub radii: Vec, + /// The brand's accent colours: they don't count as stray accents (`color.accents`). + pub brand: Vec, + /// Rule ids this file turns off. + pub disabled: Vec, +} + +impl DesignReview { + /// Whether the settings are the default ones (nothing to save). + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// The grid in pixels, with invalid values read as 4. + pub fn grid(&self) -> f64 { + if self.grid.is_finite() && (GRID_MIN..=GRID_MAX).contains(&self.grid) { self.grid } else { 4.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_round_trip_by_id() { + for p in DesignPreset::ALL { + assert_eq!(DesignPreset::from_id(p.id()), Some(p)); + } + assert_eq!(DesignPreset::from_id("a11y"), Some(DesignPreset::Accessibility)); + assert_eq!(DesignPreset::from_id("loud"), None); + } + + #[test] + fn a_default_file_does_not_serialize_the_settings_and_junk_grid_reads_as_four() { + let doc = crate::Document::new("Untitled"); + let json = serde_json::to_value(&doc).unwrap(); + assert!(json.get("designReview").is_none(), "{json}"); + let mut settings = DesignReview::default(); + assert!(settings.is_default()); + settings.grid = -3.0; + assert_eq!(settings.grid(), 4.0); + settings.grid = f64::NAN; + assert_eq!(settings.grid(), 4.0); + settings.grid = 8.0; + assert_eq!(settings.grid(), 8.0); + assert!(!settings.is_default()); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 81760d718..ac6cf5602 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -12,6 +12,7 @@ pub mod board; mod board_route; pub mod colors; pub mod comments; +pub mod design_review; pub mod facilitation; pub mod geometry; pub mod handoff; @@ -30,6 +31,7 @@ pub use board::*; pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; +pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII}; pub use facilitation::*; pub use figcraft_color as color; pub use figcraft_geom as geom; @@ -229,6 +231,9 @@ pub struct Document { /// Image adjustment presets saved in this file. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub image_presets: Vec, + /// The design system and rules this file's review follows (`design.configure`). + #[serde(default, skip_serializing_if = "DesignReview::is_default")] + pub design_review: DesignReview, /// Annotation categories (`None`: [`AnnotationCategory::defaults`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub annotation_categories: Option>, @@ -285,6 +290,7 @@ impl Document { published: None, color_profile: ColorProfile::Srgb, image_presets: Vec::new(), + design_review: DesignReview::default(), annotation_categories: None, dev_snapshots: BTreeMap::new(), timer: None, diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index 324635071..d4615bb84 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -40,6 +40,7 @@ pub const NODE_KEYS: &[&str] = &[ "fontFamily", "fontSize", "fontStyle", + "fontWeight", "fontVariations", "gridCell", "grids", @@ -398,6 +399,7 @@ fn text_props(t: &TextData, o: &mut serde_json::Map, options: &In }); insert_prop(o, options, "fontFamily", || json!(t.style.font_family)); insert_prop(o, options, "fontStyle", || json!(t.style.font_style)); + insert_prop(o, options, "fontWeight", || json!(t.style.weight())); insert_prop(o, options, "fontSize", || json!(t.style.font_size)); if !t.style.variations.is_empty() { insert_prop(o, options, "fontVariations", || json!(t.style.variations)); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0e90dc198..8ab89c1d5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -107,6 +107,7 @@ fn registry() -> &'static Registry { list.extend(crate::dev_resources::specs()); list.extend(crate::dev_measurements::specs()); list.extend(crate::distance::specs()); + list.extend(crate::design::specs()); list.extend(crate::collab::specs()); list.extend(crate::branches::specs()); list.extend(crate::plugins::specs()); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 435c3422a..920ec1113 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -1,7 +1,7 @@ //! Creating nodes. use figcraft_color::{ImageFilters, ImageScaleMode, Paint}; -use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, TextAutoResize, TextData, VectorNetwork}; +use figcraft_doc::{Document, Node, NodeId, NodeKind, Sizing, StrokeCap, TextAutoResize, TextData, VectorNetwork}; use figcraft_geom::Point; use serde_json::{Value, json}; @@ -99,7 +99,7 @@ pub fn specs() -> Vec { spec!( "text.create", "Text", - "{text | characters, x, y, parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontFamily, …), select? (default true)}", + "{text | characters, x?, y? (ignored inside an auto layout parent), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}", true, |s, p| { create_kind(s, p, "text") } ), @@ -275,7 +275,9 @@ pub fn create(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?; let pn = doc.get(parent)?; if !pn.kind.is_container() { - return Err(bad(cmd, format!("{parent} can't contain layers"))); + let name = pn.name.trim(); + let what = if name.is_empty() { pn.kind.type_name().to_string() } else { format!("{} \"{}\"", pn.kind.type_name(), name) }; + return Err(bad(cmd, format!("{parent} ({what}) can't contain layers"))); } if base == "Section" && !doc.takes_sections(parent) { return Err(bad(cmd, "sections go on the page or in other sections")); @@ -371,6 +373,24 @@ pub fn create(s: &mut Session, p: &Value) -> Result { doc.insert(node, parent, index)?; if let Some(Value::Object(props)) = get(p, "props") { super::props::apply(cmd, doc, nid, props)?; + // An auto layout frame hugs the axes the caller left unset — the incumbent's default, and + // the difference between a card and a 100pt-tall box that silently clips its rows. + // Explicit width/height and explicit sizing keep their fixed/fill behaviour. + if doc.node(nid).is_some_and(|n| n.layout.is_some()) { + let asked = |axis: &str, keys: &[&str]| { + let long = if axis == "h" { "width" } else { "height" }; + let short = if axis == "h" { "w" } else { "h" }; + num(p, long).is_some() || props.contains_key(long) || props.contains_key(short) || keys.iter().any(|k| props.contains_key(*k)) + }; + if let Some(n) = doc.node_mut(nid) { + if !asked("h", &["sizingH", "layoutSizingHorizontal"]) { + n.child_layout.sizing_h = Sizing::Hug; + } + if !asked("v", &["sizingV", "layoutSizingVertical"]) { + n.child_layout.sizing_v = Sizing::Hug; + } + } + } } if boolean(p, "select").unwrap_or(true) { ds.selection = vec![nid]; diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 2e5da37bd..f077a31d9 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -23,7 +23,7 @@ clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, paddi mainAlign (min|center|max, or the auto gaps spaceBetween|spaceAround|spaceEvenly), crossAlign (min|center|max|baseline: first text baselines, horizontal layouts), contentAlign (wrapped lines: auto = packed where crossAlign says | spaceBetween), wrap (rows of a horizontal layout, columns of a vertical one), strokesIncluded (the frame's inside stroke takes up space), reverseZ (canvas stacking: true = first on top), \ columnGap / rowGap (aliases of gap / crossGap), gridColumns, gridRows, columnTracks / rowTracks ([120 | \"1fr\" | \"auto\" | {sizing, value}]), \ gridColumn / gridRow (0-based cell anchor, null = auto), gridColumnSpan, gridRowSpan, gridAlignH / gridAlignV (a grid child's alignment in its cell: min|center|max, auto/null = the frame's), sizingH / sizingV (fixed|hug|fill), \ -absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, \ +absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, fontWeight (a number: 400 Regular, 600 Semi Bold — the nearest face the family has), \ fontSize, lineHeight (auto|px|\"150%\"), letterSpacing (px|\"2%\"), textAlign (left|center|right|justified), textAlignVertical, textAutoResize \ (widthAndHeight|height|none|truncate), textDecoration, textDecorationStyle (solid|dotted|wavy), textDecorationThickness / textDecorationOffset \ (auto|px|\"10%\" of the font size; the offset runs from the baseline down to an underline's top edge), textDecorationSkipInk (underlines break around descenders), \ diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs new file mode 100644 index 000000000..0a39840e5 --- /dev/null +++ b/crates/engine/src/design/audit.rs @@ -0,0 +1,1318 @@ +//! Walking the scope and turning what it finds into findings. +//! +//! Nothing here edits the document: `design.audit` reads pages and reports. The walk stops at an +//! instance's children (they mirror the main component, which is audited where it lives), skips +//! hidden layers and caps the number of nodes so a huge file cannot stall the app. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{BlendMode, Color, Paint, PaintKind}; +use figcraft_doc::{ + CollectionId, DesignPreset, Document, Effect, EffectKind, LayoutMode, ModeId, Node, NodeId, NodeKind, Shadow, Sizing, StrokeAlign, + TextAutoResize, TextData, VariableValue, +}; +use serde_json::{Map, Value, json}; + +use crate::cmd::lists::paint_binding_key; + +use super::rules::{Severity, rule}; + +/// Most layers one audit looks at; past it the report says `truncated`. +const MAX_NODES: usize = 50_000; +/// Most text layers one audit lays out for the overflow check (text layout is the expensive part). +const MAX_TEXT_MEASURED: usize = 2_000; +/// Most auto layout frames one audit measures for clipped children (bounds are per-subtree). +const MAX_FRAMES_MEASURED: usize = 500; +/// Most siblings or children one backdrop lookup scans before it stops guessing; a flat frame with +/// tens of thousands of layers must not turn every text check into a full scan. +const MAX_BACKDROP_SCAN: usize = 512; + +/// The design system a run checks against: the file's settings (`design.configure`) with an +/// optional preset override from the call. +#[derive(Clone)] +pub(crate) struct Settings { + pub(crate) preset: DesignPreset, + pub(crate) grid: f64, + /// Allowed corner radii; empty: any multiple of the grid from the grid up, or a pill. + pub(crate) radii: Vec, + /// Brand accents as 8-bit RGBA. + pub(crate) brand: Vec<[u8; 4]>, + pub(crate) disabled: BTreeSet, + /// Variable modes the run resolves colours in (empty: the document's own modes). + pub(crate) modes: BTreeMap, + /// The same modes by collection and mode name, for the message and the report. + pub(crate) mode_labels: BTreeMap, +} + +impl Settings { + pub(crate) fn new(doc: &Document, preset: Option) -> Self { + let config = &doc.design_review; + Self { + preset: preset.unwrap_or(config.preset), + grid: config.grid(), + radii: config.radii.iter().copied().filter(|r| r.is_finite() && (0.0..=999.0).contains(r)).collect(), + brand: config.brand.iter().map(|c| c.to_rgba8()).collect(), + disabled: config.disabled.iter().cloned().collect(), + modes: BTreeMap::new(), + mode_labels: BTreeMap::new(), + } + } + + /// Resolve colours in `modes` (collection and mode ids, already checked against the document). + pub(crate) fn in_modes(mut self, doc: &Document, modes: BTreeMap) -> Self { + for (collection, mode) in &modes { + let Some(c) = doc.variables.collection_by_id(collection) else { continue }; + let Some(m) = c.mode_by_id(mode) else { continue }; + self.mode_labels.insert(c.name.clone(), m.name.clone()); + } + self.modes = modes; + self + } + + /// The mode names for a finding's message, when any are overridden. + fn mode_note(&self) -> String { + self.mode_labels.iter().map(|(c, m)| format!("{c}: {m}")).collect::>().join(", ") + } + + /// Whether a run using these settings reports `id`. + pub(crate) fn enabled(&self, id: &str) -> bool { + !self.disabled.contains(id) && super::rules::enabled(id, self.preset) + } + + fn on_grid(&self, v: f64) -> bool { + v.is_finite() && ((v / self.grid) - (v / self.grid).round()).abs() <= 0.01 + } + + pub(crate) fn snap(&self, v: f64) -> f64 { + if v.is_finite() { ((v / self.grid).round() * self.grid).max(0.0) } else { 0.0 } + } + + pub(crate) fn radius_ok(&self, r: f64, w: f64, h: f64) -> bool { + if !r.is_finite() || r <= 0.01 { + return true; + } + let min = w.min(h); + let pill = min > 0.0 && (r - min / 2.0).abs() <= 1.0; + if pill { + return true; + } + if !self.radii.is_empty() { + return self.radii.iter().any(|a| (r - a).abs() <= 0.5); + } + r >= self.grid && self.on_grid(r) + } + + pub(crate) fn snap_radius(&self, r: f64) -> f64 { + if !r.is_finite() { + return self.grid; + } + if !self.radii.is_empty() { + let mut best = self.grid; + let mut distance = f64::INFINITY; + for a in &self.radii { + let d = (r - a).abs(); + if d < distance { + best = *a; + distance = d; + } + } + return best; + } + ((r / self.grid).round() * self.grid).max(self.grid) + } + + /// Whether `c` is one of the file's brand accents (within a few 8-bit steps per channel). + pub(crate) fn is_brand(&self, c: Color) -> bool { + let rgba = c.to_rgba8(); + self.brand.iter().any(|b| (0..4).all(|i| b[i].abs_diff(rgba[i]) <= 12)) + } + + /// The settings a report or the window shows. + pub(crate) fn json(&self) -> Value { + let mut v = json!({"preset": self.preset.id(), "grid": self.grid}); + if !self.mode_labels.is_empty() + && let Some(o) = v.as_object_mut() + { + o.insert("modes".into(), json!(self.mode_labels)); + } + v + } +} + +/// One finding, owned so `design.fix` can act on it after the walk. +#[derive(Clone)] +pub(crate) struct Finding { + pub(crate) rule: &'static str, + pub(crate) severity: Severity, + pub(crate) node: NodeId, + pub(crate) path: String, + pub(crate) message: String, + pub(crate) fixable: bool, + pub(crate) suggestion: Option, + /// The values behind the message, for a localized line in the window and for agents. + pub(crate) details: Option, + /// Why a finding is not fixable: `"bound"` (owned by a variable or style), `"modes"` (read in + /// the chosen variable modes), `None` (needs a decision). Only for `fixable: false`. + pub(crate) reason: Option<&'static str>, +} + +impl Finding { + fn json(&self) -> Value { + let mut v = json!({ + "rule": self.rule, + "severity": self.severity.id(), + "node": self.node, + "path": self.path, + "message": self.message, + "fixable": self.fixable, + }); + if let (Some(s), Some(o)) = (&self.suggestion, v.as_object_mut()) { + o.insert("suggestion".into(), s.clone()); + } + if let (Some(d), Some(o)) = (&self.details, v.as_object_mut()) { + o.insert("details".into(), d.clone()); + } + if !self.fixable + && let Some(o) = v.as_object_mut() + { + o.insert("reason".into(), json!(self.reason.unwrap_or("decision"))); + } + v + } +} + +/// What one walk found. +pub(crate) struct Report { + pub(crate) findings: Vec, + pub(crate) nodes: usize, + pub(crate) truncated: bool, +} + +/// A colour token's default-mode value, for the hardcoded-value check. +struct TokenColor { + name: String, + rgba: [u8; 4], +} + +/// A number token's default-mode value. +struct TokenNumber { + name: String, + value: f64, +} + +/// The file's variables in their collections' default modes. Layers with explicit modes are left +/// out of the token checks (the default value may not be what they show). +struct Tokens { + colors: Vec, + numbers: Vec, +} + +impl Tokens { + fn new(doc: &Document) -> Self { + if doc.variables.variables.is_empty() { + return Self { colors: Vec::new(), numbers: Vec::new() }; + } + let modes: BTreeMap = + doc.variables.collections.iter().filter_map(|c| c.default_mode().map(|m| (c.id.clone(), m.clone()))).collect(); + let mut colors = Vec::new(); + let mut numbers = Vec::new(); + for var in &doc.variables.variables { + let name = if var.name.is_empty() { var.id.clone() } else { var.name.clone() }; + match doc.variables.resolve(&var.id, &modes) { + Some(VariableValue::Color(c)) if c.a > 0.01 => colors.push(TokenColor { name, rgba: c.to_rgba8() }), + Some(VariableValue::Number(n)) if n.is_finite() && n > 0.01 => numbers.push(TokenNumber { name, value: n }), + _ => {} + } + } + colors.sort_by_key(|c| c.rgba); + colors.dedup_by(|a, b| a.rgba == b.rgba); + numbers.sort_by(|a, b| a.value.total_cmp(&b.value)); + numbers.dedup_by(|a, b| (a.value - b.value).abs() <= 1e-6); + Self { colors, numbers } + } + + fn is_empty(&self) -> bool { + self.colors.is_empty() && self.numbers.is_empty() + } + + fn number(&self, value: f64) -> Option<&TokenNumber> { + self.numbers.iter().find(|t| (t.value - value).abs() <= 1e-6) + } + + fn color(&self, color: Color) -> Option<&TokenColor> { + let rgba = color.to_rgba8(); + self.colors.iter().find(|t| t.rgba == rgba) + } +} + +struct Ctx<'a> { + doc: &'a Document, + findings: Vec, + visited: usize, + text_nodes: usize, + /// Font sizes in half-pixels, so 12.5 stays distinct from 12. + sizes: BTreeSet, + families: BTreeSet, + /// Layers carrying at least one shadow. + shadowed: usize, + /// Text layers laid out for the overflow check. + measured: usize, + /// Auto layout frames measured for clipped children. + measured_frames: usize, + tokens: Tokens, + /// The design system this run checks against. + settings: Settings, + /// Distinct accent colours, with the first layer that paints each (for `color.accents`). + accents: BTreeMap<[u8; 4], String>, + truncated: bool, +} + +/// Walk `roots` and collect every finding. `design.audit` reports them; `design.fix` acts on the +/// ones marked fixable. +pub(crate) fn collect(doc: &Document, roots: &[NodeId], anchor: Option, anchor_path: &str, scope: &str, settings: &Settings) -> Report { + let mut ctx = Ctx { + doc, + findings: Vec::new(), + visited: 0, + text_nodes: 0, + sizes: BTreeSet::new(), + families: BTreeSet::new(), + shadowed: 0, + measured: 0, + measured_frames: 0, + tokens: Tokens::new(doc), + settings: settings.clone(), + accents: BTreeMap::new(), + truncated: false, + }; + for root in roots { + ctx.walk(*root); + } + ctx.scope_rules(anchor, anchor_path, scope); + Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated } +} + +/// Audit `roots` (pages, frames or layers), labelled `scope` in the report. Aggregate findings +/// (too many type sizes…) point at `anchor`. +pub(crate) fn run( + doc: &Document, + roots: &[NodeId], + scope: &str, + anchor: Option, + anchor_path: &str, + min: Severity, + filter: Option<&BTreeSet>, + preset: Option, + modes: BTreeMap, +) -> Value { + let settings = Settings::new(doc, preset).in_modes(doc, modes); + let report = collect(doc, roots, anchor, anchor_path, scope, &settings); + let shown: Vec<&Finding> = report + .findings + .iter() + .filter(|f| f.severity >= min && settings.enabled(f.rule)) + .filter(|f| filter.is_none_or(|set| set.contains(f.rule))) + .collect(); + let mut counts = [0usize; 3]; + for f in &shown { + counts[f.severity.index()] += 1; + } + let score = (100.0 - shown.iter().map(|f| f.severity.penalty()).sum::()).clamp(0.0, 100.0).round(); + let mut by_rule: BTreeMap<&str, usize> = BTreeMap::new(); + for f in &shown { + *by_rule.entry(f.rule).or_default() += 1; + } + let findings: Vec = shown.into_iter().map(Finding::json).collect(); + let mut out = settings.json(); + if let Some(o) = out.as_object_mut() { + o.insert("scope".into(), json!(scope)); + o.insert("score".into(), json!(score)); + o.insert("counts".into(), json!({"high": counts[2], "medium": counts[1], "low": counts[0]})); + o.insert("byRule".into(), json!(by_rule)); + o.insert("nodes".into(), json!(report.nodes)); + o.insert("findings".into(), json!(findings)); + o.insert("truncated".into(), json!(report.truncated)); + } + out +} + +impl Ctx<'_> { + fn walk(&mut self, root: NodeId) { + let mut stack = vec![(root, String::new())]; + while let Some((id, parent)) = stack.pop() { + if self.visited >= MAX_NODES { + self.truncated = true; + return; + } + let Some(n) = self.doc.node(id) else { continue }; + if !n.visible || n.locked || n.opacity <= 0.001 { + continue; + } + self.visited += 1; + let name = label(n); + let path = if parent.is_empty() { name } else { format!("{parent} / {name}") }; + if !n.is_page() { + self.check_node(n, &path); + } + // An instance's children mirror its main component; audit the main where it lives. + if matches!(&n.kind, NodeKind::Instance { .. }) { + continue; + } + for child in n.children.iter().rev() { + stack.push((*child, path.clone())); + } + } + } + + fn check_node(&mut self, n: &Node, path: &str) { + self.check_naming(n, path); + self.check_spacing(n, path); + self.check_radius(n, path); + self.check_paints(n, path); + self.check_effects(n, path); + if let NodeKind::Text(t) = &n.kind { + self.check_text(n, t, path); + } + self.check_layout(n, path); + self.check_clipping(n, path); + self.note_accents(n); + self.check_tokens(n, path); + } + + fn check_naming(&mut self, n: &Node, path: &str) { + if is_default_name(&n.name) { + self.push_details( + "naming.auto", + n.id, + path, + format!("Layer still has its default name \"{}\"", n.name.trim()), + None, + Some(json!({"name": n.name.trim()})), + ); + } + } + + /// A frame or component holding several layers without auto layout: in the Strict preset. + fn check_layout(&mut self, n: &Node, path: &str) { + if n.layout.is_some() || n.children.len() < 3 { + return; + } + if matches!(n.kind, NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. }) { + let count = n.children.len(); + self.push_details( + "layout.no-auto-layout", + n.id, + path, + format!("{count} children with no auto layout"), + None, + Some(json!({"children": count})), + ); + } + } + + /// A fixed-size auto layout frame that clips children which overflow it: the rows exist but + /// are invisible — the usual headless surprise. Hug frames grow, so they cannot clip. + fn check_clipping(&mut self, n: &Node, path: &str) { + if self.measured_frames >= MAX_FRAMES_MEASURED || !n.clip || n.children.is_empty() || n.layout.is_none() { + return; + } + // An instance mirrors its main; the main is audited where it lives. + if matches!(n.kind, NodeKind::Instance { .. }) { + return; + } + let fixed_h = n.child_layout.sizing_h != Sizing::Hug; + let fixed_v = n.child_layout.sizing_v != Sizing::Hug; + if !(fixed_h || fixed_v) { + return; + } + let Some(frame) = self.doc.world_bounds(n.id) else { return }; + let mut u: Option<(f64, f64, f64, f64)> = None; + for child in &n.children { + let Some(c) = self.doc.node(*child) else { continue }; + if !c.visible { + continue; + } + if let Some(b) = self.doc.world_bounds(*child) { + u = Some(match u { + None => (b.x0, b.y0, b.x1, b.y1), + Some((x0, y0, x1, y1)) => (x0.min(b.x0), y0.min(b.y0), x1.max(b.x1), y1.max(b.y1)), + }); + } + } + self.measured_frames += 1; + let Some((ux0, uy0, ux1, uy1)) = u else { return }; + let over_h = fixed_h && (ux1 > frame.x1 + 1.0 || ux0 < frame.x0 - 1.0); + let over_v = fixed_v && (uy1 > frame.y1 + 1.0 || uy0 < frame.y0 - 1.0); + if !(over_h || over_v) { + return; + } + let mut suggestion = Map::new(); + if over_h { + suggestion.insert("sizingH".into(), json!("hug")); + } + if over_v { + suggestion.insert("sizingV".into(), json!("hug")); + } + self.push_details( + "layout.clipped", + n.id, + path, + format!( + "Fixed-size frame clips children that reach {:.0}×{:.0} inside its {:.0}×{:.0}; they are invisible", + ux1 - ux0, + uy1 - uy0, + frame.x1 - frame.x0, + frame.y1 - frame.y0 + ), + Some(Value::Object(suggestion)), + Some(json!({"width": ux1 - ux0, "height": uy1 - uy0, "frameWidth": frame.x1 - frame.x0, "frameHeight": frame.y1 - frame.y0})), + ); + } + + /// Collect the accent colours the scope paints (brand accents and neutrals excluded), for + /// `color.accents`. + fn note_accents(&mut self, n: &Node) { + let paints = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + for p in paints.iter().chain(n.strokes.iter()) { + if !p.visible || p.opacity < 0.5 { + continue; + } + let PaintKind::Solid { color } = &p.kind else { continue }; + if self.settings.is_brand(*color) { + continue; + } + if let Some(rgba) = accent_rgba(*color) + && self.accents.len() < 64 + { + self.accents.entry(rgba).or_insert_with(|| n.name.trim().to_string()); + } + } + } + + fn check_spacing(&mut self, n: &Node, path: &str) { + let Some(al) = &n.layout else { return }; + let mut off = Vec::new(); + let mut suggestion = Map::new(); + if al.mode != LayoutMode::Grid { + if !self.settings.on_grid(al.gap) { + off.push(format!("gap {}", al.gap)); + suggestion.insert("gap".into(), json!(self.settings.snap(al.gap))); + } + if al.wrap && !self.settings.on_grid(al.cross_gap) { + off.push(format!("cross gap {}", al.cross_gap)); + suggestion.insert("crossGap".into(), json!(self.settings.snap(al.cross_gap))); + } + } + let sides = ["top", "right", "bottom", "left"]; + let mut padding_off = false; + for (i, side) in sides.iter().enumerate() { + if let Some(v) = al.padding.get(i).copied().filter(|v| !self.settings.on_grid(*v)) { + off.push(format!("padding {side} {v}")); + padding_off = true; + } + } + if padding_off { + suggestion.insert("padding".into(), json!(al.padding.map(|v| self.settings.snap(v)))); + } + if !off.is_empty() { + let suggestion = if suggestion.is_empty() { None } else { Some(Value::Object(suggestion)) }; + let mut details = Map::new(); + details.insert("grid".into(), json!(self.settings.grid)); + if !self.settings.on_grid(al.gap) { + details.insert("gap".into(), json!(al.gap)); + } + if al.wrap && !self.settings.on_grid(al.cross_gap) { + details.insert("crossGap".into(), json!(al.cross_gap)); + } + if padding_off { + details.insert("padding".into(), json!(al.padding)); + } + self.push_details( + "spacing.off-grid", + n.id, + path, + format!("Off the {}px grid: {}", self.settings.grid, off.join(", ")), + suggestion, + Some(Value::Object(details)), + ); + if [ + "gap", + "columnGap", + "rowGap", + "crossGap", + "padding", + "paddingHorizontal", + "paddingVertical", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + ] + .iter() + .any(|k| n.bound.contains_key(*k)) + { + self.not_fixable(" (bound to a variable)", "bound"); + } + } + } + + fn check_radius(&mut self, n: &Node, path: &str) { + let mut bad: Vec = n.corners.radii.iter().copied().filter(|r| *r > 0.01 && !self.settings.radius_ok(*r, n.width, n.height)).collect(); + if bad.is_empty() { + return; + } + bad.sort_by(f64::total_cmp); + bad.dedup_by(|a, b| (*a - *b).abs() <= 0.01); + let shown: Vec = bad.iter().map(|r| r.to_string()).collect(); + let suggested = self.settings.snap_radius(bad.first().copied().unwrap_or(0.0)); + let suggestion = json!({"cornerRadius": suggested}); + let scale = if self.settings.radii.is_empty() { + format!("any multiple of {}, or a pill", self.settings.grid) + } else { + let list: Vec = self.settings.radii.iter().map(|r| r.to_string()).collect(); + format!("{}, or a pill", list.join(", ")) + }; + self.push_details( + "radius.off-scale", + n.id, + path, + format!("Corner radius off the scale: {} (use {scale})", shown.join(", ")), + Some(suggestion), + Some(json!({"radii": bad, "suggested": suggested})), + ); + if ["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) { + self.not_fixable(" (bound to a variable)", "bound"); + } + } + + fn check_paints(&mut self, n: &Node, path: &str) { + let is_text = matches!(&n.kind, NodeKind::Text(_)); + let fills: &[Paint] = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + let fills_gradient = fills.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))); + let strokes_gradient = n.strokes.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))); + let run_gradient = match &n.kind { + NodeKind::Text(t) => t + .runs + .iter() + .any(|r| r.style.fills.as_ref().is_some_and(|paints| paints.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))))), + _ => false, + }; + if fills_gradient || strokes_gradient || run_gradient { + let id = if is_text { "color.gradient-text" } else { "color.gradient" }; + self.push(id, n.id, path, "Painted with a gradient (a hue-to-hue wash is the usual AI tell)".into(), None); + } + // A hairline border is for container-like shapes; an icon's stroke is its whole drawing, + // so full opacity is the intent there, not a stray border. + let container_like = matches!(&n.kind, NodeKind::Frame | NodeKind::Rectangle | NodeKind::Ellipse { .. } | NodeKind::Component { .. }); + if container_like && has_stroke(n) && border_is_strong(self.doc, n) { + self.push( + "color.border-opacity", + n.id, + path, + "Border is more opaque than a hairline (6–10% is enough)".into(), + Some(json!({"strokeOpacity": 0.08})), + ); + if n.styles.stroke.is_some() || n.bound.keys().any(|k| k.starts_with("strokes/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + } + + fn check_effects(&mut self, n: &Node, path: &str) { + let mut glow = false; + let mut colored = false; + let mut shadows = 0; + for e in n.effects.iter().filter(|e| e.visible) { + if let EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) = &e.kind { + shadows += 1; + glow |= is_glow(e); + colored |= is_colored_shadow(s); + } + } + if shadows > 0 { + self.shadowed += 1; + } + if glow { + self.push( + "color.glow", + n.id, + path, + "Shadow has no offset and a large blur, so it reads as a glow".into(), + Some(json!({"removeEffects": ["dropShadow", "innerShadow"]})), + ); + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + if colored { + self.push( + "color.colored-shadow", + n.id, + path, + "Shadow carries a visible hue; shadows read as depth only when neutral".into(), + Some(json!({"neutralShadow": true})), + ); + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + } + + fn check_text(&mut self, n: &Node, t: &TextData, path: &str) { + let chars = t.characters.trim(); + let s = &t.style; + let size = if s.font_size.is_finite() { s.font_size } else { 0.0 }; + let weight = s.weight(); + // A text style (whole layer or a run) or a variable owns the type; changing it here would + // drift from the style the user chose. + let styled = n.styles.text.is_some() + || s.style_id.is_some() + || t.runs.iter().any(|r| r.style.style_id.is_some()) + || ["fontSize", "fontStyle", "fontWeight", "letterSpacing"].iter().any(|k| n.bound.contains_key(*k)); + if !chars.is_empty() { + self.text_nodes += 1; + count_size(&mut self.sizes, size); + self.families.insert(family_key(&s.font_family)); + } + for run in &t.runs { + if run.end > run.start { + count_size(&mut self.sizes, run.style.font_size); + self.families.insert(family_key(&run.style.font_family)); + } + } + + if size > 0.0 && size < 11.0 && !chars.is_empty() { + self.push_details( + "type.too-small", + n.id, + path, + format!("Body text at {size}px is below the 11px floor"), + None, + Some(json!({"size": size})), + ); + } + if size >= 20.0 && weight > 600 { + self.push_details( + "type.weight", + n.id, + path, + format!("Heading weight {weight} is heavier than a heading needs"), + Some(json!({"fontWeight": 600})), + Some(json!({"weight": weight})), + ); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + if s.italic() && !chars.is_empty() { + self.push("type.italic", n.id, path, "Interface text is italic".into(), Some(json!({"italic": false}))); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + let tracking = s.letter_spacing.resolve(size); + if tracking.is_finite() && tracking < -0.01 && size > 0.0 && size < 24.0 { + self.push_details( + "type.negative-tracking", + n.id, + path, + format!("Small text is tracked {tracking}px tighter; use size or weight instead"), + Some(json!({"letterSpacing": 0})), + Some(json!({"tracking": tracking})), + ); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + + // A run with its own fill makes the text more than one colour; the base fill is not the + // whole story, so the contrast check skips rather than judging the wrong pair. + let mixed_fills = t.runs.iter().any(|r| r.style.fills.is_some()); + self.check_contrast(n, t, path, size, weight, mixed_fills); + + if contains_emoji(&t.characters) || contains_emoji(&n.name) { + self.push("icon.emoji", n.id, path, "Emoji in interface text or a layer name; use a line icon set instead".into(), None); + } + if t.characters.contains('!') || t.characters.contains('!') { + self.push("copy.exclamation", n.id, path, "Copy uses an exclamation mark".into(), Some(json!({"removeExclamations": true}))); + } + if short_label_ends_with_period(chars) { + self.push("copy.trailing-period", n.id, path, "Short label ends with a period".into(), Some(json!({"removeTrailingPeriod": true}))); + } + if has_hype(chars) { + self.push("copy.hype", n.id, path, "Copy uses a hype word (\"AI-powered\", \"supercharge\"…)".into(), None); + } + + // A fixed-width text box whose stored height is shorter than the laid-out text clips or + // overlaps what follows it. Truncating boxes and auto-width boxes are intentional. + if !chars.is_empty() + && n.width > 0.0 + && self.measured < MAX_TEXT_MEASURED + && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) + { + self.measured += 1; + let needed = figcraft_text::layout_cached(t, Some(n.width), None).height; + if needed.is_finite() && needed > n.height + 1.0 { + self.push_details( + "layout.text-overflow", + n.id, + path, + format!("Text needs {needed:.0}px of height but its box is {:.0}px; it clips or overlaps", n.height), + None, + Some(json!({"needed": needed, "height": n.height})), + ); + } + } + } + + /// WCAG contrast for single-colour text, in the run's variable modes when any were given. + fn check_contrast(&mut self, n: &Node, t: &TextData, path: &str, size: f64, weight: u16, mixed_fills: bool) { + if mixed_fills { + return; + } + let (fg, bg) = if self.settings.modes.is_empty() { + (text_color(n, t), backdrop(self.doc, n)) + } else { + (text_color_in(self.doc, n, t, &self.settings.modes), backdrop_in(self.doc, n, Some(&self.settings.modes))) + }; + let (Some(fg), Some(bg)) = (fg, bg) else { return }; + let ratio = fg.contrast(bg); + if !ratio.is_finite() { + return; + } + let large = size >= 24.0 || (size >= 18.0 && weight >= 700); + let need = if large { 3.0 } else { 4.5 }; + if ratio >= need { + return; + } + let mode_note = if self.settings.mode_labels.is_empty() { String::new() } else { format!(" in {}", self.settings.mode_note()) }; + let mut details = json!({"ratio": ratio, "needed": need, "foreground": fg.to_hex(), "background": bg.to_hex()}); + if !self.settings.mode_labels.is_empty() + && let Some(o) = details.as_object_mut() + { + o.insert("modes".into(), json!(self.settings.mode_labels)); + } + self.push_details( + "color.contrast", + n.id, + path, + format!("Contrast {ratio:.2}:1, needs {need:.2}:1 ({} on {}){mode_note}", fg.to_hex(), bg.to_hex()), + None, + Some(details), + ); + if !self.settings.modes.is_empty() { + self.not_fixable(" (read in the chosen variable modes)", "modes"); + } else if n.styles.fill.is_some() || n.bound.keys().any(|k| k.starts_with("fills/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + + fn check_tokens(&mut self, n: &Node, path: &str) { + if self.tokens.is_empty() || !n.var_modes.is_empty() { + return; + } + // Colours: a solid paint that is exactly a colour variable's default value, unbound and + // not styled, is a hardcoded token. + let mut hits: Vec<(&str, String, String)> = Vec::new(); + let is_text = matches!(&n.kind, NodeKind::Text(_)); + let fills: &[Paint] = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + if n.styles.fill.is_none() { + for (i, p) in fills.iter().enumerate() { + if !p.visible || paint_binding_key(n, true, i).is_some() { + continue; + } + let Some(c) = p.solid_color() else { continue }; + if let Some(tok) = self.tokens.color(c) { + hits.push((if is_text { "text" } else { "fill" }, c.to_hex(), tok.name.clone())); + } + } + } + if n.styles.stroke.is_none() { + for (i, p) in n.strokes.iter().enumerate() { + if !p.visible || paint_binding_key(n, false, i).is_some() { + continue; + } + let Some(c) = p.solid_color() else { continue }; + if let Some(tok) = self.tokens.color(c) { + hits.push(("stroke", c.to_hex(), tok.name.clone())); + } + } + } + if !hits.is_empty() { + hits.sort(); + hits.dedup(); + let shown: Vec = hits.iter().map(|(kind, hex, token)| format!("{kind} #{hex} = \"{token}\"")).collect(); + let details: Vec = + hits.iter().map(|(kind, hex, token)| json!({"kind": kind, "color": format!("#{hex}"), "token": token})).collect(); + self.push_details( + "token.hardcoded-color", + n.id, + path, + format!("Matches a variable but is not bound: {}", shown.join(", ")), + None, + Some(json!({"hits": details})), + ); + } + + // Numbers: spacing, radii, a text size and opacity. + let mut hits: Vec<(String, f64, String)> = Vec::new(); + { + let mut check = |value: f64, field: &str| { + if value.is_finite() + && value > 0.01 + && let Some(tok) = self.tokens.number(value) + { + hits.push((field.to_string(), value, tok.name.clone())); + } + }; + if let Some(al) = &n.layout { + if al.mode != LayoutMode::Grid && !n.bound.contains_key("gap") { + check(al.gap, "gap"); + } + if al.wrap && !n.bound.contains_key("crossGap") { + check(al.cross_gap, "crossGap"); + } + let keys = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"]; + for (i, key) in keys.iter().enumerate() { + if !n.bound.contains_key(*key) + && let Some(v) = al.padding.get(i).copied() + { + check(v, key); + } + } + } + if !["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) + { + for r in n.corners.radii { + check(r, "cornerRadius"); + } + } + if let NodeKind::Text(t) = &n.kind { + let styled = n.styles.text.is_some() || t.style.style_id.is_some() || t.runs.iter().any(|r| r.style.style_id.is_some()); + if !styled && !n.bound.contains_key("fontSize") { + check(t.style.font_size, "fontSize"); + } + } + if n.opacity < 0.99 && !n.bound.contains_key("opacity") { + check(f64::from(n.opacity), "opacity"); + } + } + if !hits.is_empty() { + hits.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.total_cmp(&b.1))); + hits.dedup_by(|a, b| a.0 == b.0 && (a.1 - b.1).abs() <= 1e-6); + let shown: Vec = hits.iter().map(|(field, value, token)| format!("{field} {value} = \"{token}\"")).collect(); + let details: Vec = hits.iter().map(|(field, value, token)| json!({"field": field, "value": value, "token": token})).collect(); + self.push_details( + "token.hardcoded-number", + n.id, + path, + format!("Matches a variable but is not bound: {}", shown.join(", ")), + None, + Some(json!({"hits": details})), + ); + } + } + + fn scope_rules(&mut self, anchor: Option, path: &str, scope: &str) { + let Some(node) = anchor else { return }; + if self.text_nodes >= 8 { + if self.sizes.len() > 5 { + let sizes: Vec = self.sizes.iter().map(|v| trim_half(*v)).collect(); + self.push_details( + "type.sizes", + node, + path, + format!("{} font sizes in this {scope}: {}", sizes.len(), sizes.join(", ")), + None, + Some(json!({"sizes": sizes, "count": sizes.len()})), + ); + } + if self.families.len() > 2 { + let families: Vec<&str> = self.families.iter().map(String::as_str).collect(); + self.push_details( + "type.families", + node, + path, + format!("{} font families in this {scope}: {}", families.len(), families.join(", ")), + None, + Some(json!({"families": families, "count": families.len()})), + ); + } + } + if self.visited >= 20 && self.shadowed > 5 && self.shadowed * 5 > self.visited { + self.push_details( + "detail.shadow-count", + node, + path, + format!("{} of {} layers carry a shadow or blur", self.shadowed, self.visited), + None, + Some(json!({"shadowed": self.shadowed, "nodes": self.visited})), + ); + } + if self.accents.len() > 2 { + let colors: Vec = self.accents.keys().take(6).map(|c| format!("#{:02X}{:02X}{:02X}", c[0], c[1], c[2])).collect(); + self.push_details( + "color.accents", + node, + path, + format!("{} accent colours in this {scope}: {} (keep two)", self.accents.len(), colors.join(", ")), + None, + Some(json!({"count": self.accents.len(), "colors": colors})), + ); + } + } + + fn push(&mut self, id: &'static str, node: NodeId, path: &str, message: String, suggestion: Option) { + self.push_details(id, node, path, message, suggestion, None); + } + + /// A finding whose message has values, with those values in `details` too. + fn push_details(&mut self, id: &'static str, node: NodeId, path: &str, message: String, suggestion: Option, details: Option) { + let Some(r) = rule(id) else { return }; + self.findings.push(Finding { + rule: r.id, + severity: r.severity, + node, + path: path.to_string(), + message, + fixable: r.fixable, + suggestion, + details, + reason: None, + }); + } + + /// Mark the finding just pushed as not auto-fixable, with the reason in its message and as a + /// machine code for the window (`"bound"`: owned by a variable or style; `"modes"`: read in + /// the chosen variable modes). + fn not_fixable(&mut self, note: &str, reason: &'static str) { + if let Some(f) = self.findings.last_mut() { + f.fixable = false; + f.message.push_str(note); + f.reason = Some(reason); + } + } +} + +/// The layer's name, or a stand-in when it has none; long names are cut so paths stay readable. +fn label(n: &Node) -> String { + let name = n.name.trim(); + if name.is_empty() { + return format!("{} {}", n.kind.type_name(), n.id.0); + } + let mut chars = name.chars(); + let short: String = chars.by_ref().take(60).collect(); + if chars.next().is_some() { format!("{short}…") } else { short } +} + +/// A colour that reads as an accent: enough chroma to be a hue rather than a neutral, and neither +/// near-black nor near-white. +fn accent_rgba(c: Color) -> Option<[u8; 4]> { + if !c.a.is_finite() || c.a < 0.5 { + return None; + } + let max = c.r.max(c.g).max(c.b); + let min = c.r.min(c.g).min(c.b); + (max - min >= 0.18 && max >= 0.2 && min <= 0.88).then(|| c.to_rgba8()) +} + +fn has_stroke(n: &Node) -> bool { + n.stroke.weight > 0.01 || n.stroke.sides.is_some_and(|s| s.iter().any(|w| *w > 0.01)) +} + +/// Whether a stroke reads as a strong border rather than a hairline: its colour blended over what +/// is behind it, compared with that backdrop. With no known backdrop, the paint's alpha decides. +fn border_is_strong(doc: &Document, n: &Node) -> bool { + let Some(p) = n.strokes.iter().rev().find(|p| p.visible) else { return false }; + if p.blend != BlendMode::Normal { + return false; + } + let Some(c) = p.solid_color() else { return p.opacity > 0.12 }; + // An inside stroke sits on the layer's own fill; centre and outside strokes sit on what is + // behind it. Default strokes are inside, so a border on a dark panel is judged on that panel. + let bg = if n.stroke.align == StrokeAlign::Inside { solid_fill(n).or_else(|| backdrop(doc, n)) } else { backdrop(doc, n) }; + match bg { + Some(bg) => blend(c, bg).contrast(bg) > 1.5, + None => c.a > 0.12, + } +} + +fn blend(fg: Color, bg: Color) -> Color { + let a = fg.a; + Color::new(fg.r * a + bg.r * (1.0 - a), fg.g * a + bg.g * (1.0 - a), fg.b * a + bg.b * (1.0 - a), 1.0) +} + +fn chroma(c: Color) -> f32 { + let [r, g, b, _] = c.to_rgba8(); + let (max, min) = (r.max(g).max(b) as f32, r.min(g).min(b) as f32); + (max - min) / 255.0 +} + +/// A shadow with no offset and a large blur: it lights the layer instead of giving it depth. +pub(crate) fn is_glow(e: &Effect) -> bool { + if !e.visible { + return false; + } + match &e.kind { + EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) => { + s.offset.0.abs() <= 1.0 && s.offset.1.abs() <= 1.0 && s.radius >= 8.0 && s.color.a > 0.05 + } + _ => false, + } +} + +/// A shadow whose colour carries a visible hue. +pub(crate) fn is_colored_shadow(s: &Shadow) -> bool { + chroma(s.color) > 0.12 && s.color.a > 0.05 +} + +/// The topmost visible solid paint, if it is opaque enough to know what shows through it. +fn solid_fill(n: &Node) -> Option { + let p = n.fills.iter().rev().find(|p| p.visible)?; + // A blend mode changes what the colour looks like over what is behind it; do not guess. + if !matches!(n.blend, BlendMode::Normal | BlendMode::PassThrough) || p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + match &p.kind { + PaintKind::Solid { color } if color.a >= 0.95 => Some(*color), + _ => None, + } +} + +/// The colour a text layer's characters show in, when it is a single opaque solid paint. +pub(crate) fn text_color(n: &Node, t: &TextData) -> Option { + let paints = t.style.fills.as_deref().unwrap_or(&n.fills); + let p = paints.iter().rev().find(|p| p.visible)?; + if p.blend != BlendMode::Normal { + return None; + } + if p.opacity < 0.95 { + return None; + } + match &p.kind { + PaintKind::Solid { color } if color.a >= 0.95 => Some(*color), + _ => None, + } +} + +/// `base`, resolved in the layer's variable modes (with `overrides` on top) when the paint's colour +/// is bound to a colour variable. +fn bound_color(doc: &Document, n: &Node, fills: bool, index: usize, base: Color, overrides: &BTreeMap) -> Color { + let Some(key) = paint_binding_key(n, fills, index) else { return base }; + let Some(id) = n.bound.get(key) else { return base }; + let mut modes = doc.modes_for(n.id); + modes.extend(overrides.iter().map(|(c, m)| (c.clone(), m.clone()))); + match doc.variables.resolve(id, &modes) { + Some(VariableValue::Color(c)) => c, + _ => base, + } +} + +/// [`solid_fill`], with bound colours resolved in `overrides` (the layer's own modes first). +fn solid_fill_in(doc: &Document, n: &Node, overrides: &BTreeMap) -> Option { + let index = n.fills.iter().rposition(|p| p.visible)?; + let p = n.fills.get(index)?; + if !matches!(n.blend, BlendMode::Normal | BlendMode::PassThrough) || p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + let PaintKind::Solid { color } = &p.kind else { return None }; + if color.a < 0.95 { + return None; + } + let color = bound_color(doc, n, true, index, *color, overrides); + (color.a >= 0.95).then_some(color) +} + +/// [`text_color`], with bound colours resolved in `overrides`. +fn text_color_in(doc: &Document, n: &Node, t: &TextData, overrides: &BTreeMap) -> Option { + let paints = t.style.fills.as_deref().unwrap_or(&n.fills); + let (index, p) = paints.iter().enumerate().rev().find(|(_, p)| p.visible)?; + if p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + let PaintKind::Solid { color } = &p.kind else { return None }; + if color.a < 0.95 { + return None; + } + let color = bound_color(doc, n, true, index, *color, overrides); + (color.a >= 0.95).then_some(color) +} + +/// What lies directly behind a layer, or why it cannot be sampled. +enum Behind { + Known(Color), + /// A gradient, image, translucency or partial cover: the audit does not guess. + Unknown, +} + +/// The first opaque solid behind a layer. At each ancestor level, look at the siblings painted +/// below it (z-order, `reverse_z` respected) for the topmost one that covers it, then at that +/// ancestor's own fill. The old version only walked ancestors, so white text on a dark rectangle +/// sibling was compared with the page behind both and reported as unreadable. +pub(crate) fn backdrop(doc: &Document, n: &Node) -> Option { + backdrop_in(doc, n, None) +} + +/// [`backdrop`], resolving bound colours in `overrides` when given. +fn backdrop_in(doc: &Document, n: &Node, overrides: Option<&BTreeMap>) -> Option { + let target = doc.world_bounds(n.id)?; + let mut current = n.id; + for _ in 0..256 { + let node = doc.node(current)?; + let parent_id = node.parent?; + let parent = doc.node(parent_id)?; + if parent.opacity < 0.99 { + return None; + } + match sibling_behind(doc, parent, current, target, overrides) { + Some(Behind::Known(c)) => return Some(c), + Some(Behind::Unknown) => return None, + None => {} + } + if let NodeKind::Page { background, .. } = &parent.kind { + return if background.a >= 0.95 { Some(*background) } else { None }; + } + if parent.fills.iter().any(|p| p.visible) { + return match overrides { + Some(modes) => solid_fill_in(doc, parent, modes), + None => solid_fill(parent), + }; + } + current = parent_id; + } + None +} + +/// The topmost sibling painted below `current` that covers `target`, if it has visible paint. +fn sibling_behind( + doc: &Document, + parent: &Node, + current: NodeId, + target: figcraft_geom::Rect, + overrides: Option<&BTreeMap>, +) -> Option { + let index = parent.children.iter().position(|c| *c == current)?; + let reverse = parent.layout.as_ref().is_some_and(|l| l.reverse_z); + // Last child on top: siblings before `index` are below it. First on top: siblings after are. + let total = if reverse { parent.children.len().saturating_sub(index + 1) } else { index }; + let order: Box> = if reverse { Box::new(index + 1..parent.children.len()) } else { Box::new((0..index).rev()) }; + for i in order.take(MAX_BACKDROP_SCAN) { + let Some(sibling) = parent.children.get(i).and_then(|id| doc.node(*id)) else { continue }; + if let Some(behind) = paint_behind(doc, sibling, target, 1, overrides) { + return Some(behind); + } + } + // Past the cap the topmost paint is unknown, not the page behind the container. + (total > MAX_BACKDROP_SCAN).then_some(Behind::Unknown) +} + +/// The topmost paint a layer (and what it contains) puts under `target`: its children first (they +/// paint above its fill), then its own fill. Text and lines paint glyphs or a stroke, not a +/// background; a container without a fill is entered so a background rectangle inside a group is +/// found too. Clipped children outside the frame are left out. +fn paint_behind( + doc: &Document, + node: &Node, + target: figcraft_geom::Rect, + depth: usize, + overrides: Option<&BTreeMap>, +) -> Option { + if depth > 64 || !node.visible { + return None; + } + let bounds = doc.world_bounds(node.id); + let clipped_away = node.clip && bounds.is_some_and(|b| !contains(b, target)); + if !clipped_away { + let reverse = node.layout.as_ref().is_some_and(|l| l.reverse_z); + let order: Box> = + if reverse { Box::new(0..node.children.len()) } else { Box::new((0..node.children.len()).rev()) }; + for i in order.take(MAX_BACKDROP_SCAN) { + let Some(child) = node.children.get(i).and_then(|id| doc.node(*id)) else { continue }; + if let Some(behind) = paint_behind(doc, child, target, depth + 1, overrides) { + return Some(behind); + } + } + if node.children.len() > MAX_BACKDROP_SCAN { + return Some(Behind::Unknown); + } + } + if matches!(&node.kind, NodeKind::Text(_) | NodeKind::Line) || !node.fills.iter().any(|p| p.visible) { + return None; + } + let b = bounds?; + if !overlaps(b, target) { + return None; + } + if !contains(b, target) || node.opacity < 0.99 { + return Some(Behind::Unknown); + } + let color = match overrides { + Some(modes) => solid_fill_in(doc, node, modes), + None => solid_fill(node), + }; + Some(match color { + Some(c) => Behind::Known(c), + None => Behind::Unknown, + }) +} + +fn overlaps(b: figcraft_geom::Rect, target: figcraft_geom::Rect) -> bool { + b.x0 < target.x1 && target.x0 < b.x1 && b.y0 < target.y1 && target.y0 < b.y1 +} + +fn contains(b: figcraft_geom::Rect, target: figcraft_geom::Rect) -> bool { + b.x0 <= target.x0 && b.y0 <= target.y0 && b.x1 >= target.x1 && b.y1 >= target.y1 +} + +fn count_size(sizes: &mut BTreeSet, size: f64) { + if size.is_finite() && size > 0.0 { + sizes.insert((size * 2.0).round() as i64); + } +} + +fn trim_half(v: i64) -> String { + let n = v as f64 / 2.0; + if (n - n.round()).abs() < 0.01 { format!("{}", n.round() as i64) } else { format!("{n}") } +} + +fn family_key(family: &str) -> String { + let f = family.trim().to_ascii_lowercase(); + if f.is_empty() { "inter".into() } else { f } +} + +fn contains_emoji(s: &str) -> bool { + s.chars().any(|c| { + let u = c as u32; + (0x1F000..=0x1FAFF).contains(&u) || (0x2600..=0x27BF).contains(&u) || matches!(u, 0x2B50 | 0x2B55 | 0x203C | 0x2049) + }) +} + +fn short_label_ends_with_period(s: &str) -> bool { + let s = s.trim_end(); + let body = s.trim_end_matches(['.', '。']).trim_end(); + if body == s || body.is_empty() { + return false; + } + !body.contains('\n') && !body.contains(". ") && body.chars().count() <= 24 +} + +fn has_hype(s: &str) -> bool { + let s = s.to_ascii_lowercase(); + ["ai-powered", "supercharge", "revolutioniz", "game-chang", "unleash the"].iter().any(|w| s.contains(w)) +} + +fn is_default_name(name: &str) -> bool { + let Some((word, number)) = name.trim().rsplit_once(' ') else { return false }; + const KINDS: [&str; 13] = + ["Frame", "Rectangle", "Ellipse", "Group", "Text", "Component", "Section", "Vector", "Line", "Polygon", "Star", "Slice", "Boolean"]; + KINDS.contains(&word) && !number.is_empty() && number.chars().all(|c| c.is_ascii_digit()) +} diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs new file mode 100644 index 000000000..e6a5e6d7e --- /dev/null +++ b/crates/engine/src/design/fix.rs @@ -0,0 +1,319 @@ +//! `design.fix`: repair the findings `design.audit` marks fixable, as one undo step. +//! +//! Every repair is the safe, unambiguous one the audit already suggested: spacing snapped to the +//! 4px grid, radii to the scale, heavy headings to Semi Bold, italic and negative tracking removed, +//! glows taken out, shadow colours neutralised and strong borders thinned. Content rules (copy, +//! naming) and gradients are left alone: those need a decision, not arithmetic. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{Color, PaintKind}; +use figcraft_doc::{DesignPreset, Document, EffectKind, LayoutMode, LetterSpacing, Node, NodeId, NodeKind, TextData, TextStyle}; +use serde_json::{Value, json}; + +use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color}; + +/// Fix what `roots` made fixable among `filter`'s rules. With `exact`, only findings on the roots +/// themselves are repaired, not findings on their descendants. `dry_run` reports the same counts +/// without changing the document. +pub(crate) fn run( + doc: &mut Document, + roots: &[NodeId], + anchor: Option, + anchor_path: &str, + scope: &str, + preset: Option, + filter: Option<&BTreeSet>, + exact: bool, + dry_run: bool, +) -> Value { + let settings = Settings::new(doc, preset); + let before = collect(doc, roots, anchor, anchor_path, scope, &settings); + let targets: Vec<(NodeId, &'static str)> = before + .findings + .iter() + .filter(|f| f.fixable && settings.enabled(f.rule)) + .filter(|f| filter.is_none_or(|set| set.contains(f.rule))) + .filter(|f| !exact || roots.contains(&f.node)) + .map(|f| (f.node, f.rule)) + .collect(); + let mut by_rule: BTreeMap<&'static str, usize> = BTreeMap::new(); + let mut changed = 0usize; + let mut skipped = 0usize; + if dry_run { + changed = targets.len(); + for (_, rule) in &targets { + *by_rule.entry(*rule).or_default() += 1; + } + } else { + for (id, rule) in &targets { + match apply(doc, *id, rule, &settings) { + Some(true) => { + changed += 1; + *by_rule.entry(*rule).or_default() += 1; + } + _ => skipped += 1, + } + } + } + let after = collect(doc, roots, anchor, anchor_path, scope, &settings); + json!({ + "scope": scope, + "dryRun": dry_run, + "changed": changed, + "skipped": skipped, + "byRule": by_rule, + "before": tally(&before, &settings), + "after": tally(&after, &settings), + }) +} + +fn tally(report: &Report, settings: &Settings) -> Value { + let shown: Vec<&super::audit::Finding> = report.findings.iter().filter(|f| settings.enabled(f.rule)).collect(); + let mut counts = [0usize; 3]; + for f in &shown { + counts[f.severity.index()] += 1; + } + let score = (100.0 - shown.iter().map(|f| f.severity.penalty()).sum::()).clamp(0.0, 100.0).round(); + json!({ + "score": score, + "counts": {"high": counts[2], "medium": counts[1], "low": counts[0]}, + "nodes": report.nodes, + "findings": shown.len(), + }) +} + +/// Apply one finding's repair. `None` when the layer is gone or the repair does not apply to it; +/// `Some(false)` when it applied to nothing (a no-op the caller counts as skipped). +fn apply(doc: &mut Document, id: NodeId, rule: &str, settings: &Settings) -> Option { + if rule == "color.contrast" { + return apply_contrast(doc, id); + } + let n = doc.node_mut(id)?; + match rule { + "spacing.off-grid" => apply_spacing(n, settings), + "radius.off-scale" => { + if ["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) { + return Some(false); + } + apply_radius(n, settings) + } + "type.weight" | "type.italic" | "type.negative-tracking" => { + if text_styled(n) || ["fontSize", "fontStyle", "fontWeight", "letterSpacing"].iter().any(|k| n.bound.contains_key(*k)) { + return Some(false); + } + match rule { + "type.weight" => apply_text(n, cap_weight), + "type.italic" => apply_text(n, unitalic), + _ => apply_text(n, zero_tracking), + } + } + "color.glow" | "color.colored-shadow" => { + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + return Some(false); + } + if rule == "color.glow" { apply_glow(n) } else { apply_neutral_shadows(n) } + } + "color.border-opacity" => { + if n.styles.stroke.is_some() || n.bound.keys().any(|k| k.starts_with("strokes/")) { + return Some(false); + } + apply_border(n) + } + _ => Some(false), + } +} + +/// A text layer whose type comes from a text style (the whole layer or one run). +fn text_styled(n: &Node) -> bool { + match &n.kind { + NodeKind::Text(t) => n.styles.text.is_some() || t.style.style_id.is_some() || t.runs.iter().any(|r| r.style.style_id.is_some()), + _ => false, + } +} + +/// Darken (or lighten, on a dark backdrop) the text colour until it reaches the WCAG ratio. The +/// hue is kept as far as the blend allows; when even black or white cannot reach the ratio, the +/// text is left as it is and counted as skipped. +fn apply_contrast(doc: &mut Document, id: NodeId) -> Option { + let n = doc.node(id)?; + let NodeKind::Text(t) = &n.kind else { return Some(false) }; + if n.styles.fill.is_some() || n.bound.keys().any(|k| k.starts_with("fills/")) { + return Some(false); + } + let fg = text_color(n, t)?; + let bg = backdrop(doc, n)?; + let size = t.style.font_size; + let large = size >= 24.0 || (size >= 18.0 && t.style.weight() >= 700); + let need = if large { 3.0 } else { 4.5 }; + if fg.contrast(bg) >= need { + return Some(false); + } + let fixed = accessible(fg, bg, need); + if fixed.contrast(bg) < need { + return Some(false); + } + let n = doc.node_mut(id)?; + let NodeKind::Text(t) = &mut n.kind else { return Some(false) }; + let paints = match &mut t.style.fills { + Some(fills) => fills, + None => &mut n.fills, + }; + let paint = paints.iter_mut().rev().find(|p| p.visible && matches!(&p.kind, PaintKind::Solid { .. }))?; + paint.opacity = 1.0; + if let PaintKind::Solid { color } = &mut paint.kind { + *color = fixed.with_alpha(fg.a); + Some(true) + } else { + Some(false) + } +} + +/// The closest shade of `fg` towards black (light backdrop) or white (dark backdrop) that meets +/// `need` against `bg`, by bisection. +fn accessible(fg: Color, bg: Color, need: f32) -> Color { + let target = if bg.luminance() > 0.5 { Color::BLACK } else { Color::WHITE }; + let (mut lo, mut hi) = (0.0f32, 1.0f32); + let mut best = target; + for _ in 0..24 { + let t = (lo + hi) / 2.0; + let c = Color::new(fg.r + (target.r - fg.r) * t, fg.g + (target.g - fg.g) * t, fg.b + (target.b - fg.b) * t, 1.0); + if c.contrast(bg) >= need { + best = c; + hi = t; + } else { + lo = t; + } + } + best +} + +fn apply_spacing(n: &mut Node, settings: &Settings) -> Option { + // Any spacing binding owns the whole layout value: fixing one field next to a token would + // leave a mixed layout and is not what the audit promised. + if [ + "gap", + "columnGap", + "rowGap", + "crossGap", + "padding", + "paddingHorizontal", + "paddingVertical", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + ] + .iter() + .any(|k| n.bound.contains_key(*k)) + { + return Some(false); + } + let al = n.layout.as_mut()?; + let mut changed = false; + if al.mode != LayoutMode::Grid { + let gap = settings.snap(al.gap); + if (gap - al.gap).abs() > 1e-6 { + al.gap = gap; + changed = true; + } + if al.wrap { + let cross = settings.snap(al.cross_gap); + if (cross - al.cross_gap).abs() > 1e-6 { + al.cross_gap = cross; + changed = true; + } + } + } + for side in &mut al.padding { + let value = settings.snap(*side); + if (value - *side).abs() > 1e-6 { + *side = value; + changed = true; + } + } + Some(changed) +} + +fn apply_radius(n: &mut Node, settings: &Settings) -> Option { + let (w, h) = (n.width, n.height); + let pill = w.min(h); + let mut changed = false; + for r in &mut n.corners.radii { + if *r > 0.01 && !settings.radius_ok(*r, w, h) { + *r = if pill > 0.0 && (*r - pill / 2.0).abs() <= 1.0 { pill / 2.0 } else { settings.snap_radius(*r) }; + changed = true; + } + } + Some(changed) +} + +/// Run `f` over a text layer's base style and its runs; true when any style changed. +fn apply_text(n: &mut Node, f: fn(&mut TextStyle) -> bool) -> Option { + let NodeKind::Text(t) = &mut n.kind else { return Some(false) }; + let TextData { style, runs, .. } = t; + let mut changed = f(style); + for run in runs { + changed |= f(&mut run.style); + } + Some(changed) +} + +fn cap_weight(s: &mut TextStyle) -> bool { + if s.font_size >= 20.0 && s.weight() > 600 { + s.set_font_style("Semi Bold"); + true + } else { + false + } +} + +fn unitalic(s: &mut TextStyle) -> bool { + if !s.italic() { + return false; + } + let words: Vec<&str> = s.font_style.split_whitespace().filter(|w| !w.eq_ignore_ascii_case("italic")).collect(); + let name = if words.is_empty() { "Regular".to_string() } else { words.join(" ") }; + s.set_font_style(name); + true +} + +fn zero_tracking(s: &mut TextStyle) -> bool { + let px = s.letter_spacing.resolve(s.font_size); + if s.font_size > 0.0 && s.font_size < 24.0 && px.is_finite() && px < -0.01 { + s.letter_spacing = LetterSpacing::Percent(0.0); + true + } else { + false + } +} + +fn apply_glow(n: &mut Node) -> Option { + let before = n.effects.len(); + n.effects.retain(|e| !is_glow(e)); + Some(n.effects.len() != before) +} + +fn apply_neutral_shadows(n: &mut Node) -> Option { + let mut changed = false; + for e in &mut n.effects { + if let EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) = &mut e.kind + && is_colored_shadow(s) + { + s.color = Color::new(0.0, 0.0, 0.0, s.color.a); + changed = true; + } + } + Some(changed) +} + +fn apply_border(n: &mut Node) -> Option { + let mut changed = false; + for p in &mut n.strokes { + if p.visible && p.opacity > 0.08 { + p.opacity = 0.08; + changed = true; + } + } + Some(changed) +} diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs new file mode 100644 index 000000000..7e8229323 --- /dev/null +++ b/crates/engine/src/design/mod.rs @@ -0,0 +1,378 @@ +//! Design review: deterministic checks for the usual AI-generated interface tells. +//! +//! `design.audit` reads a selection, a page or the whole document and reports what a designer +//! would fix first — spacing off the 4px grid, radii outside the scale, too many type sizes, +//! gradient text, glows, low-contrast text, emoji labels. It changes nothing. `design.fix` (the +//! planned follow-up) repairs the findings marked `fixable`. +//! +//! The rules are our own reading of the public "unslop" checklist (CC BY 4.0, heydamir/unslop): +//! only the ideas, no text or assets from it. + +mod audit; +mod fix; +mod rules; + +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_doc::{CollectionId, DesignPreset, DesignReview, Document, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII, ModeId, NodeId}; +use serde_json::{Value, json}; + +use crate::cmd::CommandSpec; +use crate::params; +use crate::{EngineError, Result, Session, bad, spec}; +use rules::{RULES, Severity, presets_of, rule}; + +pub fn specs() -> Vec { + vec![ + spec!( + "design.audit", + "Check design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", + false, + audit_cmd + ), + spec!( + "design.fix", + "Fix design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone", + true, + fix_cmd + ), + spec!( + "design.assert", + "Assert design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists or the score is below minScore; read-only, for CI", + false, + assert_cmd + ), + spec!( + "design.configure", + "Configure design review", + "{preset?: recommended|strict|accessibility, grid?: 1-64 (px, default 4), radii?: [px] (empty: the grid scale and a pill), brand?: [colour] (accent colours the file owns), disabled?: [rule ids] (rules off in this file), reset?: bool} → {preset, grid, radii, brand, disabled} changes the file's design review settings in one undo step; audit, fix and assert use them from then on", + true, + configure_cmd + ), + spec!( + "design.rules", + "List design rules", + "{} → {rules: [{id, severity, fixable, description, presets}], presets: [{id, description}]}", + false, + |_, _| Ok(json!({ + "rules": RULES.iter().map(|r| json!({ + "id": r.id, + "severity": r.severity.id(), + "fixable": r.fixable, + "description": r.description, + "presets": presets_of(r.id), + })).collect::>(), + "presets": DesignPreset::ALL.iter().map(|p| json!({ + "id": p.id(), + "description": preset_description(*p), + })).collect::>(), + })) + ), + ] +} + +fn audit_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.audit", p)?; + let min = severity_arg("design.audit", p)?; + let filter = filter_arg("design.audit", p)?; + let preset = preset_arg("design.audit", p)?; + let modes = modes_arg("design.audit", p, s.doc()?)?; + Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes)) +} + +fn fix_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.fix", p)?; + let filter = filter_arg("design.fix", p)?; + let preset = preset_arg("design.fix", p)?; + let exact = params::boolean(p, "exact").unwrap_or(false); + let dry = params::boolean(p, "dryRun").unwrap_or(false); + Ok(fix::run(s.doc_mut()?, &roots, anchor, &path, &label, preset, filter.as_ref(), exact, dry)) +} + +/// `design.assert`: a read-only gate for CI. Returns the score when the design passes; an error +/// that names the counts when it does not. +fn assert_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.assert", p)?; + let filter = filter_arg("design.assert", p)?; + let fail_on = severity_named("design.assert", p, "failOn", Severity::High)?; + let preset = preset_arg("design.assert", p)?; + let modes = modes_arg("design.assert", p, s.doc()?)?; + let min_score = match params::get(p, "minScore") { + None => 0.0, + Some(v) => match params::f64_of(v) { + Some(v) if (0.0..=100.0).contains(&v) => v, + _ => return Err(bad("design.assert", "`minScore` must be a number between 0 and 100")), + }, + }; + // The score covers the whole review (as the window shows it); only findings at or above + // `failOn` fail the gate. + let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes); + let failing: Vec<&Value> = report["findings"] + .as_array() + .map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect()) + .unwrap_or_default(); + let score = report["score"].as_f64().unwrap_or(0.0); + if !failing.is_empty() || score < min_score { + let mut by_rule: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); + for f in &failing { + if let Some(rule) = f["rule"].as_str() { + *by_rule.entry(rule).or_default() += 1; + } + } + let rules: Vec = by_rule.iter().take(4).map(|(rule, count)| format!("{rule} ×{count}")).collect(); + let detail = if rules.is_empty() { String::new() } else { format!(" ({})", rules.join(", ")) }; + return Err(EngineError::Other(format!( + "design review failed: score {score:.0}, {} finding(s) at {} or above{detail}", + failing.len(), + fail_on.id() + ))); + } + Ok(json!({"ok": true, "score": score, "counts": report["counts"]})) +} + +fn severity_named(cmd: &str, p: &Value, key: &str, default: Severity) -> Result { + match params::string(p, key).map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(default), + Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`{key}` must be low, medium or high, not `{s}`"))), + } +} + +fn preset_arg(cmd: &str, p: &Value) -> Result> { + match params::string(p, "preset").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(None), + Some(s) => { + DesignPreset::from_id(&s).map(Some).ok_or_else(|| bad(cmd, format!("`preset` must be recommended, strict or accessibility, not `{s}`"))) + } + } +} + +fn preset_description(preset: DesignPreset) -> &'static str { + match preset { + DesignPreset::Recommended => "The usual AI-generated tells", + DesignPreset::Strict => "Recommended plus accent colours and frames without auto layout", + DesignPreset::Accessibility => "Contrast, the type floor, gradient text and clipped text only", + } +} + +/// The variable modes a run resolves colours in: `{collection: mode}`, by id or by name. +fn modes_arg(cmd: &str, p: &Value, doc: &Document) -> Result> { + let Some(v) = params::get(p, "modes") else { return Ok(BTreeMap::new()) }; + let Value::Object(map) = v else { return Err(bad(cmd, "`modes` must be an object of collection → mode")) }; + if map.len() > 64 { + return Err(bad(cmd, "at most 64 collections in `modes`")); + } + let mut out = BTreeMap::new(); + for (collection_key, mode_value) in map { + let Some(mode_key) = mode_value.as_str().map(str::trim).filter(|s| !s.is_empty()) else { + return Err(bad(cmd, "`modes` values must be mode ids or names")); + }; + let Some(collection) = doc.variables.collection(collection_key.trim()) else { + return Err(bad(cmd, format!("unknown collection `{collection_key}`"))); + }; + let Some(mode) = collection.find_mode(mode_key) else { + return Err(bad(cmd, format!("unknown mode `{mode_key}` in `{}`", collection.name))); + }; + out.insert(collection.id.clone(), mode.id.clone()); + } + Ok(out) +} + +/// `design.configure`: change the file's design system and rules in one undo step. +fn configure_cmd(s: &mut Session, p: &Value) -> Result { + let mut config = if params::boolean(p, "reset").unwrap_or(false) { DesignReview::default() } else { s.doc()?.design_review.clone() }; + if let Some(preset) = preset_arg("design.configure", p)? { + config.preset = preset; + } + if let Some(v) = params::get(p, "grid") { + let grid = params::f64_of(v) + .filter(|g| g.is_finite() && (GRID_MIN..=GRID_MAX).contains(g)) + .ok_or_else(|| bad("design.configure", format!("`grid` must be a number from {GRID_MIN} to {GRID_MAX}")))?; + config.grid = grid; + } + if let Some(v) = params::get(p, "radii") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`radii` must be an array of numbers")) }; + if items.len() > MAX_RADII { + return Err(bad("design.configure", format!("at most {MAX_RADII} radii"))); + } + let mut radii = Vec::new(); + for item in items { + let r = params::f64_of(item) + .filter(|r| r.is_finite() && (0.0..=999.0).contains(r)) + .ok_or_else(|| bad("design.configure", "each radius must be a number from 0 to 999"))?; + radii.push((r * 100.0).round() / 100.0); + } + radii.sort_by(f64::total_cmp); + radii.dedup_by(|a, b| (*a - *b).abs() <= 1e-6); + config.radii = radii; + } + if let Some(v) = params::get(p, "brand") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`brand` must be an array of colours")) }; + if items.len() > MAX_BRAND_COLORS { + return Err(bad("design.configure", format!("at most {MAX_BRAND_COLORS} brand colours"))); + } + let mut brand = Vec::new(); + for item in items { + let color = params::color_of(item).ok_or_else(|| bad("design.configure", "each brand colour must be a colour"))?; + if color.a > 0.05 { + brand.push(color); + } + } + config.brand = brand; + } + if let Some(v) = params::get(p, "disabled") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`disabled` must be an array of rule ids")) }; + let mut ids = BTreeSet::new(); + for item in items { + let Some(id) = item.as_str().map(str::trim) else { + return Err(bad("design.configure", "`disabled` must be an array of rule ids")); + }; + if rule(id).is_none() { + return Err(bad("design.configure", format!("unknown rule `{id}` (run design.rules for the list)"))); + } + ids.insert(id.to_string()); + } + config.disabled = ids.into_iter().collect(); + } + if s.doc()?.design_review == config { + return Ok(settings_json(&config)); + } + let doc = s.doc_mut()?; + doc.design_review = config; + Ok(settings_json(&doc.design_review)) +} + +fn settings_json(config: &DesignReview) -> Value { + let brand: Vec = config + .brand + .iter() + .map(|c| { + let rgba = c.to_rgba8(); + format!("#{:02X}{:02X}{:02X}", rgba[0], rgba[1], rgba[2]) + }) + .collect(); + json!({ + "preset": config.preset.id(), + "grid": config.grid(), + "radii": config.radii, + "brand": brand, + "disabled": config.disabled, + }) +} + +/// The layers a command works on, its scope label, the layer aggregate findings point at and that +/// layer's path. +fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, Option, String)> { + let doc = s.doc()?; + // `ids` names the layers directly (the review window fixes only the findings the user kept). + if let Some(v) = params::get(p, "ids") { + let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + let mut ids = Vec::new(); + for item in items { + let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + ids.push(id); + } + let roots = top_most(doc, &ids); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + return Ok(("selection".into(), roots, anchor, path)); + } + let scope = scope_arg(cmd, p)?; + let selection = s.selection(); + let page = s.page()?; + let (roots, label, anchor, path) = match scope.as_deref() { + None if selection.is_empty() => (vec![page], "page", Some(page), node_label(doc, page)), + None => selection_scope(doc, &selection), + Some("selection") => selection_scope(doc, &selection), + Some("page") => (vec![page], "page", Some(page), node_label(doc, page)), + Some("document") => { + let roots = doc.pages.clone(); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + (roots, "document", anchor, path) + } + Some(other) => return Err(bad(cmd, format!("`scope` must be selection, page or document, not `{other}`"))), + }; + Ok((label.to_string(), roots, anchor, path)) +} + +fn selection_scope(doc: &Document, selection: &[NodeId]) -> (Vec, &'static str, Option, String) { + let roots = top_most(doc, selection); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + (roots, "selection", anchor, path) +} + +fn scope_arg(cmd: &str, p: &Value) -> Result> { + let Some(v) = params::get(p, "scope") else { return Ok(None) }; + let Value::String(s) = v else { return Err(bad(cmd, "`scope` must be a string")) }; + let s = s.trim().to_ascii_lowercase(); + if s.is_empty() { + return Ok(None); + } + if matches!(s.as_str(), "selection" | "page" | "document") { + Ok(Some(s)) + } else { + Err(bad(cmd, format!("`scope` must be selection, page or document, not `{s}`"))) + } +} + +fn severity_arg(cmd: &str, p: &Value) -> Result { + match params::string(p, "minSeverity").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(Severity::Low), + Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`minSeverity` must be low, medium or high, not `{s}`"))), + } +} + +fn filter_arg(cmd: &str, p: &Value) -> Result>> { + let Some(v) = params::get(p, "rules") else { return Ok(None) }; + let Value::Array(items) = v else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; + let mut set = BTreeSet::new(); + for item in items { + let Some(s) = item.as_str() else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; + let id = s.trim(); + if rule(id).is_none() { + return Err(bad(cmd, format!("unknown rule `{id}` (run design.rules for the list)"))); + } + set.insert(id.to_string()); + } + Ok(Some(set)) +} + +/// Selected layers without the ones whose ancestor is selected too: their subtrees would be +/// audited twice. +fn top_most(doc: &Document, ids: &[NodeId]) -> Vec { + let mut out: Vec = Vec::new(); + for id in ids { + if out.contains(id) { + continue; + } + let mut parent = doc.node(*id).and_then(|n| n.parent); + let mut depth = 0; + let mut nested = false; + while let Some(pid) = parent { + if depth > 256 { + break; + } + if ids.contains(&pid) { + nested = true; + break; + } + parent = doc.node(pid).and_then(|n| n.parent); + depth += 1; + } + if !nested { + out.push(*id); + } + } + out +} + +fn node_label(doc: &Document, id: NodeId) -> String { + doc.node(id).map(|n| n.name.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Layer {}", id.0)) +} diff --git a/crates/engine/src/design/rules.rs b/crates/engine/src/design/rules.rs new file mode 100644 index 000000000..89fdc700e --- /dev/null +++ b/crates/engine/src/design/rules.rs @@ -0,0 +1,132 @@ +//! The rules `design.audit` checks, with the severity and fixability the report carries. + +use figcraft_doc::DesignPreset; + +/// How much a finding matters: `High` first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Severity { + Low, + Medium, + High, +} + +impl Severity { + pub(crate) fn id(self) -> &'static str { + match self { + Severity::Low => "low", + Severity::Medium => "medium", + Severity::High => "high", + } + } + + pub(crate) fn from_id(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "low" => Some(Severity::Low), + "medium" | "med" => Some(Severity::Medium), + "high" => Some(Severity::High), + _ => None, + } + } + + /// `0` for low, `1` for medium, `2` for high. + pub(crate) fn index(self) -> usize { + match self { + Severity::Low => 0, + Severity::Medium => 1, + Severity::High => 2, + } + } + + /// The points a finding of this severity takes off the score. + pub(crate) fn penalty(self) -> f64 { + match self { + Severity::Low => 0.5, + Severity::Medium => 2.0, + Severity::High => 5.0, + } + } +} + +/// One check: what it looks for, how much it matters and whether `design.fix` can repair it. +pub(crate) struct Rule { + pub id: &'static str, + pub severity: Severity, + /// The planned fixer can change this without guessing (see `docs/design-review.md`). + pub fixable: bool, + pub description: &'static str, +} + +pub(crate) const RULES: &[Rule] = &[ + Rule { id: "spacing.off-grid", severity: Severity::Medium, fixable: true, description: "Auto layout gap or padding is not on the 4px grid" }, + Rule { id: "radius.off-scale", severity: Severity::Low, fixable: true, description: "A corner radius is not on the 4px scale or a pill" }, + Rule { id: "type.sizes", severity: Severity::Medium, fixable: false, description: "More than five font sizes in one scope" }, + Rule { id: "type.families", severity: Severity::Medium, fixable: false, description: "More than two font families in one scope" }, + Rule { id: "type.weight", severity: Severity::Low, fixable: true, description: "A heading uses a weight above 600" }, + Rule { id: "type.italic", severity: Severity::Low, fixable: true, description: "Interface text is italic" }, + Rule { id: "type.too-small", severity: Severity::Medium, fixable: false, description: "Body text is smaller than 11px" }, + Rule { id: "type.negative-tracking", severity: Severity::Low, fixable: true, description: "Small text has negative letter spacing" }, + Rule { id: "color.gradient", severity: Severity::Medium, fixable: false, description: "A shape is filled or stroked with a gradient" }, + Rule { id: "color.gradient-text", severity: Severity::High, fixable: false, description: "Text is painted with a gradient" }, + Rule { + id: "color.glow", + severity: Severity::Medium, + fixable: true, + description: "A shadow has no offset and a large blur, so it reads as a glow", + }, + Rule { id: "color.colored-shadow", severity: Severity::Low, fixable: true, description: "A shadow has a visible hue instead of a neutral" }, + Rule { id: "color.border-opacity", severity: Severity::Low, fixable: true, description: "A border is more opaque than a hairline" }, + Rule { id: "color.contrast", severity: Severity::High, fixable: true, description: "Text contrast is below 4.5:1 (3:1 for large text)" }, + Rule { id: "color.accents", severity: Severity::Medium, fixable: false, description: "More than two accent colours in one scope (Strict)" }, + Rule { id: "token.hardcoded-color", severity: Severity::Low, fixable: false, description: "A colour matches a variable but is not bound to it" }, + Rule { + id: "token.hardcoded-number", + severity: Severity::Low, + fixable: false, + description: "A spacing, radius, size or opacity value matches a variable but is not bound", + }, + Rule { id: "icon.emoji", severity: Severity::Low, fixable: false, description: "Text or a layer name contains an emoji" }, + Rule { id: "copy.exclamation", severity: Severity::Low, fixable: false, description: "Interface copy uses an exclamation mark" }, + Rule { id: "copy.trailing-period", severity: Severity::Low, fixable: false, description: "A short label ends with a period" }, + Rule { id: "copy.hype", severity: Severity::Low, fixable: false, description: "Copy uses hype words such as \"AI-powered\"" }, + Rule { id: "naming.auto", severity: Severity::Low, fixable: false, description: "A layer still has its default auto name (Frame 12)" }, + Rule { id: "detail.shadow-count", severity: Severity::Low, fixable: false, description: "Shadows and blurs sit on too many layers" }, + Rule { + id: "layout.no-auto-layout", + severity: Severity::Low, + fixable: false, + description: "A frame or component with several children has no auto layout (Strict)", + }, + Rule { + id: "layout.text-overflow", + severity: Severity::High, + fixable: false, + description: "A fixed-width text box is shorter than the text it holds, so it clips or overlaps", + }, + Rule { + id: "layout.clipped", + severity: Severity::High, + fixable: false, + description: "A fixed-size auto layout frame clips children that overflow it, so they are invisible", + }, +]; + +pub(crate) fn rule(id: &str) -> Option<&'static Rule> { + RULES.iter().find(|r| r.id == id) +} + +/// Whether `preset` checks `id`. Recommended and Strict check every rule except the Strict-only +/// ones; Accessibility checks only the findings that keep a design usable. +pub(crate) fn enabled(id: &str, preset: DesignPreset) -> bool { + match preset { + DesignPreset::Recommended => !matches!(id, "color.accents" | "layout.no-auto-layout"), + DesignPreset::Strict => true, + DesignPreset::Accessibility => { + matches!(id, "color.contrast" | "color.gradient-text" | "type.too-small" | "layout.text-overflow" | "layout.clipped") + } + } +} + +/// The presets that check `id`, for `design.rules`. +pub(crate) fn presets_of(id: &str) -> Vec<&'static str> { + DesignPreset::ALL.iter().copied().filter(|p| enabled(id, *p)).map(DesignPreset::id).collect() +} diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs new file mode 100644 index 000000000..0033dcb9d --- /dev/null +++ b/crates/engine/src/design/tests.rs @@ -0,0 +1,863 @@ +//! `design.audit`, `design.fix` and `design.rules`: the checks, the repairs and the report. + +use figcraft_doc::{EffectKind, NodeId, NodeKind, Sizing}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; + +fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap() +} + +fn id(v: &Value) -> NodeId { + id_of(&v["id"]).unwrap() +} + +fn rules(report: &Value) -> Vec { + report["findings"].as_array().unwrap().iter().filter_map(|f| f["rule"].as_str().map(str::to_string)).collect() +} + +fn has(report: &Value, rule: &str) -> bool { + rules(report).iter().any(|r| r == rule) +} + +fn rule_nodes(report: &Value, rule: &str) -> Vec { + report["findings"].as_array().unwrap().iter().filter(|f| f["rule"] == rule).filter_map(|f| f["node"].as_u64()).collect() +} + +#[test] +fn reports_spacing_radius_copy_and_small_type() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 320, "height": 480, + "props": {"layout": "vertical", "gap": 13, "padding": 11, "cornerRadius": 7}}), + )); + ex(&mut s, "text.create", json!({"text": "Welcome back, Sam!", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 10}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + for rule in ["spacing.off-grid", "radius.off-scale", "copy.exclamation", "type.too-small"] { + assert!(has(&r, rule), "{rule} missing from {r}"); + } + let spacing = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(spacing["suggestion"]["gap"], 12.0, "{r}"); + assert_eq!(spacing["suggestion"]["padding"], json!([12.0, 12.0, 12.0, 12.0]), "{r}"); + assert_eq!(spacing["details"]["gap"], 13.0, "{r}"); + assert_eq!(spacing["details"]["padding"], json!([11.0, 11.0, 11.0, 11.0]), "{r}"); + assert_eq!(spacing["details"]["grid"], 4.0, "{r}"); + assert_eq!(spacing["fixable"], true); +} + +#[test] +fn reports_gradient_text_glow_and_low_contrast() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Ship it", "x": 0, "y": 0}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + let box_id = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 200, "width": 200, "height": 100}))); + ex( + &mut s, + "node.set", + json!({"id": box_id, "props": {"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 0], "radius": 24}]}}), + ); + let white = id(&ex(&mut s, "text.create", json!({"text": "Invisible", "x": 0, "y": 400}))); + ex(&mut s, "node.set", json!({"id": white, "props": {"fill": "#FFFFFF"}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + for rule in ["color.gradient-text", "color.glow", "color.contrast"] { + assert!(has(&r, rule), "{rule} missing from {r}"); + } + let contrast = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "color.contrast").unwrap(); + assert!(contrast["details"]["ratio"].as_f64().is_some_and(|v| v < 4.5), "{r}"); + assert_eq!(contrast["details"]["foreground"], "FFFFFF", "{r}"); +} + +#[test] +fn reports_a_gradient_on_a_shape() { + let mut s = Session::new(); + let rect = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50}))); + ex(&mut s, "node.set", json!({"id": rect, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "color.gradient"), "{r}"); + assert!(!has(&r, "color.gradient-text"), "{r}"); +} + +#[test] +fn counts_type_sizes_and_families_across_the_scope() { + let mut s = Session::new(); + for size in [12, 13, 14, 15, 16, 17, 18, 19] { + ex(&mut s, "text.create", json!({"text": "Text", "x": 0, "y": size as f64 * 20.0, "props": {"fontSize": size}})); + } + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "type.sizes"), "{r}"); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "type.sizes").unwrap(); + assert!(f["message"].as_str().unwrap().contains("8 font sizes"), "{r}"); + assert_eq!(f["details"]["count"], 8, "{r}"); + assert_eq!(f["details"]["sizes"].as_array().map(Vec::len), Some(8), "{r}"); +} + +#[test] +fn selection_scope_ignores_other_layers() { + let mut s = Session::new(); + let bad = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + let good = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 8}}), + )); + s.set_selection(vec![good]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + assert!(!has(&r, "spacing.off-grid"), "{r}"); + s.set_selection(vec![bad]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + assert!(has(&r, "spacing.off-grid"), "{r}"); +} + +#[test] +fn a_nested_selection_is_audited_once() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + let child = id(&ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 20, "height": 20}))); + s.set_selection(vec![f, child]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + // The rectangle is only in the report through the frame's subtree. + let rect_findings = r["findings"].as_array().unwrap().iter().filter(|f| f["path"].as_str().unwrap().contains("Rectangle")).count(); + assert!(rect_findings <= 1, "{r}"); +} + +#[test] +fn filters_by_rule_and_severity() { + let mut s = Session::new(); + ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}})); + let only = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + assert_eq!(rules(&only), vec!["spacing.off-grid".to_string()], "{only}"); + assert_eq!(only["byRule"]["spacing.off-grid"], 1, "{only}"); + let high = ex(&mut s, "design.audit", json!({"scope": "page", "minSeverity": "high"})); + assert!(rules(&high).is_empty(), "{high}"); + assert_eq!(high["score"], 100.0, "{high}"); + let all = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(all["score"].as_f64().unwrap() < 100.0, "{all}"); + assert!(all["nodes"].as_u64().unwrap() >= 2, "the report counts the layers it walked: {all}"); +} + +#[test] +fn a_light_border_is_a_hairline() { + let mut s = Session::new(); + let light = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 0, "width": 200, "height": 60, + "props": {"stroke": "#E0E0E0", "strokeWeight": 1} + }), + )); + let strong = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 100, "width": 200, "height": 60, + "props": {"stroke": "#333333", "strokeWeight": 1} + }), + )); + // An inside stroke on a dark panel sits on the panel, not on the page behind it. + let dark_panel = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 200, "width": 200, "height": 60, + "props": {"fill": "#1E1E1E", "stroke": "#2A2A2A", "strokeWeight": 1, "strokeAlign": "inside"} + }), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.border-opacity"]})); + let flagged: Vec = r["findings"].as_array().unwrap().iter().filter_map(|f| f["node"].as_u64()).collect(); + assert!(!flagged.contains(&light.0), "{r}"); + assert!(flagged.contains(&strong.0), "{r}"); + assert!(!flagged.contains(&dark_panel.0), "a dark border on a dark panel is not a strong hairline: {r}"); +} + +#[test] +fn reports_emoji_and_default_names() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + ex(&mut s, "text.create", json!({"text": "Ship it 🚀", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 16}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "icon.emoji"), "{r}"); + assert!(has(&r, "naming.auto"), "{r}"); +} + +#[test] +fn lists_the_rules() { + let mut s = Session::new(); + let r = ex(&mut s, "design.rules", json!({})); + let rules = r["rules"].as_array().unwrap(); + assert!(rules.len() >= 15, "{r}"); + let spacing = rules.iter().find(|r| r["id"] == "spacing.off-grid").unwrap(); + assert_eq!(spacing["severity"], "medium"); + assert_eq!(spacing["fixable"], true); + assert_eq!(spacing["presets"], json!(["recommended", "strict"])); + let accents = rules.iter().find(|r| r["id"] == "color.accents").unwrap(); + assert_eq!(accents["presets"], json!(["strict"])); + assert_eq!(r["presets"].as_array().unwrap().len(), 3, "{r}"); +} + +#[test] +fn configure_changes_the_files_design_system() { + let mut s = Session::new(); + let r = ex( + &mut s, + "design.configure", + json!({"preset": "strict", "grid": 8, "radii": [0, 10, 20], "brand": ["#3366FF"], "disabled": ["icon.emoji"]}), + ); + assert_eq!(r["preset"], "strict", "{r}"); + assert_eq!(r["grid"], 8.0, "{r}"); + assert_eq!(r["radii"], json!([0.0, 10.0, 20.0]), "{r}"); + assert_eq!(r["brand"], json!(["#3366FF"]), "{r}"); + assert_eq!(r["disabled"], json!(["icon.emoji"]), "{r}"); + assert_eq!(s.doc().unwrap().design_review.grid(), 8.0); + // The settings are part of the file and undoable with it. + let reset = ex(&mut s, "design.configure", json!({"reset": true})); + assert_eq!(reset["preset"], "recommended", "{reset}"); + assert_eq!(reset["grid"], 4.0, "{reset}"); + assert!(s.doc().unwrap().design_review.is_default()); + assert!(s.execute("design.configure", &json!({"grid": 0})).is_err()); + assert!(s.execute("design.configure", &json!({"radii": ["wide"]})).is_err()); + assert!(s.execute("design.configure", &json!({"disabled": ["no.such.rule"]})).is_err()); +} + +#[test] +fn the_configured_grid_drives_spacing_and_the_fixer() { + let mut s = Session::new(); + ex(&mut s, "design.configure", json!({"grid": 8})); + let on = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "cornerRadius": 8}}), + )); + let off = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 6, "padding": 10, "cornerRadius": 12}}), + )); + let only = json!(["spacing.off-grid", "radius.off-scale"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(!rule_nodes(&r, "spacing.off-grid").contains(&on.0), "{r}"); + assert!(!rule_nodes(&r, "radius.off-scale").contains(&on.0), "{r}"); + assert_eq!(rule_nodes(&r, "spacing.off-grid"), vec![off.0], "{r}"); + assert_eq!(rule_nodes(&r, "radius.off-scale"), vec![off.0], "{r}"); + assert!(r["grid"] == json!(8.0), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let n = s.doc().unwrap().node(off).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 8.0); + assert_eq!(n.layout.as_ref().unwrap().padding, [8.0; 4]); + assert_eq!(n.corners.radii, [16.0; 4]); +} + +#[test] +fn a_custom_radius_scale_is_the_only_scale() { + let mut s = Session::new(); + ex(&mut s, "design.configure", json!({"radii": [10, 20]})); + let ok = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"cornerRadius": 10}}))); + let off = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"cornerRadius": 8}}))); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["radius.off-scale"]})); + assert!(!rule_nodes(&r, "radius.off-scale").contains(&ok.0), "{r}"); + assert_eq!(rule_nodes(&r, "radius.off-scale"), vec![off.0], "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(s.doc().unwrap().node(off).unwrap().corners.radii, [10.0; 4]); +} + +#[test] +fn presets_choose_the_rules_and_disabled_rules_stay_off() { + let mut s = Session::new(); + for (i, fill) in ["#FF0000", "#00AA00", "#0000FF"].iter().enumerate() { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 60, "y": 0, "width": 40, "height": 40, "props": {"fill": fill}})); + } + let stack = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 100, "width": 200, "height": 200}))); + for i in 0..3 { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 20, "y": 0, "width": 10, "height": 10, "parent": stack})); + } + let off_grid = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 100, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + + let recommended = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert_eq!(recommended["preset"], "recommended", "{recommended}"); + assert!(!has(&recommended, "color.accents"), "{recommended}"); + assert!(!has(&recommended, "layout.no-auto-layout"), "{recommended}"); + let strict = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(has(&strict, "color.accents"), "{strict}"); + assert!(has(&strict, "layout.no-auto-layout"), "{strict}"); + let a11y = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "accessibility"})); + assert!(!has(&a11y, "spacing.off-grid"), "{a11y}"); + + // The file can make Strict its own, and a disabled rule is neither reported nor fixed. + ex(&mut s, "design.configure", json!({"preset": "strict", "disabled": ["spacing.off-grid"]})); + let file = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert_eq!(file["preset"], "strict", "{file}"); + assert!(has(&file, "color.accents"), "{file}"); + assert!(!has(&file, "spacing.off-grid"), "{file}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(s.doc().unwrap().node(off_grid).unwrap().layout.as_ref().unwrap().gap, 13.0, "a disabled rule is not fixed"); +} + +#[test] +fn contrast_is_checked_in_the_given_variable_modes() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Theme"})); + ex(&mut s, "variable.addMode", json!({"collection": "Theme", "name": "Dark"})); + ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "surface", "type": "color", "value": "#FFFFFF"})); + ex(&mut s, "variable.set", json!({"variable": "surface", "mode": "Dark", "value": "#222222"})); + ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "ink", "type": "color", "value": "#111111"})); + ex(&mut s, "variable.set", json!({"variable": "ink", "mode": "Dark", "value": "#777777"})); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"fill": "#FFFFFF"}}))); + let t = id(&ex(&mut s, "text.create", json!({"text": "Read me", "x": 10, "y": 10, "parent": f}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "solid", "color": "#111111"}]})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "fill", "variable": "surface"})); + ex(&mut s, "variable.bind", json!({"ids": [t], "field": "fill", "variable": "ink"})); + let only = json!(["color.contrast"]); + let light = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(!has(&light, "color.contrast"), "{light}"); + let dark = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only, "modes": {"Theme": "Dark"}})); + assert!(has(&dark, "color.contrast"), "{dark}"); + assert_eq!(dark["modes"], json!({"Theme": "Dark"}), "{dark}"); + let finding = dark["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "color.contrast").unwrap(); + assert_eq!(finding["fixable"], false, "{dark}"); + assert_eq!(finding["reason"], "modes", "{dark}"); + assert!(finding["message"].as_str().unwrap().contains("Theme: Dark"), "{finding}"); + assert!(s.execute("design.audit", &json!({"scope": "page", "modes": {"Theme": "Dusk"}})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "modes": {"Theme": "Dark"}, "failOn": "high"})).is_err()); +} + +#[test] +fn unfixable_findings_carry_a_reason_code() { + let mut s = Session::new(); + let bound = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 13})); + ex(&mut s, "variable.bind", json!({"ids": [bound], "field": "gap", "variable": "space"})); + let loose = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid", "naming.auto"]})); + let findings = r["findings"].as_array().unwrap(); + let bound_f = findings.iter().find(|f| f["node"] == bound.0 && f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(bound_f["fixable"], false, "{r}"); + assert_eq!(bound_f["reason"], "bound", "{r}"); + let loose_f = findings.iter().find(|f| f["node"] == loose.0 && f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(loose_f["fixable"], true, "{r}"); + assert!(loose_f.get("reason").is_none(), "{r}"); + let named = findings.iter().find(|f| f["rule"] == "naming.auto").unwrap(); + assert_eq!(named["reason"], "decision", "{r}"); +} + +#[test] +fn brand_colours_do_not_count_as_stray_accents() { + let mut s = Session::new(); + for (i, fill) in ["#FF0000", "#00AA00", "#0000FF"].iter().enumerate() { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 60, "y": 0, "width": 40, "height": 40, "props": {"fill": fill}})); + } + let loose = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(has(&loose, "color.accents"), "{loose}"); + let brand = ex(&mut s, "design.configure", json!({"brand": ["#FF0000", "#00AA00"]})); + assert_eq!(brand["brand"], json!(["#FF0000", "#00AA00"]), "{brand}"); + let kept = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(!has(&kept, "color.accents"), "{kept}"); +} + +#[test] +fn junk_params_are_errors_not_panics() { + let mut s = Session::new(); + for junk in [ + json!({"scope": {"x": 1}}), + json!({"scope": "everything"}), + json!({"rules": [1]}), + json!({"rules": "spacing.off-grid"}), + json!({"rules": ["no.such.rule"]}), + json!({"minSeverity": "loud"}), + ] { + assert!(s.execute("design.audit", &junk).is_err(), "{junk} was accepted"); + } + assert!(s.execute("design.audit", &json!({})).is_ok()); + // Nulls mean "the default", not junk. + assert!(s.execute("design.audit", &json!({"scope": "document", "rules": null, "minSeverity": null})).is_ok()); +} + +fn spaced_frame(s: &mut Session) -> NodeId { + id(&ex( + s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 13, "padding": 11, "cornerRadius": 7}}), + )) +} + +#[test] +fn fix_snaps_spacing_and_radius_as_one_undo_step() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(r["dryRun"], false, "{r}"); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + assert!(r["byRule"]["spacing.off-grid"].as_u64().unwrap() >= 1, "{r}"); + assert!(r["byRule"]["radius.off-scale"].as_u64().unwrap() >= 1, "{r}"); + { + let n = s.doc().unwrap().node(f).unwrap(); + let al = n.layout.as_ref().unwrap(); + assert_eq!((al.gap, al.padding[0], al.padding[1]), (12.0, 12.0, 12.0)); + assert_eq!(n.corners.uniform(), Some(8.0)); + } + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "spacing.off-grid"), "{after}"); + assert!(!has(&after, "radius.off-scale"), "{after}"); + // The whole repair is one undo step. + ex(&mut s, "edit.undo", json!({})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 13.0); + assert_eq!(n.corners.uniform(), Some(7.0)); +} + +#[test] +fn dry_run_reports_without_changing_anything() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"scope": "page", "dryRun": true})); + assert_eq!(r["dryRun"], true, "{r}"); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn fix_filters_by_rule() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["radius.off-scale"]})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 13.0, "spacing was not asked for"); + assert_eq!(n.corners.uniform(), Some(8.0)); +} + +#[test] +fn fix_caps_heading_weight_and_removes_tracking() { + let mut s = Session::new(); + let heading = id(&ex(&mut s, "text.create", json!({"text": "Title", "x": 0, "y": 0, "props": {"fontSize": 28, "fontStyle": "Bold"}}))); + let small = id(&ex( + &mut s, + "text.create", + json!({"text": "Label", "x": 0, "y": 60, + "props": {"fontSize": 16, "letterSpacing": {"unit": "pixels", "value": -1.5}}}), + )); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert!(r["changed"].as_u64().unwrap() >= 2, "{r}"); + let doc = s.doc().unwrap(); + let NodeKind::Text(h) = &doc.node(heading).unwrap().kind else { panic!() }; + assert_eq!(h.style.weight(), 600); + let NodeKind::Text(l) = &doc.node(small).unwrap().kind else { panic!() }; + assert_eq!(l.style.letter_spacing.resolve(16.0), 0.0); + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "type.weight"), "{after}"); + assert!(!has(&after, "type.negative-tracking"), "{after}"); +} + +#[test] +fn fix_removes_glows_and_neutralises_coloured_shadows() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + ex( + &mut s, + "node.set", + json!({"id": f, "props": {"effects": [ + {"type": "dropShadow", "color": "#00000040", "offset": [0, 0], "radius": 24}, + {"type": "dropShadow", "color": "#7048E880", "offset": [0, 4], "radius": 12} + ]}}), + ); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + let effects = &s.doc().unwrap().node(f).unwrap().effects; + assert_eq!(effects.len(), 1, "the glow is gone: {effects:?}"); + let EffectKind::DropShadow(shadow) = &effects[0].kind else { panic!() }; + assert_eq!((shadow.color.r, shadow.color.g, shadow.color.b), (0.0, 0.0, 0.0)); + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "color.glow"), "{after}"); + assert!(!has(&after, "color.colored-shadow"), "{after}"); +} + +#[test] +fn fix_leaves_content_and_gradients_alone() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Ship it 🚀!", "x": 0, "y": 0, "props": {"fontSize": 16}}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let doc = s.doc().unwrap(); + let NodeKind::Text(td) = &doc.node(t).unwrap().kind else { panic!() }; + assert_eq!(td.characters, "Ship it 🚀!"); + assert!(matches!(&td.style.fills.as_deref().unwrap_or(&doc.node(t).unwrap().fills)[0].kind, figcraft_color::PaintKind::Gradient(_))); +} + +#[test] +fn fix_darkens_low_contrast_text() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + let t = id(&ex(&mut s, "text.create", json!({"text": "Invisible", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + assert!(has(&ex(&mut s, "design.audit", json!({"scope": "page"})), "color.contrast")); + let r = ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + { + let doc = s.doc().unwrap(); + let n = doc.node(t).unwrap(); + let NodeKind::Text(td) = &n.kind else { panic!() }; + let paints = td.style.fills.as_deref().unwrap_or(&n.fills); + let color = paints.iter().rev().find_map(|p| p.solid_color()).unwrap(); + assert!(color.contrast(figcraft_color::Color::WHITE) >= 4.5, "{color:?}"); + } + assert!(!has(&ex(&mut s, "design.audit", json!({"scope": "page"})), "color.contrast")); +} + +#[test] +fn reports_text_that_overflows_its_box() { + let mut s = Session::new(); + let t = id(&ex( + &mut s, + "node.create", + json!({"type": "text", "text": "A long headline that needs several lines in a narrow box", + "x": 0, "y": 0, "width": 120, "height": 40, + "props": {"fontSize": 24, "textAutoResize": "none"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "layout.text-overflow").unwrap_or_else(|| panic!("{r}")); + assert_eq!(f["node"], t.0, "{r}"); +} + +#[test] +fn a_sibling_background_is_the_text_backdrop() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}})); + let white = + id(&ex(&mut s, "text.create", json!({"text": "White on dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + let dark = + id(&ex(&mut s, "text.create", json!({"text": "Dark on dark", "x": 20, "y": 80, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}))); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + let flagged = rule_nodes(&r, "color.contrast"); + assert!(!flagged.contains(&white.0), "white on the dark sibling is legible: {r}"); + assert!(flagged.contains(&dark.0), "dark on the dark sibling is not: {r}"); +} + +#[test] +fn a_background_inside_a_group_is_found() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + let rect = id(&ex(&mut s, "shape.rectangle", json!({"parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}}))); + s.set_selection(vec![rect]); + ex(&mut s, "object.group", json!({})); + let white = id(&ex( + &mut s, + "text.create", + json!({"text": "White on grouped dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(!rule_nodes(&r, "color.contrast").contains(&white.0), "the grouped background is under the text: {r}"); +} + +#[test] +fn fix_uses_the_sibling_background_for_contrast() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}})); + let white = + id(&ex(&mut s, "text.create", json!({"text": "White on dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + let dark = + id(&ex(&mut s, "text.create", json!({"text": "Dark on dark", "x": 20, "y": 80, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}))); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["color.contrast"]})); + let doc = s.doc().unwrap(); + let fill = |id| { + let n = doc.node(id).unwrap(); + let NodeKind::Text(t) = &n.kind else { panic!() }; + t.style.fills.as_deref().unwrap_or(&n.fills).iter().rev().find_map(|p| p.solid_color()).unwrap() + }; + let w = fill(white); + assert_eq!((w.r, w.g, w.b), (1.0, 1.0, 1.0), "the legible white text is left alone"); + let d = fill(dark); + assert!(d.contrast(figcraft_color::Color::from_rgb8_const(0x1E, 0x1E, 0x1E)) >= 4.5, "the dark text is lightened: {d:?}"); +} + +#[test] +fn locked_layers_are_left_alone() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "node.set", json!({"id": f, "props": {"locked": true}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&r, "spacing.off-grid") && !has(&r, "radius.off-scale"), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!((n.layout.as_ref().unwrap().gap, n.corners.uniform()), (13.0, Some(7.0))); +} + +#[test] +fn a_bound_spacing_value_is_reported_but_not_fixed() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "gap", "type": "number", "value": 13})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "gap"})); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap_or_else(|| panic!("{r}")); + assert_eq!(finding["fixable"], false, "{r}"); + assert!(finding["message"].as_str().unwrap().contains("bound"), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn a_padding_binding_owns_the_spacing() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 11})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "padding", "variable": "space"})); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap_or_else(|| panic!("{r}")); + assert_eq!(finding["fixable"], false, "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let n = s.doc().unwrap().node(f).unwrap(); + let al = n.layout.as_ref().unwrap(); + assert_eq!((al.gap, al.padding[0]), (13.0, 11.0), "a padding binding owns the whole layout"); +} + +#[test] +fn a_blended_background_is_not_sampled() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex( + &mut s, + "node.create", + json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E", "blend": "multiply"}}), + ); + let dark = id(&ex( + &mut s, + "text.create", + json!({"text": "Dark on a blended dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(!rule_nodes(&r, "color.contrast").contains(&dark.0), "a blend mode makes the backdrop unknown: {r}"); +} + +#[test] +fn fix_with_ids_leaves_other_layers_alone() { + let mut s = Session::new(); + let a = spaced_frame(&mut s); + let b = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"ids": [a]})); + assert_eq!(r["scope"], "selection", "{r}"); + let doc = s.doc().unwrap(); + assert_eq!(doc.node(a).unwrap().layout.as_ref().unwrap().gap, 12.0); + assert_eq!(doc.node(b).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn fix_with_exact_leaves_a_child_finding_alone() { + let mut s = Session::new(); + let parent = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Parent", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "cornerRadius": 3}}), + )); + let child = id(&ex( + &mut s, + "node.create", + json!({"type": "rectangle", "name": "Child", "parent": parent, "x": 0, "y": 0, "width": 80, "height": 40, + "props": {"cornerRadius": 3}}), + )); + let r = ex(&mut s, "design.fix", json!({"ids": [parent], "rules": ["radius.off-scale"], "exact": true})); + assert_eq!(r["changed"], 1, "{r}"); + let doc = s.doc().unwrap(); + assert_ne!(doc.node(parent).unwrap().corners.radii[0], 3.0, "the root is repaired"); + assert_eq!(doc.node(child).unwrap().corners.radii[0], 3.0, "an ignored child finding stays: exact means the listed layers only"); +} + +#[test] +fn hardcoded_values_that_match_variables_are_reported() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "red", "type": "color", "value": "#FF0000"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 12})); + let r = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50, "props": {"fill": "#FF0000"}}))); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 100, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 12}}), + )); + let only_rules = json!(["token.hardcoded-color", "token.hardcoded-number"]); + let before = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only_rules})); + assert!(has(&before, "token.hardcoded-color"), "{before}"); + assert!(has(&before, "token.hardcoded-number"), "{before}"); + ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "red"})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "space"})); + let after = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only_rules})); + assert!(rules(&after).is_empty(), "{after}"); +} + +#[test] +fn assert_is_a_ci_gate_on_severity_and_score() { + let mut s = Session::new(); + let _f = spaced_frame(&mut s); + // Off-grid spacing is medium: a high gate passes, a medium gate fails. + assert!(s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).is_ok()); + let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "medium"})).unwrap_err().to_string(); + assert!(err.contains("spacing.off-grid"), "{err}"); + assert!(s.execute("design.assert", &json!({"scope": "page", "minScore": 100})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "minScore": "high"})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "failOn": "loud"})).is_err()); + // A frame on the grid and the scale has nothing to report. + let mut clean = Session::new(); + ex( + &mut clean, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "cornerRadius": 8}}), + ); + let ok = ex(&mut clean, "design.assert", json!({"scope": "page", "failOn": "medium"})); + assert_eq!(ok["ok"], true, "{ok}"); + assert_eq!(ok["score"], 100.0, "{ok}"); +} + +#[test] +fn fix_junk_is_an_error_not_a_panic() { + let mut s = Session::new(); + assert!(s.execute("design.fix", &json!({"scope": "everything"})).is_err()); + assert!(s.execute("design.fix", &json!({"rules": ["no.such.rule"]})).is_err()); + assert!(s.execute("design.fix", &json!({})).is_ok()); +} + +#[test] +fn a_fixed_frame_that_clips_children_is_reported() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Card", "x": 0, "y": 0, "width": 200, "height": 40, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "fill": "#FFFFFF"}}), + )); + ex(&mut s, "text.create", json!({"text": "Row one", "parent": f})); + ex(&mut s, "text.create", json!({"text": "Row two", "parent": f})); + let only = json!(["layout.clipped"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(has(&r, "layout.clipped"), "{r}"); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "layout.clipped").unwrap(); + assert_eq!(finding["fixable"], false, "{r}"); + assert_eq!(finding["suggestion"]["sizingV"], "hug", "{r}"); + // A frame that hugs grows with its rows, so it cannot clip. + ex(&mut s, "node.set", json!({"id": f, "props": {"sizingV": "hug"}})); + let after = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&after).is_empty(), "{after}"); +} + +#[test] +fn a_plain_clipping_frame_is_not_a_layout_finding() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Crop", "x": 0, "y": 0, "width": 200, "height": 40, + "props": {"fill": "#FFFFFF"}}), + )); + // A manual frame clipping its artwork is a crop, not a layout mistake: `sizingV` cannot fix it. + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 30, "width": 200, "height": 40})); + let only = json!(["layout.clipped"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&r).is_empty(), "clipping a manual frame is intentional: {r}"); +} + +#[test] +fn an_auto_layout_frame_hugs_the_axes_no_size_names() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Card", "x": 0, "y": 0, "props": {"layout": "vertical", "gap": 8, "padding": 8}}), + )); + ex(&mut s, "text.create", json!({"text": "Row one", "parent": f})); + ex(&mut s, "text.create", json!({"text": "Row two", "parent": f})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Hug); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); + assert!(n.height > 40.0 && n.height < 90.0, "hug height fits the rows, got {}", n.height); + // An explicit width stays fixed; the unnamed height hugs. + let g = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Bar", "x": 300, "y": 0, "width": 320, "props": {"layout": "vertical", "gap": 8}}), + )); + let n = s.doc().unwrap().node(g).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); + // No auto layout: the 100×100 defaults stay. + let p = id(&ex(&mut s, "node.create", json!({"type": "frame", "name": "Plain", "x": 700, "y": 0}))); + let n = s.doc().unwrap().node(p).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.width, 100.0); + // A size in props is explicit too: it keeps that axis fixed and the other one hugs. + let q = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Props height", "x": 1000, "y": 0, + "props": {"layout": "vertical", "height": 300}}), + )); + let n = s.doc().unwrap().node(q).unwrap(); + assert_eq!(n.height, 300.0); + assert_eq!(n.child_layout.sizing_v, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_h, Sizing::Hug); + let r = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Props width", "x": 1000, "y": 400, + "props": {"layout": "vertical", "w": 320}}), + )); + let n = s.doc().unwrap().node(r).unwrap(); + assert_eq!(n.width, 320.0); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); +} + +#[test] +fn an_icons_stroke_is_not_a_border() { + let mut s = Session::new(); + ex( + &mut s, + "node.create", + json!({"type": "vector", "name": "Chevron", "x": 0, "y": 0, "points": [[0, 0], [8, 8], [0, 16]], + "props": {"stroke": "#6B7280", "strokeWeight": 1.5, "fills": []}}), + ); + let only = json!(["color.border-opacity"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&r).is_empty(), "an icon's stroke is its drawing, not a border: {r}"); + ex( + &mut s, + "node.create", + json!({"type": "rectangle", "name": "Panel", "x": 100, "y": 0, "width": 48, "height": 48, + "props": {"fills": [], "stroke": "#6B7280", "strokeWeight": 1.5}}), + ); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(has(&r, "color.border-opacity"), "{r}"); +} + +#[test] +fn a_bad_parent_error_names_the_node() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Label", "x": 0, "y": 0}))); + let err = s.execute("node.create", &json!({"type": "rectangle", "parent": t, "x": 0, "y": 0})).unwrap_err().to_string(); + assert!(err.contains("TEXT \"Label\""), "{err}"); + assert!(err.contains("can't contain"), "{err}"); +} diff --git a/crates/engine/src/inspect_fields_tests.rs b/crates/engine/src/inspect_fields_tests.rs index 2083a5108..b7b93fd0d 100644 --- a/crates/engine/src/inspect_fields_tests.rs +++ b/crates/engine/src/inspect_fields_tests.rs @@ -116,6 +116,7 @@ fn empty_options_keep_the_main_tree_and_document_output() { "fontFamily": "Synthetic", "fontSize": 18.0, "fontStyle": "Bold", + "fontWeight": 700, "height": 24.0, "id": 3, "letterSpacing": "1", diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 302e7053e..ca5feaa32 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ mod canvas; pub mod catalog; pub mod cmd; mod content; +mod design; mod dev; pub mod events; mod extensions; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 48d68a901..b2200777a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -106,6 +106,9 @@ pub struct Prefs { /// files opened or made later start with them. Missing: the toggle's default. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub view: BTreeMap, + /// Design review ignores, by document path: whole rule ids and `rule@layer` entries. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub design_review_ignored: BTreeMap>, /// The board canvas's background grid (`board.grid`). #[serde(deserialize_with = "crate::board_grid::read")] pub board_grid: crate::board_grid::BoardGrid, @@ -158,6 +161,7 @@ impl Default for Prefs { home_sort: "modified".into(), home_order: "desc".into(), view: BTreeMap::new(), + design_review_ignored: BTreeMap::new(), board_grid: Default::default(), recent_actions: Vec::new(), team_libraries: Vec::new(), diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 59b4ee818..12b74e448 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -18,7 +18,7 @@ pub struct PromptDef { pub defaults: &'static [(&'static str, &'static str)], } -const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text; call screenshot at the end and look at it. Fix anything that is off before finishing, then report the ids of the frames you made."; +const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made."; pub const PROMPTS: &[PromptDef] = &[ PromptDef { @@ -30,7 +30,7 @@ pub const PROMPTS: &[PromptDef] = &[ PromptArg { name: "device", description: "Frame preset (default \"iPhone 16\"; see run_command frame.presets)", required: false }, PromptArg { name: "brand_color", description: "Primary colour (default #3B5BDB)", required: false }, ], - template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [14,24,14,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Bold text inside).\n4. Keep spacing on an 8-point grid and text left-aligned.{verify}", + template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Semi Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [16,24,16,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Semi Bold text inside). Name every layer by what it is.\n4. Keep spacing on an 8-point grid, text left-aligned, and no emoji in the interface.{verify}", defaults: &[("device", "iPhone 16"), ("brand_color", "#3B5BDB")], }, PromptDef { @@ -41,7 +41,7 @@ pub const PROMPTS: &[PromptDef] = &[ PromptArg { name: "name", description: "Design system name (default \"Core\")", required: false }, PromptArg { name: "primary", description: "Primary colour (default #3B5BDB)", required: false }, ], - template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": }; text styles likewise from text layers (Heading 32 Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": } and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}", + template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": }; text styles likewise from text layers (Heading 32 Semi Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": } and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}", defaults: &[("name", "Core"), ("primary", "#3B5BDB")], }, PromptDef { @@ -51,10 +51,18 @@ pub const PROMPTS: &[PromptDef] = &[ args: &[ PromptArg { name: "product", description: "What the page sells", required: true }, PromptArg { name: "width", description: "Page width (default 1440)", required: false }, - PromptArg { name: "accent", description: "Accent colour (default #7048E8)", required: false }, + PromptArg { name: "accent", description: "Accent colour (default #2563EB)", required: false }, ], - template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Bold headline, an 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft dropShadow effect, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text).\n3. Use batch to apply repeated styling to several ids in one undo step.\n4. Finish with sizingV hug on the page frame so it fits its content.{verify}", - defaults: &[("width", "1440"), ("accent", "#7048E8")], + template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Semi Bold headline, a 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft neutral dropShadow, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text, no lower than #6B7280).\n3. Name every layer by what it is. Use one accent, one neutral ramp and at most three text colours; no emoji, gradient text or glows.\n4. Use batch to apply repeated styling to several ids in one undo step.\n5. Finish with sizingV hug on the page frame so it fits its content.{verify}", + defaults: &[("width", "1440"), ("accent", "#2563EB")], + }, + PromptDef { + name: "design_review", + title: "Review a design", + description: "Audit the selection, page or document for the usual AI-generated UI tells, fix the mechanical ones, then use judgment for copy, naming, gradients and overflow; re-audit and report what a person still has to decide.", + args: &[PromptArg { name: "target", description: "selection, page or document (default page)", required: false }], + template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}\n6. Take a screenshot of the frame you changed and look at it.", + defaults: &[("target", "page")], }, PromptDef { name: "prototype_flow", diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 70ac05999..78be68cec 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -42,8 +42,12 @@ screenshot returns a PNG of the page or of given layers to look at. undo/redo st Comments: comment.list returns threads (text, anchor node id, frame, page, x/y, replies); fix open ones, \ reply with what changed, then resolve (a reply reopens a thread). To react to new feedback, call \ wait_for_changes {after, timeoutMs} and pass the returned cursor back. \ +Design review: design.audit {scope} reports spacing, radii, type, colour, contrast, copy and naming findings \ +with severities; design.fix repairs the fixable ones as one undo step; design.rules lists the rules and \ +presets; design.configure {preset, grid, radii, brand, disabled} sets the file's design system, and \ +design.assert {failOn, minScore} is a read-only CI gate. \ Resources: figcraft://document, figcraft://node/{id}, figcraft://command/{id}, figcraft://comments. \ -prompts/list has workflows, including fix_comments."; +prompts/list has workflows, including fix_comments and design_review."; /// An MCP server bound to one backend. pub struct Server { diff --git a/crates/mcp/tests/it/protocol.rs b/crates/mcp/tests/it/protocol.rs index cadadbad0..1e83e5646 100644 --- a/crates/mcp/tests/it/protocol.rs +++ b/crates/mcp/tests/it/protocol.rs @@ -219,13 +219,16 @@ fn prompts_list_and_get() { let mut c = Client::new(); let r = c.rpc("prompts/list", json!({})); let names: Vec<&str> = r["result"]["prompts"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "prototype_flow", "fix_comments", "watch_comments"]); + assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments"]); let r = c.rpc("prompts/get", json!({"name": "mobile_screen", "arguments": {"screen": "login"}})); let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap(); assert!(text.contains("login") && text.contains("iPhone 16") && text.contains("#3B5BDB") && !text.contains("{device}")); assert_eq!(c.rpc("prompts/get", json!({"name": "mobile_screen"}))["error"]["code"], -32602); assert_eq!(c.rpc("prompts/get", json!({"name": "nope"}))["error"]["code"], -32602); assert_eq!(c.rpc("prompts/get", json!({"name": "landing_page", "arguments": {"product": ["x"]}}))["error"]["code"], -32602); + let r = c.rpc("prompts/get", json!({"name": "design_review", "arguments": {"target": "document"}})); + let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap(); + assert!(text.contains("design.audit") && text.contains("\"document\"") && !text.contains("{target}"), "{text}"); let r = c.rpc("prompts/get", json!({"name": "prototype_flow"})); assert!(r["result"]["messages"][0]["content"]["text"].as_str().unwrap().contains("Home, Details, Checkout")); let r = c.rpc("prompts/get", json!({"name": "fix_comments", "arguments": {"auto_resolve": "no", "author": "Ada"}})); From c0811b772b7573e772509c9643ebeb03bf84b676 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:57:32 +0800 Subject: [PATCH 010/268] M13: address the engine review findings --- crates/collab/src/change.rs | 5 ++++ crates/collab/src/diff_tests.rs | 14 ++++++++++- crates/collab/src/docprops.rs | 1 + crates/engine/src/cmd/create.rs | 2 +- crates/engine/src/design/fix.rs | 9 ++++--- crates/engine/src/design/mod.rs | 31 +++++++++++++++++------- crates/engine/src/design/tests.rs | 39 +++++++++++++++++++++++++++++++ crates/mcp/src/prompts.rs | 4 ++-- docs/collab-protocol.md | 3 ++- 9 files changed, 90 insertions(+), 18 deletions(-) diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 442376f37..e7ecf85f4 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -229,6 +229,11 @@ pub enum DocProp { Vote, /// Ended votes' results kept in the file, oldest first (whole). VoteHistory, + /// The file's design review settings (`design.configure`). + /// + /// Kept last: the wire encodes a variant's position, so adding one before it would shift the + /// existing properties. + DesignReview, } /// A document-level entry, by id. diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index bb81d0b1b..9c252c3e9 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use std::sync::Arc; use figcraft_color::{Color, Paint}; -use figcraft_doc::{Comment, DevSnapshot, Document, ImageData, Message, Node, NodeId, NodeKind, Style, StyleKind}; +use figcraft_doc::{Comment, DesignPreset, DevSnapshot, Document, ImageData, Message, Node, NodeId, NodeKind, Style, StyleKind}; use crate::change::{Change, DocProp, Entry, Json, Prop}; use crate::replica::{Mode, Replica}; @@ -48,6 +48,18 @@ fn property_edits_send_only_what_changed() { assert!(round_trip(&a, a.document()).is_empty(), "nothing changed"); } +#[test] +fn design_review_settings_round_trip_and_reach_a_snapshot() { + let (a, _, _, _) = setup(); + let mut b = a.document().clone(); + b.design_review.preset = DesignPreset::Strict; + b.design_review.grid = 8.0; + let changes = round_trip(&a, &b); + assert!(changes.contains(&Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() })); + let snapshot = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + assert!(snapshot.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "a snapshot carries the review settings"); +} + #[test] fn creations_moves_reorders_and_deletions_round_trip() { let (a, page, frame, kids) = setup(); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index b590064df..9a1305c62 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -353,6 +353,7 @@ doc_scalars! { Timer => timer, Vote => vote, VoteHistory => vote_history, + DesignReview => design_review, } /// Keyed maps (no order): changed and added entries are put, missing ones removed. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 920ec1113..5d23d6d02 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { spec!( "text.create", "Text", - "{text | characters, x?, y? (ignored inside an auto layout parent), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}", + "{text | characters, x?, y? (ignored inside an auto layout parent unless props.absolute is true, which keeps the transform they set), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}", true, |s, p| { create_kind(s, p, "text") } ), diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs index e6a5e6d7e..ca110cca7 100644 --- a/crates/engine/src/design/fix.rs +++ b/crates/engine/src/design/fix.rs @@ -13,9 +13,8 @@ use serde_json::{Value, json}; use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color}; -/// Fix what `roots` made fixable among `filter`'s rules. With `exact`, only findings on the roots -/// themselves are repaired, not findings on their descendants. `dry_run` reports the same counts -/// without changing the document. +/// Fix what `roots` made fixable among `filter`'s rules. With `exact_ids`, only findings on those +/// layers are repaired, not findings on their descendants. pub(crate) fn run( doc: &mut Document, roots: &[NodeId], @@ -24,7 +23,7 @@ pub(crate) fn run( scope: &str, preset: Option, filter: Option<&BTreeSet>, - exact: bool, + exact_ids: Option<&[NodeId]>, dry_run: bool, ) -> Value { let settings = Settings::new(doc, preset); @@ -34,7 +33,7 @@ pub(crate) fn run( .iter() .filter(|f| f.fixable && settings.enabled(f.rule)) .filter(|f| filter.is_none_or(|set| set.contains(f.rule))) - .filter(|f| !exact || roots.contains(&f.node)) + .filter(|f| exact_ids.is_none_or(|ids| ids.contains(&f.node))) .map(|f| (f.node, f.rule)) .collect(); let mut by_rule: BTreeMap<&'static str, usize> = BTreeMap::new(); diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 7e8229323..ec3fb1611 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -91,8 +91,16 @@ fn fix_cmd(s: &mut Session, p: &Value) -> Result { let filter = filter_arg("design.fix", p)?; let preset = preset_arg("design.fix", p)?; let exact = params::boolean(p, "exact").unwrap_or(false); + let exact_ids = if exact { ids_arg("design.fix", p)? } else { None }; let dry = params::boolean(p, "dryRun").unwrap_or(false); - Ok(fix::run(s.doc_mut()?, &roots, anchor, &path, &label, preset, filter.as_ref(), exact, dry)) + // A dry run or a fix that changes nothing must not mark the file unsaved or add an undo step: + // work on a copy and put it back only when it differs. + let mut doc = s.doc()?.clone(); + let result = fix::run(&mut doc, &roots, anchor, &path, &label, preset, filter.as_ref(), exact_ids.as_deref(), dry); + if !dry && s.doc()? != &doc { + *s.doc_mut()? = doc; + } + Ok(result) } /// `design.assert`: a read-only gate for CI. Returns the score when the design passes; an error @@ -267,16 +275,23 @@ fn settings_json(config: &DesignReview) -> Value { /// The layers a command works on, its scope label, the layer aggregate findings point at and that /// layer's path. +/// The `ids` parameter, parsed without collapsing ancestors: `exact` needs the layers the caller +/// listed, while the walk uses their top-most roots. +fn ids_arg(cmd: &str, p: &Value) -> Result>> { + let Some(v) = params::get(p, "ids") else { return Ok(None) }; + let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + let mut ids = Vec::new(); + for item in items { + let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + ids.push(id); + } + Ok(Some(ids)) +} + fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, Option, String)> { let doc = s.doc()?; // `ids` names the layers directly (the review window fixes only the findings the user kept). - if let Some(v) = params::get(p, "ids") { - let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; - let mut ids = Vec::new(); - for item in items { - let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; - ids.push(id); - } + if let Some(ids) = ids_arg(cmd, p)? { let roots = top_most(doc, &ids); let anchor = roots.first().copied(); let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 0033dcb9d..7984e305d 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -687,6 +687,45 @@ fn fix_with_exact_leaves_a_child_finding_alone() { assert_eq!(doc.node(child).unwrap().corners.radii[0], 3.0, "an ignored child finding stays: exact means the listed layers only"); } +#[test] +fn fix_with_exact_repairs_a_listed_parent_and_child() { + let mut s = Session::new(); + let parent = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Parent", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "cornerRadius": 3}}), + )); + let child = id(&ex( + &mut s, + "node.create", + json!({"type": "rectangle", "name": "Child", "parent": parent, "x": 0, "y": 0, "width": 80, "height": 40, + "props": {"cornerRadius": 3}}), + )); + let r = ex(&mut s, "design.fix", json!({"ids": [parent, child], "rules": ["radius.off-scale"], "exact": true})); + assert_eq!(r["changed"], 2, "{r}"); + let doc = s.doc().unwrap(); + assert_ne!(doc.node(parent).unwrap().corners.radii[0], 3.0, "the root is repaired"); + assert_ne!(doc.node(child).unwrap().corners.radii[0], 3.0, "a listed child is repaired too"); +} + +#[test] +fn fix_dry_run_and_no_op_do_not_dirty_the_document() { + let mut s = Session::new(); + let undo = s.ds().unwrap().history.undo.len(); + let redo = s.ds().unwrap().history.redo.len(); + let r = ex(&mut s, "design.fix", json!({"scope": "page", "dryRun": true})); + assert_eq!(r["changed"], 0, "{r}"); + assert_eq!(s.ds().unwrap().history.undo.len(), undo, "a dry run adds no undo step"); + assert_eq!(s.ds().unwrap().history.redo.len(), redo, "a dry run keeps redo"); + assert!(!s.ds().unwrap().is_dirty(), "a dry run leaves the file saved"); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(r["changed"], 0, "{r}"); + assert_eq!(s.ds().unwrap().history.undo.len(), undo, "a no-op fix adds no undo step"); + assert_eq!(s.ds().unwrap().history.redo.len(), redo, "a no-op fix keeps redo"); + assert!(!s.ds().unwrap().is_dirty(), "a no-op fix leaves the file saved"); +} + #[test] fn hardcoded_values_that_match_variables_are_reported() { let mut s = Session::new(); diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 12b74e448..287470d78 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -18,7 +18,7 @@ pub struct PromptDef { pub defaults: &'static [(&'static str, &'static str)], } -const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made."; +const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made or changed."; pub const PROMPTS: &[PromptDef] = &[ PromptDef { @@ -61,7 +61,7 @@ pub const PROMPTS: &[PromptDef] = &[ title: "Review a design", description: "Audit the selection, page or document for the usual AI-generated UI tells, fix the mechanical ones, then use judgment for copy, naming, gradients and overflow; re-audit and report what a person still has to decide.", args: &[PromptArg { name: "target", description: "selection, page or document (default page)", required: false }], - template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}\n6. Take a screenshot of the frame you changed and look at it.", + template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}", defaults: &[("target", "page")], }, PromptDef { diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 41c73190d..1a7e77052 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -148,7 +148,8 @@ As built: A diff gives new keys only to the children that need them (the longest run of old keys that is still increasing keeps its keys) and re-spaces a parent whose keys would grow past 48 characters. - **Document-level objects covered now**: the file name, the current page, document colours, the - colour profile, image presets, annotation categories and library data (whole values); styles, + colour profile, image presets, annotation categories, the design review settings + (`DocProp::DesignReview`) and library data (whole values); styles, comment threads, variable collections and variables (one entry per id plus the order of ids; the whole list when ids aren't unique); dev-mode snapshots (per layer); images (per content hash, the encoded bytes as base64; as an entry applies the claim is checked: every key is From 57efbc791fe83a28c204ea5479b99765325c1377 Mon Sep 17 00:00:00 2001 From: Timo Klerx <1579185+TKlerx@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:00:10 +0100 Subject: [PATCH 011/268] M6: Preserve variable prototype actions in .fig exports --- ROADMAP.md | 1 + contributors/people.toml | 4 + crates/format/src/fig/assets_tests.rs | 100 ++++++++++++++++ crates/format/src/fig/export.rs | 12 +- crates/format/src/fig/export/prototype.rs | 132 ++++++++++++++++++++-- crates/format/src/fig/kiwi.rs | 2 +- docs/file-format-parity.md | 6 +- 7 files changed, 243 insertions(+), 14 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index dc6204b44..1f4018855 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Experimental `.fig` export preserves set-variable, set-variable-mode and conditional prototype actions (#2210). | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | diff --git a/contributors/people.toml b/contributors/people.toml index c6924df5f..4b11ae582 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -115,3 +115,7 @@ display_name = "Hamza0101" [people.ashokram-si] real_name = "Ashok Ram" + +[people.TKlerx] +real_name = "Timo Klerx" +sync_github_name = true diff --git a/crates/format/src/fig/assets_tests.rs b/crates/format/src/fig/assets_tests.rs index 4e77ab4a3..f0a7cf5ab 100644 --- a/crates/format/src/fig/assets_tests.rs +++ b/crates/format/src/fig/assets_tests.rs @@ -1245,3 +1245,103 @@ fn a_scaled_instance_keeps_reset_lists_above_a_changed_style_link() { same_after_round_trip(&doc, "explicit list values above a changed style link"); } } + +#[test] +fn checkbox_variable_and_conditional_actions_round_trip() { + use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp}; + + let mut doc = Document::new("Checkbox"); + let page = doc.first_page().unwrap(); + doc.variables.collections.push(Collection { + id: "demo".into(), + name: "Demo".into(), + modes: vec![Mode { id: "default".into(), name: "Default".into() }], + extends: None, + }); + doc.variables.variables = vec![ + var("checked", "checked", "demo", VariableType::Boolean, &[("default", VariableValue::Boolean(false))]), + var("status", "status", "demo", VariableType::String, &[("default", VariableValue::String("Unchecked".into()))]), + ]; + let frame = doc.create(page, NodeKind::Frame, "Checkbox demo", 0.0, 0.0, 320.0, 180.0).unwrap(); + let toggle = doc.create(frame, NodeKind::Frame, "Toggle checkbox", 24.0, 24.0, 44.0, 44.0).unwrap(); + let mark = doc.create(toggle, NodeKind::Rectangle, "Checked indicator", 12.0, 12.0, 20.0, 20.0).unwrap(); + let label = doc.create(frame, NodeKind::Text(TextData::new("Unchecked")), "Status", 84.0, 36.0, 120.0, 20.0).unwrap(); + doc.node_mut(mark).unwrap().bound.insert("visible".into(), "checked".into()); + doc.node_mut(label).unwrap().bound.insert("characters".into(), "status".into()); + let set_status = |value| Action::SetVariable { variable: "status".into(), value: json!(value), expr: None }; + doc.node_mut(toggle).unwrap().interactions.push(Interaction { + trigger: Trigger::OnClick, + actions: vec![ + Action::SetVariable { variable: "checked".into(), value: Value::Null, expr: Some(Expr::op(ExprOp::Not, vec![Expr::var("checked")])) }, + Action::Conditional { + blocks: vec![ + ConditionalBlock { condition: Some(Expr::var("checked")), actions: vec![set_status("Checked")] }, + ConditionalBlock { condition: None, actions: vec![set_status("Unchecked")] }, + ], + }, + ], + transition: Transition::Instant, + duration_ms: 300, + easing: Easing::EaseOut, + delay_ms: 0, + }); + + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let (mut back, warnings) = import(&bytes, "Checkbox").unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let toggle = back.nodes().find(|n| n.name == "Toggle checkbox").unwrap(); + let [interaction] = toggle.interactions.as_slice() else { panic!("missing checkbox interaction") }; + assert_eq!(interaction.trigger, Trigger::OnClick); + let [Action::SetVariable { variable, expr: Some(expr), .. }, Action::Conditional { blocks }] = interaction.actions.as_slice() else { + panic!("wrong action order: {:?}", interaction.actions); + }; + let checked = back.nodes().find(|n| n.name == "Checked indicator").unwrap().bound["visible"].clone(); + let status = back.nodes().find(|n| n.name == "Status").unwrap().bound["characters"].clone(); + assert_eq!(variable, &checked); + assert_eq!(expr, &Expr::op(ExprOp::Not, vec![Expr::var(&checked)])); + assert_eq!(blocks.len(), 2); + assert_eq!(blocks[0].condition, Some(Expr::var(&checked))); + assert_eq!(blocks[1].condition, None); + let (expr, blocks) = (expr.clone(), blocks.clone()); + let modes = BTreeMap::new(); + for (is_checked, expected) in [(true, "Checked"), (false, "Unchecked")] { + let value = expr.eval(&back.variables, &modes).unwrap(); + assert_eq!(value, VariableValue::Boolean(is_checked)); + let checked = back.variables.variables.iter_mut().find(|v| v.id == checked).unwrap(); + *checked.values.values_mut().next().unwrap() = value; + let branch = ConditionalBlock::choose(&blocks, &back.variables, &modes).unwrap(); + assert_eq!(branch, &[Action::SetVariable { variable: status.clone(), value: json!(expected), expr: None }]); + } +} + +#[test] +fn overdeep_conditional_is_omitted_without_losing_the_export() { + use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp, MAX_EXPR_DEPTH}; + + let mut doc = Document::new("Depth"); + let frame = doc.create(doc.first_page().unwrap(), NodeKind::Frame, "Trigger", 0.0, 0.0, 100.0, 100.0).unwrap(); + let condition = (0..MAX_EXPR_DEPTH).fold(Expr::Value(VariableValue::Boolean(true)), |inner, _| Expr::op(ExprOp::Not, vec![inner])); + doc.node_mut(frame).unwrap().interactions.push(Interaction { + trigger: Trigger::OnClick, + actions: vec![ + Action::Conditional { + blocks: vec![ + ConditionalBlock { condition: Some(condition), actions: vec![Action::Back] }, + ConditionalBlock { condition: None, actions: vec![Action::CloseOverlay] }, + ], + }, + Action::Back, + ], + transition: Transition::Instant, + duration_ms: 300, + easing: Easing::EaseOut, + delay_ms: 0, + }); + + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.iter().any(|w| w.contains("nesting")), "{warnings:?}"); + let (back, _) = import(&bytes, "Depth").unwrap(); + let frame = back.nodes().find(|n| n.name == "Trigger").unwrap(); + assert_eq!(frame.interactions[0].actions, vec![Action::Back]); +} diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index f00de3606..5dcac9f9f 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -114,12 +114,12 @@ enum ImageType PNG=0 JPEG=1 SVG=2 PDF=3 enum ExportConstraintType CONTENT_SCALE=0 CONTENT_WIDTH=1 CONTENT_HEIGHT=2 enum ComponentPropType BOOL=0 TEXT=1 INSTANCE_SWAP=3 VARIANT=4 enum VariableField MISSING=0 CORNER_RADIUS=1 PARAGRAPH_SPACING=2 PARAGRAPH_INDENT=3 STROKE_WEIGHT=4 STACK_SPACING=5 STACK_PADDING_LEFT=6 STACK_PADDING_TOP=7 STACK_PADDING_RIGHT=8 STACK_PADDING_BOTTOM=9 VISIBLE=10 TEXT_DATA=11 WIDTH=12 HEIGHT=13 RECTANGLE_TOP_LEFT_CORNER_RADIUS=14 RECTANGLE_TOP_RIGHT_CORNER_RADIUS=15 RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS=16 RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS=17 BORDER_TOP_WEIGHT=18 BORDER_BOTTOM_WEIGHT=19 BORDER_LEFT_WEIGHT=20 BORDER_RIGHT_WEIGHT=21 STACK_COUNTER_SPACING=23 MIN_WIDTH=24 MAX_WIDTH=25 MIN_HEIGHT=26 MAX_HEIGHT=27 FONT_FAMILY=28 FONT_STYLE=29 OPACITY=31 FONT_SIZE=32 LETTER_SPACING=34 LINE_HEIGHT=36 OVERRIDDEN_SYMBOL_ID=37 -enum VariableDataType BOOLEAN=0 FLOAT=1 STRING=2 ALIAS=3 COLOR=4 SYMBOL_ID=7 TEXT_DATA=9 PROP_REF=13 +enum VariableDataType BOOLEAN=0 FLOAT=1 STRING=2 ALIAS=3 COLOR=4 EXPRESSION=5 SYMBOL_ID=7 TEXT_DATA=9 PROP_REF=13 enum VariableScope ALL_SCOPES=0 TEXT_CONTENT=1 CORNER_RADIUS=2 WIDTH_HEIGHT=3 GAP=4 ALL_FILLS=5 FRAME_FILL=6 SHAPE_FILL=7 TEXT_FILL=8 STROKE=9 STROKE_FLOAT=10 EFFECT_FLOAT=11 EFFECT_COLOR=12 OPACITY=13 FONT_STYLE=14 FONT_FAMILY=15 FONT_SIZE=16 LINE_HEIGHT=17 LETTER_SPACING=18 PARAGRAPH_SPACING=19 PARAGRAPH_INDENT=20 enum StyleType NONE=0 FILL=1 STROKE=2 TEXT=3 EFFECT=4 EXPORT=5 GRID=6 enum InteractionType ON_CLICK=0 DRAG=9 ON_HOVER=4 ON_PRESS=7 MOUSE_IN=2 MOUSE_OUT=3 MOUSE_DOWN=5 MOUSE_UP=6 AFTER_TIMEOUT=1 ON_KEY_DOWN=10 enum TriggerDevice KEYBOARD=0 UNKNOWN_CONTROLLER=1 -enum ConnectionType NONE=0 INTERNAL_NODE=1 URL=2 BACK=3 CLOSE=4 +enum ConnectionType NONE=0 INTERNAL_NODE=1 URL=2 BACK=3 CLOSE=4 SET_VARIABLE=5 CONDITIONAL=7 SET_VARIABLE_MODE=8 enum NavigationType NAVIGATE=0 OVERLAY=1 SWAP=2 SWAP_STATE=3 SCROLL_TO=4 enum TransitionType INSTANT_TRANSITION=0 DISSOLVE=1 SMART_ANIMATE=24 SLIDE_FROM_LEFT=3 SLIDE_FROM_RIGHT=4 SLIDE_FROM_TOP=5 SLIDE_FROM_BOTTOM=6 PUSH_FROM_LEFT=7 PUSH_FROM_RIGHT=8 PUSH_FROM_TOP=9 PUSH_FROM_BOTTOM=10 MOVE_FROM_LEFT=11 MOVE_FROM_RIGHT=12 MOVE_FROM_TOP=13 MOVE_FROM_BOTTOM=14 SLIDE_OUT_TO_LEFT=15 SLIDE_OUT_TO_RIGHT=16 SLIDE_OUT_TO_TOP=17 SLIDE_OUT_TO_BOTTOM=18 MOVE_OUT_TO_LEFT=19 MOVE_OUT_TO_RIGHT=20 MOVE_OUT_TO_TOP=21 MOVE_OUT_TO_BOTTOM=22 enum EasingType IN_CUBIC=0 OUT_CUBIC=1 INOUT_CUBIC=2 LINEAR=3 IN_BACK_CUBIC=4 OUT_BACK_CUBIC=5 INOUT_BACK_CUBIC=6 CUSTOM_CUBIC=7 GENTLE_SPRING=9 @@ -167,7 +167,9 @@ message VariantPropSpec GUID propDefId=1, string value=2 message StateGroupPropertyValueOrder string property=1, string[] values=2 message PropRefValue GUID defId=1 message SymbolId GUID guid=1 -message VariableAnyValue bool boolValue=1, string textValue=2, float floatValue=3, VariableID alias=4, Color colorValue=5, SymbolId symbolIdValue=8, TextData textDataValue=10, PropRefValue propRefValue=13 +message VariableAnyValue bool boolValue=1, string textValue=2, float floatValue=3, VariableID alias=4, Color colorValue=5, Expression expressionValue=6, SymbolId symbolIdValue=8, TextData textDataValue=10, PropRefValue propRefValue=13 +enum ExpressionFunction ADDITION=0 SUBTRACTION=1 MULTIPLY=3 DIVIDE=4 EQUALS=5 NOT_EQUAL=6 LESS_THAN=7 LESS_THAN_OR_EQUAL=8 GREATER_THAN=9 GREATER_THAN_OR_EQUAL=10 AND=11 OR=12 NOT=13 VAR_MODE_LOOKUP=16 NEGATE=17 +message Expression ExpressionFunction expressionFunction=1, VariableData[] expressionArguments=2 message VariableData VariableAnyValue value=1, VariableDataType dataType=2, VariableResolvedDataType resolvedDataType=3 message VariableDataMapEntry uint nodeField=1, VariableData variableData=2, VariableField variableField=3 message VariableDataMap VariableDataMapEntry[] entries=1 @@ -178,7 +180,9 @@ message VariableDataValuesEntry GUID modeID=1, VariableData variableData=2 message VariableDataValues VariableDataValuesEntry[] entries=1 message KeyTrigger int[] keyCodes=1, TriggerDevice triggerDevice=2 message PrototypeEvent InteractionType interactionType=1, float transitionTimeout=6, KeyTrigger keyTrigger=4 -message PrototypeAction GUID transitionNodeID=1, TransitionType transitionType=2, float transitionDuration=3, EasingType easingType=4, float[] easingFunction=12, ConnectionType connectionType=7, Vector overlayRelativePosition=9, NavigationType navigationType=10, string connectionURL=8, bool transitionPreserveScroll=11 +message PrototypeVariableTarget VariableID id=1 +message ConditionalActions PrototypeAction[] actions=1, VariableData condition=2 +message PrototypeAction GUID transitionNodeID=1, TransitionType transitionType=2, float transitionDuration=3, EasingType easingType=4, float[] easingFunction=12, ConnectionType connectionType=7, Vector overlayRelativePosition=9, NavigationType navigationType=10, string connectionURL=8, bool transitionPreserveScroll=11, PrototypeVariableTarget targetVariable=19, VariableData targetVariableData=20, ConditionalActions[] conditionalActions=24, VariableSetID targetVariableSetID=27, GUID targetVariableModeID=28 message PrototypeInteraction PrototypeEvent event=2, PrototypeAction[] actions=3 message PrototypeStartingPoint string name=1, string position=3 message OverlayBackgroundAppearance OverlayBackgroundType backgroundType=1, Color backgroundColor=2 diff --git a/crates/format/src/fig/export/prototype.rs b/crates/format/src/fig/export/prototype.rs index 3b0fcc122..4d86f776e 100644 --- a/crates/format/src/fig/export/prototype.rs +++ b/crates/format/src/fig/export/prototype.rs @@ -1,7 +1,10 @@ +use figcraft_doc::proto::{Expr, ExprOp, MAX_ACTION_DEPTH}; +use figcraft_doc::{VariableType, VariableValue}; + use super::common::key_codes; use super::{ - Action, Direction, Easing, Exporter, Fields, Interaction, Kv, Node, NodeId, Overflow, OverlayPosition, ScrollPosition, Transition, Trigger, arr, - b, color, e, fl, int, o, position, s, + AUX, Action, Direction, Easing, Exporter, Fields, Interaction, Kv, LAYERS, Node, NodeId, Overflow, OverlayPosition, ScrollPosition, Transition, + Trigger, arr, b, color, e, fl, guid, int, o, position, s, }; impl<'d> Exporter<'d> { @@ -73,11 +76,19 @@ impl<'d> Exporter<'d> { event.push(("transitionTimeout", fl(it.delay_secs()))); } event.insert(0, ("interactionType", e(ty))); - let actions: Vec = it.actions.iter().filter_map(|a| self.action(a, it)).collect(); + let actions: Vec = it.actions.iter().filter_map(|a| self.action(a, it, 0)).collect(); (!actions.is_empty()).then(|| o(vec![("event", o(event)), ("actions", arr(actions))])) } - fn action(&mut self, a: &Action, it: &Interaction) -> Option> { + fn action(&mut self, a: &Action, it: &Interaction, depth: usize) -> Option> { + let encoded = self.encode_action(a, it, depth); + if encoded.is_none() && matches!(a, Action::SetVariable { .. } | Action::SetVariableMode { .. } | Action::Conditional { .. }) { + self.warn("variable or conditional prototype actions with unsupported values, references or nesting were left out"); + } + encoded + } + + fn encode_action(&mut self, a: &Action, it: &Interaction, depth: usize) -> Option> { let node = |x: &mut Self, dest: &NodeId, nav: &'static str| -> Option> { let Some(g) = x.guid_of(*dest) else { x.warn("prototype actions whose destination isn't written were left out"); @@ -88,6 +99,10 @@ impl<'d> Exporter<'d> { Some(o(f)) }; let plain = |ty: &'static str| Some(o(vec![("connectionType", e(ty))])); + // Message → layer → interaction → action uses three Kiwi levels. Each + // conditional adds two, an expression operator adds three, and the deepest + // condition (an alias with a GUID) uses five levels below its action. + let expression_levels = (super::super::kiwi::MAX_DEPTH - 8 - 2 * depth) / 3; match a { Action::Navigate { dest, preserve_scroll } => { let mut act = node(self, dest, "NAVIGATE")?; @@ -120,13 +135,97 @@ impl<'d> Exporter<'d> { Action::Back => plain("BACK"), Action::CloseOverlay => plain("CLOSE"), Action::OpenUrl { url, .. } => Some(o(vec![("connectionType", e("URL")), ("connectionURL", s(url))])), - Action::SetVariable { .. } | Action::SetVariableMode { .. } | Action::Conditional { .. } => { - self.warn("variable and conditional prototype actions were left out"); - None + Action::SetVariable { variable, value, expr } => { + let target = self.doc.variables.get_by_id(variable)?; + let id = self.var_ids.get(variable.as_str())?; + let data = match expr { + Some(expr) => self.expression(expr, expression_levels)?, + None => { + let literal = match target.kind { + VariableType::Boolean => VariableValue::Boolean(value.as_bool()?), + VariableType::Number => VariableValue::Number(value.as_f64()?), + VariableType::String => VariableValue::String(value.as_str()?.to_owned()), + VariableType::Color => VariableValue::Color(super::Color::parse_css(value.as_str()?)?), + }; + literal_data(&literal)? + } + }; + Some(o(vec![ + ("connectionType", e("SET_VARIABLE")), + ("targetVariable", o(vec![("id", o(vec![("guid", guid(LAYERS, *id))]))])), + ("targetVariableData", data), + ])) } + Action::SetVariableMode { collection, mode } => { + let set = self.set_ids.get(collection.as_str())?; + let mode = self.mode_ids.get(&(collection.as_str(), mode.as_str()))?; + Some(o(vec![ + ("connectionType", e("SET_VARIABLE_MODE")), + ("targetVariableSetID", o(vec![("guid", guid(LAYERS, *set))])), + ("targetVariableModeID", guid(AUX, *mode)), + ])) + } + Action::Conditional { blocks } if depth < MAX_ACTION_DEPTH => { + let mut encoded = Vec::new(); + for block in blocks { + // Dropping an unreadable condition would turn this branch into an else. + let mut fields = Vec::new(); + if let Some(condition) = &block.condition { + fields.push(("condition", self.expression(condition, expression_levels)?)); + } + let actions = block.actions.iter().map(|action| self.action(action, it, depth + 1)).collect::>>()?; + fields.push(("actions", arr(actions))); + encoded.push(o(fields)); + } + Some(o(vec![("connectionType", e("CONDITIONAL")), ("conditionalActions", arr(encoded))])) + } + Action::Conditional { .. } => None, } } + fn expression(&self, expr: &Expr, levels: usize) -> Option> { + match expr { + Expr::Value(VariableValue::Alias(id)) => self.expression_alias(id), + Expr::Value(literal) => literal_data(literal), + Expr::Op { op, args } if levels > 0 && (1..=64).contains(&args.len()) => { + let args = args.iter().map(|arg| self.expression(arg, levels - 1)).collect::>>()?; + let (function, resolved) = match op { + ExprOp::Add => { + let string = args.iter().any(|arg| arg.get("resolvedDataType").and_then(Kv::str) == Some("STRING")); + ("ADDITION", if string { "STRING" } else { "FLOAT" }) + } + ExprOp::Subtract => ("SUBTRACTION", "FLOAT"), + ExprOp::Multiply => ("MULTIPLY", "FLOAT"), + ExprOp::Divide => ("DIVIDE", "FLOAT"), + ExprOp::Negate => ("NEGATE", "FLOAT"), + ExprOp::Equals => ("EQUALS", "BOOLEAN"), + ExprOp::NotEqual => ("NOT_EQUAL", "BOOLEAN"), + ExprOp::Less => ("LESS_THAN", "BOOLEAN"), + ExprOp::LessOrEqual => ("LESS_THAN_OR_EQUAL", "BOOLEAN"), + ExprOp::Greater => ("GREATER_THAN", "BOOLEAN"), + ExprOp::GreaterOrEqual => ("GREATER_THAN_OR_EQUAL", "BOOLEAN"), + ExprOp::And => ("AND", "BOOLEAN"), + ExprOp::Or => ("OR", "BOOLEAN"), + ExprOp::Not => ("NOT", "BOOLEAN"), + }; + Some(expression_data(function, resolved, args)) + } + Expr::InMode { variable, mode } if levels > 0 => { + let var = self.doc.variables.get_by_id(variable)?; + let mode = self.mode_ids.get(&(var.collection.as_str(), mode.as_str()))?; + let args = vec![self.expression_alias(variable)?, variable_data("STRING", "STRING", ("textValue", s(&format!("{AUX}:{mode}"))))]; + Some(expression_data("VAR_MODE_LOOKUP", super::common::resolved_type(var.kind), args)) + } + Expr::Mode { .. } | Expr::Op { .. } | Expr::InMode { .. } => None, + } + } + + fn expression_alias(&self, variable: &str) -> Option> { + let var = self.doc.variables.get_by_id(variable)?; + let local = self.var_ids.get(variable)?; + Some(variable_data("ALIAS", super::common::resolved_type(var.kind), ("alias", o(vec![("guid", guid(LAYERS, *local))])))) + } + /// An interaction's transition on one of its actions. fn transition(&mut self, it: &Interaction, f: &mut Fields) { let side_from = |d: Direction, l: &'static str, r: &'static str, t: &'static str, bo: &'static str| match d { @@ -175,3 +274,22 @@ impl<'d> Exporter<'d> { } } } + +fn variable_data(kind: &'static str, resolved: &'static str, value: (&'static str, Kv<'static>)) -> Kv<'static> { + o(vec![("dataType", e(kind)), ("resolvedDataType", e(resolved)), ("value", o(vec![value]))]) +} + +fn literal_data(value: &VariableValue) -> Option> { + let (kind, field) = match value { + VariableValue::Boolean(v) => ("BOOLEAN", ("boolValue", b(*v))), + VariableValue::Number(v) if v.is_finite() => ("FLOAT", ("floatValue", fl(*v))), + VariableValue::String(v) => ("STRING", ("textValue", s(&v.replace('\0', "")))), + VariableValue::Color(v) => ("COLOR", ("colorValue", color(*v))), + _ => return None, + }; + Some(variable_data(kind, kind, field)) +} + +fn expression_data(function: &'static str, resolved: &'static str, args: Vec>) -> Kv<'static> { + variable_data("EXPRESSION", resolved, ("expressionValue", o(vec![("expressionFunction", e(function)), ("expressionArguments", arr(args))]))) +} diff --git a/crates/format/src/fig/kiwi.rs b/crates/format/src/fig/kiwi.rs index 382311b40..d83a59a66 100644 --- a/crates/format/src/fig/kiwi.rs +++ b/crates/format/src/fig/kiwi.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; use std::fmt; /// Deepest struct/message nesting decoded. -const MAX_DEPTH: usize = 64; +pub(super) const MAX_DEPTH: usize = 64; /// Most values decoded from one message (every scalar, array element and field counts): at least /// [`MIN_VALUES`], and [`VALUES_PER_PACKED_BYTE`] per byte of the file's compressed canvas up to /// [`MAX_VALUES`], so a large real file decodes while a small one can't expand into a huge tree, diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index dd04fdf75..03c8dc2eb 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -129,7 +129,8 @@ scales and empty-style clears; they have not been checked in other software. with the area it paints); prototype interactions (clicks, hovers, presses, drags, mouse triggers, delays, keys with modifiers and controller buttons; navigate, overlays with their position, outside-click setting and - background, swap, change to, scroll to, back, close, open link; transitions and easing, custom + background, swap, change to, scroll to, back, close, open link, set variable, set variable mode + and conditional branches; transitions and easing, custom curves included), scrolling and fixed layers, flow starting points. - **Left out, with a warning each:** colour calculations that resolve to nothing (an operand missing, or more than 32 variables to read), variable bindings the format has no field for (component @@ -141,7 +142,8 @@ scales and empty-style clears; they have not been checked in other software. strokes (written plain), strokes wider on one side of their path (written as filled outlines, or with the width on both sides when the shape has a fill too), pattern fills, WebP export settings (written as PNG), image adjustments, glass settings other than frost, springs other than Gentle (written as ease - out), set-variable, set-variable-mode and conditional actions, scroll-to offsets, text decoration + out), prototype actions with unsupported values, references or nesting (including expressions + that read the current mode of a collection), scroll-to offsets, text decoration looks, variable font axes, text on a path, nested list levels, list spacing, hanging punctuation, leading trim, OpenType features, per-layer operations inside boolean groups, different stroke ends on lines, the Dash cap (no public name for it). Not written at all: stroke outlines of dashed and per-side strokes and of inside or From fb37d1733f62a57fb918b8cafc0f83349873e634 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 15:53:41 -0500 Subject: [PATCH 012/268] M9: Boards: mind maps in the document and engine (#2226) Part of #2226, step 1 of 4. A mind map node is a board object of its own (BoardItem::MindNode: a frame hugging its text, no box) and a branch is a connector marked `branch`; the tree is read from the branches alone. `board.mindMap` places a first node with three children and `board.mindMapAdd` adds a child or a sibling, each one undo step. The normalize pass (`board::settle_mind_maps`, `figcraft_doc::mind_layout`) lays a touched map out again from its first node: 88 between columns, 48 between siblings, each stack centred on its parent; a branch that no longer joins two layers of its page is removed. Branches are curved, stroke 4, #757575, round caps. Numbers are from a FigJam map saved and decoded. No toolbar entry, shortcuts or import yet. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 designed; Sonnet 5.5 wrote at medium --- ROADMAP.md | 3 +- crates/collab/src/board_sync_tests.rs | 2 + crates/doc/src/board.rs | 19 +- crates/doc/src/board_mindmap.rs | 138 +++++++ crates/doc/src/board_mindmap_tests.rs | 101 ++++++ crates/doc/src/lib.rs | 4 + crates/engine/src/board_mindmap_tests.rs | 316 ++++++++++++++++ crates/engine/src/board_tests.rs | 2 + crates/engine/src/board_tools_tests.rs | 15 +- crates/engine/src/boards/board.rs | 16 + crates/engine/src/boards/board/connectors.rs | 2 +- crates/engine/src/boards/board/edit.rs | 4 +- crates/engine/src/boards/board/items.rs | 1 + crates/engine/src/boards/board/mindmap.rs | 358 +++++++++++++++++++ crates/engine/src/boards/board/reshape.rs | 2 +- crates/engine/src/boards/board/tools.rs | 2 +- crates/engine/src/derived.rs | 5 +- crates/engine/src/lib.rs | 2 + crates/ui-egui/src/canvas/board_bar.rs | 2 +- docs/boards-parity.md | 7 +- docs/gaps.md | 5 +- docs/mcp.md | 18 +- docs/roadmap.md | 3 +- 23 files changed, 1007 insertions(+), 20 deletions(-) create mode 100644 crates/doc/src/board_mindmap.rs create mode 100644 crates/doc/src/board_mindmap_tests.rs create mode 100644 crates/engine/src/board_mindmap_tests.rs create mode 100644 crates/engine/src/boards/board/mindmap.rs diff --git a/ROADMAP.md b/ROADMAP.md index dc6204b44..0f59d1bce 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -13,6 +13,7 @@ start with [`docs/gaps.md`](docs/gaps.md). | | Value | Kind | |---|---|---| +| 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 | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Menu/command breadth | **100%** (212 / 212) | measured, [`docs/parity-checklist.md`](docs/parity-checklist.md) (`cargo xtask parity`) | | Feature breadth | **~85%** (core editor ~94%) | estimated, [`docs/target-app-parity.md`](docs/target-app-parity.md) | diff --git a/crates/collab/src/board_sync_tests.rs b/crates/collab/src/board_sync_tests.rs index 422d60134..442388477 100644 --- a/crates/collab/src/board_sync_tests.rs +++ b/crates/collab/src/board_sync_tests.rs @@ -29,6 +29,7 @@ fn a_boards_kind_and_its_objects_metadata_sync() { to: End::Point { x: 5.0, y: 5.0 }, routing: Routing::Elbow, path: None, + branch: false, })); let mut r = host.clone(); r.apply(&diff(&host, &edited).unwrap().changes, Mode::Strict).unwrap(); @@ -38,6 +39,7 @@ fn a_boards_kind_and_its_objects_metadata_sync() { to: End::Point { x: 9.0, y: 1.0 }, routing: Routing::Straight, path: None, + branch: false, })); let d = diff(&r, &moved).unwrap(); assert!(matches!(d.changes.as_slice(), [Change::Set { prop: Prop::Board, .. }]), "{:?}", d.changes); diff --git a/crates/doc/src/board.rs b/crates/doc/src/board.rs index 89413b2e9..bcd6452e8 100644 --- a/crates/doc/src/board.rs +++ b/crates/doc/src/board.rs @@ -62,18 +62,29 @@ pub enum BoardItem { /// A table: a frame of row frames holding cell frames with text (its column lines are thin /// rectangles laid over it). Table, + /// A mind map's node: a frame hugging its text, with no outline. What it hangs from is the + /// branch (a connector with `branch`) arriving at it. + MindNode, } impl BoardItem { /// Objects selected and moved as a whole: a click on their text or outline picks them, and /// they never take other layers in. pub fn is_atom(&self) -> bool { - matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table) + matches!( + self, + BoardItem::Sticky { .. } + | BoardItem::Shape { .. } + | BoardItem::Label { .. } + | BoardItem::Stamp { .. } + | BoardItem::Table + | BoardItem::MindNode + ) } /// Objects whose first text layer is their text (a double-click or Enter edits it). pub fn has_text(&self) -> bool { - matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. }) + matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) } /// Who made it (stickies and stamps; empty when unknown). @@ -115,6 +126,7 @@ impl BoardItem { BoardItem::Stamp { .. } => "stamp", BoardItem::Ink => "ink", BoardItem::Table => "table", + BoardItem::MindNode => "mindNode", } } } @@ -619,4 +631,7 @@ pub struct Connector { /// Its path as reshaped by hand; `None`: routed by itself. #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option, + /// A mind map's branch: `from` is the parent, `to` the child. The map's shape is read from these. + #[serde(default, skip_serializing_if = "crate::node::is_default")] + pub branch: bool, } diff --git a/crates/doc/src/board_mindmap.rs b/crates/doc/src/board_mindmap.rs new file mode 100644 index 000000000..53b72fbc3 --- /dev/null +++ b/crates/doc/src/board_mindmap.rs @@ -0,0 +1,138 @@ +//! Mind map layout: where the nodes of a map go, from their sizes and their tree. Pure geometry, +//! like `board_route`; the engine's normalize pass reads the tree from the branches and moves the +//! layers (#2226). + +use figcraft_geom::{Point, Rect}; + +use crate::NodeId; + +/// The room between a node's column and its children's column. +pub const MIND_GAP_X: f64 = 88.0; +/// The room between a node (with everything under it) and the next one below. +pub const MIND_GAP_Y: f64 = 48.0; +/// The most nodes one map is laid out with (a larger one is left as it is). +pub const MIND_MAX_NODES: usize = 2000; +/// The deepest level of a map that is laid out (the first node is level 0). +pub const MIND_MAX_DEPTH: usize = 64; + +/// One node of a mind map as the layout sees it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MindBox { + pub id: NodeId, + /// Its box on the page now. The root's stays; of the others only the size counts, and the + /// centre's y, which orders siblings. + pub rect: Rect, + /// Its parent's index in the slice (`None`: the root, entry 0). Always a smaller index. + pub parent: Option, + /// Left of the root. Read on the root's children only: deeper nodes follow their parent. + pub left: bool, +} + +fn finite(r: Rect) -> bool { + [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) +} + +/// Where every node but the root goes: its box's top-left on the page. Nodes whose parent isn't +/// an earlier entry, that are deeper than [`MIND_MAX_DEPTH`] or that would land off the finite +/// plane are left out; a slice that is empty, longer than [`MIND_MAX_NODES`], whose first entry +/// has a parent or that holds a box that is not finite is left alone altogether. +pub fn mind_layout(nodes: &[MindBox]) -> Vec<(NodeId, Point)> { + let n = nodes.len(); + let Some(root) = nodes.first().filter(|r| r.parent.is_none()) else { return Vec::new() }; + if n > MIND_MAX_NODES || !nodes.iter().all(|b| finite(b.rect)) { + return Vec::new(); + } + // The tree: who is a child of whom, which side of the root it is on, how deep. + let (mut left, mut depth, mut valid) = (vec![false; n], vec![0_usize; n], vec![false; n]); + if let Some(v) = valid.first_mut() { + *v = true; + } + // Children by parent and side (0: right, 1: left; below the root only the parent's side is used). + let mut kids: Vec<[Vec; 2]> = vec![[Vec::new(), Vec::new()]; n]; + for (i, b) in nodes.iter().enumerate().skip(1) { + let Some(p) = b.parent.filter(|p| *p < i && valid.get(*p).copied().unwrap_or(false)) else { continue }; + let d = depth.get(p).copied().unwrap_or(0) + 1; + if d > MIND_MAX_DEPTH { + continue; + } + let side = if p == 0 { b.left } else { left.get(p).copied().unwrap_or(false) }; + if let (Some(v), Some(l), Some(dp)) = (valid.get_mut(i), left.get_mut(i), depth.get_mut(i)) { + (*v, *l, *dp) = (true, side, d); + } + if let Some(k) = kids.get_mut(p) { + k[usize::from(side)].push(i); + } + } + // Siblings keep the order they are in: by their middles, then by id. + for k in kids.iter_mut().flatten() { + k.sort_by(|a, b| { + let (x, y) = (nodes.get(*a), nodes.get(*b)); + match (x, y) { + (Some(x), Some(y)) => x.rect.center().y.total_cmp(&y.rect.center().y).then(x.id.cmp(&y.id)), + _ => std::cmp::Ordering::Equal, + } + }); + } + let height = |i: usize| nodes.get(i).map_or(0.0, |b| b.rect.height()); + let width = |i: usize| nodes.get(i).map_or(0.0, |b| b.rect.width()); + // Span, backward: a node's room is its own height or its children's stack, whichever is more. + let stack = |span: &[f64], list: &[usize]| { + let total: f64 = list.iter().map(|c| span.get(*c).copied().unwrap_or(0.0)).sum(); + total + MIND_GAP_Y * list.len().saturating_sub(1) as f64 + }; + let mut span = vec![0.0_f64; n]; + for i in (1..n).rev() { + let own = kids.get(i).map_or(0.0, |k| stack(&span, &k[usize::from(left.get(i).copied().unwrap_or(false))])); + if let Some(s) = span.get_mut(i) { + *s = height(i).max(own); + } + } + // Place, forward. `column[i]`: where node i's children's column begins (its left edge on the + // right side, its right edge on the left side); `centre[i]`: its middle. + let mut column = vec![0.0_f64; n]; + let mut centre = vec![0.0_f64; n]; + let mut out = Vec::new(); + let root_c = root.rect.center().y; + if let Some(c) = centre.first_mut() { + *c = root_c; + } + let mut ok = vec![false; n]; + if let Some(o) = ok.first_mut() { + *o = true; + } + for i in 0..n { + if !ok.get(i).copied().unwrap_or(false) { + continue; + } + let Some(k) = kids.get(i) else { continue }; + for side in [false, true] { + let list = k[usize::from(side)].as_slice(); + if list.is_empty() { + continue; + } + // The column the group starts in: past the widest node of its parent's own group. + let x = + if i == 0 { if side { root.rect.x0 - MIND_GAP_X } else { root.rect.x1 + MIND_GAP_X } } else { column.get(i).copied().unwrap_or(0.0) }; + let widest = list.iter().map(|c| width(*c)).fold(0.0, f64::max); + let mut top = centre.get(i).copied().unwrap_or(0.0) - stack(&span, list) / 2.0; + for &c in list { + let s = span.get(c).copied().unwrap_or(0.0); + let mid = top + s / 2.0; + let at = Point::new(if side { x - width(c) } else { x }, mid - height(c) / 2.0); + top += s + MIND_GAP_Y; + if !(at.x.is_finite() && at.y.is_finite() && mid.is_finite()) { + continue; + } + if let (Some(m), Some(col), Some(o)) = (centre.get_mut(c), column.get_mut(c), ok.get_mut(c)) { + *m = mid; + *col = if side { x - widest - MIND_GAP_X } else { x + widest + MIND_GAP_X }; + *o = true; + } + if let Some(b) = nodes.get(c) { + out.push((b.id, at)); + } + } + } + } + out +} diff --git a/crates/doc/src/board_mindmap_tests.rs b/crates/doc/src/board_mindmap_tests.rs new file mode 100644 index 000000000..25e554697 --- /dev/null +++ b/crates/doc/src/board_mindmap_tests.rs @@ -0,0 +1,101 @@ +//! Mind map layout (`board_mindmap`): columns 88 apart, siblings 48 apart, stacks centred on their +//! parents (#2226). + +use figcraft_geom::{Point, Rect}; + +use crate::NodeId; +use crate::board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_NODES, MindBox, mind_layout}; + +/// The first node, always at the origin, 200 x 36. +fn root() -> MindBox { + MindBox { id: NodeId(1), rect: Rect::new(0.0, 0.0, 200.0, 36.0), parent: None, left: false } +} + +/// A node `w` x `h` whose current top is `y` (only its middle, which orders siblings, counts). +fn node(id: u64, parent: usize, (w, h): (f64, f64), y: f64) -> MindBox { + MindBox { id: NodeId(id), rect: Rect::new(0.0, y, w, y + h), parent: Some(parent), left: false } +} + +fn at(placed: &[(NodeId, Point)], id: u64) -> (f64, f64) { + let p = placed.iter().find(|(n, _)| *n == NodeId(id)).map(|(_, p)| *p).unwrap_or_else(|| panic!("node {id} not placed in {placed:?}")); + (p.x, p.y) +} + +/// The root and three children (100, 60 and 80 wide) whose middles are in that order; `middle` is +/// the second child's size. +fn three(middle: (f64, f64)) -> Vec { + vec![root(), node(2, 0, (100.0, 24.0), 0.0), node(3, 0, middle, 22.0 - middle.1 / 2.0), node(4, 0, (80.0, 24.0), 20.0)] +} + +#[test] +fn three_children_stand_88_right_of_the_root_72_apart_centred_on_it() { + assert_eq!((MIND_GAP_X, MIND_GAP_Y), (88.0, 48.0)); + let placed = mind_layout(&three((60.0, 24.0))); + assert_eq!([at(&placed, 2), at(&placed, 3), at(&placed, 4)], [(288.0, -66.0), (288.0, 6.0), (288.0, 78.0)]); + assert!(placed.iter().all(|(n, _)| *n != NodeId(1)), "the first node stays where it is"); +} + +#[test] +fn a_taller_node_pushes_its_neighbours_half_its_growth_each_way() { + let placed = mind_layout(&three((60.0, 72.0))); + assert_eq!([at(&placed, 2), at(&placed, 3), at(&placed, 4)], [(288.0, -90.0), (288.0, -18.0), (288.0, 102.0)]); +} + +#[test] +fn grandchildren_share_a_column_past_the_widest_sibling_and_their_parents_make_room() { + let nodes = vec![ + root(), + node(2, 0, (100.0, 24.0), 0.0), + node(3, 0, (60.0, 24.0), 10.0), + node(4, 1, (40.0, 24.0), 0.0), + node(5, 1, (40.0, 24.0), 10.0), + node(6, 2, (40.0, 24.0), 0.0), + ]; + let placed = mind_layout(&nodes); + // 476 = 288 + 100 + 88, although B is only 60 wide. + let got: Vec<(f64, f64)> = (2..=6).map(|i| at(&placed, i)).collect(); + assert_eq!(got, [(288.0, -30.0), (288.0, 78.0), (476.0, -66.0), (476.0, 6.0), (476.0, 78.0)]); +} + +#[test] +fn left_children_mirror_the_right_ones() { + let mut l = node(2, 0, (80.0, 24.0), 0.0); + l.left = true; + let placed = mind_layout(&[root(), l, node(3, 1, (50.0, 24.0), 0.0)]); + assert_eq!((at(&placed, 2), at(&placed, 3)), ((-168.0, 6.0), (-306.0, 6.0))); +} + +#[test] +fn the_layout_is_a_fixed_point_ties_go_by_id_and_junk_is_skipped() { + let nodes = vec![ + root(), + node(2, 0, (100.0, 24.0), 0.0), + node(3, 0, (60.0, 24.0), 10.0), + node(4, 1, (40.0, 24.0), 0.0), + node(5, 1, (40.0, 24.0), 10.0), + node(6, 2, (40.0, 24.0), 0.0), + ]; + let placed = mind_layout(&nodes); + let again: Vec = nodes + .iter() + .map(|b| { + let p = placed.iter().find(|(n, _)| *n == b.id).map_or(b.rect.origin(), |(_, p)| *p); + MindBox { rect: Rect::from_origin_size(p, b.rect.size()), ..*b } + }) + .collect(); + assert_eq!(mind_layout(&again), placed, "a laid out map is left as it is"); + // The same height: the lower id goes first. + let tied = mind_layout(&[root(), node(9, 0, (10.0, 24.0), 5.0), node(7, 0, (10.0, 24.0), 5.0)]); + assert!(at(&tied, 7).1 < at(&tied, 9).1); + // Junk: nothing placed, nothing panics. + assert!(mind_layout(&[]).is_empty()); + let mut nan = three((60.0, 24.0)); + nan[2].rect = Rect::new(f64::NAN, 0.0, 1.0, 1.0); + assert!(mind_layout(&nan).is_empty()); + let mut orphan = three((60.0, 24.0)); + orphan.push(node(8, 9, (10.0, 24.0), 0.0)); + assert!(!mind_layout(&orphan).iter().any(|(n, _)| *n == NodeId(8)), "a parent that doesn't come first"); + let mut huge = vec![root()]; + huge.extend((0..MIND_MAX_NODES as u64).map(|i| node(i + 2, 0, (10.0, 24.0), i as f64))); + assert!(mind_layout(&huge).is_empty()); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 81760d718..6a0c2aedf 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -9,6 +9,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod board; +mod board_mindmap; mod board_route; pub mod colors; pub mod comments; @@ -27,6 +28,7 @@ pub mod vector_faces; pub mod vector_regions; pub use board::*; +pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, MindBox, mind_layout}; pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; @@ -1314,6 +1316,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap) { #[cfg(test)] mod blur_tests; #[cfg(test)] +mod board_mindmap_tests; +#[cfg(test)] mod board_route_tests; #[cfg(test)] mod board_shape_tests; diff --git a/crates/engine/src/board_mindmap_tests.rs b/crates/engine/src/board_mindmap_tests.rs new file mode 100644 index 000000000..d8105bf0f --- /dev/null +++ b/crates/engine/src/board_mindmap_tests.rs @@ -0,0 +1,316 @@ +//! Mind maps (#2226): `board.mindMap` and `board.mindMapAdd` make nodes and branches, and the +//! normalize pass lays a touched map out again from its first node after every edit. + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{BoardItem, Connector, Document, END_GAP, End, LetterSpacing, LineHeight, NodeId, NodeKind, Routing, Side, StrokeCap}; +use figcraft_geom::{Point, Rect}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::board::text_of; +use crate::board_tests::{board, connector, drawn, id, near, node}; +use crate::collab_live_tests::Room; + +fn bx(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().world_bounds(id).unwrap() +} + +fn same(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// `board.mindMap` at (100, 200): the first node, its three children and their branches. +fn map(s: &mut Session) -> (NodeId, [NodeId; 3], [NodeId; 3]) { + let out = s.execute("board.mindMap", &json!({"x": 100, "y": 200})).unwrap(); + let kids: Vec = out["children"].as_array().unwrap().clone(); + let (c, k): (Vec, Vec) = kids.iter().map(|v| (id(v, "id"), id(v, "connector"))).unzip(); + (id(&out, "id"), [c[0], c[1], c[2]], [k[0], k[1], k[2]]) +} + +fn text_data(s: &Session, n: NodeId) -> figcraft_doc::TextData { + let t = text_of(s.doc().unwrap(), n).unwrap(); + match node(s, t).kind { + NodeKind::Text(td) => td, + other => panic!("not text: {other:?}"), + } +} + +fn is_mind_node(s: &Session, n: NodeId) -> bool { + node(s, n).board == Some(BoardItem::MindNode) +} + +/// The nodes hanging off `parent`, top to bottom, in `doc`. +fn kids(doc: &Document, parent: NodeId) -> Vec { + let mut v: Vec<(f64, NodeId)> = doc + .nodes() + .filter_map(|n| match &n.board { + Some(BoardItem::Connector(Connector { from: End::Node { node, .. }, to: End::Node { node: to, .. }, branch: true, .. })) + if *node == parent => + { + doc.world_bounds(*to).map(|b| (b.center().y, *to)) + } + _ => None, + }) + .collect(); + v.sort_by(|a, b| a.0.total_cmp(&b.0)); + v.into_iter().map(|p| p.1).collect() +} + +fn places(s: &Session, ids: &[NodeId]) -> Vec { + ids.iter().map(|i| bx(s, *i)).collect() +} + +fn branches(s: &Session) -> Vec { + s.doc().unwrap().nodes().filter(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.branch)).map(|n| n.id).collect() +} + +/// Starter child `i` (`k`, on branch `line`) of the first node: its text, its place and its branch. +fn check_child(s: &Session, root: NodeId, (k, line): (NodeId, NodeId), i: usize) { + let r = bx(s, root); + let td = text_data(s, k); + assert_eq!(td.characters, ["A concept", "An idea", "A thought"][i]); + assert_eq!((td.style.font_size, td.style.font_style.as_str()), (16.0, "Medium")); + assert_eq!((td.style.line_height, td.style.letter_spacing), (LineHeight::Percent(150.0), LetterSpacing::Percent(-1.1))); + let b = bx(s, k); + assert!(same(b.x0, r.x1 + 88.0), "child {i}: 88 right of the root"); + assert_eq!(b.height(), 24.0); + let t = bx(s, text_of(s.doc().unwrap(), k).unwrap()); + assert!(same(b.width(), t.width()), "child {i}: the node is its text, no padding"); + assert!(is_mind_node(s, k)); + let want = Connector { + from: End::Node { node: root, side: Side::Right, at: None }, + to: End::Node { node: k, side: Side::Left, at: None }, + routing: Routing::Curved, + path: None, + branch: true, + }; + assert_eq!(connector(s, line), want); + let l = node(s, line); + assert_eq!((l.stroke.cap_start, l.stroke.cap_end), (StrokeCap::Round, StrokeCap::Round)); + assert_eq!((l.stroke.weight, l.strokes), (4.0, vec![Paint::solid(Color::from_rgb8_const(0x75, 0x75, 0x75))])); + let pts = drawn(s, line); + assert!(near(pts[0], Point::new(r.x1 + END_GAP, r.center().y)), "{pts:?}"); + assert!(near(*pts.last().unwrap(), Point::new(b.x0 - END_GAP, b.center().y)), "{pts:?}"); +} + +#[test] +fn a_mind_map_is_a_first_node_with_three_children_on_branches() { + let mut s = board(); + let before = s.doc().unwrap().ids().count(); + let depth = s.undo_depth().0; + let (root, kids, lines) = map(&mut s); + assert_eq!(node(&s, root).board, Some(BoardItem::MindNode)); + assert!(node(&s, root).is_board_atom()); + let r = bx(&s, root); + assert_eq!((r.x0, r.y0), (100.0, 200.0)); + let td = text_data(&s, root); + assert_eq!((td.characters.as_str(), td.style.font_size, td.style.font_style.as_str()), ("Topic", 24.0, "Bold")); + assert_eq!((td.style.line_height, td.style.letter_spacing), (LineHeight::Percent(150.0), LetterSpacing::Percent(-1.9))); + assert_eq!(r.height(), 36.0, "one line at 150%"); + let text = text_of(s.doc().unwrap(), root).unwrap(); + assert_eq!(node(&s, text).fills, vec![Paint::solid(Color::from_rgb8_const(0x1E, 0x1E, 0x1E))]); + for (i, pair) in kids.into_iter().zip(lines).enumerate() { + check_child(&s, root, pair, i); + } + let h = bx(&s, kids[0]).height(); + assert!(same(bx(&s, kids[1]).center().y, r.center().y)); + assert!(same(bx(&s, kids[0]).center().y, r.center().y - h - 48.0)); + assert!(same(bx(&s, kids[2]).center().y, r.center().y + h + 48.0)); + assert_eq!(s.selection(), vec![root]); + assert_eq!(s.undo_depth().0, depth + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().ids().count(), before); +} + +#[test] +fn a_new_child_goes_below_its_siblings_and_the_stack_stays_centred() { + let mut s = board(); + let (root, kids3, _) = map(&mut s); + let h = bx(&s, kids3[0]).height(); + let was = places(&s, &kids3); + s.ui_requests.clear(); + let out = s.execute("board.mindMapAdd", &json!({"id": root, "text": "Four", "edit": true})).unwrap(); + let new = id(&out, "id"); + assert!(is_mind_node(&s, new)); + assert_eq!(text_data(&s, new).style.font_size, 16.0); + let order = kids(s.doc().unwrap(), root); + assert_eq!(order, [kids3[0], kids3[1], kids3[2], new]); + let cy: Vec = order.iter().map(|n| bx(&s, *n).center().y).collect(); + assert!(cy.windows(2).all(|w| same(w[1] - w[0], h + 48.0)), "{cy:?}"); + assert!(same((cy[0] + cy[3]) / 2.0, bx(&s, root).center().y)); + assert!(same(bx(&s, kids3[0]).y0, was[0].y0 - (h + 48.0) / 2.0), "the first one moved up 36"); + assert_eq!(s.selection(), vec![new]); + assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(new))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(places(&s, &kids3), was, "the three are back exactly"); + // Without an id the selected first node is the one. + s.execute("select.set", &json!({"ids": [root]})).unwrap(); + s.execute("board.mindMapAdd", &json!({})).unwrap(); + assert_eq!(kids(s.doc().unwrap(), root).len(), 4); +} + +#[test] +fn a_childs_child_starts_the_next_column_and_a_sibling_goes_right_after() { + let mut s = board(); + let (root, [c0, c1, c2], _) = map(&mut s); + let h = bx(&s, c0).height(); + let g1 = id(&s.execute("board.mindMapAdd", &json!({"id": c0})).unwrap(), "id"); + let g2 = id(&s.execute("board.mindMapAdd", &json!({"id": c0})).unwrap(), "id"); + let column = [c0, c1, c2].iter().map(|n| bx(&s, *n).x1).fold(f64::MIN, f64::max) + 88.0; + assert!(same(bx(&s, g1).x0, column) && same(bx(&s, g2).x0, column), "past the widest of the three"); + assert!(same(bx(&s, g2).center().y - bx(&s, g1).center().y, h + 48.0)); + assert!(same((bx(&s, g1).center().y + bx(&s, g2).center().y) / 2.0, bx(&s, c0).center().y)); + for g in [g1, g2] { + let line = s.doc().unwrap().nodes().find(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.to.node() == Some(g))).unwrap().id; + assert!(matches!(connector(&s, line).from, End::Node { node, side: Side::Right, .. } if node == c0)); + } + assert!(same(bx(&s, c1).center().y - bx(&s, c0).center().y, (2.0 * h + 48.0) / 2.0 + 48.0 + h / 2.0), "108 below"); + let new = id(&s.execute("board.mindMapAdd", &json!({"id": c1, "relation": "sibling"})).unwrap(), "id"); + let line = s.doc().unwrap().nodes().find(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.to.node() == Some(new))).unwrap().id; + assert!(matches!(connector(&s, line).from, End::Node { node, .. } if node == root)); + assert_eq!(kids(s.doc().unwrap(), root), [c0, c1, new, c2]); +} + +#[test] +fn more_lines_push_the_siblings_apart() { + let mut s = board(); + let (root, [c0, c1, c2], _) = map(&mut s); + let (h, was) = (bx(&s, c1).height(), places(&s, &[c0, c1, c2])); + let t = text_of(s.doc().unwrap(), c1).unwrap(); + s.execute("node.set", &json!({"id": t, "props": {"characters": "one\ntwo\nthree"}})).unwrap(); + let h3 = bx(&s, c1).height(); + assert_eq!((h, h3), (24.0, 72.0)); + assert!(same(bx(&s, c1).center().y, bx(&s, root).center().y)); + for k in [c0, c2] { + assert!(same((bx(&s, k).center().y - bx(&s, c1).center().y).abs(), (h + h3) / 2.0 + 48.0)); + } + assert!(same(bx(&s, c0).y0, was[0].y0 - (h3 - h) / 2.0), "24 up"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(places(&s, &[c0, c1, c2]), was); +} + +#[test] +fn the_first_node_carries_the_map_and_a_child_moved_by_hand_goes_back_or_swaps() { + let mut s = board(); + let (root, kids3, lines) = map(&mut s); + let was = places(&s, &kids3); + s.execute("transform.move", &json!({"ids": [root], "dx": 50, "dy": 30})).unwrap(); + for (k, w) in kids3.iter().zip(&was) { + let b = bx(&s, *k); + assert!(same(b.x0, w.x0 + 50.0) && same(b.y0, w.y0 + 30.0), "{b:?} from {w:?}"); + } + for l in lines { + assert!(near(drawn(&s, l)[0], Point::new(bx(&s, root).x1 + END_GAP, bx(&s, root).center().y))); + } + let now = places(&s, &kids3); + s.execute("transform.move", &json!({"ids": [kids3[2]], "dx": 300, "dy": 5})).unwrap(); + assert_eq!(places(&s, &kids3), now, "it goes back"); + s.execute("transform.move", &json!({"ids": [kids3[0]], "dx": 0, "dy": 100})).unwrap(); + assert_eq!(kids(s.doc().unwrap(), root), [kids3[1], kids3[0], kids3[2]], "past the middle one's middle: they swap"); + assert!(same(bx(&s, kids3[1]).center().y, bx(&s, root).center().y - 72.0)); +} + +#[test] +fn a_deleted_node_leaves_its_children_in_place_and_takes_its_branches() { + let mut s = board(); + let (root, [c0, c1, c2], _) = map(&mut s); + let h = bx(&s, c0).height(); + let g = id(&s.execute("board.mindMapAdd", &json!({"id": c1})).unwrap(), "id"); + let at = bx(&s, g); + let (undo, _) = s.undo_depth(); + s.execute("edit.delete", &json!({"ids": [c1]})).unwrap(); + let left = branches(&s); + assert_eq!(left.len(), 2, "the root's two others"); + for l in &left { + assert!(!matches!(connector(&s, *l).to, End::Node { node, .. } if node == c1 || node == g), "none to the gone node or its child"); + } + assert_eq!(bx(&s, g), at, "the child stays where it was"); + assert!(is_mind_node(&s, g)); + let r = bx(&s, root).center().y; + assert!(same(bx(&s, c0).center().y, r - (h + 48.0) / 2.0) && same(bx(&s, c2).center().y, r + (h + 48.0) / 2.0)); + let line = s.doc().unwrap().nodes().find(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.to.node() == Some(c2))).unwrap().id; + let spot = bx(&s, c2); + s.execute("edit.delete", &json!({"ids": [line]})).unwrap(); + assert_eq!(bx(&s, c2), spot, "a detached node stays"); + assert!(same(bx(&s, c0).center().y, r)); + assert_eq!(branches(&s).len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.undo_depth().0, undo); + assert_eq!(branches(&s).len(), 4); + assert!(s.doc().unwrap().contains(c1)); +} + +#[test] +fn two_people_adding_at_once_end_with_one_layout() { + let mut s = board(); + let (root, [c0, ..], _) = map(&mut s); + let h = bx(&s, c0).height(); + let mut room = Room::new(s.doc().unwrap().clone(), 2, 7); + for i in 0..2 { + room.s(i).execute("board.mindMapAdd", &json!({"id": root})).unwrap(); + } + room.settle(); + room.check(); + let doc = room.server.document(); + let order = kids(doc, root); + assert_eq!(order.len(), 5); + let centres = |doc: &Document, order: &[NodeId]| order.iter().map(|n| doc.world_bounds(*n).unwrap().center().y).collect::>(); + let cy = centres(doc, &order); + assert!(cy.windows(2).all(|w| w[1] > w[0] && same(w[1] - w[0], h + 48.0)), "{cy:?}"); + assert!(same((cy[0] + cy[4]) / 2.0, doc.world_bounds(root).unwrap().center().y)); + // One makes a child three lines tall while the other adds one. + let t = text_of(doc, order[1]).unwrap(); + room.s(0).execute("node.set", &json!({"id": t, "props": {"characters": "one\ntwo\nthree"}})).unwrap(); + room.s(1).execute("board.mindMapAdd", &json!({"id": root})).unwrap(); + room.settle(); + room.check(); + let doc = room.server.document(); + let order = kids(doc, root); + assert_eq!(order.len(), 6); + let (boxes, mut gap_ok) = (order.iter().map(|n| doc.world_bounds(*n).unwrap()).collect::>(), true); + for w in boxes.windows(2) { + gap_ok &= same(w[1].y0 - w[0].y1, 48.0); + } + assert!(gap_ok, "48 between every pair: {boxes:?}"); + assert!(boxes.iter().any(|b| same(b.height(), 3.0 * h))); + let (top, bottom) = (boxes[0].y0, boxes[5].y1); + assert!(same((top + bottom) / 2.0, doc.world_bounds(root).unwrap().center().y)); +} + +#[test] +fn refusals_saved_files_and_a_second_pass_changes_nothing() { + let mut d = Session::new(); + d.execute("file.new", &json!({})).unwrap(); + for cmd in ["board.mindMap", "board.mindMapAdd"] { + assert!(matches!(d.execute(cmd, &json!({})), Err(crate::EngineError::Disabled(..))), "{cmd} on a design file"); + } + let mut s = board(); + let (root, ..) = map(&mut s); + let sticky = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "id"); + for p in [json!({"id": sticky}), json!({"id": root, "relation": "cousin"}), json!({"id": root, "relation": "sibling"})] { + assert!(s.execute("board.mindMapAdd", &p).is_err(), "{p}"); + } + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("board.mindMapAdd", &json!({})).is_err(), "nothing selected"); + let twenty_one: Vec = (0..21).map(|i| format!("n{i}")).collect(); + assert!(s.execute("board.mindMap", &json!({"children": twenty_one})).is_err()); + assert!(s.execute("board.mindMap", &json!({"children": "x"})).is_err()); + let doc = s.doc().unwrap(); + let (back, _) = figcraft_format::from_json(&figcraft_format::to_json(doc).unwrap().to_string()).unwrap(); + assert_eq!(back.nodes().filter(|n| n.board == Some(BoardItem::MindNode)).count(), 4); + assert_eq!(back.nodes().filter(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.branch)).count(), 3); + // An ordinary connector writes no `branch`; a file without it reads `false`. + let mut plain = board(); + let a = id(&plain.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap(), "id"); + let b = id(&plain.execute("board.sticky", &json!({"x": 400, "y": 0})).unwrap(), "id"); + plain.execute("board.connector", &json!({"from": a, "to": b})).unwrap(); + assert!(!figcraft_format::to_json(plain.doc().unwrap()).unwrap().to_string().contains("\"branch\"")); + let item: BoardItem = serde_json::from_value(json!({"type": "connector", "from": {"x": 0, "y": 0}, "to": {"x": 1, "y": 1}})).unwrap(); + assert!(matches!(item, BoardItem::Connector(c) if !c.branch)); + // Every layer touched again: a laid out map is not an edit. + let mut again = doc.clone(); + again.mark_dirty(doc.ids().collect::>()); + crate::normalize(&mut again, doc); + assert!(again == *doc, "a second pass changes nothing"); +} diff --git a/crates/engine/src/board_tests.rs b/crates/engine/src/board_tests.rs index 9e99bd1c9..5ddd4e1be 100644 --- a/crates/engine/src/board_tests.rs +++ b/crates/engine/src/board_tests.rs @@ -206,6 +206,7 @@ fn routes_are_the_same_for_the_same_document() { to: End::Point { x: 300.0, y: 500.0 }, routing: Routing::Elbow, path: None, + branch: false, }; let doc = s.doc().unwrap(); let r = route(doc, &c).unwrap(); @@ -357,6 +358,7 @@ fn board_commands_survive_junk() { json!({"path": "M0 0 L 1e308 1e308", "points": [[0, 0], [1e308, 1]]}), json!({"end": "from", "target": {"x": 1e308, "y": -1e308}, "side": "inside", "style": "curved"}), json!({"id": 99_999, "end": 7, "target": [1], "style": "wavy"}), + json!({"id": 99_999, "relation": 7, "children": "x", "text": [1], "x": "NaN", "y": 1e308}), ]; let ids: Vec<&str> = crate::cmd::all_commands() .iter() diff --git a/crates/engine/src/board_tools_tests.rs b/crates/engine/src/board_tools_tests.rs index 6ed291e13..1e306a7d9 100644 --- a/crates/engine/src/board_tools_tests.rs +++ b/crates/engine/src/board_tools_tests.rs @@ -96,7 +96,8 @@ fn routes_take_named_sides_and_free_points() { let a = id(&s.execute("board.shape", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(), "id"); let b = id(&s.execute("board.shape", &json!({"x": 300, "y": 300, "width": 100, "height": 100})).unwrap(), "id"); let doc = s.doc().unwrap(); - let elbow = |from, to| route(doc, &figcraft_doc::Connector { from, to, routing: figcraft_doc::Routing::Elbow, path: None }).unwrap(); + let elbow = + |from, to| route(doc, &figcraft_doc::Connector { from, to, routing: figcraft_doc::Routing::Elbow, path: None, branch: false }).unwrap(); let side = |n, side| End::Node { node: n, side, at: None }; let p = |x, y| End::Point { x, y }; let pt = Point::new; @@ -109,8 +110,16 @@ fn routes_take_named_sides_and_free_points() { assert_eq!(elbow(p(0.0, 0.0), p(100.0, 40.0)), vec![pt(0.0, 0.0), pt(50.0, 0.0), pt(50.0, 40.0), pt(100.0, 40.0)]); assert_eq!(elbow(p(0.0, 0.0), p(100.0, 0.0)), vec![pt(0.0, 0.0), pt(100.0, 0.0)]); // An automatic side faces the other end. - let straight = - route(doc, &figcraft_doc::Connector { from: side(a, Side::Auto), to: p(50.0, 500.0), routing: figcraft_doc::Routing::Straight, path: None }); + let straight = route( + doc, + &figcraft_doc::Connector { + from: side(a, Side::Auto), + to: p(50.0, 500.0), + routing: figcraft_doc::Routing::Straight, + path: None, + branch: false, + }, + ); assert_eq!(straight.unwrap(), vec![pt(50.0, 104.0), pt(50.0, 500.0)]); assert_eq!(Side::from_id("TOP"), Some(Side::Top)); assert_eq!(Side::from_id("inside"), None); diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index 1a66eed22..c7564967a 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -25,6 +25,7 @@ mod connectors; mod derived; mod edit; mod items; +mod mindmap; mod reshape; mod tools; @@ -70,6 +71,7 @@ pub(crate) use items::add_text; pub use items::{CONNECTED_GAP, connected_place}; use items::{add_connected, ink_cmd, next_sticky, shape_cmd, stamp_cmd, sticky_cmd}; pub use items::{edit_text, owner_of_text, sticky_font_size, text_of}; +pub(crate) use mindmap::settle_mind_maps; pub(crate) use reshape::path_handle_at; pub use reshape::selected_connector_handles; @@ -176,6 +178,20 @@ pub fn specs() -> Vec { true, reshape::reshape ), + spec!( + "board.mindMap", + "Mind map", + "{x?, y? (the first node's top-left in the parent; default the middle of the view), text? (default Topic), children? (their texts, at most 20; default A concept, An idea, A thought), parent?, edit? (start typing in the first node; default false)} → {id, text, children: [{id, text, connector}...]} a first node with children on its right, joined by branches; the map lays itself out", + true, + mindmap::mind_map_cmd + ), + spec!( + "board.mindMapAdd", + "Add mind map node", + "{id? (a mind map node; default the selected or edited one), relation?: child|sibling (default child), text?, edit? (start typing in it; default false)} → {id, text, connector} a child below the node's other children, or a sibling right after it; the map lays itself out again", + true, + mindmap::mind_map_add + ), spec!("board.label", "Connector label", "{id (a connector; default the selection), text (empty removes it)} → {id, label}", true, label_cmd), spec!( "board.stamp", diff --git a/crates/engine/src/boards/board/connectors.rs b/crates/engine/src/boards/board/connectors.rs index f12a7792a..408de045a 100644 --- a/crates/engine/src/boards/board/connectors.rs +++ b/crates/engine/src/boards/board/connectors.rs @@ -65,7 +65,7 @@ pub(super) fn connector_cmd(s: &mut Session, p: &Value) -> Result { let end = cap_of(cmd, p, "endCap")?.unwrap_or(CAPS.1); let page = s.page()?; let doc = s.doc_mut()?; - let id = make(doc, page, Connector { from, to, routing, path: None }, (start, end))?; + let id = make(doc, page, Connector { from, to, routing, path: None, branch: false }, (start, end))?; let mut out = json!({"id": id}); if let Some(text) = string(p, "label").filter(|t| !t.trim().is_empty()) { out["label"] = json!(set_label(doc, id, &text)?); diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs index 97be2ba96..88a38d438 100644 --- a/crates/engine/src/boards/board/edit.rs +++ b/crates/engine/src/boards/board/edit.rs @@ -84,7 +84,7 @@ pub(super) fn set_color(s: &mut Session, p: &Value) -> Result { n.strokes = vec![Paint::solid(line_shade(color))]; } BoardItem::Connector(_) | BoardItem::Ink => doc.get_mut(id)?.strokes = vec![Paint::solid(line_shade(color))], - BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table => continue, + BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode => continue, } changed.push(id); } @@ -132,7 +132,7 @@ impl Restyle { }; // Text sizes: shapes' and labels' text (stickies size theirs to fit). let sized = match (self.size, &item) { - (Some(size), BoardItem::Shape { .. } | BoardItem::Label { .. }) => resize_text(doc, id, size), + (Some(size), BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) => resize_text(doc, id, size), _ => false, }; Ok(changed || sized) diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index b409eeb90..2a264c5b5 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -250,6 +250,7 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result { to: End::Node { node: id, side: to_side, at: None }, routing, path: None, + branch: false, }; let line = make(doc, page, connector, CAPS)?; s.set_selection(vec![id]); diff --git a/crates/engine/src/boards/board/mindmap.rs b/crates/engine/src/boards/board/mindmap.rs new file mode 100644 index 000000000..858255d74 --- /dev/null +++ b/crates/engine/src/boards/board/mindmap.rs @@ -0,0 +1,358 @@ +//! Mind maps (#2226): a node is a frame hugging one text ([`BoardItem::MindNode`]) and a branch is +//! a connector with `branch` set, from the parent to the child. The tree is read from the branches +//! and from nothing else; [`settle_mind_maps`] lays a touched map out again in the normalize pass, +//! so the commands only make nodes and branches. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{ + AutoLayout, BoardItem, Connector, Document, End, LetterSpacing, LineHeight, MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, MindBox, + NodeId, NodeKind, Routing, Side, Sizing, StrokeCap, TextAlignH, TextAutoResize, mind_layout, +}; +use figcraft_geom::{Affine, Point, Rect}; +use serde_json::{Value, json}; + +use super::connectors::make; +use super::items::{add, add_text, owner_of_text}; +use super::{INK, Result, Session, bad, boolean, get, id, is_board, num_or, parent_of, require, string, textedit}; +use crate::EngineError; + +/// The first node's text size and the other nodes'. +const MIND_ROOT_SIZE: f64 = 24.0; +const MIND_NODE_SIZE: f64 = 16.0; +/// The line height of every node's text, in percent, and the letter spacing of the first node's +/// and the others' (percent of the size). +const MIND_LINE_HEIGHT: f64 = 150.0; +const MIND_ROOT_TRACKING: f64 = -1.9; +const MIND_NODE_TRACKING: f64 = -1.1; +/// A node's least width: an emptied one stays clickable. +const MIND_MIN_W: f64 = 8.0; +/// What `board.mindMap` puts in the first node and its children when it isn't told. +const MIND_ROOT_TEXT: &str = "Topic"; +const MIND_STARTERS: [&str; 3] = ["A concept", "An idea", "A thought"]; +/// The most children `board.mindMap` makes, and the longest text it puts in a node. +const MIND_MAX_STARTERS: usize = 20; +const MIND_MAX_TEXT: usize = 500; +/// How far from the page's middle a first node may be put. +const MIND_MAX_COORD: f64 = 1.0e9; +/// Branches' look. +const BRANCH: Color = Color::from_rgb8_const(0x75, 0x75, 0x75); +const BRANCH_WEIGHT: f64 = 4.0; + +/// A node's frame and its text, `text` at `size`: the frame hugs the text with no padding, and the +/// text grows on one line. +fn make_node(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, root: bool) -> Result<(NodeId, NodeId)> { + let size = if root { MIND_ROOT_SIZE } else { MIND_NODE_SIZE }; + let line = size * MIND_LINE_HEIGHT / 100.0; + let frame = add(doc, parent, NodeKind::Frame, "Mind map node", at, (MIND_MIN_W, line), |n| { + n.fills.clear(); + n.clip = false; + n.layout = Some(AutoLayout { padding: [0.0; 4], ..AutoLayout::default() }); + n.child_layout.sizing_h = Sizing::Hug; + n.child_layout.sizing_v = Sizing::Hug; + n.child_layout.min_w = Some(MIND_MIN_W); + n.child_layout.min_h = Some(line); + n.board = Some(BoardItem::MindNode); + })?; + let label = add_text(doc, frame, text, size, INK, TextAlignH::Left, 1.0)?; + if let Some(n) = doc.node_mut(label) { + n.child_layout.sizing_h = Sizing::Hug; + if let NodeKind::Text(td) = &mut n.kind { + td.auto_resize = TextAutoResize::WidthAndHeight; + td.style.line_height = LineHeight::Percent(MIND_LINE_HEIGHT); + td.style.letter_spacing = LetterSpacing::Percent(if root { MIND_ROOT_TRACKING } else { MIND_NODE_TRACKING }); + if root { + td.style.font_style = "Bold".into(); + } else { + td.style.font_style = "Medium".into(); + } + } + } + Ok((frame, label)) +} + +/// The branch from `parent` to `child` (on its left side when `left`), on `page`. +fn branch(doc: &mut Document, page: NodeId, parent: NodeId, child: NodeId, left: bool) -> Result { + let (out, back) = if left { (Side::Left, Side::Right) } else { (Side::Right, Side::Left) }; + let c = Connector { + from: End::Node { node: parent, side: out, at: None }, + to: End::Node { node: child, side: back, at: None }, + routing: Routing::Curved, + path: None, + branch: true, + }; + let line = make(doc, page, c, (StrokeCap::Round, StrokeCap::Round))?; + let n = doc.get_mut(line)?; + n.strokes = vec![Paint::solid(BRANCH)]; + n.stroke.weight = BRANCH_WEIGHT; + Ok(line) +} + +/// A branch of a map as the tree reads it. +#[derive(Clone, Copy)] +struct Branch { + line: NodeId, + parent: NodeId, + child: NodeId, + left: bool, +} + +/// The branches of `doc` that join two different layers of their own page, by id. (Others are +/// the normalize pass's to remove.) +fn branches(doc: &Document) -> Vec { + let mut v: Vec = doc + .nodes() + .filter_map(|n| match &n.board { + Some(BoardItem::Connector(Connector { from: End::Node { node: a, side, .. }, to: End::Node { node: b, .. }, branch: true, .. })) + if a != b && doc.contains(*a) && doc.contains(*b) && doc.page_of(*a) == doc.page_of(n.id) && doc.page_of(*b) == doc.page_of(n.id) => + { + Some(Branch { line: n.id, parent: *a, child: *b, left: *side == Side::Left }) + } + _ => None, + }) + .collect(); + v.sort_by_key(|b| b.line); + v +} + +/// The branch arriving at `node`: the one with the lowest connector id, when it has several. +fn arriving(bs: &[Branch], node: NodeId) -> Option { + bs.iter().find(|b| b.child == node).copied() +} + +/// The children of `node` on one side, in layout order (by their middles, then id). +fn map_children(doc: &Document, bs: &[Branch], node: NodeId, left: bool) -> Vec { + let mut v: Vec<(f64, NodeId)> = bs + .iter() + .filter(|b| b.parent == node && b.left == left && arriving(bs, b.child).is_some_and(|a| a.line == b.line)) + .filter_map(|b| doc.world_bounds(b.child).map(|r| (r.center().y, b.child))) + .collect(); + v.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + v.into_iter().map(|p| p.1).collect() +} + +/// Whether `node` is on the left of its map (a first node: no). +fn map_side(bs: &[Branch], node: NodeId) -> bool { + let (mut at, mut left) = (node, false); + for _ in 0..MIND_MAX_DEPTH { + let Some(b) = arriving(bs, at) else { break }; + (at, left) = (b.parent, b.left); + } + left +} + +/// The text `p` gives for `key`, a node's at most [`MIND_MAX_TEXT`] characters. +fn text_param(p: &Value, key: &str) -> String { + string(p, key).unwrap_or_default().chars().take(MIND_MAX_TEXT).collect() +} + +/// A coordinate from the params, finite and within [`MIND_MAX_COORD`] of the origin. +fn coord(cmd: &str, p: &Value, key: &str, default: f64) -> Result { + let v = num_or(p, key, default); + if v.is_finite() && v.abs() <= MIND_MAX_COORD { Ok(v) } else { Err(bad(cmd, format!("`{key}` is a position within a billion of the origin"))) } +} + +/// `children?` of `board.mindMap`: the starter texts. +fn starters(cmd: &str, p: &Value) -> Result> { + match get(p, "children") { + None => Ok(MIND_STARTERS.iter().map(|t| (*t).to_string()).collect()), + Some(Value::Array(a)) if a.len() <= MIND_MAX_STARTERS => { + a.iter().map(|v| v.as_str().map(|t| t.chars().take(MIND_MAX_TEXT).collect()).ok_or_else(|| bad(cmd, "`children` holds texts"))).collect() + } + _ => Err(bad(cmd, format!("`children` is a list of at most {MIND_MAX_STARTERS} texts"))), + } +} + +pub(super) fn mind_map_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "board.mindMap"; + require(s, cmd)?; + let parent = parent_of(cmd, s, p)?; + let (vx, vy) = { + let v = &s.ds()?.view; + (v.cx, v.cy) + }; + let (x, y) = (coord(cmd, p, "x", vx)?, coord(cmd, p, "y", vy)?); + let texts = starters(cmd, p)?; + let root_text = string(p, "text").map_or_else(|| MIND_ROOT_TEXT.to_string(), |_| text_param(p, "text")); + let page = s.page()?; + let doc = s.doc_mut()?; + let (root, label) = make_node(doc, parent, (x, y), &root_text, true)?; + let mut made = Vec::new(); + // Anywhere below one another will do: the normalize pass puts them right, in this order. + let line = MIND_NODE_SIZE * MIND_LINE_HEIGHT / 100.0 + MIND_GAP_Y; + for (i, t) in texts.iter().enumerate() { + let (k, text) = make_node(doc, parent, (x + MIND_MIN_W + MIND_GAP_X, y + i as f64 * line), t, false)?; + let b = branch(doc, page, root, k, false)?; + made.push(json!({"id": k, "text": text, "connector": b})); + } + s.set_selection(vec![root]); + if boolean(p, "edit") == Some(true) { + s.request_ui("board.editText", json!({"id": root})); + } + Ok(json!({"id": root, "text": label, "children": made})) +} + +pub(super) fn mind_map_add(s: &mut Session, p: &Value) -> Result { + let cmd = "board.mindMapAdd"; + require(s, cmd)?; + let editing = s.ds()?.text_edit.as_ref().map(|t| t.id); + let doc = s.doc()?; + let from = id(p, "id") + .or_else(|| editing.and_then(|t| owner_of_text(doc, t))) + .or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i))) + .ok_or_else(|| EngineError::Disabled(cmd.into(), "select a mind map node first".into()))?; + let n = doc.get(from)?; + if n.board != Some(BoardItem::MindNode) { + return Err(bad(cmd, "that isn't a mind map node")); + } + let sibling = match string(p, "relation").as_deref() { + None | Some("child") => false, + Some("sibling") => true, + Some(other) => return Err(bad(cmd, format!("`relation` is child or sibling, not `{other}`"))), + }; + let (page, container) = (s.page()?, n.parent.ok_or_else(|| bad(cmd, "that node has no parent"))?); + if doc.page_of(from) != Some(page) { + return Err(bad(cmd, "that node is on another page")); + } + let bs = branches(doc); + let at = doc.world_bounds(from).ok_or_else(|| bad(cmd, "that node has no place"))?; + let new_h = MIND_NODE_SIZE * MIND_LINE_HEIGHT / 100.0; + // The parent, the side, and where the new node's top-left goes on the page. + let (parent, left, top_left) = if sibling { + let a = arriving(&bs, from).ok_or_else(|| bad(cmd, "the first node has no siblings: add a child"))?; + // Its middle lands between this node and the next sibling, so the order puts it right after. + (a.parent, a.left, Point::new(at.x0, at.y1 + MIND_GAP_Y / 2.0 - new_h / 2.0)) + } else { + let left = map_side(&bs, from); + let last = map_children(doc, &bs, from, left).last().and_then(|l| doc.world_bounds(*l)); + let top = last.map_or(at.center().y - new_h / 2.0, |l| l.y1 + MIND_GAP_Y); + (from, left, Point::new(if left { at.x0 - MIND_GAP_X - MIND_MIN_W } else { at.x1 + MIND_GAP_X }, top)) + }; + let local = doc.world_transform(container).inverse() * top_left; + if !(local.x.is_finite() && local.y.is_finite()) { + return Err(bad(cmd, "the new node can't be placed there")); + } + let text = text_param(p, "text"); + if editing.is_some() { + textedit::end(s)?; + } + let doc = s.doc_mut()?; + let (node, label) = make_node(doc, container, (local.x, local.y), &text, false)?; + let line = branch(doc, page, parent, node, left)?; + s.set_selection(vec![node]); + if boolean(p, "edit") == Some(true) { + s.request_ui("board.editText", json!({"id": node})); + } + Ok(json!({"id": node, "text": label, "connector": line})) +} + +/// The tree of a document's branches: for each layer its arriving branch (the lowest connector +/// id), and each parent's children by it. +type Children = BTreeMap>; + +fn children_of(bs: &[Branch]) -> (BTreeSet, Children) { + let mut arrived = BTreeSet::new(); + let mut kids: Children = BTreeMap::new(); + for b in bs { + if arrived.insert(b.child) { + kids.entry(b.parent).or_default().push(*b); + } + } + (arrived, kids) +} + +/// Every branch that no longer joins two layers of its own page is removed, and the layers it +/// joined that are still there count as stirred (so does an end of a branch that is gone). +fn prune_branches(doc: &mut Document, before: &Document, touched: &BTreeSet) -> BTreeSet { + let mut stirred = BTreeSet::new(); + let ends = |c: &Connector| [c.from.node(), c.to.node()].into_iter().flatten().collect::>(); + for id in touched.iter().filter(|i| !doc.contains(**i)) { + if let Some(BoardItem::Connector(c)) = before.node(*id).and_then(|n| n.board.as_ref()) + && c.branch + { + stirred.extend(ends(c)); + } + } + let mut gone = Vec::new(); + for n in doc.nodes() { + let Some(BoardItem::Connector(c)) = &n.board else { continue }; + let page = doc.page_of(n.id); + let joins = |e: &End| matches!(e, End::Node { node, .. } if doc.contains(*node) && page.is_some() && doc.page_of(*node) == page); + if c.branch && !(joins(&c.from) && joins(&c.to) && c.from.node() != c.to.node()) { + gone.push((n.id, ends(c))); + } + } + for (line, joined) in gone { + stirred.extend(joined); + let _ = doc.remove(line); + } + stirred.retain(|i| doc.contains(*i)); + stirred +} + +/// The boxes of the map under `root`, breadth first (so a parent always comes before its +/// children), and the connectors that hold it together. `None`: a box is missing. +fn map_boxes(doc: &Document, root: NodeId, kids: &Children) -> Option<(Vec, Vec)> { + let first = doc.world_bounds(root)?; + let mut boxes = vec![MindBox { id: root, rect: first, parent: None, left: false }]; + let (mut lines, mut seen) = (Vec::new(), BTreeSet::from([root])); + let (mut at, mut depths) = (0, vec![0_usize]); + while let Some(b) = boxes.get(at).copied() { + let depth = depths.get(at).copied().unwrap_or(MIND_MAX_DEPTH); + for k in kids.get(&b.id).filter(|_| depth < MIND_MAX_DEPTH).into_iter().flatten() { + if boxes.len() >= MIND_MAX_NODES || !seen.insert(k.child) { + continue; + } + boxes.push(MindBox { id: k.child, rect: doc.world_bounds(k.child)?, parent: Some(at), left: k.left }); + depths.push(depth + 1); + lines.push(k.line); + } + at += 1; + } + Some((boxes, lines)) +} + +/// Move layer `id` by `d` on the page. +fn shift(doc: &mut Document, id: NodeId, d: Point) { + let parent = doc.node(id).and_then(|n| n.parent).map_or(Affine::IDENTITY, |p| doc.world_transform(p)); + if let Some(n) = doc.node_mut(id) { + n.transform = parent.inverse() * Affine::translate((d.x, d.y)) * parent * n.transform; + } +} + +/// After layout and before connectors follow: the maps an edit touched are laid out again from +/// their first nodes (a map that is already in place is not written to, so the pass is idempotent). +/// A branch that no longer joins two layers of its page is removed first: the only structural +/// write, and what makes a deleted node's children float free and a detached node stay detached. +pub(crate) fn settle_mind_maps(doc: &mut Document, before: &Document, touched: &BTreeSet) { + if !is_board(doc) || touched.is_empty() { + return; + } + let stirred = prune_branches(doc, before, touched); + let bs = branches(doc); + if bs.is_empty() { + return; + } + let hit = |doc: &Document, id: NodeId| touched.contains(&id) || doc.ancestors(id).iter().any(|a| touched.contains(a)); + let (arrived, kids) = children_of(&bs); + let roots: Vec = kids.keys().copied().filter(|p| !arrived.contains(p)).collect(); + for root in roots { + let Some((boxes, lines)) = map_boxes(doc, root, &kids) else { continue }; + if boxes.iter().any(|b| !(b.rect.x0.is_finite() && b.rect.y0.is_finite() && b.rect.x1.is_finite() && b.rect.y1.is_finite())) { + continue; + } + let stale = boxes.iter().any(|b| stirred.contains(&b.id) || hit(doc, b.id)) || lines.iter().any(|l| hit(doc, *l)); + if !stale { + continue; + } + let now: BTreeMap = boxes.iter().map(|b| (b.id, b.rect)).collect(); + for (id, to) in mind_layout(&boxes) { + let Some(was) = now.get(&id) else { continue }; + let d = to - was.origin(); + if d.x.is_finite() && d.y.is_finite() && d.hypot() > 1e-6 { + shift(doc, id, Point::new(d.x, d.y)); + } + } + } +} diff --git a/crates/engine/src/boards/board/reshape.rs b/crates/engine/src/boards/board/reshape.rs index 2f441c7ce..2295b94b6 100644 --- a/crates/engine/src/boards/board/reshape.rs +++ b/crates/engine/src/boards/board/reshape.rs @@ -26,7 +26,7 @@ fn moved(doc: &Document, c: &Connector, portion: usize, p: Point) -> Option Option { }); line.ids.push(n.id); } - Some(BoardItem::Label { .. }) => h.text = true, + Some(BoardItem::Label { .. } | BoardItem::MindNode) => h.text = true, Some(BoardItem::Table) => h.table = true, Some(BoardItem::Stamp { .. }) | None => {} } diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 16456492c..11d4aaf41 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,13 +1,13 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) **Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that follow what they join (straight, elbow or curved, their ends dragged onto other objects), marker, highlighter and eraser, stamps, text and sections, five built-in templates and tables, edited together in the existing live sessions, with a shared countdown and voting sessions to run a -workshop. Music, board widgets, mind maps and the rest of the tail are missing. Remaining: +workshop. Music, board widgets, the mind maps' toolbar entry and gestures, and the rest of the tail are missing. Remaining: ~20–44 h. Tracked as area 22 of [`target-app-parity.md`](target-app-parity.md) (not in its weighted sum: the target there is the design product). The work item is gap 24 in [`gaps.md`](gaps.md). @@ -61,7 +61,7 @@ all end with the same geometry. | Board widgets | missing | design-file widgets exist (`crates/engine/src/extensions/widgets.rs`), not wired to boards | | Templates (retrospective, brainstorm, flow chart…) | partial | five built-in templates drawn up for FigCraft (retrospective, brainstorm, weekly planner, flow chart, kanban board), placed from the toolbar's templates picker (each with a picture of itself) or `board.template {name, x?, y?}` as ordinary sections, stickies, shapes, connectors and text in one undo step; `board.templates` lists them. No community templates, no saving your own | | Tables | partial | `board.table {rows, columns, cells?, x?, y?}` (at most 50 × 20): an auto layout frame of rows of cells with text, a tinted header row and lines between rows and columns; a cell's row grows with its text; a double-click types in the cell under the pointer; add or remove a row or column from the bar over the selection or `board.tableEdit {id, action, index?}`; cells copied from a spreadsheet (tab-separated text, quoted cells kept whole) paste as a table, up to 50 × 20 with a note when there was more; undoable and synced in live sessions. No column resizing by dragging, no cell colours, no Tab between cells; comma-separated text pastes as text | -| Mind maps | missing | | +| Mind maps | partial | from commands only so far (#2226): `board.mindMap {x?, y?, text?, children?}` places a first node (bold, no box) with three children on its right, joined by curved branches; `board.mindMapAdd {id?, relation?: child\|sibling}` adds a node. Nodes are text that grows wider as it is typed and taller with line breaks; a node's children stand in one column 88 units right of the widest node of its own column, 48 apart, centred on it, and the map lays itself out again in the normalize pass after every edit, undo and live-session change; moving the first node moves the map; a deleted node's children stay where they are without their branch. Branches are board connectors (`branch`: stroke 4, #757575, round caps), so their style, end points, weight and colour change like any connector's. No toolbar entry, shortcuts, "+" handles, dragging a node onto another, left side or `.jam` import yet | | Washi tape, code blocks, image cropping on boards | missing | images can be placed as in design files | | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | @@ -72,6 +72,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. A mind map node is a board object of its own (`BoardItem::MindNode`: text with no box) and a branch is a connector marked `branch`; the map's shape is read from its branches. `board.mindMap` places a first node with three children and `board.mindMapAdd` adds a child or a sibling, each one undo step. The normalize pass lays a touched map out again from its first node (`board::settle_mind_maps`, `figcraft_doc::mind_layout`): 88 between columns, 48 between siblings, each stack centred on its parent, numbers from a FigJam file saved and decoded. Tests: `board_mindmap_tests` in doc (five) and engine (eight). Numbers unchanged (no toolbar entry yet). | | 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. | | 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. | | 2026-11-04 | patch | M6, #1910: a `.jam` elbowed connector saved with its path (FigJam's `connectorControlPoints`) keeps it on import: the points become the `ConnectorPath::Runs` a connector reshaped by hand has and the line is walked along them, so a connector drawn around a layer stays around it; one whose points don't make a path from its ends' sides is routed as before. Still a vector, not a native board object. Details in [`file-format-parity.md`](file-format-parity.md). | diff --git a/docs/gaps.md b/docs/gaps.md index f42b97e4e..ee855922c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -582,7 +582,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe connector's ends drag onto another object or empty canvas (`board.reattach`); curved connectors; elbows that go around the objects they join. - **Missing:** timer music, board widgets, saving your own templates, table column resizing and - cell colours, mind maps, washi tape, code blocks, audio and huddles, quick-create handles, + cell colours, the mind maps' toolbar entry, shortcuts, drag to re-parent and import, washi tape, code blocks, audio and huddles, quick-create handles, the stamp wheel, emotes and stickers, `.jam` files ([`boards-parity.md`](boards-parity.md)). - **User impact:** boards cover a brainstorm, a retrospective, a flow sketch and a timed, voted @@ -593,6 +593,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Gap 24: mind maps, first step (`board.mindMap`, `board.mindMapAdd`; the map lays itself out again after every edit, #2226); the toolbar entry, shortcuts, drag to re-parent and `.jam` import are what is missing of them. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | | 2026-10-31 | minor | Gap 10: library analytics list the layers and files using each style and variable; their insertions, detachments and modes stay on the missing list. | | 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. | diff --git a/docs/mcp.md b/docs/mcp.md index 04b37e1f0..9c07377ca 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -470,7 +470,8 @@ Returns `{fitted: [{id, fontSize, lines, fits, orphan}]}`. Use case: a carousel A board is a file of its own kind for thinking together: `file.newBoard {name?}` opens one (its page is light; `inspect_document` says `kind: "board"`). Board objects are ordinary layers with a -`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink, …}`), so the usual +`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink|mindNode, …}`; a connector may say +`branch: true`), so the usual commands move, resize, recolour, copy, delete and undo them. On a design file the board commands refuse; on a board `proto.*`, `dev.*`, `view.prototype` and `view.devMode` refuse. Each of these is one undo step and returns the ids it made: @@ -488,6 +489,21 @@ one undo step and returns the ids it made: one, 80 units away, joined to it by a connector the way the Connector tool makes one; one undo step. With `edit: true` the app goes on typing in it (the "+" beside a selected sticky or shape in the app does both). +- `board.mindMap {x?, y?, text?, children?, parent?, edit?}` → `{id, text, children: [{id, text, connector}]}`: + a mind map: a first node (`mindNode`, bold 24, no box; `text` defaults to `Topic`, `x`/`y` to the + middle of the view) with up to 20 `children` (texts; default `A concept`, `An idea`, `A thought`) + on its right, each joined to it by a curved branch (a connector with `branch: true`: stroke 4, + `#757575`, round caps). The map lays itself out: children stand in one column 88 units right of + the widest node of their parent's column, 48 apart, centred on their parent; a node is its text, + sized to it. One undo step. A map's shape is read from its branches alone: the parent of a node + is the layer a branch arrives from. After every edit (a command, typing, a gesture, undo, a live + session's change) a touched map is laid out again from its first node, so moving the first node + moves the map, a child moved by hand goes back (or swaps with the sibling whose middle it + passed), and a deleted node's children stay where they are, without their branch. +- `board.mindMapAdd {id?, relation?: child|sibling, text?, edit?}` → `{id, text, connector}`: a node + of the map that the given (or selected, or edited) one belongs to: a child below its other + children, or a sibling right after it (the first node has none); the map lays itself out again. + One undo step. With `edit: true` the app goes on typing in it. - `board.shape {shape, x, y, width?, height?, text?, color?, parent?}` → `{id, text}`: a shape with centred, wrapping text: `rectangle roundedRectangle ellipse diamond triangle triangleDown parallelogramRight parallelogramLeft trapezoid pentagon hexagon octagon star plus arrowLeft arrowRight chevron speechBubble database document predefinedProcess manualInput internalStorage`. - `board.connector {from, to, fromSide?, toSide?, fromAt?, toAt?, style?: straight|elbow|curved, startCap?, endCap?, label?}` diff --git a/docs/roadmap.md b/docs/roadmap.md index f2dd92966..0bbe9bd55 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -29,6 +29,7 @@ builders' side-by-side checks with synthetic files; nothing has been run on real | Workflow | Works end to end? | Evidence | Hours to pass | |---|---|---|---| +| 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 | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Design screens: frames, shapes, vectors, text, auto layout, styles; save, reopen, export assets | yes | tools and panels in `crates/engine` and `crates/ui-egui`; `.figcraft` round trips (`crates/format/src/large_tests.rs`); PNG/JPG/SVG/PDF export tests | — | | Build and use a design system: components, variants, properties, variables and modes, libraries | yes | `components_scale_tests.rs` (300 components, 2,000 instances), `library_tests.rs`, `library_variables_tests.rs`; libraries are local files, not shared | — | From 0f644195c3f990b55a5afe09dddd420a577e5d0e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 16:17:50 -0500 Subject: [PATCH 013/268] M12: Mind maps: a map around its own container stays put; a moved branch re-flows its old map (#2226) A map holding a layer and something inside it is skipped by the settle pass (it never settled). Every touched branch now stirs its old ends, so re-attaching a branch's start re-flows the map it left. Boards without branches return early, a map over MIND_MAX_NODES is left whole, shift skips non-finite moves, and the doc tests share one six-node helper. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 reviewed; Sonnet 5.5 wrote at medium --- crates/doc/src/board_mindmap_tests.rs | 30 +++++----- crates/engine/src/board_mindmap_tests.rs | 69 +++++++++++++++++++++++ crates/engine/src/boards/board/mindmap.rs | 32 +++++++++-- 3 files changed, 110 insertions(+), 21 deletions(-) diff --git a/crates/doc/src/board_mindmap_tests.rs b/crates/doc/src/board_mindmap_tests.rs index 25e554697..add424574 100644 --- a/crates/doc/src/board_mindmap_tests.rs +++ b/crates/doc/src/board_mindmap_tests.rs @@ -27,6 +27,18 @@ fn three(middle: (f64, f64)) -> Vec { vec![root(), node(2, 0, (100.0, 24.0), 0.0), node(3, 0, middle, 22.0 - middle.1 / 2.0), node(4, 0, (80.0, 24.0), 20.0)] } +/// The root, two children (100 and 60 wide) under it, two more under the first and one under the second. +fn six() -> Vec { + vec![ + root(), + node(2, 0, (100.0, 24.0), 0.0), + node(3, 0, (60.0, 24.0), 10.0), + node(4, 1, (40.0, 24.0), 0.0), + node(5, 1, (40.0, 24.0), 10.0), + node(6, 2, (40.0, 24.0), 0.0), + ] +} + #[test] fn three_children_stand_88_right_of_the_root_72_apart_centred_on_it() { assert_eq!((MIND_GAP_X, MIND_GAP_Y), (88.0, 48.0)); @@ -43,14 +55,7 @@ fn a_taller_node_pushes_its_neighbours_half_its_growth_each_way() { #[test] fn grandchildren_share_a_column_past_the_widest_sibling_and_their_parents_make_room() { - let nodes = vec![ - root(), - node(2, 0, (100.0, 24.0), 0.0), - node(3, 0, (60.0, 24.0), 10.0), - node(4, 1, (40.0, 24.0), 0.0), - node(5, 1, (40.0, 24.0), 10.0), - node(6, 2, (40.0, 24.0), 0.0), - ]; + let nodes = six(); let placed = mind_layout(&nodes); // 476 = 288 + 100 + 88, although B is only 60 wide. let got: Vec<(f64, f64)> = (2..=6).map(|i| at(&placed, i)).collect(); @@ -67,14 +72,7 @@ fn left_children_mirror_the_right_ones() { #[test] fn the_layout_is_a_fixed_point_ties_go_by_id_and_junk_is_skipped() { - let nodes = vec![ - root(), - node(2, 0, (100.0, 24.0), 0.0), - node(3, 0, (60.0, 24.0), 10.0), - node(4, 1, (40.0, 24.0), 0.0), - node(5, 1, (40.0, 24.0), 10.0), - node(6, 2, (40.0, 24.0), 0.0), - ]; + let nodes = six(); let placed = mind_layout(&nodes); let again: Vec = nodes .iter() diff --git a/crates/engine/src/board_mindmap_tests.rs b/crates/engine/src/board_mindmap_tests.rs index d8105bf0f..87edbbac1 100644 --- a/crates/engine/src/board_mindmap_tests.rs +++ b/crates/engine/src/board_mindmap_tests.rs @@ -314,3 +314,72 @@ fn refusals_saved_files_and_a_second_pass_changes_nothing() { crate::normalize(&mut again, doc); assert!(again == *doc, "a second pass changes nothing"); } + +/// Every layer touched again on a copy of `s`'s document: a map in place is left as it is. +fn second_pass_is_a_no_op(s: &Session) { + let doc = s.doc().unwrap(); + let mut again = doc.clone(); + again.mark_dirty(doc.ids().collect::>()); + crate::normalize(&mut again, doc); + assert!(again == *doc, "a second pass changes nothing"); +} + +#[test] +fn a_map_around_its_own_container_stays_put() { + let mut s = board(); + let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 0, "y": 0, "width": 800, "height": 600})).unwrap(), "id"); + let out = s.execute("board.mindMap", &json!({"parent": sec, "x": 40, "y": 40})).unwrap(); + let line = id(&out["children"][1], "connector"); + s.execute("board.reattach", &json!({"id": line, "end": "to", "target": sec})).unwrap(); + let was = bx(&s, sec); + second_pass_is_a_no_op(&s); + s.execute("node.set", &json!({"id": id(&out, "id"), "props": {"name": "again"}})).unwrap(); + assert_eq!(bx(&s, sec), was, "the section stays where it is"); + second_pass_is_a_no_op(&s); +} + +#[test] +fn a_branch_moved_by_its_start_leaves_no_gap_and_odd_structures_settle() { + let mut s = board(); + let (root, [c0, c1, c2], lines) = map(&mut s); + let (h, at) = (bx(&s, c1).height(), bx(&s, c1)); + s.execute("board.reattach", &json!({"id": lines[1], "end": "from", "target": {"x": 900, "y": 900}})).unwrap(); + assert_eq!(branches(&s).len(), 2, "one branch fewer"); + assert_eq!(bx(&s, c1), at, "that child stays where it was"); + let r = bx(&s, root).center().y; + assert!(same(bx(&s, c0).center().y, r - (h + 48.0) / 2.0), "{:?}", bx(&s, c0)); + assert!(same(bx(&s, c2).center().y, r + (h + 48.0) / 2.0), "{:?}", bx(&s, c2)); + second_pass_is_a_no_op(&s); + + // Two branches arrive at one node: the lower connector id stays its parent. + let mut s = board(); + let (root, [c0, c1, _], lines) = map(&mut s); + let g = id(&s.execute("board.mindMapAdd", &json!({"id": c0})).unwrap(), "id"); + let gl = branches(&s).into_iter().find(|b| !lines.contains(b)).unwrap(); + s.execute("board.reattach", &json!({"id": gl, "end": "to", "target": c1})).unwrap(); + assert_eq!(kids(s.doc().unwrap(), root).len(), 3); + assert!(same(bx(&s, c1).x0, bx(&s, root).x1 + 88.0), "c1 stays in the root's column"); + assert!(is_mind_node(&s, g)); + second_pass_is_a_no_op(&s); + + // A cycle: nothing in it moves, and nothing changes after. + let mut s = board(); + let (_, [c0, ..], lines) = map(&mut s); + let g = id(&s.execute("board.mindMapAdd", &json!({"id": c0})).unwrap(), "id"); + let gg = id(&s.execute("board.mindMapAdd", &json!({"id": g})).unwrap(), "id"); + s.execute("board.reattach", &json!({"id": lines[0], "end": "from", "target": gg})).unwrap(); + let ring = places(&s, &[c0, g, gg]); + second_pass_is_a_no_op(&s); + assert_eq!(places(&s, &[c0, g, gg]), ring); +} + +#[test] +fn the_caps_refuse_what_is_too_far_and_cut_what_is_too_long() { + let mut s = board(); + assert!(s.execute("board.mindMap", &json!({"x": 2.0e9})).is_err()); + assert!(s.execute("board.mindMap", &json!({"y": -2.0e9})).is_err()); + let long = "x".repeat(600); + let out = s.execute("board.mindMap", &json!({"text": long, "children": [long]})).unwrap(); + assert_eq!(text_data(&s, id(&out, "id")).characters.chars().count(), 500); + assert_eq!(text_data(&s, id(&out["children"][0], "id")).characters.chars().count(), 500); +} diff --git a/crates/engine/src/boards/board/mindmap.rs b/crates/engine/src/boards/board/mindmap.rs index 858255d74..7cf741526 100644 --- a/crates/engine/src/boards/board/mindmap.rs +++ b/crates/engine/src/boards/board/mindmap.rs @@ -263,11 +263,12 @@ fn children_of(bs: &[Branch]) -> (BTreeSet, Children) { } /// Every branch that no longer joins two layers of its own page is removed, and the layers it -/// joined that are still there count as stirred (so does an end of a branch that is gone). +/// joined that are still there count as stirred (so do the old ends of a touched branch: one that +/// is gone, or that was moved to join something else). fn prune_branches(doc: &mut Document, before: &Document, touched: &BTreeSet) -> BTreeSet { let mut stirred = BTreeSet::new(); let ends = |c: &Connector| [c.from.node(), c.to.node()].into_iter().flatten().collect::>(); - for id in touched.iter().filter(|i| !doc.contains(**i)) { + for id in touched { if let Some(BoardItem::Connector(c)) = before.node(*id).and_then(|n| n.board.as_ref()) && c.branch { @@ -292,7 +293,8 @@ fn prune_branches(doc: &mut Document, before: &Document, touched: &BTreeSet Option<(Vec, Vec)> { let first = doc.world_bounds(root)?; let mut boxes = vec![MindBox { id: root, rect: first, parent: None, left: false }]; @@ -301,9 +303,12 @@ fn map_boxes(doc: &Document, root: NodeId, kids: &Children) -> Option<(Vec= MIND_MAX_NODES || !seen.insert(k.child) { + if !seen.insert(k.child) { continue; } + if boxes.len() >= MIND_MAX_NODES { + return None; + } boxes.push(MindBox { id: k.child, rect: doc.world_bounds(k.child)?, parent: Some(at), left: k.left }); depths.push(depth + 1); lines.push(k.line); @@ -316,8 +321,15 @@ fn map_boxes(doc: &Document, root: NodeId, kids: &Children) -> Option<(Vec = boxes.iter().map(|b| b.id).collect(); + if boxes.iter().any(|b| doc.ancestors(b.id).iter().any(|a| ids.contains(a))) { + continue; + } let stale = boxes.iter().any(|b| stirred.contains(&b.id) || hit(doc, b.id)) || lines.iter().any(|l| hit(doc, *l)); if !stale { continue; From 8e5c7d927985dc0b96fb9f17ec1d28df73beddfa Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 17:02:28 -0500 Subject: [PATCH 014/268] M12: Mind maps: FigCraft's own starter texts (#2226) A new map's starter children read "Idea 1", "Idea 2" and "Idea 3", as the design specified, instead of the incumbent's wording, which the first commit had copied from the measurement. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/engine/src/board_mindmap_tests.rs | 2 +- crates/engine/src/boards/board.rs | 2 +- crates/engine/src/boards/board/mindmap.rs | 2 +- docs/mcp.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/board_mindmap_tests.rs b/crates/engine/src/board_mindmap_tests.rs index 87edbbac1..19bb459ae 100644 --- a/crates/engine/src/board_mindmap_tests.rs +++ b/crates/engine/src/board_mindmap_tests.rs @@ -68,7 +68,7 @@ fn branches(s: &Session) -> Vec { fn check_child(s: &Session, root: NodeId, (k, line): (NodeId, NodeId), i: usize) { let r = bx(s, root); let td = text_data(s, k); - assert_eq!(td.characters, ["A concept", "An idea", "A thought"][i]); + assert_eq!(td.characters, ["Idea 1", "Idea 2", "Idea 3"][i]); assert_eq!((td.style.font_size, td.style.font_style.as_str()), (16.0, "Medium")); assert_eq!((td.style.line_height, td.style.letter_spacing), (LineHeight::Percent(150.0), LetterSpacing::Percent(-1.1))); let b = bx(s, k); diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index c7564967a..99f43faea 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -181,7 +181,7 @@ pub fn specs() -> Vec { spec!( "board.mindMap", "Mind map", - "{x?, y? (the first node's top-left in the parent; default the middle of the view), text? (default Topic), children? (their texts, at most 20; default A concept, An idea, A thought), parent?, edit? (start typing in the first node; default false)} → {id, text, children: [{id, text, connector}...]} a first node with children on its right, joined by branches; the map lays itself out", + "{x?, y? (the first node's top-left in the parent; default the middle of the view), text? (default Topic), children? (their texts, at most 20; default Idea 1, Idea 2, Idea 3), parent?, edit? (start typing in the first node; default false)} → {id, text, children: [{id, text, connector}...]} a first node with children on its right, joined by branches; the map lays itself out", true, mindmap::mind_map_cmd ), diff --git a/crates/engine/src/boards/board/mindmap.rs b/crates/engine/src/boards/board/mindmap.rs index 7cf741526..5e2cff1ce 100644 --- a/crates/engine/src/boards/board/mindmap.rs +++ b/crates/engine/src/boards/board/mindmap.rs @@ -30,7 +30,7 @@ const MIND_NODE_TRACKING: f64 = -1.1; const MIND_MIN_W: f64 = 8.0; /// What `board.mindMap` puts in the first node and its children when it isn't told. const MIND_ROOT_TEXT: &str = "Topic"; -const MIND_STARTERS: [&str; 3] = ["A concept", "An idea", "A thought"]; +const MIND_STARTERS: [&str; 3] = ["Idea 1", "Idea 2", "Idea 3"]; /// The most children `board.mindMap` makes, and the longest text it puts in a node. const MIND_MAX_STARTERS: usize = 20; const MIND_MAX_TEXT: usize = 500; diff --git a/docs/mcp.md b/docs/mcp.md index 9c07377ca..170b316b0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -491,7 +491,7 @@ one undo step and returns the ids it made: in the app does both). - `board.mindMap {x?, y?, text?, children?, parent?, edit?}` → `{id, text, children: [{id, text, connector}]}`: a mind map: a first node (`mindNode`, bold 24, no box; `text` defaults to `Topic`, `x`/`y` to the - middle of the view) with up to 20 `children` (texts; default `A concept`, `An idea`, `A thought`) + middle of the view) with up to 20 `children` (texts; default `Idea 1`, `Idea 2`, `Idea 3`) on its right, each joined to it by a curved branch (a connector with `branch: true`: stroke 4, `#757575`, round caps). The map lays itself out: children stand in one column 88 units right of the widest node of their parent's column, 48 apart, centred on their parent; a node is its text, From 3e31ba4ed97db1496ba2839c1bda05d212b6e20d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 17:34:45 -0500 Subject: [PATCH 015/268] M12: Boards: mind maps in the toolbar, with keys for children and siblings (#2226) Part of #2226, step 2 of 4. The Shapes flyout ends in a mind map tool (tool.mindMap): a click places a map whose first node's text starts at the click, and typing starts in it. Cmd/Ctrl+Enter on a mind map node (selected or being typed in) adds a child (board.mindMapAdd), Shift+Cmd/Ctrl+Enter its next sibling (board.nextSticky forwards a node to board.mindMapAdd), both typing on in the new node. Tab and Shift+Tab walk a node's siblings in the map's order. The bar over a node sets its text colour and size; over a branch it shows the connector's controls without the line types. Cmd/Ctrl+Enter ends every text edit, so its new binding is filtered to mind map nodes at the four places keys resolve (the canvas and the text editor, in the app and on the control channel); a guard test pins that. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 designed; Sonnet 5.5 wrote at medium --- ROADMAP.md | 3 +- crates/engine/src/board_mindmap_tests.rs | 154 ++++++++++++++ crates/engine/src/board_tests.rs | 14 +- crates/engine/src/boards/board.rs | 12 +- crates/engine/src/boards/board/edit.rs | 11 +- crates/engine/src/boards/board/items.rs | 8 +- crates/engine/src/boards/board/mindmap.rs | 35 +++- crates/engine/src/boards/board/tools.rs | 10 + crates/engine/src/canvas/tools.rs | 15 +- crates/engine/src/cmd/edit/select.rs | 5 + crates/engine/src/cmd/view.rs | 2 +- crates/engine/src/keymap.rs | 5 +- crates/engine/src/keymap_tests.rs | 7 + crates/engine/src/shortcut_parity_tests.rs | 3 +- crates/ui-egui/locales/en.toml | 1 + crates/ui-egui/src/board_line_tests.rs | 2 +- crates/ui-egui/src/board_ui_tests.rs | 221 ++++++++++++++++++++- crates/ui-egui/src/canvas/board_bar.rs | 57 ++++-- crates/ui-egui/src/control.rs | 4 +- crates/ui-egui/src/icons.rs | 2 + crates/ui-egui/src/icons/draw.rs | 7 + crates/ui-egui/src/menus.rs | 4 +- crates/ui-egui/src/shortcuts.rs | 11 +- crates/ui-egui/src/shortcuts_tests.rs | 2 +- crates/ui-egui/src/toolbar.rs | 13 +- docs/boards-parity.md | 13 +- docs/gaps.md | 7 +- docs/mcp.md | 16 +- docs/roadmap.md | 3 +- docs/target-app-parity.md | 7 +- docs/ui-parity.md | 5 +- 31 files changed, 594 insertions(+), 65 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 0f59d1bce..d810affd5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -13,6 +13,7 @@ start with [`docs/gaps.md`](docs/gaps.md). | | Value | Kind | |---|---|---| +| 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-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 | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Menu/command breadth | **100%** (212 / 212) | measured, [`docs/parity-checklist.md`](docs/parity-checklist.md) (`cargo xtask parity`) | diff --git a/crates/engine/src/board_mindmap_tests.rs b/crates/engine/src/board_mindmap_tests.rs index 19bb459ae..7cfce1c99 100644 --- a/crates/engine/src/board_mindmap_tests.rs +++ b/crates/engine/src/board_mindmap_tests.rs @@ -10,6 +10,7 @@ use crate::Session; use crate::board::text_of; use crate::board_tests::{board, connector, drawn, id, near, node}; use crate::collab_live_tests::Room; +use crate::tools::{PointerEvent, PointerKind, ToolId}; fn bx(s: &Session, id: NodeId) -> Rect { s.doc().unwrap().world_bounds(id).unwrap() @@ -383,3 +384,156 @@ fn the_caps_refuse_what_is_too_far_and_cut_what_is_too_long() { assert_eq!(text_data(&s, id(&out, "id")).characters.chars().count(), 500); assert_eq!(text_data(&s, id(&out["children"][0], "id")).characters.chars().count(), 500); } + +fn next_sticky(s: &mut Session, p: Value) -> NodeId { + id(&s.execute("board.nextSticky", &p).unwrap(), "id") +} + +fn arrives_from(s: &Session, n: NodeId) -> Option { + s.doc().unwrap().nodes().find_map(|l| match &l.board { + Some(BoardItem::Connector(c)) if c.branch && c.to.node() == Some(n) => c.from.node(), + _ => None, + }) +} + +#[test] +fn the_next_sticky_key_gives_a_mind_map_node_its_next_sibling() { + let mut s = board(); + let (root, [c0, c1, c2], _) = map(&mut s); + let depth = s.undo_depth().0; + let out = s.execute("board.nextSticky", &json!({"id": c1})).unwrap(); + let a = id(&out, "id"); + assert!(is_mind_node(&s, a)); + assert!(connector(&s, id(&out, "connector")).branch); + assert_eq!(arrives_from(&s, a), Some(root)); + assert_eq!(kids(s.doc().unwrap(), root), [c0, c1, a, c2]); + assert_eq!(s.undo_depth().0, depth + 1); + // Unequal heights and a subtree. + s.execute("board.mindMapAdd", &json!({"id": c1})).unwrap(); + s.execute("board.mindMapAdd", &json!({"id": c1})).unwrap(); + s.execute("node.set", &json!({"id": text_of(s.doc().unwrap(), c1).unwrap(), "props": {"characters": "one\ntwo\nthree"}})).unwrap(); + let b = next_sticky(&mut s, json!({"id": c1})); + assert_eq!(kids(s.doc().unwrap(), root), [c0, c1, b, a, c2]); + assert!(same(bx(&s, b).x0, bx(&s, c1).x0)); + let mids: Vec = [c0, c1, b, a, c2].iter().map(|n| bx(&s, *n).center().y).collect(); + assert!(mids.windows(2).all(|w| w[0] < w[1]), "{mids:?}"); + assert!(bx(&s, b).y0 >= bx(&s, c1).y1 + 48.0 - 1e-6); + // The last sibling, and the selection as the default. + s.execute("select.set", &json!({"ids": [c2]})).unwrap(); + let last = next_sticky(&mut s, json!({})); + assert_eq!(kids(s.doc().unwrap(), root).last(), Some(&last)); + // While typing. + crate::board::edit_text(&mut s, c0).unwrap(); + s.ui_requests.clear(); + let d = next_sticky(&mut s, json!({"edit": true})); + assert!(s.ds().unwrap().text_edit.is_none()); + assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(d))); + let order = kids(s.doc().unwrap(), root); + assert_eq!(order.iter().position(|n| *n == d), order.iter().position(|n| *n == c0).map(|i| i + 1)); + assert_eq!(s.selection(), vec![d]); + // The first node has no sibling: refused, and an open edit stays open. + let count = s.doc().unwrap().ids().count(); + crate::board::edit_text(&mut s, root).unwrap(); + let err = s.execute("board.nextSticky", &json!({"id": root})).unwrap_err().to_string(); + assert!(err.contains("first node"), "{err}"); + assert!(s.ds().unwrap().text_edit.is_some()); + assert_eq!(s.doc().unwrap().ids().count(), count); +} + +#[test] +fn tab_walks_a_nodes_siblings_in_the_maps_order() { + let mut s = board(); + let (_, [c0, c1, c2], _) = map(&mut s); + s.execute("select.set", &json!({"ids": [c0]})).unwrap(); + for want in [c1, c2, c0] { + s.execute("select.next", &json!({})).unwrap(); + assert_eq!(s.selection(), vec![want]); + } + s.execute("select.previous", &json!({})).unwrap(); + assert_eq!(s.selection(), vec![c2]); + s.execute("transform.move", &json!({"ids": [c0], "dx": 0, "dy": 100})).unwrap(); + s.execute("select.set", &json!({"ids": [c1]})).unwrap(); + s.execute("select.next", &json!({})).unwrap(); + assert_eq!(s.selection(), vec![c0]); + // An only child stays. + let g = id(&s.execute("board.mindMapAdd", &json!({"id": c1})).unwrap(), "id"); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + s.execute("select.next", &json!({})).unwrap(); + assert_eq!(s.selection(), vec![g]); + // Layers keep the layer order. + let mut t = board(); + let a = id(&t.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap(), "id"); + let b = id(&t.execute("board.sticky", &json!({"x": 400, "y": 0})).unwrap(), "id"); + t.execute("select.set", &json!({"ids": [b]})).unwrap(); + t.execute("select.next", &json!({})).unwrap(); + assert_eq!(t.selection(), vec![a]); + let mut u = board(); + let (root, _, _) = map(&mut u); + u.execute("select.set", &json!({"ids": [root]})).unwrap(); + u.execute("select.next", &json!({})).unwrap(); + assert_eq!(u.selection().len(), 1); +} + +#[test] +fn the_mind_map_tool_starts_the_first_nodes_text_at_the_click() { + let mut s = board(); + s.execute("tool.mindMap", &json!({})).unwrap(); + assert_eq!(s.tool.tool, ToolId::MindMap); + s.pointer(&PointerEvent::at(PointerKind::Down, 300.0, 200.0, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Up, 300.0, 200.0, 1.0)).unwrap(); + let nodes: Vec = s.doc().unwrap().nodes().filter(|n| n.board == Some(BoardItem::MindNode)).map(|n| n.id).collect(); + assert_eq!((nodes.len(), branches(&s).len()), (4, 3)); + let root = *nodes.iter().find(|n| arrives_from(&s, **n).is_none()).unwrap(); + assert_eq!(bx(&s, root).x0, 300.0); + assert!(same(bx(&s, root).center().y, 200.0)); + let te = s.ds().unwrap().text_edit.clone().expect("typing in the first node"); + assert_eq!(crate::board::owner_of_text(s.doc().unwrap(), te.id), Some(root)); + assert_eq!((te.anchor.min(te.caret), te.anchor.max(te.caret)), (0, 5)); + assert_eq!(s.tool.tool, ToolId::Move); + crate::textedit::insert(&mut s, "Plan").unwrap(); + crate::textedit::end(&mut s).unwrap(); + assert_eq!(text_data(&s, root).characters, "Plan"); + for k in nodes.iter().filter(|n| **n != root) { + assert!(same(bx(&s, *k).x0, bx(&s, root).x1 + 88.0)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text_data(&s, root).characters, "Topic"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().nodes().all(|n| n.board != Some(BoardItem::MindNode))); + // Tools kept on. + s.prefs.keep_tool = true; + s.execute("tool.mindMap", &json!({})).unwrap(); + for y in [200.0, 900.0] { + s.pointer(&PointerEvent::at(PointerKind::Down, 300.0, y, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Up, 300.0, y, 1.0)).unwrap(); + } + assert_eq!(s.doc().unwrap().nodes().filter(|n| n.board == Some(BoardItem::MindNode)).count(), 8); + assert_eq!(s.tool.tool, ToolId::MindMap); + // Refusals and names. + let mut d = Session::new(); + for (cmd, p) in [("tool.mindMap", json!({})), ("tool.set", json!({"tool": "mindMap"}))] { + assert!(matches!(d.execute(cmd, &p), Err(crate::EngineError::Disabled(..))), "{cmd} on a design file"); + } + assert_eq!(ToolId::from_id("mindMap"), Some(ToolId::MindMap)); + assert!(ToolId::MindMap.on_boards()); +} + +#[test] +fn a_board_colour_on_a_mind_map_node_is_its_text_colour() { + let mut s = board(); + let (_, [c0, ..], lines) = map(&mut s); + let ink = Paint::solid(Color::from_rgb8_const(0x1E, 0x1E, 0x1E)); + s.execute("board.setColor", &json!({"ids": [c0, lines[0]], "color": "blue"})).unwrap(); + let text = text_of(s.doc().unwrap(), c0).unwrap(); + assert_eq!(node(&s, text).fills, node(&s, lines[0]).strokes); + assert!(node(&s, c0).fills.is_empty(), "no box"); + s.execute("board.setColor", &json!({"ids": [c0], "color": "#FF0000"})).unwrap(); + assert_eq!(node(&s, text).fills, vec![Paint::solid(Color::from_rgb8_const(0xFF, 0, 0))]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, text).fills, vec![ink.clone()]); + let st = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "id"); + s.execute("board.setColor", &json!({"ids": [c0, st], "color": "green"})).unwrap(); + assert_ne!(node(&s, text).fills, vec![ink]); + assert_eq!(node(&s, st).fills.len(), 1); +} diff --git a/crates/engine/src/board_tests.rs b/crates/engine/src/board_tests.rs index 5ddd4e1be..739291399 100644 --- a/crates/engine/src/board_tests.rs +++ b/crates/engine/src/board_tests.rs @@ -365,8 +365,18 @@ fn board_commands_survive_junk() { .map(|c| c.id) .filter(|i| { i.starts_with("board.") - || ["tool.sticky", "tool.shape", "tool.connector", "tool.marker", "tool.highlighter", "tool.eraser", "tool.stamp", "file.newBoard"] - .contains(i) + || [ + "tool.sticky", + "tool.shape", + "tool.connector", + "tool.marker", + "tool.highlighter", + "tool.eraser", + "tool.stamp", + "tool.mindMap", + "file.newBoard", + ] + .contains(i) }) .collect(); assert!(ids.len() >= 17, "{ids:?}"); diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index 99f43faea..b3c787037 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -72,6 +72,7 @@ pub use items::{CONNECTED_GAP, connected_place}; use items::{add_connected, ink_cmd, next_sticky, shape_cmd, stamp_cmd, sticky_cmd}; pub use items::{edit_text, owner_of_text, sticky_font_size, text_of}; pub(crate) use mindmap::settle_mind_maps; +pub use mindmap::{mind_node_target, mind_sibling}; pub(crate) use reshape::path_handle_at; pub use reshape::selected_connector_handles; @@ -139,7 +140,7 @@ pub fn specs() -> Vec { spec!( "board.nextSticky", "Next sticky note", - "{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected", + "{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected; after a mind map node, its next sibling, as board.mindMapAdd {relation: sibling}", true, next_sticky ), @@ -210,7 +211,7 @@ pub fn specs() -> Vec { spec!( "board.setColor", "Board color", - "{ids?, color (a board colour name or hex)} stickies and shapes take it as their fill, connectors and ink as their line", + "{ids?, color (a board colour name or hex)} stickies and shapes take it as their fill, connectors and ink as their line, mind map nodes as their text colour", true, set_color ), @@ -227,6 +228,13 @@ pub fn specs() -> Vec { } board_tool(s, ToolId::Sticky) }), + spec!( + "tool.mindMap", + "Mind map tool", + "{} (a click places a mind map, the first node's text starting at the click, and starts typing in it)", + false, + |s, _| board_tool(s, ToolId::MindMap) + ), spec!("tool.shape", "Shapes", "{shape?} (a click places a shape with text)", false, |s, p| { if let Some(v) = string(p, "shape") { s.tool.board.shape = shape_of("tool.shape", &v)?; diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs index 88a38d438..922a99b6c 100644 --- a/crates/engine/src/boards/board/edit.rs +++ b/crates/engine/src/boards/board/edit.rs @@ -84,12 +84,19 @@ pub(super) fn set_color(s: &mut Session, p: &Value) -> Result { n.strokes = vec![Paint::solid(line_shade(color))]; } BoardItem::Connector(_) | BoardItem::Ink => doc.get_mut(id)?.strokes = vec![Paint::solid(line_shade(color))], - BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode => continue, + BoardItem::MindNode => { + let Some(text) = text_of(doc, id) else { continue }; + let n = doc.get_mut(text)?; + // Characters coloured one by one follow the layer's colour. + crate::cmd::lists::take_character_fills(n); + n.fills = vec![Paint::solid(line_shade(color))]; + } + BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table => continue, } changed.push(id); } if changed.is_empty() { - return Err(bad(cmd, "select stickies, shapes, connectors or ink")); + return Err(bad(cmd, "select stickies, shapes, connectors, ink or mind map nodes")); } Ok(json!({"ids": changed})) } diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index 2a264c5b5..39ae4314c 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -145,14 +145,18 @@ pub(super) fn next_sticky(s: &mut Session, p: &Value) -> Result { let from = id(p, "id") .or_else(|| editing.and_then(|t| owner_of_text(doc, t))) .or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i))) - .ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky or a shape first".into()))?; + .ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky, a shape or a mind map node first".into()))?; let n = doc.get(from)?; + if n.board == Some(BoardItem::MindNode) { + // A mind map node gets its next sibling (#2226), as a shape gets the next shape joined to it. + return super::mindmap::mind_map_add(s, &json!({"id": from, "relation": "sibling", "edit": boolean(p, "edit").unwrap_or(false)})); + } if matches!(n.board, Some(BoardItem::Shape { .. })) { // A shape gets the next one joined to it, as the "+" beside it makes (#1597). return add_connected(s, p); } if !matches!(n.board, Some(BoardItem::Sticky { .. })) { - return Err(bad(cmd, "that isn't a sticky or a shape")); + return Err(bad(cmd, "that isn't a sticky, a shape or a mind map node")); } let color = n.fills.iter().find_map(Paint::solid_color).unwrap_or(s.tool.board.sticky); let parent = n.parent.ok_or_else(|| bad(cmd, "that sticky has no parent"))?; diff --git a/crates/engine/src/boards/board/mindmap.rs b/crates/engine/src/boards/board/mindmap.rs index 5e2cff1ce..2b7bdb634 100644 --- a/crates/engine/src/boards/board/mindmap.rs +++ b/crates/engine/src/boards/board/mindmap.rs @@ -21,6 +21,8 @@ use crate::EngineError; /// The first node's text size and the other nodes'. const MIND_ROOT_SIZE: f64 = 24.0; const MIND_NODE_SIZE: f64 = 16.0; +/// The first node's height with one line of text (the mind map tool centres it on the click). +pub(super) const MIND_ROOT_H: f64 = MIND_ROOT_SIZE * MIND_LINE_HEIGHT / 100.0; /// The line height of every node's text, in percent, and the letter spacing of the first node's /// and the others' (percent of the size). const MIND_LINE_HEIGHT: f64 = 150.0; @@ -193,15 +195,40 @@ pub(super) fn mind_map_cmd(s: &mut Session, p: &Value) -> Result { Ok(json!({"id": root, "text": label, "children": made})) } +/// What `board.mindMapAdd` adds to when it is given no `id`: the owner of the text being typed in, +/// else the first selected layer (or the board object whose text that is). +fn target(s: &Session) -> Option { + let doc = s.doc().ok()?; + let editing = s.ds().ok()?.text_edit.as_ref().map(|t| t.id); + editing.and_then(|t| owner_of_text(doc, t)).or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i))) +} + +/// The mind map node `board.mindMapAdd` would add to with no `id` (the UI asks before it binds a key). +pub fn mind_node_target(s: &Session) -> Option { + let doc = s.doc().ok()?; + target(s).filter(|n| doc.node(*n).is_some_and(|n| n.board == Some(BoardItem::MindNode))) +} + +/// The sibling `dir` places after `node` (1: below, -1: above) among the children of its branch's +/// parent on its side, around the ends; `None` when no branch arrives at `node`. +pub fn mind_sibling(doc: &Document, node: NodeId, dir: i64) -> Option { + if !is_board(doc) { + return None; + } + let bs = branches(doc); + let a = arriving(&bs, node)?; + let sibs = map_children(doc, &bs, a.parent, a.left); + let at = sibs.iter().position(|n| *n == node)? as i64; + let len = sibs.len() as i64; + sibs.get((at + dir).rem_euclid(len.max(1)) as usize).copied() +} + pub(super) fn mind_map_add(s: &mut Session, p: &Value) -> Result { let cmd = "board.mindMapAdd"; require(s, cmd)?; let editing = s.ds()?.text_edit.as_ref().map(|t| t.id); let doc = s.doc()?; - let from = id(p, "id") - .or_else(|| editing.and_then(|t| owner_of_text(doc, t))) - .or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i))) - .ok_or_else(|| EngineError::Disabled(cmd.into(), "select a mind map node first".into()))?; + let from = id(p, "id").or_else(|| target(s)).ok_or_else(|| EngineError::Disabled(cmd.into(), "select a mind map node first".into()))?; let n = doc.get(from)?; if n.board != Some(BoardItem::MindNode) { return Err(bad(cmd, "that isn't a mind map node")); diff --git a/crates/engine/src/boards/board/tools.rs b/crates/engine/src/boards/board/tools.rs index dd7f0db19..d411a2fa9 100644 --- a/crates/engine/src/boards/board/tools.rs +++ b/crates/engine/src/boards/board/tools.rs @@ -2,6 +2,7 @@ use super::connectors::{CAPS, at_json, end_json, make, other_end, side_json}; use super::derived::{ends_now, route}; use super::edit::label_of; use super::items::edit_text; +use super::mindmap::MIND_ROOT_H; use super::{ BoardItem, Connector, Document, ERASER_PX, End, EngineError, Gesture, NodeId, Point, PointerEvent, Result, SHAPE, STICKY, Session, Side, ToolId, id_of, is_board, json, @@ -65,6 +66,15 @@ impl Session { self.board_placed(); Ok(()) } + ToolId::MindMap => { + // The first node's text starts at the click: its left edge there, its middle level with it. + let r = self.execute("board.mindMap", &json!({"x": ev.x, "y": ev.y - MIND_ROOT_H / 2.0}))?; + self.board_placed(); + if let Some(id) = r.get("id").and_then(id_of) { + edit_text(self, id)?; + } + Ok(()) + } ToolId::Stamp => { // Stamps go on one after another: the tool stays. self.execute("board.stamp", &json!({"x": ev.x, "y": ev.y}))?; diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index a3284cd52..44b64cf93 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -68,10 +68,11 @@ pub enum ToolId { Highlighter, Eraser, Stamp, + MindMap, } impl ToolId { - pub const ALL: [ToolId; 26] = [ + pub const ALL: [ToolId; 27] = [ ToolId::Move, ToolId::Scale, ToolId::Hand, @@ -98,6 +99,7 @@ impl ToolId { ToolId::Highlighter, ToolId::Eraser, ToolId::Stamp, + ToolId::MindMap, ]; pub fn id(self) -> &'static str { match self { @@ -127,6 +129,7 @@ impl ToolId { ToolId::Highlighter => "highlighter", ToolId::Eraser => "eraser", ToolId::Stamp => "stamp", + ToolId::MindMap => "mindMap", } } pub fn from_id(s: &str) -> Option { @@ -160,6 +163,7 @@ impl ToolId { ToolId::Highlighter => "Highlighter", ToolId::Eraser => "Eraser", ToolId::Stamp => "Stamp", + ToolId::MindMap => "Mind map", } } @@ -167,7 +171,14 @@ impl ToolId { pub fn on_boards(self) -> bool { matches!( self, - ToolId::Sticky | ToolId::BoardShape | ToolId::Connector | ToolId::Marker | ToolId::Highlighter | ToolId::Eraser | ToolId::Stamp + ToolId::Sticky + | ToolId::BoardShape + | ToolId::Connector + | ToolId::Marker + | ToolId::Highlighter + | ToolId::Eraser + | ToolId::Stamp + | ToolId::MindMap ) } /// The tool's key (from [`crate::keymap`]; empty when it has none). diff --git a/crates/engine/src/cmd/edit/select.rs b/crates/engine/src/cmd/edit/select.rs index ca1da3bbc..cfc740a3c 100644 --- a/crates/engine/src/cmd/edit/select.rs +++ b/crates/engine/src/cmd/edit/select.rs @@ -100,6 +100,11 @@ pub(super) fn select_sibling(s: &mut Session, dir: i64) -> Result { s.set_selection(first.into_iter().collect()); return Ok(json!({"selection": s.selection()})); }; + // A mind map node's siblings, in the map's order (#2226); every other layer keeps the layer order. + if let Some(next) = crate::board::mind_sibling(doc, cur, dir) { + s.set_selection(vec![next]); + return Ok(json!({"selection": [next]})); + } let parent = doc.get(cur)?.parent.ok_or_else(|| bad("select.next", "no parent"))?; let kids = &doc.get(parent)?.children; let idx = kids.iter().position(|c| *c == cur).unwrap_or(0) as i64; diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 46ca701ff..90166e8bf 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -528,7 +528,7 @@ pub fn specs() -> Vec { spec!( "tool.set", "Choose tool", - "{tool: move|scale|hand|frame|section|slice|rectangle|line|arrow|ellipse|polygon|star|pen|pencil|text|comment|shapeBuilder | on boards: sticky|shape|connector|marker|highlighter|eraser|stamp}", + "{tool: move|scale|hand|frame|section|slice|rectangle|line|arrow|ellipse|polygon|star|pen|pencil|text|comment|shapeBuilder | on boards: sticky|shape|connector|marker|highlighter|eraser|stamp|mindMap}", false, |s, p| { let t = req_string("tool.set", p, "tool")?; diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index e45ced8d4..21163a589 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -201,7 +201,10 @@ pub static KEYS: &[Binding] = &[ k(Tools, "tool.highlighter", &["U"]), k(Tools, "tool.eraser", &["E"]), k(Tools, "tool.stamp", &["W"]), - k(Tools, "board.nextSticky", &["Shift+Cmd+Enter"]).label("Board: a new sticky beside the selected one, or the next shape joined to it").both(), + k(Tools, "board.nextSticky", &["Shift+Cmd+Enter"]) + .label("Board: a new sticky beside the selected one, the next shape joined to it, or a mind map node's next sibling") + .both(), + k(Tools, "board.mindMapAdd", &["Cmd+Enter"]).label("Board: a child of the selected mind map node").both(), // View // The documentation gives both keys for the pixel grid in different places. k(View, "view.pixelGrid", &["Shift+'", "Cmd+'"]), diff --git a/crates/engine/src/keymap_tests.rs b/crates/engine/src/keymap_tests.rs index 67c5bf258..9bf24d74a 100644 --- a/crates/engine/src/keymap_tests.rs +++ b/crates/engine/src/keymap_tests.rs @@ -123,6 +123,13 @@ fn lookups_on_every_platform() { assert_eq!(id_for(p, Context::Canvas, "B", mods(false, false, true, false)), Some("text.bold")); assert_eq!(id_for(p, Context::Text, "V", none), None); assert_eq!(id_for(p, Context::Text, "A", mods(false, true, false, false)), None); + // Cmd+Enter adds a mind map node's child, with Shift its next sibling (#2226). + for c in [Context::Canvas, Context::Text] { + assert_eq!(id_for(p, c, "Enter", mods(false, false, true, false)), Some("board.mindMapAdd")); + assert_eq!(id_for(p, c, "Enter", mods(true, false, true, false)), Some("board.nextSticky")); + } + assert_eq!(id_for(p, Context::Canvas, "Enter", none), Some("select.children")); + assert_eq!(id_for(p, Context::Canvas, "Enter", mods(false, true, true, false)), Some("proto.present")); } } diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index ae73b022d..755f64faa 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -129,6 +129,7 @@ static ROWS: &[Row] = &[ pin(Tools, "tool.eraser", &["E"], &[]), pin(Tools, "tool.stamp", &["W"], &[]), pin(Tools, "board.nextSticky", &["Shift+Cmd+Enter"], &[]), + pin(Tools, "board.mindMapAdd", &["Cmd+Enter"], &[]), // Vector edit mode doc(Selection, "Edit the selected shape's points", &["Enter"], &[], Bound("select.children"), "Enter on a shape edits it; on a frame or group it selects the children"), doc(Shape, "Vector edit: move", &["V"], &[], VectorTool(VTool::Move), ""), @@ -416,7 +417,7 @@ fn counts_match_the_docs() { let reserved = documented.iter().filter(|r| !r.reserved.is_empty()).count(); let pinned = ROWS.len() - documented.len(); // docs/ui-parity.md quotes these. - assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (136, 135, 1, 0, 2, 57)); + assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (136, 135, 1, 0, 2, 58)); } #[test] diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 625ee3bd8..afc5fa34f 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -908,6 +908,7 @@ name = "English" "Merged PRs" = "Merged PRs" "Min H" = "Min H" "Min W" = "Min W" +"Mind map" = "Mind map" "Minimize" = "Minimize" "Minutes" = "Minutes" "Mirror angle" = "Mirror angle" diff --git a/crates/ui-egui/src/board_line_tests.rs b/crates/ui-egui/src/board_line_tests.rs index 536cfcf15..4303e7bd8 100644 --- a/crates/ui-egui/src/board_line_tests.rs +++ b/crates/ui-egui/src/board_line_tests.rs @@ -41,7 +41,7 @@ fn connector() -> (Ui, NodeId, NodeId) { } /// Open the menu at `x` from the bar's left edge and pick `item` in it. -fn pick(u: &mut Ui, x: f32, item: &str) { +pub(crate) fn pick(u: &mut Ui, x: f32, item: &str) { let r = bar(u).expect("the bar shows"); click(u, pos2(r.min.x + x, r.center().y)); let shapes = flat(&u.frame_output(vec![]).shapes); diff --git a/crates/ui-egui/src/board_ui_tests.rs b/crates/ui-egui/src/board_ui_tests.rs index 867ba139a..495940bd3 100644 --- a/crates/ui-egui/src/board_ui_tests.rs +++ b/crates/ui-egui/src/board_ui_tests.rs @@ -4,7 +4,7 @@ //! board objects selected, never on a file you can only view), the home screen's New board card, //! and the marks design files and boards get. -use egui::{Event, Modifiers, PointerButton, Pos2, Rect, pos2}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, pos2}; use figcraft_doc::{BoardItem, BoardShape, FileKind, NodeId, Routing, Stamp, board_color}; use figcraft_engine::Session; use figcraft_engine::tools::ToolId; @@ -12,6 +12,7 @@ use serde_json::{Value, json}; use crate::layers_drag_tests::Ui; use crate::live_tests::{flat, has_text, text_center}; +use crate::shortcuts_tests::press; fn click(u: &mut Ui, p: Pos2) { for pressed in [true, false] { @@ -398,3 +399,221 @@ fn cmd_while_moving_a_connector_end_places_it_on_the_object() { drag(&mut u, Modifiers::NONE); assert!(matches!(end(&u), figcraft_doc::End::Node { at: None, side: figcraft_doc::Side::Right, .. }), "{:?}", end(&u)); } + +/// `board.mindMap` at the page's origin: the first node, its three children and their branches. +fn mind_map(u: &mut Ui) -> (NodeId, [NodeId; 3], [NodeId; 3]) { + let out = u.app.run("board.mindMap", json!({"x": 0, "y": 0})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let kids = out["children"].as_array().unwrap(); + let pick = |key: &str| -> [NodeId; 3] { [0, 1, 2].map(|i| NodeId(kids[i][key].as_u64().unwrap())) }; + (id(&out), pick("id"), pick("connector")) +} + +/// The node whose text is being typed in. +fn typing_in(u: &Ui) -> Option { + let te = u.app.session.ds().ok()?.text_edit.clone()?; + figcraft_engine::board::owner_of_text(u.app.session.doc().ok()?, te.id) +} + +/// The layer a mind map branch arrives at `n` from. +fn parent(u: &Ui, n: NodeId) -> Option { + u.app.session.doc().unwrap().nodes().find_map(|l| match &l.board { + Some(BoardItem::Connector(c)) if c.branch && c.to.node() == Some(n) => c.from.node(), + _ => None, + }) +} + +fn mind_nodes(u: &Ui) -> usize { + u.app.session.doc().unwrap().nodes().filter(|n| n.board == Some(BoardItem::MindNode)).count() +} + +fn middle(u: &Ui, n: NodeId) -> f64 { + u.app.session.doc().unwrap().world_bounds(n).unwrap().center().y +} + +fn text_of_node(u: &Ui, n: NodeId) -> String { + let t = figcraft_engine::board::text_of(u.app.session.doc().unwrap(), n).unwrap(); + u.app.session.doc().unwrap().node(t).unwrap().kind.text().unwrap().characters.clone() +} + +fn select(u: &mut Ui, ids: &[NodeId]) { + u.app.session.execute("select.set", &json!({"ids": ids})).unwrap(); + u.frame(vec![]); + u.frame(vec![]); +} + +#[test] +fn the_shapes_flyout_ends_in_a_mind_map_that_a_click_places_and_types_in() { + let mut u = board(); + let cells = BoardShape::ALL.len() + 1; + pick_option(&mut u, 3, cells - 1, cells); + assert_eq!(u.app.session.tool.tool, ToolId::MindMap); + assert!(u.app.ui.tool_flyout.is_none(), "the flyout closed"); + let at = u.app.canvas.rect.center(); + let p = u.app.to_page(at); + click(&mut u, at); + assert_eq!(mind_nodes(&u), 4); + let doc = u.app.session.doc().unwrap(); + assert_eq!(doc.nodes().filter(|n| matches!(&n.board, Some(BoardItem::Connector(c)) if c.branch)).count(), 3); + let root = typing_in(&u).expect("typing in the first node"); + assert_eq!(parent(&u, root), None); + let b = doc.world_bounds(root).unwrap(); + assert!((b.x0 - p.x).abs() < 0.01 && (b.center().y - p.y).abs() < 0.01, "{b:?} at {p:?}"); + let te = u.app.session.ds().unwrap().text_edit.clone().unwrap(); + assert_eq!((te.anchor.min(te.caret), te.anchor.max(te.caret)), (0, 5)); + assert_eq!(u.app.session.tool.tool, ToolId::Move); + u.frame(vec![Event::Text("Plan".into())]); + assert_eq!(text_of_node(&u, root), "Plan"); + let x1 = u.app.session.doc().unwrap().world_bounds(root).unwrap().x1; + for n in u.app.session.doc().unwrap().nodes().filter(|n| n.board == Some(BoardItem::MindNode) && n.id != root) { + let k = u.app.session.doc().unwrap().world_bounds(n.id).unwrap(); + assert!((k.x0 - (x1 + 88.0)).abs() < 1e-6, "the map followed the typing"); + } + press(&mut u, Key::Escape, Modifiers::NONE); + assert_eq!(typing_in(&u), None); + assert_eq!(u.app.session.selection(), vec![root]); +} + +#[test] +fn cmd_enter_adds_a_child_shift_cmd_enter_a_sibling_and_typing_goes_on() { + let mut u = board(); + let (root, [_, c1, _], _) = mind_map(&mut u); + select(&mut u, &[c1]); + press(&mut u, Key::Enter, Modifiers::COMMAND); + let g = typing_in(&u).expect("typing in the new child"); + assert!(![c1, root].contains(&g)); + assert_eq!(parent(&u, g), Some(c1)); + u.frame(vec![Event::Text("deep".into())]); + press(&mut u, Key::Enter, Modifiers::COMMAND); + let gg = typing_in(&u).expect("typing in the grandchild"); + assert_eq!(parent(&u, gg), Some(g)); + assert_eq!(text_of_node(&u, g), "deep"); + press(&mut u, Key::Enter, Modifiers::SHIFT | Modifiers::COMMAND); + let h = typing_in(&u).expect("typing in the sibling"); + assert_eq!(parent(&u, h), Some(g)); + assert!(middle(&u, h) > middle(&u, gg)); + press(&mut u, Key::Escape, Modifiers::NONE); + assert_eq!(u.app.session.selection(), vec![h]); + press(&mut u, Key::Enter, Modifiers::SHIFT | Modifiers::COMMAND); + let i = typing_in(&u).expect("typing in the next sibling"); + assert_eq!(parent(&u, i), Some(g)); + assert!(middle(&u, i) > middle(&u, h)); + // The first node has no sibling. + press(&mut u, Key::Escape, Modifiers::NONE); + let count = mind_nodes(&u); + select(&mut u, &[root]); + press(&mut u, Key::Enter, Modifiers::SHIFT | Modifiers::COMMAND); + assert_eq!(mind_nodes(&u), count); + assert!(u.app.ui.last_error.as_deref().is_some_and(|e| e.contains("first node")), "{:?}", u.app.ui.last_error); + // A sticky keeps its key. + let st = id(&u.app.run("board.sticky", json!({"x": 900, "y": 0})).unwrap()); + select(&mut u, &[st]); + press(&mut u, Key::Enter, Modifiers::SHIFT | Modifiers::COMMAND); + let n = typing_in(&u).expect("typing in the new sticky"); + assert_eq!(u.app.session.doc().unwrap().node(n).unwrap().transform.translation().x, 1124.0); +} + +#[test] +fn tab_selects_the_next_sibling_and_enter_types_in_it() { + let mut u = board(); + let (_, [c0, c1, c2], _) = mind_map(&mut u); + select(&mut u, &[c0]); + for want in [c1, c2, c0] { + press(&mut u, Key::Tab, Modifiers::NONE); + assert_eq!(u.app.session.selection(), vec![want]); + } + press(&mut u, Key::Tab, Modifiers::SHIFT); + assert_eq!(u.app.session.selection(), vec![c2]); + press(&mut u, Key::Enter, Modifiers::NONE); + assert_eq!(typing_in(&u), Some(c2)); + let te = u.app.session.ds().unwrap().text_edit.clone().unwrap(); + assert_eq!((te.anchor.min(te.caret), te.anchor.max(te.caret)), (0, 6), "all of Idea 3"); + u.frame(vec![Event::Text("x".into())]); + assert_eq!(text_of_node(&u, c2), "x"); +} + +#[test] +fn the_bar_colours_and_sizes_a_node_and_restyles_a_branch_without_line_types() { + let mut u = board(); + let (_, [c0, c1, _], lines) = mind_map(&mut u); + select(&mut u, &[c0]); + let r = bar(&u).expect("the bar shows"); + assert_eq!(r.width(), 336.0); + let text = figcraft_engine::board::text_of(u.app.session.doc().unwrap(), c0).unwrap(); + let ink = u.app.session.doc().unwrap().node(text).unwrap().fills.clone(); + click(&mut u, pos2(r.min.x + 8.0 + 5.0 * 24.0 + 10.0, r.center().y)); + assert_ne!(u.app.session.doc().unwrap().node(text).unwrap().fills, ink); + let r = bar(&u).unwrap(); + click(&mut u, pos2(r.min.x + 208.0 + 2.0 * 30.0 + 14.0, r.center().y)); + assert_eq!(u.app.session.doc().unwrap().node(text).unwrap().kind.text().unwrap().style.font_size, 24.0); + select(&mut u, &[lines[1]]); + assert_eq!(bar(&u).unwrap().width(), 414.0); + let child = u.app.session.doc().unwrap().world_bounds(c1).unwrap(); + crate::board_line_tests::pick(&mut u, 232.0 + 31.0, "Circle"); + let doc = u.app.session.doc().unwrap(); + let line = doc.node(lines[1]).unwrap(); + assert_eq!(line.stroke.cap_start, figcraft_doc::StrokeCap::CircleFilled); + assert!(matches!(&line.board, Some(BoardItem::Connector(c)) if c.routing == Routing::Curved && c.branch)); + assert_eq!(doc.world_bounds(c1).unwrap(), child, "the child has not moved"); + // A branch with an ordinary connector keeps the line types. + let a = id(&u.app.run("board.sticky", json!({"x": 900, "y": 0})).unwrap()); + let b = id(&u.app.run("board.sticky", json!({"x": 1300, "y": 0})).unwrap()); + let k = id(&u.app.run("board.connector", json!({"from": a, "to": b})).unwrap()); + select(&mut u, &[lines[1], k]); + assert_eq!(bar(&u).unwrap().width(), 512.0); +} + +#[test] +fn cmd_enter_is_the_mind_maps_only_on_a_mind_map_node() { + let mut u = board(); + let st = id(&u.app.run("board.sticky", json!({"x": 900, "y": 0})).unwrap()); + select(&mut u, &[st]); + let count = u.app.session.doc().unwrap().ids().count(); + press(&mut u, Key::Enter, Modifiers::COMMAND); + assert_eq!(u.app.session.doc().unwrap().ids().count(), count); + assert!(u.app.session.ds().unwrap().text_edit.is_none()); + assert_eq!(u.app.ui.last_error, None); + // While typing in the sticky it ends the edit, as before. + press(&mut u, Key::Enter, Modifiers::NONE); + u.frame(vec![Event::Text("x".into())]); + assert_eq!(typing_in(&u), Some(st)); + press(&mut u, Key::Enter, Modifiers::COMMAND); + assert!(u.app.session.ds().unwrap().text_edit.is_none(), "the edit ended"); + assert_eq!(text_of_node(&u, st), "x"); + assert_eq!(u.app.session.doc().unwrap().ids().count(), count); + assert_eq!(u.app.ui.last_error, None); + // A design file. + let mut d = Ui::new(Session::new()); + d.frame(vec![]); + d.app.session.execute("text.create", &json!({"x": 0, "y": 0, "text": "hi"})).unwrap(); + d.frame(vec![]); + press(&mut d, Key::Enter, Modifiers::NONE); + assert!(d.app.session.ds().unwrap().text_edit.is_some()); + press(&mut d, Key::Enter, Modifiers::COMMAND); + assert!(d.app.session.ds().unwrap().text_edit.is_none()); + assert_eq!(d.app.ui.last_error, None); + // The control channel's key. + let key = json!({"key": "Enter", "cmd": true}); + let ctx = u.ctx.clone(); + select(&mut u, &[st]); + let count = u.app.session.doc().unwrap().ids().count(); + let r = crate::control::handle(&mut u.app, &ctx, "ui.key", &key); + assert!(!format!("{r:?}").contains("board.mindMapAdd"), "{r:?}"); + assert_eq!(u.app.session.doc().unwrap().ids().count(), count); + assert_eq!(u.app.ui.last_error, None); + press(&mut u, Key::Enter, Modifiers::NONE); + assert_eq!(typing_in(&u), Some(st)); + let r = crate::control::handle(&mut u.app, &ctx, "ui.key", &key); + assert!(!format!("{r:?}").contains("board.mindMapAdd"), "{r:?}"); + assert_eq!(u.app.session.doc().unwrap().ids().count(), count); + assert_eq!(u.app.ui.last_error, None); + // On a mind map node it is the child. + press(&mut u, Key::Escape, Modifiers::NONE); + let (_, [c0, ..], _) = mind_map(&mut u); + select(&mut u, &[c0]); + let r = crate::control::handle(&mut u.app, &ctx, "ui.key", &key).unwrap(); + assert_eq!(r, json!({"command": "board.mindMapAdd"})); + let g = typing_in(&u).expect("typing in the new child"); + assert_eq!(parent(&u, g), Some(c0)); +} diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index e75116b66..d76e48ca2 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -4,6 +4,7 @@ use egui::{Color32, CornerRadius, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use figcraft_doc::{BOARD_COLORS, BoardItem, BoardShape, NodeId, NodeKind, Routing, Stamp, StrokeCap}; +use figcraft_engine::ToolId; use figcraft_engine::board::{BoardTool, TEXT_SIZES}; use figcraft_engine::board_grid::GridStyle; use serde_json::{Value, json}; @@ -20,6 +21,7 @@ pub(crate) enum Mark { Color(figcraft_color::Color), Shape(BoardShape), Stamp(Stamp), + Icon(Icon), } /// One choice of a board tool's flyout: its name, the tool's params, whether it is the tool's now. @@ -28,22 +30,37 @@ pub(crate) struct Choice { pub params: Value, pub on: bool, pub mark: Mark, + /// The tool the choice picks when it isn't the group's own. + pub tool: Option, } /// The choices a board tool's flyout offers. -pub(crate) fn choices(options: Options, board: &BoardTool) -> Vec { +pub(crate) fn choices(options: Options, board: &BoardTool, current: ToolId) -> Vec { match options { Options::Colors => BOARD_COLORS .iter() - .map(|(n, c)| Choice { label: color_label(n), params: json!({"color": n}), on: board.sticky == *c, mark: Mark::Color(*c) }) + .map(|(n, c)| Choice { label: color_label(n), params: json!({"color": n}), on: board.sticky == *c, mark: Mark::Color(*c), tool: None }) .collect(), Options::Shapes => BoardShape::ALL .iter() - .map(|b| Choice { label: b.label(), params: json!({"shape": b.id()}), on: board.shape == *b, mark: Mark::Shape(*b) }) + .map(|b| Choice { + label: b.label(), + params: json!({"shape": b.id()}), + on: current != ToolId::MindMap && board.shape == *b, + mark: Mark::Shape(*b), + tool: None, + }) + .chain([Choice { + label: ToolId::MindMap.label(), + params: json!({}), + on: current == ToolId::MindMap, + mark: Mark::Icon(Icon::MindMap), + tool: Some(ToolId::MindMap), + }]) .collect(), Options::Stamps => Stamp::ALL .iter() - .map(|b| Choice { label: b.label(), params: json!({"stamp": b.id()}), on: board.stamp == *b, mark: Mark::Stamp(*b) }) + .map(|b| Choice { label: b.label(), params: json!({"stamp": b.id()}), on: board.stamp == *b, mark: Mark::Stamp(*b), tool: None }) .collect(), Options::None => Vec::new(), } @@ -75,6 +92,7 @@ pub(crate) fn paint_choice(p: &egui::Painter, r: Rect, mark: &Mark, ink: Color32 let path = figcraft_geom::Affine::translate((1.0, 1.0)) * path; icons::paint_outlines(p, r, 16.0, &[(&path, false)], ink, 1.2); } + Mark::Icon(icon) => icons::paint(p, r, *icon, ink), Mark::Stamp(s) => { p.circle_filled(r.center(), r.width().min(r.height()) / 2.0, c32(s.color())); let parts: Vec<(figcraft_geom::BezPath, bool)> = @@ -109,6 +127,8 @@ struct Line { end: StrokeCap, weight: f64, dashed: bool, + /// Every selected connector is a mind map's branch: no line types. + branch: bool, ids: Vec, } @@ -136,11 +156,18 @@ fn has(app: &FigApp) -> Option { end: s.cap_end, weight: s.weight, dashed: !s.dashes.is_empty(), + branch: true, ids: Vec::new(), }); + line.branch &= c.branch; line.ids.push(n.id); } - Some(BoardItem::Label { .. } | BoardItem::MindNode) => h.text = true, + Some(BoardItem::MindNode) => { + // A node's text takes the board colours as its colour. + h.color = true; + h.text = true; + } + Some(BoardItem::Label { .. }) => h.text = true, Some(BoardItem::Table) => h.table = true, Some(BoardItem::Stamp { .. }) | None => {} } @@ -172,7 +199,7 @@ impl Has { w += TEXT_SIZES.len() as f32 * (CELL + 2.0) + PART_END; } if self.connector.is_some() { - w += LINE_W; + w += LINE_W - if self.connector.as_ref().is_some_and(|l| l.branch) { ROUTING_W } else { 0.0 }; } if self.table { w += crate::board_picker::TABLE_PART_W; @@ -343,7 +370,9 @@ const CAP_W: f32 = 62.0; /// The line style menu's width. const STYLE_W: f32 = CELL + 12.0; /// The connector part's width: the three routings, the two ends and the line style. -const LINE_W: f32 = 3.0 * (CELL + 2.0) + 8.0 + 2.0 * CAP_W + 2.0 + 8.0 + STYLE_W + PART_END; +const LINE_W: f32 = ROUTING_W + 2.0 * CAP_W + 2.0 + 8.0 + STYLE_W + PART_END; +/// The three routing cells and the divider after them (a mind map's branch has none). +const ROUTING_W: f32 = 3.0 * (CELL + 2.0) + 8.0; /// The weights the line style menu offers. const WEIGHTS: [f64; 4] = [1.0, 2.0, 4.0, 6.0]; /// A dashed connector's dashes and gaps. @@ -358,14 +387,16 @@ fn line_part(app: &mut FigApp, ui: &mut Ui, line: &Line, at: Pos2, t: &Tokens) { (Icon::CurvedConnector, tr("Curved"), Routing::Curved, "curved"), ]; let mut x = at.x; - for (i, (icon, tip, routing, id)) in cells.into_iter().enumerate() { - let r = Rect::from_center_size(pos2(x + CELL / 2.0, at.y), vec2(CELL, CELL)); - if crate::toolbar::tool_cell(ui, t, r, ("bb_line", i), icon, line.routing == routing, tip).clicked() { - app.run("board.setStyle", json!({"style": id})); + if !line.branch { + for (i, (icon, tip, routing, id)) in cells.into_iter().enumerate() { + let r = Rect::from_center_size(pos2(x + CELL / 2.0, at.y), vec2(CELL, CELL)); + if crate::toolbar::tool_cell(ui, t, r, ("bb_line", i), icon, line.routing == routing, tip).clicked() { + app.run("board.setStyle", json!({"style": id})); + } + x += CELL + 2.0; } - x += CELL + 2.0; + x = divider(ui, t, x - 2.0, at.y); } - x = divider(ui, t, x - 2.0, at.y); for (start, cap) in [(true, line.start), (false, line.end)] { cap_menu(app, ui, t, pos2(x, at.y), start, cap); x += CAP_W + 2.0; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 925b1fc39..ab371a6d8 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1000,7 +1000,7 @@ fn ui_key(app: &mut FigApp, ctx: &Context, p: &Value) -> Result { use figcraft_engine::keymap::{Context, lookup, normalize}; // Text editing keys go to the editor (after the shortcuts live while editing). if app.session.ds().map(|d| d.text_edit.is_some()).unwrap_or(false) { - if let Some(bd) = lookup(platform, Context::Text, key, m).filter(|_| m.cmd || m.alt || m.ctrl) { + if let Some(bd) = lookup(platform, Context::Text, key, m).filter(|bd| (m.cmd || m.alt || m.ctrl) && crate::shortcuts::applies(app, bd)) { crate::menus::invoke(app, bd.id); return Ok(json!({"command": bd.id})); } @@ -1024,7 +1024,7 @@ fn ui_key(app: &mut FigApp, ctx: &Context, p: &Value) -> Result { let r = crate::comments::step(app, ctx, if matches!(key, "ArrowUp" | "Up") { -1 } else { 1 }); return Ok(json!({"comment": r.and_then(|v| v.get("id").cloned())})); } - if let Some(bd) = lookup(platform, Context::Canvas, key, m) { + if let Some(bd) = lookup(platform, Context::Canvas, key, m).filter(|bd| crate::shortcuts::applies(app, bd)) { crate::shortcuts::run_binding(app, bd.id); return Ok(json!({"command": bd.id})); } diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index eac47a241..1c67509c7 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -232,6 +232,8 @@ icons! { CurvedConnector, Shapes, Stamp, + /// A mind map: a first node with two branches curving out to two lines of text. + MindMap, /// Running a board session: a stopwatch (the timer), two bars (pause) and a ballot going /// into a box (voting). Timer, diff --git a/crates/ui-egui/src/icons/draw.rs b/crates/ui-egui/src/icons/draw.rs index 7d46ab11d..4a3c7a18f 100644 --- a/crates/ui-egui/src/icons/draw.rs +++ b/crates/ui-egui/src/icons/draw.rs @@ -1054,6 +1054,13 @@ fn draw(p: &P, icon: Icon) { p.circle(8.0, 8.0, 6.0); p.poly(&[(5.0, 8.3), (7.2, 10.5), (11.0, 6.0)], false); } + MindMap => { + p.fill_rect(1.0, 6.5, 6.0, 9.5, 1.0); + p.path(&[(6.0, 8.0), (7.5, 8.0), (8.3, 7.2), (8.7, 5.0), (9.5, 4.0), (11.0, 4.0)], false); + p.path(&[(6.0, 8.0), (7.5, 8.0), (8.3, 8.8), (8.7, 11.0), (9.5, 12.0), (11.0, 12.0)], false); + p.line(11.0, 4.0, 15.0, 4.0); + p.line(11.0, 12.0, 15.0, 12.0); + } Timer => { p.circle(8.0, 9.0, 5.5); p.line(8.0, 9.0, 8.0, 6.0); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a5361778c..ec702a830 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -93,8 +93,8 @@ pub fn invoke(app: &mut FigApp, id: &str) { app.run(id, json!({})); } "file.open" => app.open_dialog(), - // From the keyboard or a menu, typing goes on in the new sticky. - "board.nextSticky" => { + // From the keyboard, a menu or the Actions palette, typing goes on in what was made. + "board.nextSticky" | "board.mindMapAdd" | "board.mindMap" => { app.run(id, json!({"edit": true})); } "help.checkForUpdates" | "app.checkForUpdates" => crate::updates_ui::check(app), diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 26bdb60d2..fe84e01b2 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -63,6 +63,13 @@ pub fn lookup(context: keymap::Context, key: Key, physical: Option, m: Modi keymap::lookup(platform(), context, key.name(), held) } +/// Whether binding `b` is live for the app as it is. Cmd/Ctrl+Enter adds a mind map node's child +/// only from a mind map node (selected, or being typed in); anywhere else the key is nobody's on +/// the canvas and ends the edit while typing, as before the binding. +pub(crate) fn applies(app: &FigApp, b: &keymap::Binding) -> bool { + b.id != "board.mindMapAdd" || figcraft_engine::board::mind_node_target(&app.session).is_some() +} + /// The key a menu shows for a command. pub fn shortcut(id: &str) -> Option<&'static str> { keymap::primary(id, platform()) @@ -453,7 +460,7 @@ fn key_event(app: &mut FigApp, key: Key, physical: Option, m: Modifiers, re return true; } } - if let Some(b) = lookup(keymap::Context::Canvas, key, physical, m) { + if let Some(b) = lookup(keymap::Context::Canvas, key, physical, m).filter(|b| applies(app, b)) { // Copy/cut/paste arrive as clipboard events on most platforms. if matches!(b.id, "edit.copy" | "edit.cut" | "edit.paste") { return true; @@ -958,7 +965,7 @@ fn text_line_index(app: &FigApp, id: figcraft_doc::NodeId, p: figcraft_geom::Poi /// Shortcuts live while editing text (Bold, lists, alignment, size/weight/spacing steps, Save…). fn text_shortcut(app: &mut FigApp, key: Key, physical: Option, m: Modifiers) -> bool { - match lookup(keymap::Context::Text, key, physical, m) { + match lookup(keymap::Context::Text, key, physical, m).filter(|b| applies(app, b)) { Some(b) => { crate::menus::invoke(app, b.id); true diff --git a/crates/ui-egui/src/shortcuts_tests.rs b/crates/ui-egui/src/shortcuts_tests.rs index 4b223b211..67fc87491 100644 --- a/crates/ui-egui/src/shortcuts_tests.rs +++ b/crates/ui-egui/src/shortcuts_tests.rs @@ -16,7 +16,7 @@ fn id(v: serde_json::Value) -> NodeId { NodeId(v["id"].as_u64().unwrap()) } -fn press(u: &mut Ui, key: Key, modifiers: Modifiers) { +pub(crate) fn press(u: &mut Ui, key: Key, modifiers: Modifiers) { u.frame(vec![ Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }, Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }, diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 7aff24993..9ee20af65 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -99,7 +99,12 @@ const BOARD_GROUPS: &[Group] = &[ &[(ToolId::Marker, Icon::Marker), (ToolId::Highlighter, Icon::Highlighter), (ToolId::Eraser, Icon::Eraser)], ), Group { key: "sticky", name: tr_noop("Sticky note colors"), tools: &[(ToolId::Sticky, Icon::Board)], options: Options::Colors }, - Group { key: "bshape", name: tr_noop("Shapes"), tools: &[(ToolId::BoardShape, Icon::Shapes)], options: Options::Shapes }, + Group { + key: "bshape", + name: tr_noop("Shapes"), + tools: &[(ToolId::BoardShape, Icon::Shapes), (ToolId::MindMap, Icon::MindMap)], + options: Options::Shapes, + }, Group::tools("connector", tr_noop("Connector"), &[(ToolId::Connector, Icon::Connector)]), Group::tools("text", tr_noop("Text"), &[(ToolId::Text, Icon::Text)]), Group::tools("section", tr_noop("Section"), &[(ToolId::Section, Icon::Section)]), @@ -546,7 +551,7 @@ fn done_button(ui: &mut Ui, t: &Tokens, x: f32, cy: f32, tip: &str) -> bool { fn options_flyout(app: &mut FigApp, ui: &mut Ui, g: &Group, bottom_left: egui::Pos2) { let t = Tokens::get(ui.ctx()); let Some(&(tool, _)) = g.tools.first() else { return }; - let items = crate::board_bar::choices(g.options, &app.session.tool.board); + let items = crate::board_bar::choices(g.options, &app.session.tool.board, app.session.tool.tool); let (cell, pad) = (32.0, 8.0); let cols = items.len().clamp(1, 8); let rows = items.len().div_ceil(cols); @@ -566,14 +571,14 @@ fn options_flyout(app: &mut FigApp, ui: &mut Ui, g: &Group, bottom_left: egui::P } crate::board_bar::paint_choice(ui.painter(), r.shrink(5.0), &c.mark, t.menu_text); if resp.clicked() { - chosen = Some(c.params.clone()); + chosen = Some((c.tool.unwrap_or(tool), c.params.clone())); } } }); if ui.input(|i| i.key_pressed(egui::Key::Escape)) { app.ui.tool_flyout = None; } - if let Some(params) = chosen { + if let Some((tool, params)) = chosen { app.run(&format!("tool.{}", tool.id()), params); app.ui.tool_flyout = None; } diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 11d4aaf41..9bec53b12 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,13 +1,13 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) -**Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind +**Breadth ~48%, ready ~30% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that follow what they join (straight, elbow or curved, their ends dragged onto other objects), marker, highlighter and eraser, stamps, text and sections, five built-in templates and tables, edited together in the existing live sessions, with a shared countdown and voting sessions to run a -workshop. Music, board widgets, the mind maps' toolbar entry and gestures, and the rest of the tail are missing. Remaining: +workshop. Music, board widgets, the mind maps' "+" handles and drag gestures, and the rest of the tail are missing. Remaining: ~20–44 h. Tracked as area 22 of [`target-app-parity.md`](target-app-parity.md) (not in its weighted sum: the target there is the design product). The work item is gap 24 in [`gaps.md`](gaps.md). @@ -27,8 +27,8 @@ all end with the same geometry. | Feature | Status | Notes | |---|---|---| | Board files: File ▸ New board, the home screen's New board card, a light page | done | `file.newBoard`; the kind shows in `inspect_document`, tabs and file rows (a note mark; design files a pen nib) | -| Board toolbar at the bottom | done | Move/Hand, Marker/Highlighter/Eraser, Sticky (colour flyout), Shapes (flyout), Connector, Text, Section, Stamp (flyout), Comment, Actions, then the templates and the Design panel's buttons — on the same 32 pt grid as a design file's (no Resources button, as there) | -| Design panel hidden by default; a contextual bar above the selection | done | colour, shape, text size (S/M/L/XL); for connectors straight/elbow/curved, the start and end points (none, round, square, line arrow, triangle arrow, reversed triangle, circle, diamond), solid or dashed, the weight, and any colour in the colour picker beside the board colours (#1596); each control says what it is on hover; the Design panel opens with its button or View ▸ Design panel | +| Board toolbar at the bottom | done | Move/Hand, Marker/Highlighter/Eraser, Sticky (colour flyout), Shapes (flyout, the mind map at its end), Connector, Text, Section, Stamp (flyout), Comment, Actions, then the templates and the Design panel's buttons — on the same 32 pt grid as a design file's (no Resources button, as there) | +| Design panel hidden by default; a contextual bar above the selection | done | colour, shape, text size (S/M/L/XL); for connectors straight/elbow/curved, the start and end points (none, round, square, line arrow, triangle arrow, reversed triangle, circle, diamond), solid or dashed, the weight, and any colour in the colour picker beside the board colours (#1596); a mind map node takes the colours as its text colour and the text sizes; a branch has the connector's controls without the line types; each control says what it is on hover; the Design panel opens with its button or View ▸ Design panel | | Prototyping and Developer Mode refuse on boards | done | `proto.*`, `dev.*`, `view.prototype`, `view.devMode` say why | | Sticky notes | done | a square frame (200 wide, growing taller through auto layout), 8 soft colours, a soft shadow, the note's text size shrinking as it grows (24 → 11, by characters and lines), the author's name at the bottom; a click places one and starts typing; Enter or a double-click edits; Shift+Cmd/Ctrl+Enter adds the next one beside it | | Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; no size presets or stacks | @@ -61,7 +61,7 @@ all end with the same geometry. | Board widgets | missing | design-file widgets exist (`crates/engine/src/extensions/widgets.rs`), not wired to boards | | Templates (retrospective, brainstorm, flow chart…) | partial | five built-in templates drawn up for FigCraft (retrospective, brainstorm, weekly planner, flow chart, kanban board), placed from the toolbar's templates picker (each with a picture of itself) or `board.template {name, x?, y?}` as ordinary sections, stickies, shapes, connectors and text in one undo step; `board.templates` lists them. No community templates, no saving your own | | Tables | partial | `board.table {rows, columns, cells?, x?, y?}` (at most 50 × 20): an auto layout frame of rows of cells with text, a tinted header row and lines between rows and columns; a cell's row grows with its text; a double-click types in the cell under the pointer; add or remove a row or column from the bar over the selection or `board.tableEdit {id, action, index?}`; cells copied from a spreadsheet (tab-separated text, quoted cells kept whole) paste as a table, up to 50 × 20 with a note when there was more; undoable and synced in live sessions. No column resizing by dragging, no cell colours, no Tab between cells; comma-separated text pastes as text | -| Mind maps | partial | from commands only so far (#2226): `board.mindMap {x?, y?, text?, children?}` places a first node (bold, no box) with three children on its right, joined by curved branches; `board.mindMapAdd {id?, relation?: child\|sibling}` adds a node. Nodes are text that grows wider as it is typed and taller with line breaks; a node's children stand in one column 88 units right of the widest node of its own column, 48 apart, centred on it, and the map lays itself out again in the normalize pass after every edit, undo and live-session change; moving the first node moves the map; a deleted node's children stay where they are without their branch. Branches are board connectors (`branch`: stroke 4, #757575, round caps), so their style, end points, weight and colour change like any connector's. No toolbar entry, shortcuts, "+" handles, dragging a node onto another, left side or `.jam` import yet | +| Mind maps | partial | Shapes ▸ Mind map in the toolbar, then a click: a first node (bold, no box) whose text starts at the click, with three children on its right joined by curved branches, and typing starts in the first node (#2226). Cmd/Ctrl+Enter on a node, selected or being typed in, adds a child below its other children; Shift+Cmd/Ctrl+Enter adds a sibling right after it (the first node has none); both go on typing in the new node. Tab and Shift+Tab select the next and previous sibling; Enter types in the selected node. The bar over a node sets its text colour and size; over a branch its colour, start and end points, dashes and weight. From commands: `board.mindMap {x?, y?, text?, children?}`, `board.mindMapAdd {id?, relation?: child\|sibling}`, `tool.mindMap`. Nodes are text that grows wider as it is typed and taller with line breaks; a node's children stand in one column 88 units right of the widest node of its own column, 48 apart, centred on it, and the map lays itself out again in the normalize pass after every edit, undo and live-session change; moving the first node moves the map; a deleted node's children stay where they are without their branch. Branches are board connectors (`branch`: stroke 4, #757575, round caps). No "+" handles, outline around the map, dragging a node onto another, left side or `.jam` import yet | | Washi tape, code blocks, image cropping on boards | missing | images can be placed as in design files | | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | @@ -72,6 +72,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 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-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. A mind map node is a board object of its own (`BoardItem::MindNode`: text with no box) and a branch is a connector marked `branch`; the map's shape is read from its branches. `board.mindMap` places a first node with three children and `board.mindMapAdd` adds a child or a sibling, each one undo step. The normalize pass lays a touched map out again from its first node (`board::settle_mind_maps`, `figcraft_doc::mind_layout`): 88 between columns, 48 between siblings, each stack centred on its parent, numbers from a FigJam file saved and decoded. Tests: `board_mindmap_tests` in doc (five) and engine (eight). Numbers unchanged (no toolbar entry yet). | | 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. | | 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index ee855922c..d2e330f55 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (gap 24: mind maps from the toolbar and the keyboard (#2226); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -185,7 +185,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe mode and measuring, then (2026-10-12) comments and version history, and the layers and Assets panels (`crates/engine/src/*_behaviour_tests.rs`, `crates/ui-egui/src/layers_behaviour_tests.rs`), each with its fixes; then keyboard shortcuts per platform (`shortcut_parity_tests.rs`: 129 - documented rows, now 128 bound, 1 moved off a documented conflict, none missing, 57 undocumented + documented rows, now 128 bound, 1 moved off a documented conflict, none missing, 58 undocumented bindings pinned), with 16 rows newly bound, Control suspending snapping on macOS and shifted symbols on other keyboard layouts; then the everyday partials of [`ui-parity.md`](ui-parity.md): number fields, outline mode's options, Hide when publishing, a @@ -582,7 +582,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe connector's ends drag onto another object or empty canvas (`board.reattach`); curved connectors; elbows that go around the objects they join. - **Missing:** timer music, board widgets, saving your own templates, table column resizing and - cell colours, the mind maps' toolbar entry, shortcuts, drag to re-parent and import, washi tape, code blocks, audio and huddles, quick-create handles, + cell colours, the mind maps' "+" handles, drag to re-parent and import, washi tape, code blocks, audio and huddles, quick-create handles, the stamp wheel, emotes and stickers, `.jam` files ([`boards-parity.md`](boards-parity.md)). - **User impact:** boards cover a brainstorm, a retrospective, a flow sketch and a timed, voted @@ -593,6 +593,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Gap 24: mind maps in the UI (step 2): Shapes ▸ Mind map in the toolbar, Cmd/Ctrl+Enter and Shift+Cmd/Ctrl+Enter for a child and a sibling, Tab between siblings, the bar over a node and a branch (#2226); the "+" handles, drag to re-parent and `.jam` import are what is missing of them. | | 2026-11-10 | minor | Gap 24: mind maps, first step (`board.mindMap`, `board.mindMapAdd`; the map lays itself out again after every edit, #2226); the toolbar entry, shortcuts, drag to re-parent and `.jam` import are what is missing of them. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | | 2026-10-31 | minor | Gap 10: library analytics list the layers and files using each style and variable; their insertions, detachments and modes stay on the missing list. | diff --git a/docs/mcp.md b/docs/mcp.md index 170b316b0..bafc25cde 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -483,7 +483,8 @@ one undo step and returns the ids it made: - `board.nextSticky {id?, side?: right|below|left|above, edit?}` → `{id, text}`: a sticky of the same colour beside the selected (or edited) one; with `edit: true` the app goes on typing in it (`Shift+Cmd/Ctrl+Enter` in the app does both). On a shape it does what `board.addConnected` does: - the next shape, joined to it by a connector (`{id, text, connector}`). + the next shape, joined to it by a connector (`{id, text, connector}`). On a mind map node it is + the node's next sibling, as `board.mindMapAdd {relation: sibling}`. - `board.addConnected {id?, side?: right|below|left|above, edit?}` → `{id, text, connector}`: the next sticky or shape of the same kind, size and colour on that side of the selected (or edited) one, 80 units away, joined to it by a connector the way the Connector tool makes one; one undo @@ -531,7 +532,8 @@ one undo step and returns the ids it made: - `board.ink {path | points, highlighter?, color?, select? (default true)}` → `{id}`: a marker (or wide, see-through highlighter) stroke. - `board.setColor {ids?, color}`: stickies and shapes take it as their fill, connectors and ink as - their line. `board.setStyle {ids?, shape?, fontSize?, style?: straight|elbow|curved, startCap?, + their line, mind map nodes as their text colour (a board colour in its deeper shade). + `board.setStyle {ids?, shape?, fontSize?, style?: straight|elbow|curved, startCap?, endCap?}`: a shape's outline and text size, a connector's routing and arrowheads. - `board.templates` → `[{id, name, description, width, height}]` lists the built-in templates: `retrospective brainstorm weeklyPlanner flowChart kanban`. `board.template {name, x?, y?}` → @@ -546,7 +548,8 @@ one undo step and returns the ids it made: (default the last); `id` may be the table or any layer in it. - Tools for `pointer`: `tool.sticky {color?}`, `tool.shape {shape?}`, `tool.connector {style?: straight|elbow|curved}` (drag from one object to another), `tool.marker {color?}`, `tool.highlighter {color?}`, - `tool.eraser` (drag over strokes), `tool.stamp {stamp?}`; Text and Section are the usual tools. + `tool.eraser` (drag over strokes), `tool.stamp {stamp?}`, `tool.mindMap` (a click places a mind map, the first node's text starting + there, and types in it); Text and Section are the usual tools. ```json {"command": "file.newBoard", "params": {"name": "Retro"}} @@ -635,8 +638,9 @@ on; `key` resolves keys the way the canvas does. Commands behind keys: - `doc.nextTab` / `doc.previousTab` (`Ctrl+Tab` / `Ctrl+Shift+Tab`): the next or previous open file. - Board tools (boards only): `tool.sticky` (`Q`), `tool.shape` (`B`), `tool.connector` (`X`), `tool.marker` (`M`), `tool.highlighter` (`U`), `tool.eraser` (`E`), `tool.stamp` (`W`), and - `board.nextSticky` (`Shift+Cmd/Ctrl+Enter`, also while typing in a sticky). Keys no design-file - shortcut uses; on a design file they refuse. + `board.nextSticky` (`Shift+Cmd/Ctrl+Enter`, also while typing in a sticky; on a mind map node it + makes the node's next sibling) and `board.mindMapAdd` (`Cmd/Ctrl+Enter` on a mind map node, also + while typing in one). Keys no design-file shortcut uses; on a design file they refuse. - `view.pan {dx, dy, big?}`: the arrow keys with nothing selected (`key ArrowRight` does the same) pan the view by 20 screen pixels a step, 200 with `big` (Shift). - `view.multiplayerCursors {on?}` (`Alt+Cmd+\`): show or hide others' cursors in a live session. @@ -2072,7 +2076,7 @@ turned off 0°. other than miter (`strokeJoin`) or a miter angle other than the default ~28.96° (`miterAngle`). - **Select**: `select.layersAt {x, y}` lists every layer under a page point, front-most first with its depth (the context menu's Select layer); `select.set`, `select.children` / `select.parent` (Enter - / Shift+Enter), `select.next` / `select.previous` (Tab / Shift+Tab). With `pointer`, `cmd: true` + / Shift+Enter), `select.next` / `select.previous` (Tab / Shift+Tab; on a board, a mind map node's next or previous sibling). With `pointer`, `cmd: true` clicks select the nested layer, `cmd` drags from empty canvas select the nested layers they touch, and `shift` drags toggle what they touch. A press on the background of a top-level frame with layers in it (the frame not selected) starts a marquee inside it, as on the canvas; an empty frame diff --git a/docs/roadmap.md b/docs/roadmap.md index 0bbe9bd55..eb9a6af48 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -29,6 +29,7 @@ builders' side-by-side checks with synthetic files; nothing has been run on real | Workflow | Works end to end? | Evidence | Hours to pass | |---|---|---|---| +| 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-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 | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Design screens: frames, shapes, vectors, text, auto layout, styles; save, reopen, export assets | yes | tools and panels in `crates/engine` and `crates/ui-egui`; `.figcraft` round trips (`crates/format/src/large_tests.rs`); PNG/JPG/SVG/PDF export tests | — | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 031521f51..c6a247db4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -117,7 +117,7 @@ Breadth: does it exist. Ready: depth, correctness and fidelity for real projects | 19 | Team libraries & organization | 2 | 70% | 40% | Libraries kept on `figcraft-server` under their file and enabled by a share link (per-asset versions, background update checks, overrides kept), usage counts per component and file, swapping a library by names. Left: team-wide library lists, accounts and permissions, analytics over time, pushed update notices | 4–8 | | 20 | Figma Draw extras | 2 | 88% | 60% | Have: variable width, lasso, shape builder, noise/texture, text on a path, pattern fills, stretch and scatter brushes, pen pressure (Windows pens, browser styluses), multi-edit (several vector layers in edit mode at once). Missing: pressure from macOS/Linux tablets | 1–3 | | 21 | AI features | 3 | 0% | 0% | First draft, rename layers, image edit/remove background, visual search, Make: needs local models (owner decision) | 30–60 | -| 22 | Boards (whiteboarding) | 0 | ~47% | ~29% | Board files with a dot grid, sticky notes, shapes with text, connectors that follow what they join (straight, elbow around the objects, or curved; ends dragged to re-attach), marker, highlighter and eraser, stamps, text and sections, five built-in templates and tables, a shared timer and voting sessions, in live sessions (M12); missing: timer music, board widgets, mind maps, washi tape, audio, quick-create handles, connector waypoints, stamps sticking to objects, `.jam` files ([boards-parity](boards-parity.md)). Not in the weighted sum | 20–44 | +| 22 | Boards (whiteboarding) | 0 | ~48% | ~30% | Board files with a dot grid, sticky notes, shapes with text, connectors that follow what they join (straight, elbow around the objects, or curved; ends dragged to re-attach), marker, highlighter and eraser, stamps, text and sections, five built-in templates and tables, a shared timer and voting sessions, mind maps from the toolbar and the keyboard, in live sessions (M12); missing: timer music, board widgets, the mind maps' drag gestures, washi tape, audio, quick-create handles, connector waypoints, stamps sticking to objects, `.jam` files ([boards-parity](boards-parity.md)). Not in the weighted sum | 20–44 | | | **Weighted (÷113)** | 113 | **~85%** | **~63%** | | **117–255** | | | Core editor only (1–16, ÷94) | 94 | ~94% | ~72% | | 32–74 | @@ -467,7 +467,7 @@ Hours in this narrative are the builders' estimates; the tables above supersede shortcuts panel docks at the bottom with a tab per group and search, keycaps per platform. A shortcut parity suite (`shortcut_parity_tests.rs`) checks every documented shortcut on both platforms (129 rows: 128 bound, including moving the rotation origin with Alt+R and placing an - object with Enter from the toolbar; 1 moved off a documented conflict) and pins the 57 undocumented + object with Enter from the toolbar; 1 moved off a documented conflict) and pins the 58 undocumented bindings; others' cursors (`Alt+Cmd+\`), list levels while editing (Cmd/Ctrl+] and [), the keyboard box selection on Alt+Space / Ctrl+Space, arrows that pan with nothing selected, Control to suspend snapping on macOS and Space/N/C/F while presenting landed with it @@ -674,6 +674,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | 2026-10-28 | minor | Arabic draft: 1,857 UI strings, 620 command labels, 31 menu wordings; count-neutral plurals and web font gate. Native review and panel mirroring remain open; grade and estimates unchanged. Evidence: `crates/ui-egui/locales/ar.toml`, i18n catalog tests and [translation notes](translating.md#arabic-draft) | | 2026-10-24 | patch | Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds, which landed (`view.outlinesHiddenLayers`, `view.outlinesObjectBounds`, `crates/engine/src/outline_options_tests.rs`). Numbers unchanged | | 2026-10-24 | minor | Boards (area 22, weight 0): a shared timer and voting sessions (M12); ~35%/~20% → ~40%/~24%, 30–60 h → 26–54 h; weighted numbers unchanged | +| 2026-11-10 | minor | Boards (M12, #2226, step 2 of 4): mind maps from the toolbar and the keyboard; area 22 ~47%/~29% → ~48%/~30%, the hours unchanged (outside the weighted sum) | | 2026-10-24 | minor | Boards (M12): templates (five built in, `board.template`) and tables (`board.table`, `board.tableEdit`); area 22 ~35%/~20% → ~40%/~24%, 30–60 h → 26–54 h (outside the weighted sum) | | 2026-10-24 | minor | Plugin widgets take text input and a property menu (gap 6, plugin API 4; API 1–3 plugins and existing widgets unchanged): a widget's text layer can be an editable field, edited on the canvas with a double-click like any text (or `widget.setText`), its value cleaned and capped at 1,000 characters, written into the widget's state under the field's name and the field's text, and the plugin called back to redraw, all as one undo step that syncs in live sessions; a widget can carry a property menu of up to 8 actions, toggles and colour choices (up to 8 colours each), shown in a small bar over the widget while it is selected and driven with `widget.menu`; descriptions, values and menus read back from files are checked, an API 3 plugin that draws a field or a menu is refused, and older FigCraft builds refuse API 4 manifests. The Counter example gained a label field and a menu (reset, steps of ten, a colour); the SDK reads the new events. Hover and timers are still missing. Plugins & widgets 60%/35% → 65%/38%, 8–26 h → 6–22 h; Ecosystem dimension 38% → 40%; weighted totals unchanged at this rounding; full parity ~262–519 h → ~260–515 h | | 2026-10-24 | minor | Boards (M12): a file kind of its own (`file.newBoard`, saved in `.figcraft`, carried to live-session joiners) with sticky notes, shapes with text, connectors that re-route when what they join moves (an engine recompute, the same for local edits, undo and others' edits), marker, highlighter and eraser, stamps with the placer's name, a board toolbar and a contextual bar; prototyping and Dev Mode refuse on boards; design files and boards have their own marks on tabs and file rows. Area 22 added at weight 0 (breadth ~35%, ready ~20%); headline numbers unchanged (the weighted sum leaves area 22 out) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 463be3b47..e51ac4e01 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -143,7 +143,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Bound on other keys (documented conflict) | 1 | Run last plugin: the documentation also gives Ctrl+Alt+P to pixel preview on Windows; the plugin takes Ctrl+Alt+Shift+P there | | Missing | 0 | moving the rotation origin (Alt+R, `transform.rotationOrigin`) and placing an object with Enter after choosing its tool (`tool.place`) were the last two | | Documented keys a platform keeps | 2 | Ctrl+Space (Windows/Linux keyboard box selection) switches some CJK input methods; F6 goes to a browser's address bar in the web build | -| Undocumented bindings pinned | 57 | of which Cmd/Ctrl+W, Cmd/Ctrl+N and Ctrl+Tab are taken by browsers (web build) and Ctrl+Alt+T / Ctrl+Alt+L by some Linux desktops | +| Undocumented bindings pinned | 58 | of which Cmd/Ctrl+W, Cmd/Ctrl+N and Ctrl+Tab are taken by browsers (web build) and Ctrl+Alt+T / Ctrl+Alt+L by some Linux desktops | - **Newly bound:** A for the Frame tool, Shift+' for the pixel grid (Cmd+' kept: the articles disagree), Alt+Cmd+\ / Ctrl+Alt+\ for others' cursors (`view.multiplayerCursors`, new), Ctrl+F6 @@ -272,3 +272,4 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | 2026-10-11 | minor | Outline mode done: outlines for the selection (the selected layers draw as outlines, the rest normally) and mask outlines | | 2026-10-11 | minor | Design panel arc fields, live boolean editing (operands on the canvas, live results, per-operand operations), shape builder on strokes and open paths, one-sided widths (Alt-drag a width handle) | | 2026-10-10 | major | Created from the ROADMAP's look-and-feel and interaction items, the keymap and the canvas code | +| 2026-11-10 | minor | Boards (M12, #2226): Cmd/Ctrl+Enter pinned for a mind map node's child (`board.mindMapAdd`; live only on a mind map node: elsewhere the key is free on the canvas and still ends a text edit): 57 → 58 pinned | From 937af6eee608fccc1fff5a045affed54824802e9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 17:36:39 -0500 Subject: [PATCH 016/268] M12: Docs: the mind-map revision rows go in the revision history (#2226) The 2026-11-10 rows sat in ROADMAP.md's Headline numbers table and docs/roadmap.md's Alpha gate table; each now opens its file's revision history. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- ROADMAP.md | 2 +- docs/roadmap.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 0f59d1bce..74638c4cc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -13,7 +13,6 @@ start with [`docs/gaps.md`](docs/gaps.md). | | Value | Kind | |---|---|---| -| 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 | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Menu/command breadth | **100%** (212 / 212) | measured, [`docs/parity-checklist.md`](docs/parity-checklist.md) (`cargo xtask parity`) | | Feature breadth | **~85%** (core editor ~94%) | estimated, [`docs/target-app-parity.md`](docs/target-app-parity.md) | @@ -366,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 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-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | diff --git a/docs/roadmap.md b/docs/roadmap.md index 0bbe9bd55..0e12d327c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,7 +29,6 @@ builders' side-by-side checks with synthetic files; nothing has been run on real | Workflow | Works end to end? | Evidence | Hours to pass | |---|---|---|---| -| 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 | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Design screens: frames, shapes, vectors, text, auto layout, styles; save, reopen, export assets | yes | tools and panels in `crates/engine` and `crates/ui-egui`; `.figcraft` round trips (`crates/format/src/large_tests.rs`); PNG/JPG/SVG/PDF export tests | — | | Build and use a design system: components, variants, properties, variables and modes, libraries | yes | `components_scale_tests.rs` (300 components, 2,000 instances), `library_tests.rs`, `library_variables_tests.rs`; libraries are local files, not shared | — | @@ -77,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 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-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | | 2026-11-03 | patch | M4, #1747: a text layer still carrying the name its characters gave it is renamed as they are typed, so the Layers panel no longer shows the word a layer started with while the canvas shows another (`hello` typed into `hello there` read as `hello` in the panel). A name the author typed is kept, and only the editor follows the characters: commands leave the name alone, so the layer names `data.fill`, component property bindings and templates use as field keys stay put. Tests: `text_behaviour_tests::typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it`, `setting_characters_as_a_command_never_renames_the_layer`. Grade unchanged | | 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged | From d928da29bad36e4903083b9ede7122cbc304c5c2 Mon Sep 17 00:00:00 2001 From: Timo Klerx <1579185+TKlerx@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:16:46 +0100 Subject: [PATCH 017/268] M6: Test prototype expression export depth limits --- crates/format/src/fig/assets_tests.rs | 45 +++++++++++++++++++++++ crates/format/src/fig/export/prototype.rs | 8 ++++ 2 files changed, 53 insertions(+) diff --git a/crates/format/src/fig/assets_tests.rs b/crates/format/src/fig/assets_tests.rs index f0a7cf5ab..1fdb82a40 100644 --- a/crates/format/src/fig/assets_tests.rs +++ b/crates/format/src/fig/assets_tests.rs @@ -1246,6 +1246,7 @@ fn a_scaled_instance_keeps_reset_lists_above_a_changed_style_link() { } } +/// The checkbox toggles the imported variable before choosing its status branch. #[test] fn checkbox_variable_and_conditional_actions_round_trip() { use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp}; @@ -1315,6 +1316,7 @@ fn checkbox_variable_and_conditional_actions_round_trip() { } } +/// An unrepresentable condition leaves other actions in the interaction intact. #[test] fn overdeep_conditional_is_omitted_without_losing_the_export() { use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp, MAX_EXPR_DEPTH}; @@ -1345,3 +1347,46 @@ fn overdeep_conditional_is_omitted_without_losing_the_export() { let frame = back.nodes().find(|n| n.name == "Trigger").unwrap(); assert_eq!(frame.interactions[0].actions, vec![Action::Back]); } + +/// The longest conditions with a variable-reference leaf survive at each tested nesting level. +#[test] +fn conditional_expression_depth_boundary_round_trips() { + use figcraft_doc::proto::{ConditionalBlock, Expr, ExprOp}; + + let conditional = |condition, action| Action::Conditional { blocks: vec![ConditionalBlock { condition, actions: vec![action] }] }; + let nested_action = |depth, operators, variable: String| { + let flag = Expr::var(variable); + let condition = (0..operators).fold(flag.clone(), |inner, _| Expr::op(ExprOp::Not, vec![inner])); + (0..depth).fold(conditional(Some(condition), Action::Back), |inner, _| conditional(Some(flag.clone()), inner)) + }; + + // The deepest alias is at Kiwi depth 8 + 2 × conditional depth + 3 × operator count. + for (depth, operators) in [(0, 18), (1, 18), (15, 8)] { + let mut doc = Document::new("Depth boundary"); + let page = doc.first_page().unwrap(); + doc.variables.collections.push(Collection { + id: "demo".into(), + name: "Demo".into(), + modes: vec![Mode { id: "default".into(), name: "Default".into() }], + extends: None, + }); + doc.variables.variables.push(var("checked", "checked", "demo", VariableType::Boolean, &[("default", VariableValue::Boolean(true))])); + let frame = doc.create(page, NodeKind::Frame, "Trigger", 0.0, 0.0, 100.0, 100.0).unwrap(); + doc.node_mut(frame).unwrap().interactions.push(Interaction { + trigger: Trigger::OnClick, + actions: vec![nested_action(depth, operators, "checked".into())], + transition: Transition::Instant, + duration_ms: 300, + easing: Easing::EaseOut, + delay_ms: 0, + }); + + let (bytes, warnings) = export(&doc, None).unwrap(); + assert!(warnings.is_empty(), "export at conditional depth {depth}: {warnings:?}"); + let (back, warnings) = import(&bytes, "Depth boundary").unwrap(); + assert!(warnings.is_empty(), "import at conditional depth {depth}: {warnings:?}"); + let trigger = back.nodes().find(|node| node.name == "Trigger").unwrap(); + let checked = back.variables.variables.iter().find(|variable| variable.name == "checked").unwrap(); + assert_eq!(trigger.interactions[0].actions, [nested_action(depth, operators, checked.id.clone())], "conditional depth {depth}"); + } +} diff --git a/crates/format/src/fig/export/prototype.rs b/crates/format/src/fig/export/prototype.rs index 4d86f776e..08b3f031a 100644 --- a/crates/format/src/fig/export/prototype.rs +++ b/crates/format/src/fig/export/prototype.rs @@ -46,6 +46,7 @@ impl<'d> Exporter<'d> { } } + /// Encode the trigger and the actions that can be represented in the export. fn interaction(&mut self, it: &Interaction) -> Option> { let mut event: Fields = Vec::new(); let ty = match &it.trigger { @@ -80,6 +81,7 @@ impl<'d> Exporter<'d> { (!actions.is_empty()).then(|| o(vec![("event", o(event)), ("actions", arr(actions))])) } + /// Encode one action and warn when a variable or conditional action must be omitted. fn action(&mut self, a: &Action, it: &Interaction, depth: usize) -> Option> { let encoded = self.encode_action(a, it, depth); if encoded.is_none() && matches!(a, Action::SetVariable { .. } | Action::SetVariableMode { .. } | Action::Conditional { .. }) { @@ -88,6 +90,7 @@ impl<'d> Exporter<'d> { encoded } + /// Map an action to Kiwi, preserving branch order and bounding conditional recursion. fn encode_action(&mut self, a: &Action, it: &Interaction, depth: usize) -> Option> { let node = |x: &mut Self, dest: &NodeId, nav: &'static str| -> Option> { let Some(g) = x.guid_of(*dest) else { @@ -183,6 +186,7 @@ impl<'d> Exporter<'d> { } } + /// Encode an expression within the remaining Kiwi operator nesting budget. fn expression(&self, expr: &Expr, levels: usize) -> Option> { match expr { Expr::Value(VariableValue::Alias(id)) => self.expression_alias(id), @@ -220,6 +224,7 @@ impl<'d> Exporter<'d> { } } + /// Reference an exported variable by GUID and include its resolved type. fn expression_alias(&self, variable: &str) -> Option> { let var = self.doc.variables.get_by_id(variable)?; let local = self.var_ids.get(variable)?; @@ -275,10 +280,12 @@ impl<'d> Exporter<'d> { } } +/// Wrap a literal, alias or expression in the Kiwi variable-data record. fn variable_data(kind: &'static str, resolved: &'static str, value: (&'static str, Kv<'static>)) -> Kv<'static> { o(vec![("dataType", e(kind)), ("resolvedDataType", e(resolved)), ("value", o(vec![value]))]) } +/// Encode a finite, typed literal without variable references. fn literal_data(value: &VariableValue) -> Option> { let (kind, field) = match value { VariableValue::Boolean(v) => ("BOOLEAN", ("boolValue", b(*v))), @@ -290,6 +297,7 @@ fn literal_data(value: &VariableValue) -> Option> { Some(variable_data(kind, kind, field)) } +/// Encode an operator and its ordered arguments with their result type. fn expression_data(function: &'static str, resolved: &'static str, args: Vec>) -> Kv<'static> { variable_data("EXPRESSION", resolved, ("expressionValue", o(vec![("expressionFunction", e(function)), ("expressionArguments", arr(args))]))) } From f62e58860ba846384c389ec77ece2e3585f2b9be Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 00:05:25 -0500 Subject: [PATCH 018/268] M12: Mind maps: an icon that reads as one idea branching into three (#2226) Redraw Icon::MindMap as an outlined root node on the left with three curved branches to three outlined child nodes on the right, the middle one level with the root. Same stroke and corner style as its outlined neighbours, centred in the 16-unit box, instead of the filled blob and fork that read as a tuning fork. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/icons/draw.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/icons/draw.rs b/crates/ui-egui/src/icons/draw.rs index 4a3c7a18f..f271b0d4a 100644 --- a/crates/ui-egui/src/icons/draw.rs +++ b/crates/ui-egui/src/icons/draw.rs @@ -1055,11 +1055,24 @@ fn draw(p: &P, icon: Icon) { p.poly(&[(5.0, 8.3), (7.2, 10.5), (11.0, 6.0)], false); } MindMap => { - p.fill_rect(1.0, 6.5, 6.0, 9.5, 1.0); - p.path(&[(6.0, 8.0), (7.5, 8.0), (8.3, 7.2), (8.7, 5.0), (9.5, 4.0), (11.0, 4.0)], false); - p.path(&[(6.0, 8.0), (7.5, 8.0), (8.3, 8.8), (8.7, 11.0), (9.5, 12.0), (11.0, 12.0)], false); - p.line(11.0, 4.0, 15.0, 4.0); - p.line(11.0, 12.0, 15.0, 12.0); + // One outlined idea on the left branching into three outlined ideas on the right, + // the middle one level with the root. + p.rect(1.5, 6.0, 5.5, 10.0, 1.0); + p.line(5.5, 8.0, 10.5, 8.0); + for (y, ty) in [(1.5, 3.0), (11.5, 13.0)] { + p.rect(10.5, y, 14.5, y + 3.0, 1.0); + let curve: Vec<(f32, f32)> = (0..=10) + .map(|i| { + let t = i as f32 / 10.0; + let u = 1.0 - t; + let x = u * u * u * 5.5 + 3.0 * u * u * t * 8.0 + 3.0 * u * t * t * 8.0 + t * t * t * 10.5; + let y = u * u * u * 8.0 + 3.0 * u * u * t * 8.0 + 3.0 * u * t * t * ty + t * t * t * ty; + (x, y) + }) + .collect(); + p.path(&curve, false); + } + p.rect(10.5, 6.5, 14.5, 9.5, 1.0); } Timer => { p.circle(8.0, 9.0, 5.5); From 9beff066520756432f39d2809177517a95572e15 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:11:55 +0800 Subject: [PATCH 019/268] M13: a truncated audit never passes the CI gate --- crates/engine/src/design/mod.rs | 11 ++++++++++- crates/engine/src/design/tests.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index ec3fb1611..3dc4d261c 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -44,7 +44,7 @@ pub fn specs() -> Vec { spec!( "design.assert", "Assert design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists or the score is below minScore; read-only, for CI", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit was truncated by the node cap (what it did not reach is unchecked: narrow the scope or filter the rules); read-only, for CI", false, assert_cmd ), @@ -126,6 +126,15 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { .map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect()) .unwrap_or_default(); let score = report["score"].as_f64().unwrap_or(0.0); + // A truncated audit checked only the first nodes of the scope: what it did not reach is + // unchecked, so it can never prove a design passes (a white-on-white label past the cap + // would sail through as score 100). + if report["truncated"].as_bool() == Some(true) { + let nodes = report["nodes"].as_u64().unwrap_or(0); + return Err(EngineError::Other(format!( + "design review failed: the audit stopped at the node cap after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or filter the rules, then assert again" + ))); + } if !failing.is_empty() || score < min_score { let mut by_rule: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); for f in &failing { diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 7984e305d..075210ce5 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -726,6 +726,34 @@ fn fix_dry_run_and_no_op_do_not_dirty_the_document() { assert!(!s.ds().unwrap().is_dirty(), "a no-op fix leaves the file saved"); } +#[test] +fn assert_fails_when_the_audit_is_truncated() { + let mut s = Session::new(); + // The audit stops at the 50,000-node cap, so the badge at the end is never reached: white + // text in a white frame, a contrast failure the truncated report cannot see. + let page = s.page().unwrap(); + { + let doc = s.doc_mut().unwrap(); + for i in 0..50_100 { + doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 1.0, 1.0).unwrap(); + } + } + let holder = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Badge holder", "x": 0.0, "y": 0.0, "width": 40.0, "height": 24.0, "props": {"fill": "#FFFFFF"}}), + )); + let badge = id(&ex(&mut s, "text.create", json!({"text": "0", "name": "Badge", "parent": holder, "props": {"fill": "#FFFFFF"}}))); + // Auditing the badge alone reports it: the cap is what hides it, not innocence. + let r = ex(&mut s, "design.audit", json!({"ids": [badge], "rules": ["color.contrast"]})); + assert!(has(&r, "color.contrast"), "{r}"); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert_eq!(r["truncated"], true, "{r}"); + // The gate must not turn a truncated audit into a pass at score 100. + let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).unwrap_err().to_string(); + assert!(err.contains("node cap"), "{err}"); +} + #[test] fn hardcoded_values_that_match_variables_are_reported() { let mut s = Session::new(); From a96edd9f7f5acf027705b90d00261e565efa0b09 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 19:15:26 -0500 Subject: [PATCH 020/268] M3, #2033: a page switch no longer keeps the drag base render (without the dragged layers) as the page image Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/canvas.rs | 28 +++++++++++++++++++++- crates/ui-egui/src/canvas/render_worker.rs | 4 +++- crates/ui-egui/src/canvas_drag_tests.rs | 18 ++++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d13ea3525..5cd12d59c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -56,6 +56,8 @@ pub struct CanvasState { tex_of: Option<(u64, NodeId)>, /// The texture is a coarse preview (see [`crate::render_worker`]). pub tex_coarse: bool, + /// The texture leaves out layers ([`crate::render_worker::Done::skipped`]): it is not kept as the page's image. + tex_skipped: bool, /// The request the texture answers ([`crate::render_worker::Done::seq`]). tex_seq: u64, /// Refined images of the files and pages shown before, newest first: switching back to one @@ -105,6 +107,26 @@ impl CanvasState { self.submitted.as_ref().map(|k| k.skip.as_slice()) } + /// The file and page the texture shows. + pub(crate) fn tex_of(&self) -> Option<(u64, NodeId)> { + self.tex_of + } + + /// A page or tab switch to `shown`, as the canvas does on a frame. + pub(crate) fn switch_to(&mut self, shown: (u64, NodeId)) { + self.switch_texture(Some(shown), |_| true); + } + + /// Whether an image of `of` is kept for a switch back to it. + pub(crate) fn keeps(&self, of: (u64, NodeId)) -> bool { + self.kept.iter().any(|k| k.of == of) + } + + /// Whether the canvas holds a texture. + pub(crate) fn has_texture(&self) -> bool { + self.texture.is_some() + } + /// Where the drag sprite shows on screen (at one pixel per point), if there is one. pub(crate) fn sprite_rect(&self, app: &FigApp) -> Option { drag_sprite::screen_rect(app, 1.0) @@ -119,6 +141,7 @@ impl Default for CanvasState { tex_view: None, tex_of: None, tex_coarse: false, + tex_skipped: false, tex_seq: 0, kept: Vec::new(), submitted: None, @@ -164,10 +187,12 @@ impl CanvasState { if shown.is_some() && self.tex_of != shown { let back = self.kept.iter().position(|k| Some(k.of) == shown).map(|i| self.kept.remove(i)); let (texture, view, of) = (self.texture.take(), self.tex_view.take(), self.tex_of.take()); - if let (Some(texture), Some(view), Some(of), false) = (texture, view, of, self.tex_coarse) { + // An image without the dragged layers isn't the page's complete one: not kept. + if let (Some(texture), Some(view), Some(of), false, false) = (texture, view, of, self.tex_coarse, self.tex_skipped) { self.kept.insert(0, Kept { texture, view, of, seq: self.tex_seq }); } self.tex_coarse = false; + self.tex_skipped = false; if let Some(k) = back { (self.texture, self.tex_view, self.tex_of, self.tex_seq) = (Some(k.texture), Some(k.view), Some(k.of), k.seq); } @@ -358,6 +383,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_view = Some(done.view); app.canvas.tex_of = Some((done.uid, done.page)); app.canvas.tex_coarse = done.coarse; + app.canvas.tex_skipped = done.skipped; app.canvas.tex_seq = done.seq; drag_sprite::arrived(&mut app.canvas, done_at, done.coarse); } diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 44a478807..81cb44fde 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -86,6 +86,8 @@ pub struct Done { pub page: NodeId, /// A coarse preview, refined by a later image unless a newer request replaced it. pub coarse: bool, + /// The image leaves out the layers of [`Job::skip`] (a drag's base render): not the page's complete image. + pub skipped: bool, /// [`Job::at`]. pub at: Instant, /// The request it answers, numbered by the worker in order (0 outside a worker). @@ -142,7 +144,7 @@ fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool) if job.proof { mark_outside_srgb(&mut image, pix, job.doc.color_profile); } - Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 } + Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, skipped: !job.skip.is_empty(), at: job.at, seq: 0 } } /// `view` with [`PREVIEW_FACTOR`] times fewer pixels each way, showing at least the same area. diff --git a/crates/ui-egui/src/canvas_drag_tests.rs b/crates/ui-egui/src/canvas_drag_tests.rs index 65292869f..5c8f4c4ad 100644 --- a/crates/ui-egui/src/canvas_drag_tests.rs +++ b/crates/ui-egui/src/canvas_drag_tests.rs @@ -302,3 +302,21 @@ fn outline_views_keep_the_old_path() { u.button(p + vec2(30.0, 10.0), false); } } + +#[test] +fn a_page_switch_does_not_keep_the_drags_base_render_as_the_pages_image() { + let (mut u, f, p) = frame_with_child(false); + u.button(p, true); + drag_frames(&mut u, p, 4); + settle(&mut u); + assert_eq!(u.app.canvas.submitted_skip(), Some(&[f][..]), "the render shown leaves the dragged layer out"); + let ds = u.app.session.ds().unwrap(); + let (here, other) = ((ds.uid, ds.page), (ds.uid, figcraft_doc::NodeId(ds.page.0 + 1))); + assert_eq!(u.app.canvas.tex_of(), Some(here)); + // Switching away while it shows must not keep it: coming back would show the page without the dragged layer. + u.app.canvas.switch_to(other); + assert!(!u.app.canvas.keeps(here), "an image without the dragged layers is not kept"); + u.app.canvas.switch_to(here); + assert!(!u.app.canvas.has_texture(), "so coming back shows no image until the render lands"); + u.button(p + vec2(30.0, 10.0), false); +} From b60cdfcba66d72ca1dd31f16a297980d705420b1 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:31:35 +0800 Subject: [PATCH 021/268] M13: the audit's node limit is a parameter --- crates/engine/src/design/audit.rs | 30 +++++++++++++++++----- crates/engine/src/design/fix.rs | 7 +++--- crates/engine/src/design/mod.rs | 28 +++++++++++++++------ crates/engine/src/design/tests.rs | 41 ++++++++++++++++++++++++++++++- 4 files changed, 89 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index 0a39840e5..42a53767a 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -17,8 +17,11 @@ use crate::cmd::lists::paint_binding_key; use super::rules::{Severity, rule}; -/// Most layers one audit looks at; past it the report says `truncated`. -const MAX_NODES: usize = 50_000; +/// Most layers one audit looks at; past it the report says `truncated`. A call may raise it with +/// `limit` (a CI gate over a huge file), but never past [`MAX_LIMIT`]. +pub(crate) const MAX_NODES: usize = 50_000; +/// The most nodes one audit may be asked to look at, so a typo cannot stall a machine for minutes. +pub(crate) const MAX_LIMIT: usize = 1_000_000; /// Most text layers one audit lays out for the overflow check (text layout is the expensive part). const MAX_TEXT_MEASURED: usize = 2_000; /// Most auto layout frames one audit measures for clipped children (bounds are per-subtree). @@ -186,6 +189,8 @@ pub(crate) struct Report { pub(crate) findings: Vec, pub(crate) nodes: usize, pub(crate) truncated: bool, + /// The node cap this report was collected under (`limit`). + pub(crate) limit: usize, } /// A colour token's default-mode value, for the hardcoded-value check. @@ -265,11 +270,21 @@ struct Ctx<'a> { /// Distinct accent colours, with the first layer that paints each (for `color.accents`). accents: BTreeMap<[u8; 4], String>, truncated: bool, + /// The node cap this run stops at. + max_nodes: usize, } /// Walk `roots` and collect every finding. `design.audit` reports them; `design.fix` acts on the /// ones marked fixable. -pub(crate) fn collect(doc: &Document, roots: &[NodeId], anchor: Option, anchor_path: &str, scope: &str, settings: &Settings) -> Report { +pub(crate) fn collect( + doc: &Document, + roots: &[NodeId], + anchor: Option, + anchor_path: &str, + scope: &str, + settings: &Settings, + max_nodes: usize, +) -> Report { let mut ctx = Ctx { doc, findings: Vec::new(), @@ -284,12 +299,13 @@ pub(crate) fn collect(doc: &Document, roots: &[NodeId], anchor: Option, settings: settings.clone(), accents: BTreeMap::new(), truncated: false, + max_nodes, }; for root in roots { ctx.walk(*root); } ctx.scope_rules(anchor, anchor_path, scope); - Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated } + Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated, limit: max_nodes } } /// Audit `roots` (pages, frames or layers), labelled `scope` in the report. Aggregate findings @@ -304,9 +320,10 @@ pub(crate) fn run( filter: Option<&BTreeSet>, preset: Option, modes: BTreeMap, + max_nodes: usize, ) -> Value { let settings = Settings::new(doc, preset).in_modes(doc, modes); - let report = collect(doc, roots, anchor, anchor_path, scope, &settings); + let report = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes); let shown: Vec<&Finding> = report .findings .iter() @@ -330,6 +347,7 @@ pub(crate) fn run( o.insert("counts".into(), json!({"high": counts[2], "medium": counts[1], "low": counts[0]})); o.insert("byRule".into(), json!(by_rule)); o.insert("nodes".into(), json!(report.nodes)); + o.insert("limit".into(), json!(report.limit)); o.insert("findings".into(), json!(findings)); o.insert("truncated".into(), json!(report.truncated)); } @@ -340,7 +358,7 @@ impl Ctx<'_> { fn walk(&mut self, root: NodeId) { let mut stack = vec![(root, String::new())]; while let Some((id, parent)) = stack.pop() { - if self.visited >= MAX_NODES { + if self.visited >= self.max_nodes { self.truncated = true; return; } diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs index ca110cca7..891e23bd4 100644 --- a/crates/engine/src/design/fix.rs +++ b/crates/engine/src/design/fix.rs @@ -14,7 +14,7 @@ use serde_json::{Value, json}; use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color}; /// Fix what `roots` made fixable among `filter`'s rules. With `exact_ids`, only findings on those -/// layers are repaired, not findings on their descendants. +/// layers are repaired, not findings on their descendants. The walk stops at `max_nodes` nodes. pub(crate) fn run( doc: &mut Document, roots: &[NodeId], @@ -24,10 +24,11 @@ pub(crate) fn run( preset: Option, filter: Option<&BTreeSet>, exact_ids: Option<&[NodeId]>, + max_nodes: usize, dry_run: bool, ) -> Value { let settings = Settings::new(doc, preset); - let before = collect(doc, roots, anchor, anchor_path, scope, &settings); + let before = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes); let targets: Vec<(NodeId, &'static str)> = before .findings .iter() @@ -55,7 +56,7 @@ pub(crate) fn run( } } } - let after = collect(doc, roots, anchor, anchor_path, scope, &settings); + let after = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes); json!({ "scope": scope, "dryRun": dry_run, diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 3dc4d261c..03a8bfe59 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -30,21 +30,21 @@ pub fn specs() -> Vec { spec!( "design.audit", "Check design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them), limit?: 1000-1000000 (nodes before the report says truncated; default 50000)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, limit, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", false, audit_cmd ), spec!( "design.fix", "Fix design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), limit?: 1000-1000000 (nodes the walk looks at; default 50000), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone", true, fix_cmd ), spec!( "design.assert", "Assert design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit was truncated by the node cap (what it did not reach is unchecked: narrow the scope or filter the rules); read-only, for CI", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit was truncated at the node limit it ran with (what it did not reach is unchecked: narrow the scope, filter the rules or raise `limit`); read-only, for CI", false, assert_cmd ), @@ -83,7 +83,8 @@ fn audit_cmd(s: &mut Session, p: &Value) -> Result { let filter = filter_arg("design.audit", p)?; let preset = preset_arg("design.audit", p)?; let modes = modes_arg("design.audit", p, s.doc()?)?; - Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes)) + let limit = limit_arg("design.audit", p)?; + Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes, limit)) } fn fix_cmd(s: &mut Session, p: &Value) -> Result { @@ -92,11 +93,12 @@ fn fix_cmd(s: &mut Session, p: &Value) -> Result { let preset = preset_arg("design.fix", p)?; let exact = params::boolean(p, "exact").unwrap_or(false); let exact_ids = if exact { ids_arg("design.fix", p)? } else { None }; + let limit = limit_arg("design.fix", p)?; let dry = params::boolean(p, "dryRun").unwrap_or(false); // A dry run or a fix that changes nothing must not mark the file unsaved or add an undo step: // work on a copy and put it back only when it differs. let mut doc = s.doc()?.clone(); - let result = fix::run(&mut doc, &roots, anchor, &path, &label, preset, filter.as_ref(), exact_ids.as_deref(), dry); + let result = fix::run(&mut doc, &roots, anchor, &path, &label, preset, filter.as_ref(), exact_ids.as_deref(), limit, dry); if !dry && s.doc()? != &doc { *s.doc_mut()? = doc; } @@ -120,7 +122,8 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { }; // The score covers the whole review (as the window shows it); only findings at or above // `failOn` fail the gate. - let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes); + let limit = limit_arg("design.assert", p)?; + let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes, limit); let failing: Vec<&Value> = report["findings"] .as_array() .map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect()) @@ -132,7 +135,7 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { if report["truncated"].as_bool() == Some(true) { let nodes = report["nodes"].as_u64().unwrap_or(0); return Err(EngineError::Other(format!( - "design review failed: the audit stopped at the node cap after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or filter the rules, then assert again" + "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids), filter the rules, or raise `limit`, then assert again" ))); } if !failing.is_empty() || score < min_score { @@ -160,6 +163,17 @@ fn severity_named(cmd: &str, p: &Value, key: &str, default: Severity) -> Result< } } +/// The `limit` parameter: how many nodes one audit walk may look at before the report says +/// `truncated`. Default 50,000; a CI gate over a huge file may raise it, never past the hard cap. +fn limit_arg(cmd: &str, p: &Value) -> Result { + let Some(v) = params::get(p, "limit") else { return Ok(audit::MAX_NODES) }; + let Some(n) = params::f64_of(v) else { return Err(bad(cmd, "`limit` must be a whole number of nodes between 1,000 and 1,000,000")) }; + if !n.is_finite() || n.fract() != 0.0 || !(1_000.0..=(audit::MAX_LIMIT as f64)).contains(&n) { + return Err(bad(cmd, "`limit` must be a whole number of nodes between 1,000 and 1,000,000")); + } + Ok(n as usize) +} + fn preset_arg(cmd: &str, p: &Value) -> Result> { match params::string(p, "preset").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { None => Ok(None), diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 075210ce5..61145f215 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -749,9 +749,48 @@ fn assert_fails_when_the_audit_is_truncated() { assert!(has(&r, "color.contrast"), "{r}"); let r = ex(&mut s, "design.audit", json!({"scope": "page"})); assert_eq!(r["truncated"], true, "{r}"); + assert_eq!(r["limit"], 50_000, "{r}"); // The gate must not turn a truncated audit into a pass at score 100. let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).unwrap_err().to_string(); - assert!(err.contains("node cap"), "{err}"); + assert!(err.contains("stopped at the 50000-node limit"), "{err}"); +} + +#[test] +fn a_raised_limit_lets_a_huge_page_finish_and_assert_for_real() { + let mut s = Session::new(); + let page = s.page().unwrap(); + { + let doc = s.doc_mut().unwrap(); + for i in 0..50_100 { + doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 1.0, 1.0).unwrap(); + } + } + let holder = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Badge holder", "x": 0.0, "y": 0.0, "width": 40.0, "height": 24.0, "props": {"fill": "#FFFFFF"}}), + )); + ex(&mut s, "text.create", json!({"text": "0", "name": "Badge", "parent": holder, "props": {"fill": "#FFFFFF"}})); + // With the limit raised, the same page finishes: the audit is not truncated and reports the + // badge's real contrast failure, so the gate fails on the finding, not on the cap. + let r = ex(&mut s, "design.audit", json!({"scope": "page", "limit": 60_000, "rules": ["color.contrast"]})); + assert_eq!(r["truncated"], false, "{r}"); + assert_eq!(r["limit"], 60_000, "{r}"); + assert!(has(&r, "color.contrast"), "{r}"); + let err = s.execute("design.assert", &json!({"scope": "page", "limit": 60_000, "failOn": "high"})).unwrap_err().to_string(); + assert!(err.contains("color.contrast"), "{err}"); +} + +#[test] +fn a_bad_limit_is_an_error() { + let mut s = Session::new(); + for limit in [json!(999), json!(1_000_001), json!(5.5), json!("many")] { + let err = s.execute("design.audit", &json!({"scope": "page", "limit": limit})).unwrap_err().to_string(); + assert!(err.contains("`limit` must be a whole number of nodes between 1,000 and 1,000,000"), "{err}"); + } + // The bounds themselves are accepted. + let r = ex(&mut s, "design.audit", json!({"scope": "page", "limit": 1_000})); + assert_eq!(r["limit"], 1_000, "{r}"); } #[test] From 569471dd70bd56d27708a1ce31ef99837579c397 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:43:23 +0800 Subject: [PATCH 022/268] M13: the review says what it did not check --- crates/engine/src/design/audit.rs | 55 +++++++++++++++---- crates/engine/src/design/fix.rs | 15 ++++++ crates/engine/src/design/mod.rs | 24 ++++++++- crates/engine/src/design/tests.rs | 88 +++++++++++++++++++++++++++++++ 4 files changed, 170 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index 42a53767a..ff7e1fbae 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -191,6 +191,11 @@ pub(crate) struct Report { pub(crate) truncated: bool, /// The node cap this report was collected under (`limit`). pub(crate) limit: usize, + /// How many text layers the walk saw past the overflow-measure cap. They were counted but not + /// measured, so an assertion on `layout.text-overflow` cannot prove a pass. + pub(crate) text_unmeasured: usize, + /// How many clip-holding frames the walk saw past the clipping-measure cap, likewise. + pub(crate) frames_unmeasured: usize, } /// A colour token's default-mode value, for the hardcoded-value check. @@ -272,6 +277,10 @@ struct Ctx<'a> { truncated: bool, /// The node cap this run stops at. max_nodes: usize, + /// Text layers seen past the overflow-measure cap. + text_unmeasured: usize, + /// Clip-holding frames seen past the clipping-measure cap. + frames_unmeasured: usize, } /// Walk `roots` and collect every finding. `design.audit` reports them; `design.fix` acts on the @@ -300,12 +309,21 @@ pub(crate) fn collect( accents: BTreeMap::new(), truncated: false, max_nodes, + text_unmeasured: 0, + frames_unmeasured: 0, }; for root in roots { ctx.walk(*root); } ctx.scope_rules(anchor, anchor_path, scope); - Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated, limit: max_nodes } + Report { + findings: ctx.findings, + nodes: ctx.visited, + truncated: ctx.truncated, + limit: max_nodes, + text_unmeasured: ctx.text_unmeasured, + frames_unmeasured: ctx.frames_unmeasured, + } } /// Audit `roots` (pages, frames or layers), labelled `scope` in the report. Aggregate findings @@ -350,6 +368,13 @@ pub(crate) fn run( o.insert("limit".into(), json!(report.limit)); o.insert("findings".into(), json!(findings)); o.insert("truncated".into(), json!(report.truncated)); + // Checks the walk capped before finishing: what they did not measure is unchecked. + if report.text_unmeasured > 0 { + o.insert("textUnmeasured".into(), json!(report.text_unmeasured)); + } + if report.frames_unmeasured > 0 { + o.insert("framesUnmeasured".into(), json!(report.frames_unmeasured)); + } } out } @@ -358,14 +383,16 @@ impl Ctx<'_> { fn walk(&mut self, root: NodeId) { let mut stack = vec![(root, String::new())]; while let Some((id, parent)) = stack.pop() { - if self.visited >= self.max_nodes { - self.truncated = true; - return; - } let Some(n) = self.doc.node(id) else { continue }; if !n.visible || n.locked || n.opacity <= 0.001 { continue; } + // Past the limit what follows is unchecked: say so once a further auditable node + // exists, not for a hidden or missing node the walk would skip anyway. + if self.visited >= self.max_nodes { + self.truncated = true; + return; + } self.visited += 1; let name = label(n); let path = if parent.is_empty() { name } else { format!("{parent} / {name}") }; @@ -431,7 +458,12 @@ impl Ctx<'_> { /// A fixed-size auto layout frame that clips children which overflow it: the rows exist but /// are invisible — the usual headless surprise. Hug frames grow, so they cannot clip. fn check_clipping(&mut self, n: &Node, path: &str) { - if self.measured_frames >= MAX_FRAMES_MEASURED || !n.clip || n.children.is_empty() || n.layout.is_none() { + if !n.clip || n.children.is_empty() || n.layout.is_none() { + return; + } + if self.measured_frames >= MAX_FRAMES_MEASURED { + // The frame was seen but not measured: an assertion on this rule cannot prove a pass. + self.frames_unmeasured += 1; return; } // An instance mirrors its main; the main is audited where it lives. @@ -769,11 +801,12 @@ impl Ctx<'_> { // A fixed-width text box whose stored height is shorter than the laid-out text clips or // overlaps what follows it. Truncating boxes and auto-width boxes are intentional. - if !chars.is_empty() - && n.width > 0.0 - && self.measured < MAX_TEXT_MEASURED - && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) - { + if !chars.is_empty() && n.width > 0.0 && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) { + if self.measured >= MAX_TEXT_MEASURED { + // The box was seen but not laid out: an assertion on this rule cannot prove a pass. + self.text_unmeasured += 1; + return; + } self.measured += 1; let needed = figcraft_text::layout_cached(t, Some(n.width), None).height; if needed.is_finite() && needed > n.height + 1.0 { diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs index 891e23bd4..7e890cdb6 100644 --- a/crates/engine/src/design/fix.rs +++ b/crates/engine/src/design/fix.rs @@ -29,6 +29,20 @@ pub(crate) fn run( ) -> Value { let settings = Settings::new(doc, preset); let before = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes); + // A truncated walk would repair only the visited prefix and stay silent about the rest: the + // caller would leave with a "fixed" file that never was whole. Say so instead of guessing. + if before.truncated { + return json!({ + "scope": scope, + "dryRun": dry_run, + "changed": 0, + "skipped": 0, + "truncated": true, + "byRule": {}, + "before": tally(&before, &settings), + "after": tally(&before, &settings), + }); + } let targets: Vec<(NodeId, &'static str)> = before .findings .iter() @@ -62,6 +76,7 @@ pub(crate) fn run( "dryRun": dry_run, "changed": changed, "skipped": skipped, + "truncated": false, "byRule": by_rule, "before": tally(&before, &settings), "after": tally(&after, &settings), diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 03a8bfe59..6ce809c5f 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -135,7 +135,21 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { if report["truncated"].as_bool() == Some(true) { let nodes = report["nodes"].as_u64().unwrap_or(0); return Err(EngineError::Other(format!( - "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids), filter the rules, or raise `limit`, then assert again" + "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or raise `limit`, then assert again" + ))); + } + // The overflow and clipping checks cap how much they measure per run, independently of + // `limit`: boxes or frames past the cap were seen but not measured, so a gate that includes + // those rules cannot prove a pass on a scope that big. + let unchecked: Vec = [("textUnmeasured", "layout.text-overflow"), ("framesUnmeasured", "layout.clipped")] + .into_iter() + .filter(|(key, rule)| report[*key].as_u64().unwrap_or(0) > 0 && filter.as_ref().is_none_or(|set| set.contains(*rule))) + .map(|(_, rule)| rule.to_string()) + .collect(); + if !unchecked.is_empty() { + return Err(EngineError::Other(format!( + "design review failed: the audit did not measure all of {} on this scope (past the per-run measure cap), so what it skipped is unchecked; audit a smaller scope, then assert again", + unchecked.join(", ") ))); } if !failing.is_empty() || score < min_score { @@ -314,7 +328,15 @@ fn ids_arg(cmd: &str, p: &Value) -> Result>> { fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, Option, String)> { let doc = s.doc()?; // `ids` names the layers directly (the review window fixes only the findings the user kept). + // An empty or unknown id checks nothing, which a CI gate must not mistake for a pass. if let Some(ids) = ids_arg(cmd, p)? { + if ids.is_empty() { + return Err(bad(cmd, "`ids` is empty: name at least one layer to audit, or drop `ids` for the selection, page or document")); + } + let missing: Vec = ids.iter().filter(|id| doc.node(**id).is_none()).map(|id| id.to_string()).collect(); + if !missing.is_empty() { + return Err(bad(cmd, format!("`ids` names layers that do not exist: {}", missing.join(", ")))); + } let roots = top_most(doc, &ids); let anchor = roots.first().copied(); let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 61145f215..099eba7e7 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -793,6 +793,94 @@ fn a_bad_limit_is_an_error() { assert_eq!(r["limit"], 1_000, "{r}"); } +#[test] +fn assert_refuses_a_scope_that_checks_nothing() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))); + // An empty id list and a missing id check nothing: a CI gate must not read that as a pass. + for ids in [json!([]), json!([999_999])] { + for cmd in ["design.audit", "design.assert", "design.fix"] { + let err = s.execute(cmd, &json!({"ids": ids})).unwrap_err().to_string(); + assert!(err.contains("`ids`"), "{cmd}: {err}"); + } + } + // The real layer still audits and gates as before. + let r = ex(&mut s, "design.audit", json!({"ids": [f]})); + assert_eq!(r["nodes"], 1, "{r}"); + assert!(s.execute("design.assert", &json!({"ids": [f]})).is_ok()); +} + +#[test] +fn a_limit_reached_by_hidden_nodes_is_not_truncation() { + let mut s = Session::new(); + let page = s.page().unwrap(); + { + let doc = s.doc_mut().unwrap(); + for i in 0..10 { + let id = doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 1.0, 1.0).unwrap(); + doc.get_mut(id).unwrap().visible = false; + } + } + let badge = id(&ex(&mut s, "text.create", json!({"text": "0", "x": 0.0, "y": 0.0, "props": {"fill": "#FFFFFF"}}))); + // Exactly limit visible nodes were audited; the stacked hidden ones are skips, not unchecked + // work, so the walk is whole and the badge's finding stands on its own. + let r = ex(&mut s, "design.audit", json!({"scope": "page", "limit": 1_001, "rules": ["color.contrast"]})); + assert_eq!(r["truncated"], false, "{r}"); + assert!(has(&r, "color.contrast"), "{r}"); +} + +#[test] +fn fix_refuses_to_repair_a_truncated_scope() { + let mut s = Session::new(); + let page = s.page().unwrap(); + let off_grid = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Off grid", "x": 0.0, "y": 0.0, "width": 100.0, "height": 40.0, + "props": {"layout": "vertical", "gap": 13}}), + )); + { + let doc = s.doc_mut().unwrap(); + for i in 0..1_002 { + doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 1.0, 1.0).unwrap(); + } + } + // The off-grid frame sorts behind the fillers, so the capped walk never reaches it: the fix + // must say the scope was incomplete rather than repair a prefix and claim success. + let r = ex(&mut s, "design.fix", json!({"scope": "page", "limit": 1_000, "rules": ["spacing.off-grid"]})); + assert_eq!(r["truncated"], true, "{r}"); + assert_eq!(r["changed"], 0, "{r}"); + let gap = s.doc().unwrap().node(off_grid).unwrap().layout.as_ref().unwrap().gap; + assert_eq!(gap, 13.0, "nothing was repaired under truncation"); + // With the walk whole the same request repairs. + let r = ex(&mut s, "design.fix", json!({"scope": "page", "limit": 2_000, "rules": ["spacing.off-grid"]})); + assert_eq!(r["truncated"], false, "{r}"); + assert_eq!(r["changed"], 1, "{r}"); +} + +#[test] +fn assert_refuses_a_scope_whose_measured_checks_were_capped() { + let mut s = Session::new(); + // 2,001 fixed-width overflowing boxes: the overflow check measures the first 2,000, so a + // gate on that rule cannot prove a pass over this scope. + for i in 0..2_001 { + ex( + &mut s, + "text.create", + json!({"text": "Overflowing line of interface copy", "name": &format!("Box {i}"), "x": 0.0, "y": 0.0, + "width": 60, "props": {"textAutoResize": "none"}}), + ); + } + let only = json!(["layout.text-overflow"]); + let audit = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(audit["textUnmeasured"].as_u64().unwrap_or(0) >= 1, "{audit}"); + let err = s.execute("design.assert", &json!({"scope": "page", "rules": &only})).unwrap_err().to_string(); + assert!(err.contains("did not measure all of layout.text-overflow"), "{err}"); + // A gate that does not ask for the capped rule is unaffected. + let other = json!(["color.gradient"]); + assert!(s.execute("design.assert", &json!({"scope": "page", "rules": &other})).is_ok()); +} + #[test] fn hardcoded_values_that_match_variables_are_reported() { let mut s = Session::new(); From 79fec6d855d9abccd46aa491ce39058a8a26c6d6 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:03:33 +0800 Subject: [PATCH 023/268] M13: drop an unused variable from the hidden-nodes test --- crates/engine/src/design/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 099eba7e7..f6dd06600 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -821,7 +821,7 @@ fn a_limit_reached_by_hidden_nodes_is_not_truncation() { doc.get_mut(id).unwrap().visible = false; } } - let badge = id(&ex(&mut s, "text.create", json!({"text": "0", "x": 0.0, "y": 0.0, "props": {"fill": "#FFFFFF"}}))); + ex(&mut s, "text.create", json!({"text": "0", "x": 0.0, "y": 0.0, "props": {"fill": "#FFFFFF"}})); // Exactly limit visible nodes were audited; the stacked hidden ones are skips, not unchecked // work, so the walk is whole and the badge's finding stands on its own. let r = ex(&mut s, "design.audit", json!({"scope": "page", "limit": 1_001, "rules": ["color.contrast"]})); From bb9a1906d974a9dad4ec31e5570d26f90398a44c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 22:45:46 -0500 Subject: [PATCH 024/268] Docs: drop the duplicate Scale tool row left by the union merge, keeping main's Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- docs/ui-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 574b333db..bea186f92 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -69,7 +69,6 @@ interaction feel not yet compared. | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way (`canvas/drag_sprite.rs`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | | | Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | From 26b7683d51c0500b61b279e469ea79cbbd8edcd9 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:53:07 +0800 Subject: [PATCH 025/268] M13: fix the review-integrity follow-ups --- crates/collab/src/change.rs | 9 +++++++++ crates/collab/src/diff_tests.rs | 18 ++++++++++++++++++ crates/collab/src/docprops.rs | 15 +++++++++++++++ crates/collab/src/replica.rs | 2 +- crates/engine/src/design/audit.rs | 20 ++++++++++++++------ crates/engine/src/design/mod.rs | 5 +++++ crates/engine/src/design/tests.rs | 28 ++++++++++++++++++++++++++++ 7 files changed, 90 insertions(+), 7 deletions(-) diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index e7ecf85f4..4258565d0 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -326,6 +326,15 @@ impl Change { matches!(self, Change::Put { entry: Entry::Image(_), .. } | Change::Remove { entry: Entry::Image(_) }) } + /// Whether this edit carries review settings past the limits `design.configure` keeps: a + /// snapshot saved by a looser build may hold one, and opens without it (see + /// [`crate::docprops`], which refuses such a change inside an ordinary batch). + pub(crate) fn is_oversized_design_review(&self) -> bool { + let Change::SetDoc { prop: DocProp::DesignReview, value } = self else { return false }; + let Ok(config) = value.read::("design review") else { return false }; + config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS + } + /// Whether this only changes comment threads (a thread, their order, or all of them): what a /// comment link may send. pub fn is_comment(&self) -> bool { diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 9c252c3e9..33c96c4f8 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -60,6 +60,24 @@ fn design_review_settings_round_trip_and_reach_a_snapshot() { assert!(snapshot.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "a snapshot carries the review settings"); } +#[test] +fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_applies() { + let (a, _, _, _) = setup(); + // An edit peer trying to hand the file tens of thousands of radii is refused at apply. + let mut b = a.document().clone(); + b.design_review.radii = (0..40).map(|i| i as f64).collect(); + let mut r = a.clone(); + let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; + let err = r.apply(&[change.clone()], Mode::Strict).unwrap_err().to_string(); + assert!(err.contains("pass the 32 limit `design.configure` keeps"), "{err}"); + // A snapshot holding settings over the limits (an old file's) still opens: like an image + // entry that fails today's checks, the oversized entry is left out of what it loads. + let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert_eq!(left_out, 1, "the oversized settings entry is the one left out"); + assert!(r2.document().design_review.radii.is_empty(), "the file opens without them"); +} + #[test] fn creations_moves_reorders_and_deletions_round_trip() { let (a, page, frame, kids) = setup(); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index 9a1305c62..f66b0688c 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -409,6 +409,21 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Index) -> Result { match change { Change::SetDoc { prop, value } => { + // A peer's review settings stay inside the limits `design.configure` enforces, so an + // edit cannot smuggle in tens of thousands of radii or accents for every corner + // check to scan. An oversized value arrives only in an old snapshot: snapshots keep + // applying as they are. + if *prop == DocProp::DesignReview { + let config: figcraft_doc::DesignReview = value.read("design review")?; + if config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS { + return Err(Error::Invalid(format!( + "design review: {} radii and {} brand colours pass the {} limit `design.configure` keeps", + config.radii.len(), + config.brand.len(), + figcraft_doc::MAX_RADII + ))); + } + } if set_scalar(doc, *prop, value)? { return Ok(*prop == DocProp::Libraries); } diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index 547f0f59b..7e427970b 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -80,7 +80,7 @@ impl Replica { pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize), Error> { let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; let mut changes = changes.to_vec(); - let left_out = r.apply_kept(&mut changes, Change::is_image)?; + let left_out = r.apply_kept(&mut changes, |c| Change::is_image(c) || Change::is_oversized_design_review(c))?; if r.doc.pages.is_empty() { return Err(Error::Invalid("a snapshot needs a page".into())); } diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index ff7e1fbae..25a770c12 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -461,20 +461,23 @@ impl Ctx<'_> { if !n.clip || n.children.is_empty() || n.layout.is_none() { return; } - if self.measured_frames >= MAX_FRAMES_MEASURED { - // The frame was seen but not measured: an assertion on this rule cannot prove a pass. - self.frames_unmeasured += 1; - return; - } // An instance mirrors its main; the main is audited where it lives. if matches!(n.kind, NodeKind::Instance { .. }) { return; } let fixed_h = n.child_layout.sizing_h != Sizing::Hug; let fixed_v = n.child_layout.sizing_v != Sizing::Hug; + // A hug frame cannot clip, and the walk never measures it: not work the cap left behind. if !(fixed_h || fixed_v) { return; } + if self.measured_frames >= MAX_FRAMES_MEASURED { + // The frame was seen but not measured: an assertion on this rule cannot prove a pass. + if self.settings.enabled("layout.clipped") { + self.frames_unmeasured += 1; + } + return; + } let Some(frame) = self.doc.world_bounds(n.id) else { return }; let mut u: Option<(f64, f64, f64, f64)> = None; for child in &n.children { @@ -801,10 +804,15 @@ impl Ctx<'_> { // A fixed-width text box whose stored height is shorter than the laid-out text clips or // overlaps what follows it. Truncating boxes and auto-width boxes are intentional. + let overflow_asked = self.settings.enabled("layout.text-overflow"); if !chars.is_empty() && n.width > 0.0 && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) { if self.measured >= MAX_TEXT_MEASURED { // The box was seen but not laid out: an assertion on this rule cannot prove a pass. - self.text_unmeasured += 1; + // A file that disabled the rule would never have measured it either way, so it + // does not make the run incomplete. + if overflow_asked { + self.text_unmeasured += 1; + } return; } self.measured += 1; diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 6ce809c5f..287ecb2d1 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -345,6 +345,11 @@ fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, O let scope = scope_arg(cmd, p)?; let selection = s.selection(); let page = s.page()?; + // An explicitly empty selection checks nothing either; only the implicit default falls back + // to the page. A CI gate must not read an unchecked scope as a pass. + if scope.as_deref() == Some("selection") && selection.is_empty() { + return Err(bad(cmd, "nothing is selected: name `ids`, pick a scope of page or document, or select the layers to audit")); + } let (roots, label, anchor, path) = match scope.as_deref() { None if selection.is_empty() => (vec![page], "page", Some(page), node_label(doc, page)), None => selection_scope(doc, &selection), diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index f6dd06600..e537b4b13 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -879,6 +879,34 @@ fn assert_refuses_a_scope_whose_measured_checks_were_capped() { // A gate that does not ask for the capped rule is unaffected. let other = json!(["color.gradient"]); assert!(s.execute("design.assert", &json!({"scope": "page", "rules": &other})).is_ok()); + // A file that disabled the capped rule would not have measured it either way: the run is + // whole under its own settings, not incomplete. + ex(&mut s, "design.configure", json!({"disabled": ["layout.text-overflow"]})); + let audit = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(audit["textUnmeasured"].is_null(), "{audit}"); + assert!(s.execute("design.assert", &json!({"scope": "page"})).is_ok(), "a disabled rule leaves nothing unchecked"); +} + +#[test] +fn assert_refuses_an_explicit_empty_selection() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))); + s.set_selection(vec![]); + // With nothing selected, an explicit `selection` scope checks nothing: refused, while the + // implicit default (no scope) still falls back to the page and an explicit empty `ids` + // stays refused too. + for p in [json!({"scope": "selection"}), json!({"scope": "selection", "ids": []}), json!({"ids": []})] { + let err = s.execute("design.assert", &p).unwrap_err().to_string(); + assert!(err.contains("nothing is selected") || err.contains("`ids`"), "{p}: {err}"); + } + // The layer is there: selecting it audits and gates as usual. + s.set_selection(vec![f]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + assert_eq!(r["nodes"], 1, "{r}"); + assert!(s.execute("design.assert", &json!({"scope": "selection"})).is_ok()); + // The implicit page default still works with nothing selected. + s.set_selection(vec![]); + assert!(s.execute("design.audit", &json!({})).is_ok()); } #[test] From edb6a84e9d65c2d5482c856739d863fb682bfb81 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:04:03 +0800 Subject: [PATCH 026/268] M13: borrow the change instead of cloning it in the limits test --- crates/collab/src/diff_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 33c96c4f8..874403685 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -68,7 +68,7 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_applies() { b.design_review.radii = (0..40).map(|i| i as f64).collect(); let mut r = a.clone(); let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; - let err = r.apply(&[change.clone()], Mode::Strict).unwrap_err().to_string(); + let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string(); assert!(err.contains("pass the 32 limit `design.configure` keeps"), "{err}"); // A snapshot holding settings over the limits (an old file's) still opens: like an image // entry that fails today's checks, the oversized entry is left out of what it loads. From e89a3041df0dd916ae5660f787f5b8bcb46e068d Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:01:46 +0800 Subject: [PATCH 027/268] M13: gate the review settings by client_version, clamp them in snapshots --- crates/collab/src/change.rs | 22 +++++---- crates/collab/src/diff_tests.rs | 19 ++++++-- crates/collab/src/docprops.rs | 21 +++++++++ crates/collab/src/message.rs | 13 +++++- crates/collab/src/replica.rs | 5 +- crates/collab/src/server.rs | 70 ++++++++++++++++++++++++++- crates/collab/src/server_tests.rs | 78 ++++++++++++++++++++++++++++++- docs/collab-protocol.md | 5 +- 8 files changed, 212 insertions(+), 21 deletions(-) diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 4258565d0..44767ba8b 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -326,15 +326,6 @@ impl Change { matches!(self, Change::Put { entry: Entry::Image(_), .. } | Change::Remove { entry: Entry::Image(_) }) } - /// Whether this edit carries review settings past the limits `design.configure` keeps: a - /// snapshot saved by a looser build may hold one, and opens without it (see - /// [`crate::docprops`], which refuses such a change inside an ordinary batch). - pub(crate) fn is_oversized_design_review(&self) -> bool { - let Change::SetDoc { prop: DocProp::DesignReview, value } = self else { return false }; - let Ok(config) = value.read::("design review") else { return false }; - config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS - } - /// Whether this only changes comment threads (a thread, their order, or all of them): what a /// comment link may send. pub fn is_comment(&self) -> bool { @@ -344,6 +335,19 @@ impl Change { Change::Create { .. } | Change::Set { .. } | Change::Delete { .. } => false, } } + + /// Whether this writes the file's design review settings: a batch carrying one can't be read + /// by a peer that doesn't announce [`crate::message::DESIGN_REVIEW`], so the server keeps it + /// out of what it sends them ([`Self::without_design_review`]). + pub(crate) fn is_design_review(&self) -> bool { + matches!(self, Change::SetDoc { prop: DocProp::DesignReview, .. }) + } + + /// `changes` without the review-setting edits: what an older peer reads of a batch (its other + /// edits, order kept), or of a catch-up delta or snapshot. + pub(crate) fn without_design_review(changes: Vec) -> Vec { + changes.into_iter().filter(|c| !c.is_design_review()).collect() + } } impl Entry { diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 874403685..31b445486 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -61,21 +61,30 @@ fn design_review_settings_round_trip_and_reach_a_snapshot() { } #[test] -fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_applies() { +fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() { let (a, _, _, _) = setup(); // An edit peer trying to hand the file tens of thousands of radii is refused at apply. let mut b = a.document().clone(); + b.design_review.preset = DesignPreset::Strict; + b.design_review.grid = 8.0; b.design_review.radii = (0..40).map(|i| i as f64).collect(); + b.design_review.brand = vec![Color::from_rgb8_const(1, 2, 3); 40]; + b.design_review.disabled = vec!["radius.off-scale".into()]; let mut r = a.clone(); let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string(); assert!(err.contains("pass the 32 limit `design.configure` keeps"), "{err}"); - // A snapshot holding settings over the limits (an old file's) still opens: like an image - // entry that fails today's checks, the oversized entry is left out of what it loads. + // A snapshot holding settings over the limits (an old file's) opens clamped to what fits: + // the preset, grid and disabled rules exactly as saved, the lists to the limit. let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); - assert_eq!(left_out, 1, "the oversized settings entry is the one left out"); - assert!(r2.document().design_review.radii.is_empty(), "the file opens without them"); + assert_eq!(left_out, 0, "nothing needed leaving out"); + let cfg = &r2.document().design_review; + assert_eq!(cfg.preset, DesignPreset::Strict, "the preset survives"); + assert_eq!(cfg.grid, 8.0, "the grid survives"); + assert_eq!(cfg.disabled, vec!["radius.off-scale".to_string()], "the disabled rules survive"); + assert_eq!(cfg.radii, (0..32).map(|i| i as f64).collect::>(), "the radii keep their first 32"); + assert_eq!(cfg.brand, vec![Color::from_rgb8_const(1, 2, 3); 32], "the brand colours keep their first 32"); } #[test] diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index f66b0688c..a0c0b6c7a 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -403,6 +403,27 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result apply_indexed(doc, change, &mut Index::default()) } +/// Clamp the review settings a snapshot carries to the limits this build keeps, in place: an +/// older or looser snapshot may hold longer radii or brand lists, and the file opens with what +/// fits — the preset, grid and disabled rules exactly as saved. An ordinary edit is refused +/// instead (`apply_indexed`), and a peer that can't read the settings at all gets them left out +/// of what the server sends (`Change::without_design_review`). +pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) { + for c in changes { + if let Change::SetDoc { prop: DocProp::DesignReview, value } = c + && let Ok(config) = value.read::("design review") + && (config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS) + { + let mut clamped = config; + clamped.radii.truncate(figcraft_doc::MAX_RADII); + clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS); + if let Ok(v) = Json::of(&clamped) { + *value = v; + } + } + } +} + /// Apply a document-level change, with the keyed lists' positions kept in `index` between the /// changes of one batch. Returns whether it can change which pages are listed (the library store /// page is never listed). diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index 07adbb2af..2c7392fc2 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -34,9 +34,15 @@ pub const COMMENTS: &str = "comments"; /// read it). pub const PACKED: &str = "packed"; +/// The word a client puts in its [`Hello::client_version`] when it reads +/// [`DocProp::DesignReview`](crate::DocProp::DesignReview): a server keeps review-setting changes +/// out of the batches, catch-up deltas and snapshots it sends to clients that don't say so +/// (older ones couldn't decode the variant at all). +pub const DESIGN_REVIEW: &str = "design-review"; + /// The `client_version` this build announces: its version, then what it reads beyond the protocol. pub fn client_version() -> String { - format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED}", env!("CARGO_PKG_VERSION")) + format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW}", env!("CARGO_PKG_VERSION")) } /// Whether `client_version` announces `word`. @@ -64,6 +70,11 @@ pub fn reads_packed(client_version: &str) -> bool { announces(client_version, PACKED) } +/// A [`Hello::client_version`] that announces [`DESIGN_REVIEW`]. +pub fn reads_design_review(client_version: &str) -> bool { + announces(client_version, DESIGN_REVIEW) +} + /// Join a file's session. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Hello { diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index 7e427970b..b7cfb2752 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -77,10 +77,13 @@ impl Replica { /// [`from_snapshot`](Self::from_snapshot), and how many image entries it left out: a /// snapshot saved before the image checks may hold one they refuse, and opens without it. + /// Review settings past the current limits are clamped to them, not dropped (see + /// [`docprops::clamp_snapshot_design_review`]). pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize), Error> { let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; let mut changes = changes.to_vec(); - let left_out = r.apply_kept(&mut changes, |c| Change::is_image(c) || Change::is_oversized_design_review(c))?; + docprops::clamp_snapshot_design_review(&mut changes); + let left_out = r.apply_kept(&mut changes, Change::is_image)?; if r.doc.pages.is_empty() { return Err(Error::Invalid("a snapshot needs a page".into())); } diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 0f11792b7..e106472ba 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -8,7 +8,8 @@ use serde::{Deserialize, Serialize}; use crate::change::{Change, Entry, Family, Prop, Target}; use crate::message::{ - Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_signals, + Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_design_review, + reads_signals, }; use crate::replica::{Mode, Replica, create_change}; use crate::{Error, Limits, docprops, same_secret}; @@ -86,6 +87,10 @@ pub struct Server { journal: Option>, /// The connected clients that read signals (cursor chat, spotlight). signals: BTreeSet, + /// The connected clients that read the design review settings (`DocProp::DesignReview`): a + /// peer that doesn't announce them can't decode the variant, so the server keeps review + /// edits out of everything it sends them. + design_review: BTreeSet, /// Who spotlights now (a newcomer is told). spotlight: Option, /// Saved history this server restored or replayed left image entries out (or may give a @@ -146,6 +151,7 @@ impl Server { limited: BTreeMap::new(), journal: None, signals: BTreeSet::new(), + design_review: BTreeSet::new(), spotlight: None, resync: false, } @@ -333,12 +339,16 @@ impl Server { } // The log holds every batch after `floor`. let floor = self.log.front().map_or(self.seq, |a| a.seq.saturating_sub(1)); + let reads_design_review = reads_design_review(&hello.client_version); let catch_up = match resume { Some(r) if !self.resync && r.seq <= self.seq && r.seq >= floor => { CatchUp::Delta(self.log.iter().filter(|a| a.seq > r.seq).cloned().collect()) } _ => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?), }; + // A peer that doesn't read the review settings can't decode them: its catch-up carries + // everything else. + let catch_up = filter_catch_up(catch_up, reads_design_review); let (id, secret) = match resume { Some(r) => (r.client_id, *self.secrets.entry(r.client_id).or_insert(r.secret)), None => { @@ -374,9 +384,20 @@ impl Server { } else { self.signals.remove(&id); } + if reads_design_review { + self.design_review.insert(id); + } else { + self.design_review.remove(&id); + } Ok((id, outs)) } + /// Whether every connected peer reads the design review settings: then a batch goes out as + /// one message, the common case. + fn everyone_reads_design_review(&self) -> bool { + self.peers.keys().all(|id| self.design_review.contains(id)) + } + /// Whether `r` may take its client id back: it carries the secret that id was given with, or /// (after a restart, which forgets secrets) a secret for an id nobody is connected as. fn may_resume(&self, r: &Resume) -> bool { @@ -393,6 +414,7 @@ impl Server { self.acked.remove(&id); self.limited.remove(&id); self.signals.remove(&id); + self.design_review.remove(&id); if self.spotlight == Some(id) { self.spotlight = None; } @@ -430,7 +452,7 @@ impl Server { let acc = Accepted { seq: self.seq, author: from, batch_id, changes }; self.remember(acc.clone()); self.note(Journal::Accepted(acc.clone())); - vec![Outgoing::All(ServerMsg::Changes(acc))] + self.relay_changes(acc) } Err(e) => { self.note(Journal::Refused { client: from, batch_id }); @@ -482,6 +504,30 @@ impl Server { } } + /// Send an accepted batch to every connected peer. A peer that doesn't read the review + /// settings can't decode them, so it gets the same batch (its seq, batch id and the peer's + /// own accounting included) with those edits left out and everything else in order. + fn relay_changes(&self, acc: Accepted) -> Vec { + if !acc.changes.iter().any(Change::is_design_review) || self.everyone_reads_design_review() { + return vec![Outgoing::All(ServerMsg::Changes(acc))]; + } + self.peers + .keys() + .copied() + .collect::>() + .into_iter() + .filter_map(|id| { + if self.design_review.contains(&id) { + Some(Outgoing::To(id, ServerMsg::Changes(acc.clone()))) + } else { + let mut filtered = acc.clone(); + filtered.changes = Change::without_design_review(filtered.changes); + (!filtered.changes.is_empty()).then_some(Outgoing::To(id, ServerMsg::Changes(filtered))) + } + }) + .collect() + } + /// Client `from` is called `name` from now on (cleaned): everyone, itself too, hears it as its /// `PeerJoined`, and newcomers' welcomes list it so. fn rename(&mut self, from: u32, name: String) -> Vec { @@ -704,3 +750,23 @@ pub fn weight(changes: &[Change]) -> usize { }) .fold(0, usize::saturating_add) } + +/// A catch-up a peer that doesn't read the design review settings can decode: the review-setting +/// edits are left out of a delta and out of a snapshot, everything else as it was. +fn filter_catch_up(cu: CatchUp, reads_design_review: bool) -> CatchUp { + if reads_design_review { + return cu; + } + match cu { + CatchUp::Delta(list) => CatchUp::Delta( + list.into_iter() + .map(|mut a| { + a.changes = Change::without_design_review(a.changes); + a + }) + .collect(), + ), + CatchUp::Snapshot(changes) => CatchUp::Snapshot(Change::without_design_review(changes)), + packed => packed, + } +} diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs index aafff946d..f46127169 100644 --- a/crates/collab/src/server_tests.rs +++ b/crates/collab/src/server_tests.rs @@ -2,8 +2,8 @@ use figcraft_doc::{Document, Node, NodeId, NodeKind}; -use crate::change::{Change, Entry, Json, Prop}; -use crate::message::{ClientMsg, Hello, PROTOCOL, Presence, ServerMsg}; +use crate::change::{Change, DocProp, Entry, Json, Prop}; +use crate::message::{ClientMsg, Hello, PROTOCOL, Presence, ServerMsg, client_version, reads_design_review}; use crate::replica::Mode; use crate::{Client, Limits, NoRecompute, Outgoing, Server}; @@ -39,6 +39,22 @@ fn for_client(out: &[Outgoing], to: u32) -> Vec { .collect() } +/// A hello whose `client_version` says exactly `version` (what an older or newer build announces). +fn hello_of(version: &str) -> Hello { + Hello { client_version: version.to_string(), ..hello("tok") } +} + +/// The changes an `Accepted` relay or catch-up carries, or none. +fn accepted_changes(msgs: &[ServerMsg]) -> Vec<&Change> { + msgs.iter() + .filter_map(|m| match m { + ServerMsg::Changes(a) => Some(a.changes.iter().collect::>()), + _ => None, + }) + .flatten() + .collect() +} + fn edit(c: &mut Client, f: impl FnOnce(&mut Document)) -> ClientMsg { let mut d = c.document().clone(); f(&mut d); @@ -364,3 +380,61 @@ fn junk_batches_never_panic_and_never_corrupt_the_document() { assert!(s.document().validate().is_empty(), "{:?}", s.document().validate()); } } + +#[test] +fn the_client_version_announces_the_design_review() { + assert!(reads_design_review(&client_version())); + assert!(!reads_design_review("0.18.0 signals hosting comments packed")); +} + +/// A capable editor, a peer built before the review existed, and a mixed batch: the old peer +/// hears the same batch without the review-setting edit, the new peer hears it whole. +#[test] +fn a_review_edit_reaches_only_the_peers_that_read_it() { + let (d, _, _) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // One batch: rename the document (everyone) and set the review grid (capable peers only). + let batch = vec![ + Change::SetDoc { prop: DocProp::Name, value: Json::of("Renamed").unwrap() }, + Change::SetDoc { prop: DocProp::DesignReview, value: Json(serde_json::json!({"preset": "strict", "grid": 8.0})) }, + ]; + let out = s.receive(capable.id(), ClientMsg::Changes { base_seq: s.seq(), batch_id: 1, changes: batch }); + let for_old = for_client(&out, old.id()); + assert!(accepted_changes(&for_old).iter().all(|c| !c.is_design_review()), "the old peer's copy carries no review edit: {:?}", for_old); + assert!( + accepted_changes(&for_old).iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), + "the old peer still hears the rename: {:?}", + for_old + ); + let for_new = for_client(&out, capable.id()); + assert_eq!(accepted_changes(&for_new).len(), 2, "the capable peer hears both: {for_new:?}"); + + // A capable newcomer's catch-up (a fresh join, so a snapshot) carries the settings. + let (_, out) = s.join(hello("tok")).unwrap(); + let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) = + out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. }))) + else { + panic!("no welcome"); + }; + let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") }; + assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "{changes:?}"); + + // An old newcomer's catch-up carries none, and still has the rename. + let (_, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) = + out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. }))) + else { + panic!("no welcome"); + }; + let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") }; + assert!(changes.iter().all(|c| !c.is_design_review()), "{changes:?}"); + assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), "{changes:?}"); +} diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 1a7e77052..31c07420b 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -149,7 +149,10 @@ As built: still increasing keeps its keys) and re-spaces a parent whose keys would grow past 48 characters. - **Document-level objects covered now**: the file name, the current page, document colours, the colour profile, image presets, annotation categories, the design review settings - (`DocProp::DesignReview`) and library data (whole values); styles, + (`DocProp::DesignReview`, sent only to clients whose `client_version` announces + `design-review`; a client that doesn't gets every batch, catch-up delta and snapshot without + them, and a snapshot saved with longer lists opens clamped to the limits `design.configure` + keeps) and library data (whole values); styles, comment threads, variable collections and variables (one entry per id plus the order of ids; the whole list when ids aren't unique); dev-mode snapshots (per layer); images (per content hash, the encoded bytes as base64; as an entry applies the claim is checked: every key is From 2182962f7e978e41a21f49b5e3fa54bb67937655 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 20:34:43 -0500 Subject: [PATCH 028/268] Drag sprite: decline for a rotated or skewed clipping frame and for layers under different clipping frames The sprite clipped to the world bounds of each clipping ancestor, which is the real clip only when the frame is axis-aligned, and intersected the clips of unrelated frames into one. Both now fall back to the normal render path. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/geom/src/transform.rs | 8 +++++ crates/ui-egui/src/canvas/drag_sprite.rs | 40 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/crates/geom/src/transform.rs b/crates/geom/src/transform.rs index 69c6c788d..98e10fe6f 100644 --- a/crates/geom/src/transform.rs +++ b/crates/geom/src/transform.rs @@ -11,6 +11,14 @@ pub fn rotation_degrees(xf: Affine) -> f64 { if deg <= -180.0 { deg + 360.0 } else { deg } } +/// Whether `xf` maps axis-aligned rectangles to axis-aligned rectangles: scale, flip, translate or a +/// quarter turn, but no other rotation and no skew. +pub fn is_axis_aligned(xf: Affine) -> bool { + let [a, b, c, d, ..] = xf.as_coeffs(); + let tol = 1e-9 * (a.abs() + b.abs() + c.abs() + d.abs()).max(1.0); + (b.abs() <= tol && c.abs() <= tol) || (a.abs() <= tol && d.abs() <= tol) +} + /// The translation part of `xf`. pub fn translation(xf: Affine) -> Point { let c = xf.as_coeffs(); diff --git a/crates/ui-egui/src/canvas/drag_sprite.rs b/crates/ui-egui/src/canvas/drag_sprite.rs index 8ef80e575..2425d23a2 100644 --- a/crates/ui-egui/src/canvas/drag_sprite.rs +++ b/crates/ui-egui/src/canvas/drag_sprite.rs @@ -204,6 +204,11 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> if a.corners.radii.iter().any(|r| *r != 0.0) { return false; } + // Its world box is the clip only when the frame is axis-aligned: for a rotated or skewed + // one it is just the box around the real clip, and the layers would paint outside it. + if !figcraft_geom::is_axis_aligned(doc.world_transform(a.id)) { + return false; + } let Some(b) = doc.world_bounds(a.id) else { return false }; *clip = Some(clip.map_or(b, |c| c.intersect(b))); } @@ -213,6 +218,11 @@ fn plain(doc: &Document, id: NodeId, clip: &mut Option) -> true } +/// The clipping frames above layer `id`, nearest first. +fn clippers(doc: &Document, id: NodeId) -> Vec { + doc.ancestors(id).into_iter().filter(|a| doc.node(*a).is_some_and(|n| n.clip && n.kind.is_frame_like())).collect() +} + /// Render the dragged layers of `base` into a sprite, if they qualify: the roots are plain (see /// [`plain`]), none inside another, and the sprite fits a texture and a few canvases of pixels. #[allow(clippy::too_many_arguments)] @@ -230,6 +240,13 @@ fn plan( return None; } let mut clip = None; + // Layers under different clipping frames would need a clip each; one shared (intersected) clip + // could hide both, so the sprite stands aside. + if let Some((first, rest)) = sel.split_first() + && rest.iter().any(|o| clippers(base, *o) != clippers(base, *first)) + { + return None; + } for id in sel { if !plain(base, *id, &mut clip) || sel.iter().any(|o| o != id && base.ancestors(*id).contains(o)) { return None; @@ -365,4 +382,27 @@ mod plain_tests { let (_, c) = frame_with_child(&mut s, json!({"clip": true, "cornerRadius": 12})); assert!(!plain(s.doc().unwrap(), c, &mut None), "a rounded frame clips to a shape the sprite can't follow"); } + + #[test] + fn a_rotated_clipping_ancestor_is_not_plain() { + let mut s = Session::new(); + let (f, c) = frame_with_child(&mut s, json!({"clip": true})); + assert!(plain(s.doc().unwrap(), c, &mut None), "axis-aligned: plain"); + s.execute("transform.rotate", &json!({"ids": [f], "degrees": 30})).unwrap(); + assert!(!plain(s.doc().unwrap(), c, &mut None), "its world box is not its clip"); + } + + #[test] + fn layers_under_different_clipping_frames_decline_the_sprite() { + let ctx = egui::Context::default(); + let mut s = Session::new(); + let (_, a) = frame_with_child(&mut s, json!({"clip": true})); + let f2 = id(&s.execute("frame.create", &json!({"x": 300, "y": 0, "width": 200, "height": 200})).unwrap()); + s.execute("node.set", &json!({"id": f2, "props": {"clip": true}})).unwrap(); + let b = id(&s.execute("shape.rectangle", &json!({"x": 310, "y": 10, "width": 40, "height": 40, "parent": f2})).unwrap()); + let base = std::sync::Arc::new(s.doc().unwrap().clone()); + let of = (0, base.page_of(a).unwrap()); + assert!(super::plan(&ctx, &base, &[a], of, 1.0, 1.0, 4096, 1e9).is_some(), "one clipping frame: a sprite"); + assert!(super::plan(&ctx, &base, &[a, b], of, 1.0, 1.0, 4096, 1e9).is_none(), "two: no shared clip"); + } } From 846e69f206616964dd0d5b4bfa0fa5512c55b6bb Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:17:32 +0800 Subject: [PATCH 029/268] M13: keep an older peer in step through a review-only batch --- crates/collab/src/server.rs | 13 +++++---- crates/collab/src/server_tests.rs | 47 +++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index e106472ba..58ad309bb 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -511,18 +511,19 @@ impl Server { if !acc.changes.iter().any(Change::is_design_review) || self.everyone_reads_design_review() { return vec![Outgoing::All(ServerMsg::Changes(acc))]; } + // Every peer hears the batch, even one with nothing left for it: the batch still carries + // the next sequence number, and a peer that skipped it would reject its next ordinary + // batch as out of order. self.peers .keys() .copied() - .collect::>() - .into_iter() - .filter_map(|id| { - if self.design_review.contains(&id) { - Some(Outgoing::To(id, ServerMsg::Changes(acc.clone()))) + .map(|id| { + if self.design_review.contains(&id) || id == acc.author { + Outgoing::To(id, ServerMsg::Changes(acc.clone())) } else { let mut filtered = acc.clone(); filtered.changes = Change::without_design_review(filtered.changes); - (!filtered.changes.is_empty()).then_some(Outgoing::To(id, ServerMsg::Changes(filtered))) + Outgoing::To(id, ServerMsg::Changes(filtered)) } }) .collect() diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs index f46127169..e26728835 100644 --- a/crates/collab/src/server_tests.rs +++ b/crates/collab/src/server_tests.rs @@ -438,3 +438,50 @@ fn a_review_edit_reaches_only_the_peers_that_read_it() { assert!(changes.iter().all(|c| !c.is_design_review()), "{changes:?}"); assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), "{changes:?}"); } + +/// A review-only batch advances the server sequence for every peer. An older peer must still be +/// sent the accepted batch, empty as it is, or it falls a sequence behind and refuses what +/// follows. +#[test] +fn a_review_only_batch_keeps_an_older_peer_in_step() { + let (d, _, frame) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let mut capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let mut old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // Only the review settings change, so this batch has nothing for the older peer. + let msg = edit(&mut capable, |d| d.design_review.grid = 8.0); + let ClientMsg::Changes { changes, .. } = &msg else { panic!("not a batch") }; + assert!(!changes.is_empty() && changes.iter().all(Change::is_design_review), "review only: {changes:?}"); + let out = s.receive(capable.id(), msg); + assert_eq!(s.seq(), 1); + let to_old = for_client(&out, old.id()); + let empty = to_old.iter().any(|m| matches!(m, ServerMsg::Changes(a) if a.changes.is_empty())); + assert!(empty, "the older peer is told the batch happened: {to_old:?}"); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in to_old { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + + // The next ordinary edit still lands for it. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "After", 0.0, 0.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(1), "the new node is there"); +} From 38eec9895d3a72172eebdb8268a396bf2b474e28 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:56:47 +0800 Subject: [PATCH 030/268] M13: a review-only batch reaches a peer that was away as an empty delta --- crates/collab/src/server_tests.rs | 71 ++++++++++++++++++++++++++++++- docs/collab-protocol.md | 3 +- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs index e26728835..8979cb213 100644 --- a/crates/collab/src/server_tests.rs +++ b/crates/collab/src/server_tests.rs @@ -3,7 +3,7 @@ use figcraft_doc::{Document, Node, NodeId, NodeKind}; use crate::change::{Change, DocProp, Entry, Json, Prop}; -use crate::message::{ClientMsg, Hello, PROTOCOL, Presence, ServerMsg, client_version, reads_design_review}; +use crate::message::{CatchUp, ClientMsg, Hello, PROTOCOL, Presence, ServerMsg, client_version, reads_design_review}; use crate::replica::Mode; use crate::{Client, Limits, NoRecompute, Outgoing, Server}; @@ -485,3 +485,72 @@ fn a_review_only_batch_keeps_an_older_peer_in_step() { assert_eq!(old.seq(), s.seq()); assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(1), "the new node is there"); } + +/// The same batch through the other catch-up path: a peer that was away comes back with a delta, +/// and the review-only batch is there as an accepted batch with nothing in it for it, so its +/// sequence carries on and the edits after it apply. +#[test] +fn a_review_only_batch_is_an_empty_delta_for_a_peer_that_was_away() { + let (d, _, frame) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let mut capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let mut old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // One ordinary edit, so the peer's resume point sits before the review-only batch. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "Before", 0.0, 0.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), 1); + + // It drops; only the review settings change while it is away. + old.disconnect(); + let msg = edit(&mut capable, |d| d.design_review.grid = 8.0); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(s.seq(), 2); + + // It comes back: the delta holds the batch, empty, and its sequence carries on. + let ClientMsg::Hello(h) = old.reconnect(hello_of("0.18.0 signals hosting comments packed")) else { + panic!("not a hello"); + }; + let (id, out) = s.join(h).unwrap(); + assert_eq!(id, old.id()); + let welcome = out + .into_iter() + .find_map(|o| match o { + Outgoing::To(to, w @ ServerMsg::Welcome { .. }) if to == id => Some(w), + _ => None, + }) + .unwrap_or_else(|| panic!("no welcome")); + assert!( + matches!(&welcome, ServerMsg::Welcome { catch_up: CatchUp::Delta(list), .. } if list.len() == 1 && list[0].changes.is_empty()), + "{welcome:?}" + ); + old.receive(welcome, &NoRecompute).unwrap(); + assert_eq!(old.seq(), s.seq()); + + // And the next ordinary edit still applies. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "After", 0.0, 20.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(2), "both nodes are there"); +} diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 31c07420b..6cada9a59 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -151,7 +151,8 @@ As built: colour profile, image presets, annotation categories, the design review settings (`DocProp::DesignReview`, sent only to clients whose `client_version` announces `design-review`; a client that doesn't gets every batch, catch-up delta and snapshot without - them, and a snapshot saved with longer lists opens clamped to the limits `design.configure` + them, and an accepted batch still reaches it when nothing of it is left, so sequence numbers + never skip; a snapshot saved with longer lists opens clamped to the limits `design.configure` keeps) and library data (whole values); styles, comment threads, variable collections and variables (one entry per id plus the order of ids; the whole list when ids aren't unique); dev-mode snapshots (per layer); images (per content From 9d8c1efc06c82e588fb1f262b58b40366600bb68 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:56:48 +0800 Subject: [PATCH 031/268] M13: refuse a rule filter that names nothing --- crates/engine/src/design/mod.rs | 8 ++++++++ crates/engine/src/design/tests.rs | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 287ecb2d1..57fa03cb1 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -397,6 +397,14 @@ fn severity_arg(cmd: &str, p: &Value) -> Result { fn filter_arg(cmd: &str, p: &Value) -> Result>> { let Some(v) = params::get(p, "rules") else { return Ok(None) }; let Value::Array(items) = v else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; + // A filter that names nothing checks nothing: a gate would pass over a review that never + // ran, the same way a truncated audit would. + if items.is_empty() { + return Err(bad( + cmd, + "`rules` names no rule, so nothing would be checked; list at least one (design.rules has them) or leave `rules` out to check them all", + )); + } let mut set = BTreeSet::new(); for item in items { let Some(s) = item.as_str() else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index e537b4b13..1dd2ec3ff 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -909,6 +909,18 @@ fn assert_refuses_an_explicit_empty_selection() { assert!(s.execute("design.audit", &json!({})).is_ok()); } +#[test] +fn an_empty_rule_filter_is_refused() { + let mut s = Session::new(); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + for cmd in ["design.audit", "design.assert", "design.fix"] { + let err = s.execute(cmd, &json!({"scope": "page", "rules": []})).unwrap_err().to_string(); + assert!(err.contains("`rules`"), "{cmd}: {err}"); + } + // Naming a rule still works. + assert!(ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.accents"]})).is_object()); +} + #[test] fn hardcoded_values_that_match_variables_are_reported() { let mut s = Session::new(); From 654f1c4911a945cda7ce3939b39edfb20ab811c7 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 22:28:38 -0500 Subject: [PATCH 032/268] M8: a scale that would take an instance past its scale range is refused, so bound and unbound lengths stay equal (#2090) scale_node clamped only the stored scale factor while every other length took the full factor, so past 0.001 to 1000 a bound length (drawn at the variable's value times the factor) and an unbound one drifted apart. A new scale_fits checks every instance the scale multiplies (sharing the covered rule with scale_node) and scale_node and transform.scale refuse before changing anything; a selection where only one root fails changes nothing. The Scale tool drag keeps the last frame that fit. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/canvas/tools/drag.rs | 15 ++- crates/engine/src/cmd/arrange.rs | 78 +++++++++++----- crates/engine/src/scale_bound_values_tests.rs | 91 +++++++++++++++++++ docs/components-parity.md | 4 +- docs/ui-parity.md | 4 +- 5 files changed, 165 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index ea336a142..07697afaf 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -646,14 +646,25 @@ impl Session { // A layer's place in the box scales about the pivot; a negative factor turns it over. let about = frame * Affine::translate(pivot.to_vec2() * (1.0 - k)); let sign = k.signum(); - self.preview(|doc, _| { + // A factor an instance can't follow (its scale factor would leave 0.001 to 1000) is not + // applied: the drag keeps the last frame that fit. + let mut refused = false; + let shown = self.preview(|doc, _| { + if !nodes.iter().all(|(id, ..)| crate::cmd::arrange::scale_fits(doc, *id, k.abs())) { + refused = true; + return Err(crate::error::bad("transform.scale", "past the scale range")); + } for (id, world, _, _) in &nodes { let c = (inv * *world).as_coeffs(); doc.set_world_transform(*id, about * Affine::new([sign * c[0], sign * c[1], sign * c[2], sign * c[3], k * c[4], k * c[5]]))?; crate::cmd::arrange::scale_node(doc, *id, k.abs())?; } Ok(()) - })?; + }); + if refused { + return Ok(()); + } + shown?; let p = frame * pivot; self.tool.overlay.scale = Some(ScaleHint { factor: k, pivot: [p.x, p.y] }); self.tool.overlay.guides = guides; diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index b6e5362c5..57ed10a50 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -403,26 +403,10 @@ fn turn_pivot(s: &Session, ids: &[NodeId]) -> Result> { pub(crate) const MIN_SCALE_FACTOR: f64 = 1e-3; pub(crate) const MAX_SCALE_FACTOR: f64 = 1e3; -/// Scale a node and everything in it uniformly (the Scale tool): sizes and positions (whatever -/// the children's constraints), strokes, effects, radii, auto layout spacing, min/max sizes, -/// layout grids, ruler guides, tiled images and text sizes. -/// -/// Variable-bound lengths follow the incumbent (#2090): an instance multiplies its scale factor and -/// keeps its bindings, which draw at the variable's value times the factor; any other layer not -/// inside an instance keeps the scaled value and drops the binding of each length it scaled. -pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { - let k = if k.is_finite() && k > 0.0 { k } else { return Ok(()) }; - let sub = doc.subtree(id); - // The layers below `id` scale whatever their constraints, so where they are layers of an - // instance their new size and place are overrides. The edit's own diff takes geometry that - // changed with an ancestor's size for what constraints give, so the next rebuild of the - // instance would put them back at their main's size (#922). - let in_instance: Vec = sub.iter().enumerate().map(|(depth, i)| depth > 0 && crate::components::inside_instance(doc, *i)).collect(); - let nested: Vec = sub.iter().map(|i| crate::components::inside_instance(doc, *i)).collect(); - // An instance inside another instance of the subtree is covered by the outer factor through - // `scale_of`'s product (#2090); only an instance with no instance above it, up to `id`, takes k. - let covered: Vec = sub - .iter() +/// For each layer of `sub` (the subtree of `id`), whether an instance sits above it, up to `id` +/// (never `id` itself): `scale_of`'s product already carries the outer factor to it (#2090). +fn covered_by_instance(doc: &Document, sub: &[NodeId], id: NodeId) -> Vec { + sub.iter() .map(|i| { if *i == id { return false; @@ -437,7 +421,51 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { } false }) - .collect(); + .collect() +} + +/// Whether [`scale_node`] by `k` keeps every instance it multiplies inside the scale factor's +/// range. Every other length takes the full `k`, so a factor that had to be clamped would leave +/// bound lengths (drawn at the variable's value times the factor) off from unbound ones. +pub(crate) fn scale_fits(doc: &Document, id: NodeId, k: f64) -> bool { + if !(k.is_finite() && k > 0.0) { + return true; + } + let sub = doc.subtree(id); + let covered = covered_by_instance(doc, &sub, id); + sub.iter().enumerate().all(|(depth, i)| { + let Some(n) = doc.node(*i) else { return true }; + if !matches!(n.kind, NodeKind::Instance { .. }) || covered.get(depth).copied().unwrap_or(false) { + return true; + } + // A hair of slack, so 10 x 100 and 0.1 x 0.01 land on the bounds despite rounding. + let f = n.scale_factor * k; + (MIN_SCALE_FACTOR * (1.0 - 1e-9)..=MAX_SCALE_FACTOR * (1.0 + 1e-9)).contains(&f) + }) +} + +/// Scale a node and everything in it uniformly (the Scale tool): sizes and positions (whatever +/// the children's constraints), strokes, effects, radii, auto layout spacing, min/max sizes, +/// layout grids, ruler guides, tiled images and text sizes. +/// +/// Variable-bound lengths follow the incumbent (#2090): an instance multiplies its scale factor and +/// keeps its bindings, which draw at the variable's value times the factor; any other layer not +/// inside an instance keeps the scaled value and drops the binding of each length it scaled. +pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { + let k = if k.is_finite() && k > 0.0 { k } else { return Ok(()) }; + if !scale_fits(doc, id, k) { + return Err(scale_range_error()); + } + let sub = doc.subtree(id); + // The layers below `id` scale whatever their constraints, so where they are layers of an + // instance their new size and place are overrides. The edit's own diff takes geometry that + // changed with an ancestor's size for what constraints give, so the next rebuild of the + // instance would put them back at their main's size (#922). + let in_instance: Vec = sub.iter().enumerate().map(|(depth, i)| depth > 0 && crate::components::inside_instance(doc, *i)).collect(); + let nested: Vec = sub.iter().map(|i| crate::components::inside_instance(doc, *i)).collect(); + // An instance inside another instance of the subtree is covered by the outer factor through + // `scale_of`'s product (#2090); only an instance with no instance above it, up to `id`, takes k. + let covered = covered_by_instance(doc, &sub, id); let tiles = |paints: &mut Vec| { for p in paints { if let figcraft_color::PaintKind::Image(img) = &mut p.kind @@ -565,6 +593,10 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { Ok(()) } +fn scale_range_error() -> crate::EngineError { + bad("transform.scale", "the scale would take an instance past the supported scale range of 0.001 to 1000") +} + fn scale_cmd(s: &mut Session, p: &Value) -> Result { let k = req_num("transform.scale", p, "factor")?; if k <= 0.0 { @@ -575,6 +607,10 @@ fn scale_cmd(s: &mut Session, p: &Value) -> Result { let ids = roots(doc, &ids); let b = doc.bounds_of(&ids).unwrap_or_default(); let pivot = Point::new(num_or(p, "cx", b.x0), num_or(p, "cy", b.y0)); + // Refuse before anything changes, so a selection where only a later root fails stays whole. + if !ids.iter().all(|i| scale_fits(doc, *i, k)) { + return Err(scale_range_error()); + } for i in ids { let Some(nb) = doc.world_bounds(i) else { continue }; scale_node(doc, i, k)?; diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs index eb936a042..c6e7244cf 100644 --- a/crates/engine/src/scale_bound_values_tests.rs +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -246,3 +246,94 @@ fn scaling_a_frame_holding_an_instance_drops_its_own_binding_and_scales_the_inst assert!(saved.get("scale_factor").is_none(), "{saved}"); healthy(&s); } + +/// A bound instance beside an unbound rectangle with the same radius (4), as (instance, its first +/// rectangle, the unbound one). +fn bound_and_unbound(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let (_c, a, i) = row_instance(s); + let r = idv(&ex(s, "shape.rectangle", json!({"x": 500, "y": 0, "width": 24, "height": 24}))); + ex(s, "node.set", json!({"id": r, "props": {"cornerRadius": 4}})); + (i, a, r) +} + +fn radius(s: &Session, id: NodeId) -> f64 { + node(s, id).corners.radii[0] +} + +/// The bound radius (the instance's copy of `a`) and the unbound one agree: both are 4 times `k`. +fn assert_radii_equal(s: &Session, i: NodeId, a: NodeId, r: NodeId, k: f64, why: &str) { + let (bound, plain) = (radius(s, copy_of(s, i, a)), radius(s, r)); + assert!(near(bound, 4.0 * k) && near(plain, 4.0 * k), "{why}: bound {bound} unbound {plain} want {}", 4.0 * k); +} + +#[test] +fn scaling_past_the_largest_factor_is_refused_and_keeps_bound_and_unbound_lengths_equal() { + let mut s = Session::new(); + let (i, a, r) = bound_and_unbound(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [i, r], "factor": 100})); + assert!(near(factor(&s, i), 100.0)); + assert_radii_equal(&s, i, a, r, 100.0, "first"); + let again = s.execute("transform.scale", &json!({"ids": [i, r], "factor": 100})); + assert!(again.is_err(), "the second scale must be refused: {again:?}"); + assert!(near(factor(&s, i), 100.0), "factor {}", factor(&s, i)); + assert_radii_equal(&s, i, a, r, 100.0, "after the refusal"); + healthy(&s); + s.undo().unwrap(); + assert!(near(factor(&s, i), 1.0), "factor after undo {}", factor(&s, i)); + assert_radii_equal(&s, i, a, r, 1.0, "undone"); +} + +#[test] +fn scaling_past_the_smallest_factor_is_refused_the_same_way() { + let mut s = Session::new(); + let (i, a, r) = bound_and_unbound(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [i, r], "factor": 0.05})); + assert!(near(factor(&s, i), 0.05)); + assert_radii_equal(&s, i, a, r, 0.05, "first"); + let again = s.execute("transform.scale", &json!({"ids": [i, r], "factor": 0.01})); + assert!(again.is_err(), "the second scale must be refused: {again:?}"); + assert!(near(factor(&s, i), 0.05), "factor {}", factor(&s, i)); + assert_radii_equal(&s, i, a, r, 0.05, "after the refusal"); + healthy(&s); + s.undo().unwrap(); + assert!(near(factor(&s, i), 1.0), "factor after undo {}", factor(&s, i)); + assert_radii_equal(&s, i, a, r, 1.0, "undone"); +} + +#[test] +fn a_selection_where_one_instance_cannot_scale_changes_nothing() { + let mut s = Session::new(); + let (c, _a, i1) = row_instance(&mut s); + let i2 = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 600, "y": 0}))); + ex(&mut s, "transform.scale", json!({"ids": [i1], "factor": 500})); + let (before1, before2) = (node(&s, i1), node(&s, i2)); + let res = s.execute("transform.scale", &json!({"ids": [i2, i1], "factor": 4})); + assert!(res.is_err(), "{res:?}"); + assert!(near(factor(&s, i1), 500.0) && near(factor(&s, i2), 1.0), "{} {}", factor(&s, i1), factor(&s, i2)); + assert!(node(&s, i1) == before1 && node(&s, i2) == before2, "a refused scale changed a layer"); + healthy(&s); +} + +#[test] +fn dragging_the_scale_tool_past_the_limit_stops_at_the_last_factor_that_fits() { + use crate::tools::{PointerEvent, PointerKind}; + let mut s = Session::new(); + let (_c, a, i) = row_instance(&mut s); + // The instance is already 5 times; its 280 x 120 box at (300, 0) is dragged by the bottom right + // handle out to 100 times (500 in all), then to the tool's own top of 1000 times (5000 in all). + ex(&mut s, "transform.scale", json!({"ids": [i], "factor": 5})); + ex(&mut s, "select.set", json!({"ids": [i]})); + ex(&mut s, "tool.scale", json!({})); + for (kind, (x, y)) in [ + (PointerKind::Down, (580.0, 120.0)), + (PointerKind::Move, (300.0 + 280.0 * 100.0, 120.0 * 100.0)), + (PointerKind::Move, (300.0 + 280.0 * 1000.0, 120.0 * 1000.0)), + (PointerKind::Up, (300.0 + 280.0 * 1000.0, 120.0 * 1000.0)), + ] { + s.pointer(&PointerEvent::at(kind, x, y, 1.0)).unwrap(); + } + assert!(near(factor(&s, i), 500.0), "factor {}", factor(&s, i)); + assert!(near(gap(&s, i), 8.0 * 500.0), "gap {}", gap(&s, i)); + assert!(near(radius(&s, copy_of(&s, i, a)), 4.0 * 500.0), "radius {}", radius(&s, copy_of(&s, i, a))); + healthy(&s); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 9cfa2d219..ae3524a93 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -70,7 +70,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | | Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values | -| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity); on a scaled instance a bound length draws at the variable's value times the instance's scale factor (#2090) | +| Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity); on a scaled instance a bound length draws at the variable's value times the instance's scale factor (#2090); a scale that would take an instance past 0.001 to 1000 times is refused | | Explicit modes per frame, library collections' modes | done | stored variable and collection references resolve by exact id in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker and prototype playback; a collection or variable named like another's id no longer stands in for it there | | Explicit modes per frame and per page (Page section), library collections' modes | done | stored variable and collection references resolve by exact id in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker and prototype playback; a collection or variable named like another's id no longer stands in for it there | | Gradient stops and variant properties bound to variables | done | a stop's binding follows it when earlier stops are removed | @@ -82,7 +82,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured; a scale that would take an instance past 0.001 to 1000 times is refused. Tests: `scale_bound_values_tests`. | | 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-12 | minor | M7, #2215: pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215). The same section the frames' Variable modes use (`variable.setMode` without layers sets the page's mode), one undo step per pick. Binding the page background to a variable is not in the reference and is not offered | | 2026-11-10 | minor | M7, #2174: a text style binds a number variable to its weight (`style.bind {field: "fontWeight"}`): the style takes the face nearest the number and sets the `wght` axis, so static and variable fonts both follow; a face-name (string) binding and a weight binding replace each other, and the weight wins in a file carrying both. The style editor's weight menu offers number variables beside string ones. A number bound to a line height is applied in pixels, as the reference tool does, which a test now pins. Numbers unchanged. Tests: `style_vars_tests`, `style_picker::tests`. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0ef19f364..1b22668cb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -72,7 +72,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`.variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each layer-level length scaled: size, gaps, padding, radii, stroke weights, min and max sizes and the layer's text sizes (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are neither multiplied nor dropped, so on any scaled layer they go back to the variable's value at the next bindings pass; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt | +| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`.variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each layer-level length scaled: size, gaps, padding, radii, stroke weights, min and max sizes and the layer's text sizes (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are neither multiplied nor dropped, so on any scaled layer they go back to the variable's value at the next bindings pass; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt; a scale that would take an instance past 0.001 to 1000 times is refused | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | @@ -215,7 +215,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured. Tests: `scale_bound_values_tests`. | +| 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured; a scale that would take an instance past 0.001 to 1000 times is refused. Tests: `scale_bound_values_tests`. | | 2026-11-12 | patch | M8: Tab while renaming the last layer in the Layers panel commits and opens the first row's rename, as measured in Figma's web app on 2026-11-12 (it ended the rename before); Shift+Tab on the first row is unchanged, not measured; Tab and Shift+Tab now move only the rename and leave the selection on the layer first renamed, as measured in Figma's web app on 2026-11-12 (it followed the rename before) (`tab_on_the_last_row_commits_and_wraps_to_the_first`, `tab_while_renaming_leaves_the_selection_on_the_first_layer`), Rename row | | 2026-11-09 | patch | M3, #2156: the text caret takes the text's solid fill colour (red text, red caret; light grey on a dark frame, light grey, one colour and no inversion), measured in Figma's web app: the fill of the character before the caret (the first one's at the start); FigCraft draws it opaque (how Figma treats a translucent fill was not measured); gradient, image and hidden fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour (white in the dark theme, invisible on the default light page, #2190). Width and height unchanged; collaborators' carets unchanged. Tests: `caret_tests` | | 2026-11-10 | minor | The Rotation field shows and sets the layer's rotation on the page (its own angle plus its parents' when no ancestor is flipped; with a flipped ancestor FigCraft reads the composed angle, which flips the sign of the layer's own angle, and Figma's behaviour there was not measured), in frames and groups alike, as measured in Figma's web app for rotated, unflipped parents (#2196) | From 5f2c81beb2b04818ac2fe6a78c364f63e03f0a1d Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:48:52 +0800 Subject: [PATCH 033/268] M13: the audit names the rules it could not check, and gates read them --- crates/engine/src/design/audit.rs | 18 +++++++++++++++++- crates/engine/src/design/mod.rs | 25 +++++++++++++++---------- crates/engine/src/design/tests.rs | 12 ++++++++++++ 3 files changed, 44 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index 25a770c12..5045aee52 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -358,6 +358,21 @@ pub(crate) fn run( *by_rule.entry(f.rule).or_default() += 1; } let findings: Vec = shown.into_iter().map(Finding::json).collect(); + // What the walk could not check, by rule: past the node limit it looked at nothing more, and + // past a measure cap it saw layers without measuring them. A gate reads this list, so a new + // cap somewhere in the walk fails it without a second place to remember. + let mut unchecked: Vec = Vec::new(); + if report.truncated { + for r in super::rules::RULES.iter().filter(|r| settings.enabled(r.id)) { + unchecked.push(json!({"rule": r.id, "reason": "truncated"})); + } + } else { + for (rule, layers) in [("layout.text-overflow", report.text_unmeasured), ("layout.clipped", report.frames_unmeasured)] { + if layers > 0 && settings.enabled(rule) { + unchecked.push(json!({"rule": rule, "reason": "measure-cap", "layers": layers})); + } + } + } let mut out = settings.json(); if let Some(o) = out.as_object_mut() { o.insert("scope".into(), json!(scope)); @@ -368,7 +383,8 @@ pub(crate) fn run( o.insert("limit".into(), json!(report.limit)); o.insert("findings".into(), json!(findings)); o.insert("truncated".into(), json!(report.truncated)); - // Checks the walk capped before finishing: what they did not measure is unchecked. + o.insert("unchecked".into(), json!(unchecked)); + // How many layers each capped check left unmeasured, for the window and agents. if report.text_unmeasured > 0 { o.insert("textUnmeasured".into(), json!(report.text_unmeasured)); } diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 57fa03cb1..f4d308cf5 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { spec!( "design.audit", "Check design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them), limit?: 1000-1000000 (nodes before the report says truncated; default 50000)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, limit, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them), limit?: 1000-1000000 (nodes before the report says truncated; default 50000)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, limit, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated, unchecked: [{rule, reason, layers?}]} reads the design and reports the AI-slop tells; changes nothing (unchecked names the rules the run could not check: truncated, or a measure cap)", false, audit_cmd ), @@ -44,7 +44,7 @@ pub fn specs() -> Vec { spec!( "design.assert", "Assert design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit was truncated at the node limit it ran with (what it did not reach is unchecked: narrow the scope, filter the rules or raise `limit`); read-only, for CI", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit could not check a rule it asked for (truncated at the node limit it ran with, or past a measure cap: what it did not reach is unchecked, so narrow the scope, filter the rules or raise `limit`); read-only, for CI", false, assert_cmd ), @@ -138,14 +138,19 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or raise `limit`, then assert again" ))); } - // The overflow and clipping checks cap how much they measure per run, independently of - // `limit`: boxes or frames past the cap were seen but not measured, so a gate that includes - // those rules cannot prove a pass on a scope that big. - let unchecked: Vec = [("textUnmeasured", "layout.text-overflow"), ("framesUnmeasured", "layout.clipped")] - .into_iter() - .filter(|(key, rule)| report[*key].as_u64().unwrap_or(0) > 0 && filter.as_ref().is_none_or(|set| set.contains(*rule))) - .map(|(_, rule)| rule.to_string()) - .collect(); + // What the audit reported as unchecked, restricted to the rules this gate asked for. The + // audit names each rule it could not check (`limit` truncation is handled above with its own + // advice), so a cap added there fails this gate without a list here to keep in step. + let unchecked: Vec<&str> = report["unchecked"] + .as_array() + .map(|v| { + v.iter() + .filter(|e| e["reason"].as_str() == Some("measure-cap")) + .filter_map(|e| e["rule"].as_str()) + .filter(|rule| filter.as_ref().is_none_or(|set| set.contains(*rule))) + .collect() + }) + .unwrap_or_default(); if !unchecked.is_empty() { return Err(EngineError::Other(format!( "design review failed: the audit did not measure all of {} on this scope (past the per-run measure cap), so what it skipped is unchecked; audit a smaller scope, then assert again", diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 1dd2ec3ff..b01242b4b 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -750,6 +750,12 @@ fn assert_fails_when_the_audit_is_truncated() { let r = ex(&mut s, "design.audit", json!({"scope": "page"})); assert_eq!(r["truncated"], true, "{r}"); assert_eq!(r["limit"], 50_000, "{r}"); + // Every rule the file enables is named as unchecked: the report says what it could not see, + // which is what the gate reads. + let unchecked = r["unchecked"].as_array().map(Vec::as_slice).unwrap_or_default(); + assert!(unchecked.len() >= 20, "{r}"); + assert!(unchecked.iter().all(|e| e["reason"] == "truncated"), "{r}"); + assert!(unchecked.iter().any(|e| e["rule"] == "color.contrast"), "{r}"); // The gate must not turn a truncated audit into a pass at score 100. let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).unwrap_err().to_string(); assert!(err.contains("stopped at the 50000-node limit"), "{err}"); @@ -874,6 +880,11 @@ fn assert_refuses_a_scope_whose_measured_checks_were_capped() { let only = json!(["layout.text-overflow"]); let audit = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); assert!(audit["textUnmeasured"].as_u64().unwrap_or(0) >= 1, "{audit}"); + // The report names the rule the cap left unmeasured, which is what the gate reads. + let unchecked = audit["unchecked"].as_array().map(Vec::as_slice).unwrap_or_default(); + assert_eq!(unchecked.len(), 1, "{audit}"); + assert_eq!(unchecked[0]["rule"], "layout.text-overflow", "{audit}"); + assert_eq!(unchecked[0]["reason"], "measure-cap", "{audit}"); let err = s.execute("design.assert", &json!({"scope": "page", "rules": &only})).unwrap_err().to_string(); assert!(err.contains("did not measure all of layout.text-overflow"), "{err}"); // A gate that does not ask for the capped rule is unaffected. @@ -884,6 +895,7 @@ fn assert_refuses_a_scope_whose_measured_checks_were_capped() { ex(&mut s, "design.configure", json!({"disabled": ["layout.text-overflow"]})); let audit = ex(&mut s, "design.audit", json!({"scope": "page"})); assert!(audit["textUnmeasured"].is_null(), "{audit}"); + assert!(audit["unchecked"].as_array().is_some_and(Vec::is_empty), "{audit}"); assert!(s.execute("design.assert", &json!({"scope": "page"})).is_ok(), "a disabled rule leaves nothing unchecked"); } From 15d0a4683c94f83bee36e9fa473b391533f64e74 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:48:53 +0800 Subject: [PATCH 034/268] M13: cap the disabled-rule list at the wire like radii and brand --- crates/collab/src/diff_tests.rs | 20 ++++++++++++++++- crates/collab/src/docprops.rs | 38 ++++++++++++++++++++------------- crates/doc/src/design_review.rs | 4 ++++ crates/doc/src/lib.rs | 2 +- 4 files changed, 47 insertions(+), 17 deletions(-) diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 31b445486..4aafc891c 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use std::sync::Arc; use figcraft_color::{Color, Paint}; -use figcraft_doc::{Comment, DesignPreset, DevSnapshot, Document, ImageData, Message, Node, NodeId, NodeKind, Style, StyleKind}; +use figcraft_doc::{Comment, DesignPreset, DevSnapshot, Document, ImageData, MAX_DISABLED, Message, Node, NodeId, NodeKind, Style, StyleKind}; use crate::change::{Change, DocProp, Entry, Json, Prop}; use crate::replica::{Mode, Replica}; @@ -87,6 +87,24 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() { assert_eq!(cfg.brand, vec![Color::from_rgb8_const(1, 2, 3); 32], "the brand colours keep their first 32"); } +#[test] +fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them() { + let (a, _, _, _) = setup(); + let mut b = a.document().clone(); + b.design_review.disabled = (0..200).map(|i| format!("rule.{i}")).collect(); + let mut r = a.clone(); + let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; + let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string(); + assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}"); + // A snapshot with a longer list opens with the ones that fit, not without the settings. + let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert_eq!(left_out, 0, "nothing needed leaving out"); + let cfg = &r2.document().design_review; + assert_eq!(cfg.disabled.len(), MAX_DISABLED, "the list keeps its first {MAX_DISABLED}"); + assert_eq!(cfg.disabled.first().map(String::as_str), Some("rule.0")); +} + #[test] fn creations_moves_reorders_and_deletions_round_trip() { let (a, page, frame, kids) = setup(); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index a0c0b6c7a..abdf8f3c8 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -403,20 +403,33 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result apply_indexed(doc, change, &mut Index::default()) } +/// The review-settings lists that hold more than this build keeps, as (what, how many, the cap). +fn review_lists_over_limit(c: &figcraft_doc::DesignReview) -> Vec<(&'static str, usize, usize)> { + [ + ("radii", c.radii.len(), figcraft_doc::MAX_RADII), + ("brand colours", c.brand.len(), figcraft_doc::MAX_BRAND_COLORS), + ("disabled rules", c.disabled.len(), figcraft_doc::MAX_DISABLED), + ] + .into_iter() + .filter(|(_, have, max)| have > max) + .collect() +} + /// Clamp the review settings a snapshot carries to the limits this build keeps, in place: an -/// older or looser snapshot may hold longer radii or brand lists, and the file opens with what -/// fits — the preset, grid and disabled rules exactly as saved. An ordinary edit is refused -/// instead (`apply_indexed`), and a peer that can't read the settings at all gets them left out -/// of what the server sends (`Change::without_design_review`). +/// older or looser snapshot may hold longer radii, brand or disabled lists, and the file opens +/// with what fits — the preset, grid and the rest of each list exactly as saved. An ordinary edit +/// is refused instead (`apply_indexed`), and a peer that can't read the settings at all gets them +/// left out of what the server sends (`Change::without_design_review`). pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) { for c in changes { if let Change::SetDoc { prop: DocProp::DesignReview, value } = c && let Ok(config) = value.read::("design review") - && (config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS) + && !review_lists_over_limit(&config).is_empty() { let mut clamped = config; clamped.radii.truncate(figcraft_doc::MAX_RADII); clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS); + clamped.disabled.truncate(figcraft_doc::MAX_DISABLED); if let Ok(v) = Json::of(&clamped) { *value = v; } @@ -431,18 +444,13 @@ pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Ind match change { Change::SetDoc { prop, value } => { // A peer's review settings stay inside the limits `design.configure` enforces, so an - // edit cannot smuggle in tens of thousands of radii or accents for every corner - // check to scan. An oversized value arrives only in an old snapshot: snapshots keep - // applying as they are. + // edit cannot smuggle in tens of thousands of radii, accents or rule ids for every + // check to scan. An oversized value arrives only in an old snapshot, and the snapshot + // path clamps it (`clamp_snapshot_design_review`). if *prop == DocProp::DesignReview { let config: figcraft_doc::DesignReview = value.read("design review")?; - if config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS { - return Err(Error::Invalid(format!( - "design review: {} radii and {} brand colours pass the {} limit `design.configure` keeps", - config.radii.len(), - config.brand.len(), - figcraft_doc::MAX_RADII - ))); + if let Some((what, have, max)) = review_lists_over_limit(&config).first() { + return Err(Error::Invalid(format!("design review: {have} {what} pass the {max} limit `design.configure` keeps"))); } } if set_scalar(doc, *prop, value)? { diff --git a/crates/doc/src/design_review.rs b/crates/doc/src/design_review.rs index c2fce64c8..002fe6d53 100644 --- a/crates/doc/src/design_review.rs +++ b/crates/doc/src/design_review.rs @@ -50,6 +50,10 @@ pub const GRID_MAX: f64 = 64.0; pub const MAX_RADII: usize = 32; pub const MAX_BRAND_COLORS: usize = 32; +/// Most rules a file turns off. The rule catalog is smaller than this: the cap keeps a hand-edited +/// or older file from carrying thousands of ids every review would read. +pub const MAX_DISABLED: usize = 64; + /// A file's design review settings. The default is the recommended preset on a 4px grid with the /// 4px radius scale and no brand palette. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c25d0e66e..957822479 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -33,7 +33,7 @@ pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; -pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII}; +pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_DISABLED, MAX_RADII}; pub use facilitation::*; pub use figcraft_color as color; pub use figcraft_geom as geom; From 254766471d6c16f6ddbc4f50a5c844a99f1f28a7 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 23:45:13 -0500 Subject: [PATCH 035/268] M8: a scale by one keeps a plain layer's length bindings (#2090) A Scale tool drag back to where it started restores its snapshot and scales by exactly one, which changes no length, but scale_node still dropped the plain layers' length bindings. A scale by one now returns before touching anything. Test: scale_bound_values_tests::a_scale_by_one_keeps_a_plain_frames_bindings (failed before: the gap binding was gone). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/engine/src/cmd/arrange.rs | 5 +++++ crates/engine/src/scale_bound_values_tests.rs | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 57ed10a50..92c890094 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -456,6 +456,11 @@ pub fn scale_node(doc: &mut Document, id: NodeId, k: f64) -> Result<()> { if !scale_fits(doc, id, k) { return Err(scale_range_error()); } + // A scale by one changes no length, so it keeps every binding: a Scale tool drag back to where it + // started scales by exactly one, and must not unbind the lengths it never changed. + if (k - 1.0).abs() <= f64::EPSILON { + return Ok(()); + } let sub = doc.subtree(id); // The layers below `id` scale whatever their constraints, so where they are layers of an // instance their new size and place are overrides. The edit's own diff takes geometry that diff --git a/crates/engine/src/scale_bound_values_tests.rs b/crates/engine/src/scale_bound_values_tests.rs index c6e7244cf..b408e5ec6 100644 --- a/crates/engine/src/scale_bound_values_tests.rs +++ b/crates/engine/src/scale_bound_values_tests.rs @@ -116,6 +116,18 @@ fn a_file_with_a_scaled_instance_keeps_its_factor_and_bound_gap_after_save_and_o healthy(&back); } +#[test] +fn a_scale_by_one_keeps_a_plain_frames_bindings() { + // A Scale tool drag back to where it started scales by exactly one: no length changes, so no + // binding is dropped. + let mut s = Session::new(); + let (f, a) = bound_row(&mut s); + ex(&mut s, "transform.scale", json!({"ids": [f], "factor": 1})); + assert!(node(&s, f).bound.contains_key("gap"), "{:?}", node(&s, f).bound); + assert!(node(&s, a).bound.contains_key("cornerRadius"), "{:?}", node(&s, a).bound); + healthy(&s); +} + #[test] fn scaling_a_plain_frame_bakes_its_bound_gap_and_drops_the_binding() { let mut s = Session::new(); From 8a97d40b0a3429e5a8237360469388c89cf22687 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 13 Nov 2026 22:38:36 +0700 Subject: [PATCH 036/268] i18n: Spanish labels for the Mind map tool --- crates/ui-egui/locales/es.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index 5a65c5524..380fe038d 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -37,6 +37,7 @@ status = "draft — needs native review" "Couldn't download {name}" = "No se pudo descargar {name}" "Create from color" = "Crear a partir del color" "Invert zoom direction" = "Invertir la dirección del zoom" +"Mind map" = "Mapa mental" "New collection" = "Nueva colección" "Delete results" = "Eliminar resultados" "Pasted design layers" = "Capas de diseño pegadas" @@ -2381,6 +2382,7 @@ status = "draft — needs native review" "tool.highlighter" = "Resaltador" "tool.line" = "Línea" "tool.marker" = "Rotulador" +"tool.mindMap" = "Herramienta de mapa mental" "tool.move" = "Mover" "tool.pen" = "Pluma" "tool.pencil" = "Lápiz" From 94d7289f66c4f69c5105c7da960b1071116fb2dd Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 13:34:49 -0500 Subject: [PATCH 037/268] M12: docs/mcp.md keeps one Select entry, with the mind map sibling note (#2226) The last merge of main kept both versions of the Select bullet. Main's bullet (locked layers listed, the locked flag) stays, and takes this PR's note that Tab and Shift+Tab on a mind map node go to its next or previous sibling. Co-Authored-By: Claude Opus 5.5 --- docs/mcp.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 5187945a0..2e4bf1d54 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2088,12 +2088,9 @@ turned off 0°. `node.set {pointCount}` keeps stars to 3–60 points; `miterAngle` (degrees, the Design panel's Miter angle) sets the miter limit (`limit = 1 / sin(angle / 2)`); `get_node` reports a join other than miter (`strokeJoin`) or a miter angle other than the default ~28.96° (`miterAngle`). -- **Select**: `select.layersAt {x, y}` lists every layer under a page point, front-most first with its - depth (the context menu's Select layer); `select.set`, `select.children` / `select.parent` (Enter - / Shift+Enter), `select.next` / `select.previous` (Tab / Shift+Tab; on a board, a mind map node's next or previous sibling). With `pointer`, `cmd: true` - **Select**: `select.layersAt {x, y}` lists every layer under a page point, locked ones too, front-most first with its depth and a `locked` flag (true when the layer or an ancestor is locked; the context menu's Select layer); `select.set`, `select.children` / `select.parent` (Enter - / Shift+Enter), `select.next` / `select.previous` (Tab / Shift+Tab). With `pointer`, `cmd: true` + / Shift+Enter), `select.next` / `select.previous` (Tab / Shift+Tab; on a board, a mind map node's next or previous sibling). With `pointer`, `cmd: true` clicks select the nested layer, `cmd` drags from empty canvas select the nested layers they touch, and `shift` drags toggle what they touch. A press on the background of a top-level frame with layers in it (the frame not selected) starts a marquee, as on the canvas; an empty frame From 225361381bb19f926a6bd82d4c71f3f27baa07e4 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 14:38:14 -0500 Subject: [PATCH 038/268] Fix a connector clause the docs merge script duplicated in the boards Design panel row Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- docs/boards-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/boards-parity.md b/docs/boards-parity.md index e44673ffd..4a1b2cdbd 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -28,7 +28,7 @@ all end with the same geometry. |---|---|---| | Board files: File ▸ New board, the home screen's New board card, a light page | done | `file.newBoard`; the kind shows in `inspect_document`, tabs and file rows (a note mark; design files a pen nib) | | Board toolbar at the bottom | done | Move/Hand, Marker/Highlighter/Eraser, Sticky (colour flyout), Shapes (flyout, the mind map at its end), Connector, Text, Section, Stamp (flyout), Comment, Actions, then the templates and the Design panel's buttons — on the same 32 pt grid as a design file's (no Resources button, as there) | -| Design panel hidden by default; a contextual bar above the selection | done | colour, shape, text size (S/M/L/XL for shapes and labels; a size menu, Small to Huge, for stickies); for connectors straight/elbow/curved, the start and end points (none, round, square, line arrow, triangle arrow, reversed triangle, circle, diamond), solid or dashed, the weight, and any colour in the colour picker beside the board colours (#1596)); for connectors straight/elbow/curved, the start and end points (none, round, square, line arrow, triangle arrow, reversed triangle, circle, diamond), solid or dashed, the weight, and any colour in the colour picker beside the board colours (#1596); a mind map node takes the colours as its text colour and the text sizes; a branch has the connector's controls without the line types; each control says what it is on hover; the Design panel opens with its button or View ▸ Design panel | +| Design panel hidden by default; a contextual bar above the selection | done | colour, shape, text size (S/M/L/XL for shapes and labels; a size menu, Small to Huge, for stickies); for connectors straight/elbow/curved, the start and end points (none, round, square, line arrow, triangle arrow, reversed triangle, circle, diamond), solid or dashed, the weight, and any colour in the colour picker beside the board colours (#1596); a mind map node takes the colours as its text colour and the text sizes; a branch has the connector's controls without the line types; each control says what it is on hover; the Design panel opens with its button or View ▸ Design panel | | Prototyping and Developer Mode refuse on boards | done | `proto.*`, `dev.*`, `view.prototype`, `view.devMode` say why | | Sticky notes | done | a square frame (200 wide, growing taller through auto layout), 8 soft colours, a soft shadow, the note's text 16 by default (FigJam's "Small", read twice from its size field, 2026-11-12) and fixed as it fills: the note grows taller and never shrinks its text (2026-11-09, #2157); a size menu in the contextual bar (Small 16, Medium 24, Large 40, Extra large 64, Huge 96; a number when the size matches none) sets every selected sticky, the note grows taller when Huge no longer fits and shrinks back to square at Large, and the sticky tool remembers the last size for new stickies, all measured in FigJam's web app, 2026-11-12; stickies saved with another size keep it, the author's name at the bottom; a click places one and starts typing; Enter or a double-click edits; Shift+Cmd/Ctrl+Enter adds the next one beside it | | Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; size presets done (the bar's menu, `board.setStyle {fontSize}`, `board.sticky {fontSize}`); no stacks | From 258bf152573bb5e8a52b7dc152a5063b6da7da05 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 14:50:23 -0500 Subject: [PATCH 039/268] Docs: drop the old Scale tool row main already removed, keeping main's Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- docs/ui-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 231793714..f78306190 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -74,7 +74,6 @@ interaction feel only partly compared: the interactions measured so far, case by | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | A dragged layer moves with its outline | partial | #2033: the canvas image is the last render the worker finished, so a drag's content trailed its outline by a render per pointer move (63 ms, about 3.6 frames, and 150 px on screen with drop shadows on 200 layers). While a gesture only translates plain layers (Normal or pass-through blend, no effects on them or above them, not masks, not in a boolean group or beside a mask, no ancestor under 100 percent opacity; their own children may have effects) the layers are rendered once into a texture of their own (the sprite), the base is rendered once without them from the document the drag started from and then asks for no more renders, and the sprite is drawn each frame at the same shifted place as the selection outline. On release, Escape or a zoom change the document is rendered whole again and the sprite stays until that image is shown. Desktop only (the browser renders in the same frame). Trade-offs while dragging: the sprite draws above everything (z-order is lost), blends and backdrop blurs against what is behind are approximated, ancestors' clips are applied as their bounding boxes, and a sprite wider than the texture limit or over four canvases of pixels, outline and focus views, pixel preview and soft proof keep the old way (`canvas/drag_sprite.rs`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Scale tool (K): handles about the opposite handle, live factor, panel | done | Dragging a handle ignores the origin grid and pivots on the opposite handle's point (the opposite corner, or the opposite edge's middle for an edge, which scales both ways), with Alt on the centre; the origin grid (`tool.scaleAnchor`) starts at the centre and sets only what the Scale field and the W and H fields keep fixed (W and H with a non-centre origin are unmeasured). Measured in Figma's web app, 2026-11-09. Tests: `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`. Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin, which starts at the centre, as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | From 148ab21e28b8920ec834532a5602f48690c52562 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 14:50:34 -0500 Subject: [PATCH 040/268] Docs: drop the old Scale tool row main already removed, keeping main's Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- docs/ui-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a9c2868f3..c3aa74496 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -73,7 +73,6 @@ interaction feel only partly compared: the interactions measured so far, case by | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`.variable-bound lengths: an instance keeps its bindings and draws them at the variable's value times its scale factor (a field of the instance, kept through rebuilds and saves); other layers keep the scaled value and drop the binding of each layer-level length scaled: size, gaps, padding, radii, stroke weights, min and max sizes and the layer's text sizes (#2090); only the gap was measured in the incumbent, the other lengths are assumed to follow it. Not yet: `.fig` import does not set the factor, so bound lengths on an imported scaled instance go back to the variable's value at its first edit; effect, layout grid and text-run bindings are neither multiplied nor dropped, so on any scaled layer they go back to the variable's value at the next bindings pass; a layer scaled inside an instance keeps its bindings, so its bound lengths stay at the variable's value (unmeasured in the incumbent); a nested instance scaled inside an instance copy loses its factor when the copy is rebuilt; a scale that would take an instance past 0.001 to 1000 times is refused | | Scale tool (K): handles about the opposite handle, live factor, panel | done | Dragging a handle ignores the origin grid and pivots on the opposite handle's point (the opposite corner, or the opposite edge's middle for an edge, which scales both ways), with Alt on the centre; the origin grid (`tool.scaleAnchor`) starts at the centre and sets only what the Scale field and the W and H fields keep fixed (W and H with a non-centre origin are unmeasured). Measured in Figma's web app, 2026-11-09. Tests: `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`. Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin, which starts at the centre, as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | From a50fd45f8189876de5ad72eed4e08885c130dba0 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:11:27 +0100 Subject: [PATCH 041/268] M8: require a host before opening document web links Reject empty, userinfo-only and port-only hosts while retaining the existing scheme and character policy. --- crates/engine/src/automation/doc_urls.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/automation/doc_urls.rs b/crates/engine/src/automation/doc_urls.rs index 8b7d83199..2e517f982 100644 --- a/crates/engine/src/automation/doc_urls.rs +++ b/crates/engine/src/automation/doc_urls.rs @@ -55,5 +55,9 @@ pub fn openable(url: &str) -> bool { // The authority is made of host characters only (an opener that can't parse the address may // fall back to treating it as a file path). let authority = after.split(['/', '?', '#']).next().unwrap_or_default(); - authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c)) + // A query, fragment, userinfo or port alone does not supply a host. + let host = authority.rsplit('@').next().unwrap_or_default(); + !host.is_empty() + && !host.starts_with(':') + && authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c)) } From 3b86d2515d0f64c16d775384eb51e6d78c1e14c8 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:12:12 +0100 Subject: [PATCH 042/268] M8: cover document links without a host Cover empty authority, userinfo-only and port-only addresses alongside valid query, fragment and IPv6 links. --- crates/engine/src/doc_urls_tests.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/engine/src/doc_urls_tests.rs b/crates/engine/src/doc_urls_tests.rs index 7158eae06..923cbb6cb 100644 --- a/crates/engine/src/doc_urls_tests.rs +++ b/crates/engine/src/doc_urls_tests.rs @@ -9,17 +9,27 @@ fn web_links_are_opened() { "http://example.com", "https://example.com", "https://example.com/a/b?c=d#e", + "https://example.com?c=d", + "https://example.com#e", "HTTPS://EXAMPLE.COM", "HtTp://example.com", "mailto:a@b.c", "mailto:a@b.c?subject=hi", " https://example.com ", "https://user:pw@example.com:8443/p", + "https://user:pw@[::1]:8443/p", ] { assert!(openable(url), "{url:?} should open"); } } +#[test] +fn web_links_without_a_host_are_refused() { + for url in ["https://?c=d", "http://#e", "https://user@", "https://user@:443/p", "https://:443/p", "https://user:pw@?c=d", "https://@#e"] { + assert!(!openable(url), "{url:?} must be refused"); + } +} + #[test] fn script_and_handler_schemes_are_refused() { for url in [ From 7a0d6722f02098c42c4e371fdeab41d0db5d9a85 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:12:41 +0100 Subject: [PATCH 043/268] M8: record document web-link host validation Record the host-presence correction and covered valid links without changing parity estimates. --- ROADMAP.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 54921fb11..f6e34738b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (document HTTP(S) links without a host are refused before opening; a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-15 | patch | Document HTTP(S) links without a host are refused before opening; regressions retain valid query, fragment, IPv6 and mail links. | | 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-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | From 59437c776bd0aa767118a700cd572328745cb8db Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:24:44 +0100 Subject: [PATCH 044/268] M0.9: reject repeated CLI scale suffixes Accept at most one optional x suffix and cover malformed scales as usage errors for both export and render. --- apps/figcraft-cli/src/args.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index 4696b8664..e6b4aab0f 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -290,7 +290,7 @@ enum ValueError { } fn scale(s: &str) -> Result { - s.trim_end_matches('x').parse::().ok().filter(|v| v.is_finite() && *v > 0.0 && *v <= 64.0).ok_or(ValueError::Scale) + s.strip_suffix('x').unwrap_or(s).parse::().ok().filter(|v| v.is_finite() && *v > 0.0 && *v <= 64.0).ok_or(ValueError::Scale) } fn bleed(s: &str) -> Result { @@ -487,6 +487,13 @@ mod tests { assert!(try_parse(&["commands"]).is_ok_and(|cli| !cli.no_system_fonts)); } + #[test] + fn scale_accepts_numbers_and_one_optional_suffix() { + for (value, want) in [("0.5", 0.5), ("0.5x", 0.5), ("2", 2.0), ("2x", 2.0), ("64", 64.0), ("64x", 64.0)] { + assert_eq!(super::scale(value).ok(), Some(want), "{value}"); + } + } + #[test] fn bad_arguments_are_usage_errors() { use ErrorKind::{ @@ -505,6 +512,8 @@ mod tests { (&["export", "a", "-o", "b", "--scale", "0"], ValueValidation), (&["export", "a", "-o", "b", "--scale", "-3"], ValueValidation), (&["export", "a", "-o", "b", "--scale", "65"], ValueValidation), + (&["export", "a", "-o", "b", "--scale", "2xx"], ValueValidation), + (&["render", "a", "-o", "b", "--scale", "2xxx"], ValueValidation), (&["export", "a", "-o", "b", "--bleed", "lots"], ValueValidation), (&["export", "a", "-o", "b", "--bleed", "3in"], ValueValidation), (&["export", "a", "-o", "b", "--vd-compat", "sloppy"], ValueValidation), From 9406ec18128bd4f97950afba4788d634c896db55 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 23:12:58 +0530 Subject: [PATCH 045/268] Text: a fixed-size text keeps the height it is created with (#2184) --- crates/engine/src/cmd/create.rs | 14 +++++++++ crates/engine/src/text_behaviour_tests.rs | 36 +++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 435c3422a..9af5e295b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -372,6 +372,20 @@ pub fn create(s: &mut Session, p: &Value) -> Result { if let Some(Value::Object(props)) = get(p, "props") { super::props::apply(cmd, doc, nid, props)?; } + // A fixed-size text (auto-resize `none`/`truncate` in `props`) is measured as auto-height + // before `props` are applied, so the measured height overwrites the top-level `height`. Put + // the top-level `height` back through the normal command path, unless `props` set a height + // of their own (which wins). + if let Some(h) = num(p, "height") + && get(p, "props").and_then(Value::as_object).is_none_or(|o| !o.contains_key("height") && !o.contains_key("h")) + && doc.node(nid).is_some_and(|n| { + matches!(&n.kind, NodeKind::Text(t) if matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate)) + }) + { + let mut fixed = serde_json::Map::new(); + fixed.insert("height".into(), json!(h)); + super::props::apply(cmd, doc, nid, &fixed)?; + } if boolean(p, "select").unwrap_or(true) { ds.selection = vec![nid]; } diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index 74a013e90..40837bb37 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -338,6 +338,42 @@ fn a_truncated_text_keeps_truncating_when_its_box_is_resized() { assert_eq!(resize_mode(&s, plain), TextAutoResize::None); } +#[test] +fn a_fixed_size_text_keeps_the_height_it_is_created_with() { + // #2184: a fixed-size text created with a top-level `height` keeps it; `props` are applied + // after the text is measured, so the measured height used to overwrite it. + use figcraft_doc::TextAutoResize; + let font = test_mono_font(); + let mut s = Session::new(); + let style = || json!({"fontFamily": font, "fontSize": 16, "lineHeight": 24}); + let create = |s: &mut Session, params: Value| id(s.execute("node.create", ¶ms).unwrap()); + let mut base_style = style().as_object().unwrap().clone(); + for (mode, want) in [("none", TextAutoResize::None), ("truncate", TextAutoResize::Truncate)] { + base_style.insert("textAutoResize".into(), json!(mode)); + let t = create( + &mut s, + json!({"type": "text", "text": "Title", "width": 200, "height": 100, "props": Value::Object(base_style.clone())}), + ); + assert_eq!(size(&s, t), (200.0, 100.0), "mode {mode}"); + assert_eq!(resize_mode(&s, t), want, "mode {mode} stays"); + } + // A `height` inside `props` wins over the top-level one. + let mut props = style().as_object().unwrap().clone(); + props.insert("textAutoResize".into(), json!("none")); + props.insert("height".into(), json!(30)); + let t = create(&mut s, json!({"type": "text", "text": "Title", "width": 200, "height": 100, "props": Value::Object(props)})); + assert_eq!(size(&s, t).1, 30.0, "props height wins"); + assert_eq!(resize_mode(&s, t), TextAutoResize::None); + // Auto-height text still measures its own height, ignoring the top-level one. + let t = create(&mut s, json!({"type": "text", "text": "Title", "width": 200, "height": 100, "props": style()})); + assert_eq!(resize_mode(&s, t), TextAutoResize::Height); + assert_eq!(size(&s, t), (200.0, 24.0), "one line tall, not 100"); + // Auto-width text still measures both sides. + let t = create(&mut s, json!({"type": "text", "text": "Title", "height": 100, "props": style()})); + assert_eq!(resize_mode(&s, t), TextAutoResize::WidthAndHeight); + assert_eq!(size(&s, t), (40.0, 24.0), "as wide as its line and one line tall"); +} + #[test] fn max_lines_on_auto_height_text_hugs_that_many_lines() { // #1377: an auto-height text with max lines grows up to that many lines and ends in an From a7f1091e74213b59947b0c7a27c05184ea958754 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 23:27:17 +0530 Subject: [PATCH 046/268] Text: creating text warns when its font style draws in another face (#2180) --- crates/engine/src/cmd/create.rs | 9 ++++- crates/engine/src/cmd/edit.rs | 1 + crates/engine/src/cmd/edit/props.rs | 2 +- crates/engine/src/node_set_refusals_tests.rs | 39 ++++++++++++++++++++ crates/mcp/src/tools.rs | 9 ++++- crates/mcp/tests/it/create_warnings.rs | 37 +++++++++++++++++++ crates/mcp/tests/it/main.rs | 2 + docs/mcp.md | 2 +- 8 files changed, 96 insertions(+), 5 deletions(-) create mode 100644 crates/mcp/tests/it/create_warnings.rs diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 435c3422a..633281a16 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -372,10 +372,17 @@ pub fn create(s: &mut Session, p: &Value) -> Result { if let Some(Value::Object(props)) = get(p, "props") { super::props::apply(cmd, doc, nid, props)?; } + // A `fontStyle` the family lacks draws in its nearest face, the same as `node.set` says. + let warnings = match get(p, "props") { + Some(Value::Object(props)) if doc.node(nid).is_some_and(|n| n.kind.text().is_some()) => { + super::edit::font_style_warnings(doc, &[nid], props) + } + _ => Vec::new(), + }; if boolean(p, "select").unwrap_or(true) { ds.selection = vec![nid]; } - Ok(json!({"id": nid})) + if warnings.is_empty() { Ok(json!({"id": nid})) } else { Ok(json!({"id": nid, "warnings": warnings})) } } fn frame_create(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 29b0f63a8..8980d94d6 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -15,6 +15,7 @@ use crate::{BatchStep, EngineError, Result, Session, bad, spec}; mod clipboard; mod props; +pub(crate) use props::font_style_warnings; pub(crate) use props::{edit_region_fills, fill_regions}; mod select; mod vector_clipboard; diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index c39f8abe2..1478a8551 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -189,7 +189,7 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result { /// face has another weight or slant than the name asks for ("Black" on a family whose heaviest is /// Bold), say which face it is. Families that aren't installed, and names that match a style or a /// named instance (spelled any way: "SemiBold", "Semi Bold"), say nothing. -fn font_style_warnings(doc: &figcraft_doc::Document, ids: &[NodeId], props: &serde_json::Map) -> Vec { +pub(crate) fn font_style_warnings(doc: &figcraft_doc::Document, ids: &[NodeId], props: &serde_json::Map) -> Vec { let Some(style) = props.get("fontStyle").and_then(Value::as_str) else { return Vec::new() }; let mut families: Vec = match props.get("fontFamily").and_then(Value::as_str) { Some(f) => vec![f.to_string()], diff --git a/crates/engine/src/node_set_refusals_tests.rs b/crates/engine/src/node_set_refusals_tests.rs index ce316d301..b48474fd3 100644 --- a/crates/engine/src/node_set_refusals_tests.rs +++ b/crates/engine/src/node_set_refusals_tests.rs @@ -84,6 +84,45 @@ fn a_font_style_draws_in_the_nearest_face_and_says_so_when_it_differs() { assert!(out.get("warnings").is_none(), "{out}"); } +#[test] +fn creating_text_in_a_font_style_the_family_lacks_says_so_as_node_set_does() { + figcraft_text::scan_system_fonts(); + // Any installed family with a regular and a bold face and nothing heavier (CI machines differ). + let pick = figcraft_text::family_names().into_iter().find_map(|f| { + let st = figcraft_text::family_styles(&f); + let has = |w: u16| st.iter().any(|x| figcraft_doc::style_weight(x) == w && !x.to_lowercase().contains("italic")); + (has(400) && has(700) && !st.iter().any(|x| figcraft_doc::style_weight(x) > 700)).then_some((f, st)) + }); + let Some((family, styles)) = pick else { return }; + let mut s = Session::new(); + let asked = || json!({"fontFamily": family, "fontStyle": "Black"}); + // `node.create` warns the same as `node.set` does. + let out = ex(&mut s, "node.create", json!({"type": "text", "text": "Hi", "props": asked()})); + let w = out["warnings"][0].as_str().unwrap(); + assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}"); + // `text.create` says so too. + let out = ex(&mut s, "text.create", json!({"text": "Hi", "props": asked()})); + let w = out["warnings"][0].as_str().unwrap(); + assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}"); + // So does a `command.batch` step, at the step that creates the text. + let out = ex( + &mut s, + "command.batch", + json!({"commands": [{"command": "node.create", "params": {"type": "text", "text": "Hi", "props": asked()}}]}), + ); + let w = out[0]["warnings"][0].as_str().unwrap(); + assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}"); + // A style the family has says nothing, and the result is `{id}` alone as before. + let bold = styles.iter().find(|x| figcraft_doc::style_weight(x) == 700).unwrap().clone(); + let out = ex(&mut s, "node.create", json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": bold}})); + assert!(out.get("warnings").is_none(), "{out}"); + assert_eq!(out.as_object().unwrap().len(), 1, "{out}"); + // A layer without text says nothing either. + let out = ex(&mut s, "node.create", json!({"type": "rectangle", "props": {"fill": "#FF0000"}})); + assert!(out.get("warnings").is_none(), "{out}"); + assert_eq!(out.as_object().unwrap().len(), 1, "{out}"); +} + #[test] fn a_refused_call_changes_nothing() { let mut s = Session::new(); diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 9a546dc2a..f708b613b 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -183,7 +183,7 @@ fn tools() -> Vec { tool( "create_node", "Create layer", - "Create a layer (engine `node.create`) and return its id and inspected properties. Coordinates are page units, y down; x/y are relative to the parent frame (the page when there is none, so then they are page coordinates; groups don't count). Inside an auto-layout frame the position is decided by the layout. The new layer becomes the selection.", + "Create a layer (engine `node.create`) and return its id and inspected properties. Coordinates are page units, y down; x/y are relative to the parent frame (the page when there is none, so then they are page coordinates; groups don't count). Inside an auto-layout frame the position is decided by the layout. The new layer becomes the selection. `warnings` reports a fontStyle that draws in another face.", obj( json!({ "type": {"type": "string", "enum": ["frame", "rectangle", "ellipse", "polygon", "star", "line", "arrow", "text", "vector", "section", "component", "slice"], "description": "Layer type"}, @@ -687,8 +687,13 @@ fn create_node(b: &mut dyn Backend, a: &Map) -> Result) -> Result { diff --git a/crates/mcp/tests/it/create_warnings.rs b/crates/mcp/tests/it/create_warnings.rs new file mode 100644 index 000000000..3971c861f --- /dev/null +++ b/crates/mcp/tests/it/create_warnings.rs @@ -0,0 +1,37 @@ +use crate::common::Client; +use serde_json::json; + +#[test] +fn create_node_reports_a_font_style_drawn_in_another_face() { + let mut c = Client::new(); + // The headless server indexes system fonts lazily; make sure that walk has happened. + let _ = c.run("text.rescanFonts", json!({})); + // Any installed family with a regular and a bold face and nothing heavier (CI machines differ). + let names = c.run("text.fonts", json!({})); + let pick = names + .as_array() + .cloned() + .unwrap_or_default() + .into_iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .find_map(|f| { + let styles: Vec = c + .run("text.fonts", json!({"family": f})) + .as_array() + .cloned() + .unwrap_or_default() + .into_iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect(); + let has = |w: u16| styles.iter().any(|x| figcraft_doc::style_weight(x) == w && !x.to_lowercase().contains("italic")); + (has(400) && has(700) && !styles.iter().any(|x| figcraft_doc::style_weight(x) > 700)).then_some(f) + }); + let Some(family) = pick else { return }; + let out = c.ok("create_node", json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": "Black"}})); + let w = out["warnings"][0].as_str().unwrap(); + assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}"); + // `set_properties` still says so too. + let out = c.ok("set_properties", json!({"ids": [out["id"].clone()], "props": {"fontStyle": "Black"}})); + let w = out["warnings"][0].as_str().unwrap(); + assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}"); +} diff --git a/crates/mcp/tests/it/main.rs b/crates/mcp/tests/it/main.rs index 7d5195fe7..88c5045f4 100644 --- a/crates/mcp/tests/it/main.rs +++ b/crates/mcp/tests/it/main.rs @@ -11,6 +11,8 @@ mod automation_roots; #[allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod common; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod create_warnings; +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod export_hidden_roots; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod export_profile; diff --git a/docs/mcp.md b/docs/mcp.md index 9b44a0c55..1b1e88554 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -382,7 +382,7 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match. | `list_commands {filter?}` | Every command: id, label, menu, shortcut, undoable, params doc. | | `run_command {command, params}` | Run any command (e.g. `align.left`, `layout.add`, `component.create`, `instance.place` (drop an instance at a page point into the frame or auto layout slot under it), `component.exposeInstance` / `instance.exposed` (nested instance properties on instances), `component.makeSlot` / `instance.slotInsert` / `instance.resetSlot` (slots, below), `inspect.code` (CSS, HTML + CSS for a whole frame, React, Leptos, Vue, SwiftUI, Jetpack Compose, ArkUI or Flutter for a layer; components take their properties as parameters and instances are calls, see Developer Mode below), `inspect.properties` (layout, auto layout, typography, fills, strokes and effects with their style and variable names; `colorFormat`: hex, rgb, css, hsl or hsb), `inspect.assets` (layers under the selection with export settings, icons and images, each with its `kind`), `inspect.code` takes `unit: rem` and `rootFontSize` for CSS, HTML, React, Leptos and Vue, `style.create`, `variable.bind`, `variable.update` (rename, describe, scope), `variable.set` with `{alias}` or a colour calculation (`{alpha}`, `{mix}`), `variable.renameMode` / `variable.removeMode`, `variable.deleteCollection`, `proto.interaction.add`, `codeConnect.set` (components linked to real code, see Developer Mode below)). | | `batch {commands: [{command, params}], label?}` | Several commands as one undo step (`command.batch`), which keeps one copy of the document however many steps there are (an `edit.undo` step undoes the batch's edits so far together); all-or-nothing for open documents and their document state. Failed inner commands are removed from the journal; preferences, clipboard, tool state and UI requests are not rolled back. A step can use what an earlier step returned: name it with `"as": "card"` and `{"$ref": "card"}` anywhere in a later step's params becomes the `id` in its result (`{"$step": n}` does the same by zero-based position); `"field"` takes another key or a slash path such as `ids/0` (see Step references below). | -| `create_node {type, x, y, width, height, parent, index, name, text, path, props}` | Create a frame, rectangle, ellipse, polygon, star, line, arrow, text, vector, section, component or slice; returns `{id, node}`. | +| `create_node {type, x, y, width, height, parent, index, name, text, path, props}` | Create a frame, rectangle, ellipse, polygon, star, line, arrow, text, vector, section, component or slice; returns `{id, node}`. `warnings` reports a fontStyle that draws in another face. | | `set_properties {ids, props}` | `node.set` on layers (geometry, fills, strokes, effects, corner radius, auto layout, sizing, constraints, masks (`isMask`, `maskType: alpha\|vector\|luminance`), handoff status (`devStatus: none\|readyForDev\|completed`; marking again clears "Changed"), a section's `sectionContentsHidden`, text…); returns the updated layers. | | `inspect_document {depth, allPages, fields?, outline?}` | The document as JSON (its `id`, layer tree, styles, selection, history); `fields` selects layer properties, `outline: true` gives a compact tree (below). The tools that act on a document also take `document` (see Naming the document below). | | `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. | From 5e507f3721457522289e875970ac04300a913e57 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 23:39:00 +0530 Subject: [PATCH 047/268] Variables: variable.bind and aliases resolve Collection/name (#2373) --- crates/engine/src/cmd/styles.rs | 5 +++-- crates/engine/src/cmd/variables.rs | 6 +++--- crates/engine/src/variable_props_tests.rs | 17 +++++++++++++---- crates/engine/src/variables_behaviour_tests.rs | 12 ++++++++++++ 4 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 710eec76e..740f7ed0b 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -852,7 +852,7 @@ pub fn bind(s: &mut Session, p: &Value) -> Result { let ids = req_targets(cmd, s, p)?; let doc = s.doc_mut()?; let vid = match &var { - Some(v) => Some(doc.variables.get(v).map(|x| x.id.clone()).ok_or_else(|| bad(cmd, "no such variable"))?), + Some(v) => Some(super::variables::resolve_strict(cmd, doc, v)?), None => None, }; bind_variable(cmd, doc, &ids, &field, vid.as_deref())?; @@ -1028,7 +1028,8 @@ fn var_create(s: &mut Session, p: &Value) -> Result { // variable yet, so they can't loop). for val in values.values_mut() { if let VariableValue::Alias(a) = val { - let t = doc.variables.get(a).filter(|t| t.kind == kind).ok_or_else(|| bad(cmd, format!("no {} variable `{a}` to alias", kind.id())))?; + let id = super::variables::resolve_strict(cmd, doc, a)?; + let t = doc.variables.get_by_id(&id).filter(|t| t.kind == kind).ok_or_else(|| bad(cmd, format!("no {} variable `{a}` to alias", kind.id())))?; *a = t.id.clone(); } } diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index d8c20e05a..2f64ea186 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -53,9 +53,9 @@ pub fn specs() -> Vec { ] } -/// Props resolve an exact id first, then an unambiguous exact name or `Collection/name`. Compare -/// whole names: both collection and variable names can contain `/`. Other commands keep their -/// existing first-match lookup. +/// Props, `variable.bind` and `variable.create` aliases resolve an exact id first, then an +/// unambiguous exact name or `Collection/name`. Compare whole names: both collection and variable +/// names can contain `/`. Other commands keep their existing first-match lookup. pub(crate) fn resolve_strict(cmd: &str, doc: &Document, name: &str) -> Result { let vars = &doc.variables; if let Some(v) = vars.variables.iter().find(|v| v.id == name) { diff --git a/crates/engine/src/variable_props_tests.rs b/crates/engine/src/variable_props_tests.rs index 2bcb12d5b..0fdc69133 100644 --- a/crates/engine/src/variable_props_tests.rs +++ b/crates/engine/src/variable_props_tests.rs @@ -61,8 +61,11 @@ fn ambiguous_and_unknown_variable_names_are_errors_but_ids_still_work() { assert_bound(&s, id, "fill", &vid); let e = s.execute("node.set", &json!({"id": id, "props": {"fill": {"$var": "missing/surface"}}})).unwrap_err().to_string(); assert!(e.contains("no such variable `missing/surface`"), "{e}"); - // The existing command still uses the first match, not the new strict resolver. - run(&mut s, "variable.bind", json!({"id": id, "field": "fill", "variable": "palette/surface"})); + // `variable.bind` shares the layer props' strict resolver: a bare ambiguous name is refused + // and a `Collection/name` binds the variable it names. + let e = s.execute("variable.bind", &json!({"id": id, "field": "fill", "variable": "palette/surface"})).unwrap_err().to_string(); + assert!(e.contains("ambiguous variable `palette/surface`"), "{e}"); + run(&mut s, "variable.bind", json!({"id": id, "field": "fill", "variable": "Theme/palette/surface"})); assert_bound(&s, id, "fill", &vid); } @@ -77,9 +80,15 @@ fn variable_ids_choose_between_variables_with_the_same_name() { let id = create(&mut s, json!({"fill": {"$var": second}})); assert_eq!(s.doc().unwrap().node(id).unwrap().bound.get("fill"), Some(&second)); assert_eq!(color(&s, id, "fill").to_hex(), "FF0000"); - // `variable.bind` deliberately keeps its first id-or-name match. - run(&mut s, "variable.bind", json!({"id": id, "field": "fill", "variable": "palette/surface"})); + // `variable.bind` uses the same strict resolver as layer props: a bare ambiguous name is + // refused and qualified names choose between the variables sharing it. + let e = s.execute("variable.bind", &json!({"id": id, "field": "fill", "variable": "palette/surface"})).unwrap_err().to_string(); + assert!(e.contains("ambiguous variable `palette/surface`"), "{e}"); + run(&mut s, "variable.bind", json!({"id": id, "field": "fill", "variable": "Theme/palette/surface"})); assert_bound(&s, id, "fill", &first); + run(&mut s, "variable.bind", json!({"id": id, "field": "fill", "variable": "Other/palette/surface"})); + assert_eq!(s.doc().unwrap().node(id).unwrap().bound.get("fill"), Some(&second)); + assert_eq!(color(&s, id, "fill").to_hex(), "FF0000"); run(&mut s, "node.set", json!({"id": id, "props": {"fill": {"$var": second}}})); assert_eq!(s.doc().unwrap().node(id).unwrap().bound.get("fill"), Some(&second)); assert_eq!(color(&s, id, "fill").to_hex(), "FF0000"); diff --git a/crates/engine/src/variables_behaviour_tests.rs b/crates/engine/src/variables_behaviour_tests.rs index 2717726f8..3f9fd85b6 100644 --- a/crates/engine/src/variables_behaviour_tests.rs +++ b/crates/engine/src/variables_behaviour_tests.rs @@ -143,6 +143,18 @@ fn aliases_same_type_chains_and_no_cycles() { assert_eq!(fill(&s, r), "0000FF", "a chain link → accent → blue resolves"); run(&mut s, "variable.set", json!({"variable": "blue", "value": "#00FF00"})); assert_eq!(fill(&s, r), "00FF00", "the chain follows the end of it"); + // A `Collection/name` alias resolves like a layer prop's `{"$var": ...}`, even when the bare + // name matches more than one variable (then the bare name is refused). + run(&mut s, "variable.createCollection", json!({"name": "Primitive"})); + let white = vid(run(&mut s, "variable.create", json!({"collection": "Primitive", "name": "white", "type": "color", "value": "#FFFFFF"}))); + run(&mut s, "variable.create", json!({"collection": "Brand", "name": "white", "type": "color", "value": "#EEEEEE"})); + let surface = + vid(run(&mut s, "variable.create", json!({"collection": "Theme", "name": "surface", "type": "color", "value": {"alias": "Primitive/white"}}))); + let stored = s.doc().unwrap().variables.get_by_id(&surface).unwrap().clone(); + assert!(!stored.values.is_empty() && stored.values.values().all(|v| *v == VariableValue::Alias(white.clone())), "stores the qualified target's id"); + let e = s.execute("variable.create", &json!({"collection": "Theme", "name": "dup", "type": "color", "value": {"alias": "white"}})).unwrap_err().to_string(); + assert!(e.contains("ambiguous variable `white`"), "{e}"); + assert!(s.doc().unwrap().variables.get("dup").is_none(), "a refused alias leaves nothing behind"); let refused: [(&str, Value, &str); 5] = [ ("variable.set", json!({"variable": "blue", "value": {"alias": "link"}}), "a loop through the chain"), ("variable.set", json!({"variable": "accent", "value": {"alias": "accent"}}), "itself"), From d6026814f9cb9e2a178ad063650d223bd602b1b5 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:26:15 +0100 Subject: [PATCH 048/268] M0.9: record CLI scale suffix validation Updated the roadmap with the latest changes and revisions, including minor updates and patch notes for the FigCraft project. --- ROADMAP.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 54921fb11..acabd9813 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (CLI scales reject repeated x suffixes; a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-15 | patch | CLI export and render reject repeated scale suffixes such as `2xx` as usage errors (exit 2); numeric values and one optional `x` suffix retain the existing limits. | | 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-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | From 9a7ed6a8e7838929a3fe8487da8370210c8a64f8 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:39:11 +0100 Subject: [PATCH 049/268] M0.9: clarify the default CLI export and render page Name the existing first non-divider page default in both --page help descriptions. Runtime behavior is unchanged. --- apps/figcraft-cli/src/args.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index 4696b8664..4685ece3b 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -95,7 +95,7 @@ pub struct ExportArgs { pub format: Option, #[command(flatten)] pub scale: ScaleArg, - /// The page to export (default the first) + /// The page to export (default the first non-divider page) #[arg(long, value_name = "NAME")] pub page: Option, /// The layer to export, by id (12 or 0:12) or name @@ -161,7 +161,7 @@ pub struct RenderArgs { pub out: String, #[command(flatten)] pub scale: ScaleArg, - /// The page to render (default the first) + /// The page to render (default the first non-divider page) #[arg(long, value_name = "NAME")] pub page: Option, #[command(flatten)] From eaf1cc8bb98bc8429414a24031f750bf6173fda1 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:39:55 +0100 Subject: [PATCH 050/268] M0.9: document the CLI default page selection Clarify the behavior of the `export` command regarding output file naming and default page selection. Update the `render` command description to specify default behavior for non-divider pages.Explain skipped divider pages, the first-page fallback when all are dividers, and explicit --page selection for export and render. --- docs/cli.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index a83fbe5c3..4c5ab83c1 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -114,13 +114,15 @@ page 1 "Screens": 380 nodes, 4 top-level ### `export -o [--format png|jpg|svg|webp|pdf|xml|fig|penpot] [--scale N] [--page NAME] [--node ID|NAME] [--bleed LENGTH] [--crop-marks] [--bleed-marks] [--cmyk] [--vd-compat bestEffort|exact|ignore]` -- `` is a directory: one file per top-level frame of the page (default the first page), named +- `` is a directory: one file per top-level frame of the selected page, named after the frame (`Home.png`, `Settings.png`…); with no frames, one file per top-level layer. The name is kept as it is, except for the characters file systems refuse (`/ \ : * ? " < > |` and control characters), which become `_`, and leading or trailing spaces and dots, which are dropped. A name is cut at 100 characters. The app's export replaces the same characters (there a `/` makes a folder). Two layers with the same name get `Name 2`, `Name 3`… - `` has an image extension: one file with the given `--node`, or the whole page composited. +- `--page` defaults to the first non-divider page: empty pages whose names start with `-` are + skipped. If all pages are dividers, the first is used. `--page NAME` can select one explicitly. - `--node` takes a layer id (`12` or `0:12`) or a layer name. - `--format fig` (or an `` ending in `.fig`) writes the whole file as `.fig`, experimental: written from public format notes, including variables with their modes and bindings and shared @@ -177,8 +179,8 @@ frames, one page each), `.fig` (the whole file, experimental, as `export --forma ### `render -o [--scale N] [--page NAME]` -The whole page (default the first) with its background, as png, jpg or webp. Large pages are scaled -down to fit 16384 px. +The whole page with its background, as png, jpg or webp. `--page` defaults to the first non-divider +page, as for `export`. Large pages are scaled down to fit 16384 px. ### `run [--in ] [--out ]` From 9cbfe8380fb297be6792aa5474e99e69d8466a59 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:40:55 +0100 Subject: [PATCH 051/268] M0.9: record CLI default-page help correction Updated the roadmap with recent changes and revisions, including CLI export and render help documentation, mind maps implementation, and translation updates.Record the documentation correction in the status line and revision history, preserving existing progress entries. --- ROADMAP.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 54921fb11..bf5c9c9a5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (CLI help and docs name the first non-divider page as the default for export and render; a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-15 | patch | CLI export and render help and docs name the existing first non-divider page default, including the all-divider fallback and explicit page selection. Behavior unchanged. | | 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-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | From 16249aab13ee8362e69434b75e17a10b4f43624f Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:57:05 +0100 Subject: [PATCH 052/268] M0.9: clarify formats that ignore CLI page selection State in the --page guide bullet that .fig and .penpot export the whole document and ignore --page, matching the early returns before page_named. --- docs/cli.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/cli.md b/docs/cli.md index 4c5ab83c1..e0a5b87b7 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -123,6 +123,7 @@ page 1 "Screens": 380 nodes, 4 top-level - `` has an image extension: one file with the given `--node`, or the whole page composited. - `--page` defaults to the first non-divider page: empty pages whose names start with `-` are skipped. If all pages are dividers, the first is used. `--page NAME` can select one explicitly. + The `.fig` and `.penpot` formats export the whole document and ignore `--page`. - `--node` takes a layer id (`12` or `0:12`) or a layer name. - `--format fig` (or an `` ending in `.fig`) writes the whole file as `.fig`, experimental: written from public format notes, including variables with their modes and bindings and shared From bcd82873892ca0911618b845946e1c8d54fe25b4 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:20:41 +0100 Subject: [PATCH 053/268] M9: ignore invalid browser page server endpoints Validate page server metadata with the existing collaboration Endpoint parser before it can replace the sharing, join-code and team-list default. Preserve existing URL restrictions and accepted spelling. --- apps/figcraft-web/src/query.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/figcraft-web/src/query.rs b/apps/figcraft-web/src/query.rs index 547ccc34a..1cddc3408 100644 --- a/apps/figcraft-web/src/query.rs +++ b/apps/figcraft-web/src/query.rs @@ -22,7 +22,12 @@ pub fn join_link(fragment: &str) -> Option<&str> { pub fn page_server(content: &str) -> Option { let c = content.trim(); let scheme = c.starts_with("wss://") || c.starts_with("ws://"); - (scheme && c.len() <= 512 && !c.contains(|ch: char| ch.is_whitespace() || ch.is_control() || ch == '?' || ch == '#')).then(|| c.to_string()) + // Invalid metadata must not replace a usable default with an endpoint sharing cannot reach. + (scheme + && c.len() <= 512 + && !c.contains(|ch: char| ch.is_whitespace() || ch.is_control() || ch == '?' || ch == '#') + && figcraft_collab_net::Endpoint::parse(c).is_ok()) + .then(|| c.to_string()) } /// Whether `search` (`location.search`, with or without its `?`) has a `control` entry (`?control`, From 0e421e82e3330d683ab94e6ae07285490bb126b1 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:21:21 +0100 Subject: [PATCH 054/268] M9: test page server endpoint validation Cover malformed hosts, invalid and out-of-range ports, unsupported paths, and preserved valid local, IPv6 and reverse-proxy server spelling. --- apps/figcraft-web/src/query_tests.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/apps/figcraft-web/src/query_tests.rs b/apps/figcraft-web/src/query_tests.rs index 28681df68..c556bddb4 100644 --- a/apps/figcraft-web/src/query_tests.rs +++ b/apps/figcraft-web/src/query_tests.rs @@ -49,3 +49,27 @@ fn a_page_names_its_own_server_without_a_key() { assert_eq!(page_server(bad), None, "{bad:?} is ignored"); } } + +#[test] +fn a_page_ignores_invalid_server_endpoints() { + for bad in [ + "ws://", + "wss://", + "wss:///figcraft/", + "wss://:443/", + "wss://figcraft.example:0/", + "wss://figcraft.example:65536/", + "wss://figcraft.example:port/", + "wss://[::1/", + "wss://figcraft.example/a@b/", + ] { + assert_eq!(page_server(bad), None, "{bad:?} must not replace the default server"); + } +} + +#[test] +fn a_page_preserves_valid_server_endpoint_spelling() { + for server in ["ws://localhost:47900/", "wss://figcraft.example/figcraft/", "wss://[::1]:47900/figcraft/"] { + assert_eq!(page_server(server).as_deref(), Some(server), "{server}"); + } +} From 10634b40b4161ae1c21e40a4b2916940f83ac5a2 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:21:54 +0100 Subject: [PATCH 055/268] M9: record browser page server validation Record invalid endpoint metadata being ignored while valid server overrides retain their spelling, preserving prior status and history entries. --- ROADMAP.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 54921fb11..66176c00d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (invalid browser-page server endpoints are ignored before they replace the sharing default; a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-15 | patch | The browser ignores a page server meta tag with an invalid host, port or path, using the same endpoint parser as sharing; valid local, IPv6 and reverse-proxy addresses keep their spelling. | | 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-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | From e332cafe74e297ac356f47cff1df017bef4f7e94 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:38:12 +0100 Subject: [PATCH 056/268] M9: reject server metadata with pasted-link delimiters Reject trailing quotes and angle brackets that Endpoint::parse would silently strip while page_server retains the original spelling. Preserve accepted endpoint spelling. Exact-module query tests, strict Clippy, repository formatting and wasm type-check passed; full hosted CI remains required. --- apps/figcraft-web/src/query.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/figcraft-web/src/query.rs b/apps/figcraft-web/src/query.rs index 1cddc3408..f0b1b2f37 100644 --- a/apps/figcraft-web/src/query.rs +++ b/apps/figcraft-web/src/query.rs @@ -26,6 +26,8 @@ pub fn page_server(content: &str) -> Option { (scheme && c.len() <= 512 && !c.contains(|ch: char| ch.is_whitespace() || ch.is_control() || ch == '?' || ch == '#') + // Endpoint parsing strips pasted-link delimiters; metadata must retain its spelling. + && !c.ends_with(['<', '>', '"', '\'']) && figcraft_collab_net::Endpoint::parse(c).is_ok()) .then(|| c.to_string()) } From 7117f1c62d00add248293ea765a8308acc5f1f33 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:38:46 +0100 Subject: [PATCH 057/268] M9: cover page server delimiters cleaned by endpoint parsing Cover apostrophes, double quotes, angle brackets and mixed trailing delimiters using the real Endpoint parser. Regression fails original PR head; all 8 exact-module query tests pass with the guard. Strict Clippy, repository formatting and wasm type-check also pass. --- apps/figcraft-web/src/query_tests.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/apps/figcraft-web/src/query_tests.rs b/apps/figcraft-web/src/query_tests.rs index c556bddb4..0c51967dc 100644 --- a/apps/figcraft-web/src/query_tests.rs +++ b/apps/figcraft-web/src/query_tests.rs @@ -73,3 +73,12 @@ fn a_page_preserves_valid_server_endpoint_spelling() { assert_eq!(page_server(server).as_deref(), Some(server), "{server}"); } } + +#[test] +fn a_page_rejects_server_delimiters_that_endpoint_parsing_would_strip() { + for suffix in ["'", "\"", "<", ">", "\"'>"] { + let server = format!("wss://figcraft.example/{suffix}"); + assert!(figcraft_collab_net::Endpoint::parse(&server).is_ok(), "the parser cleans {server:?}"); + assert_eq!(page_server(&server), None, "{server:?} must not replace the default server"); + } +} From ca7864946a2326545d54cb16001c3b915aaeadd3 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:21:48 +0100 Subject: [PATCH 058/268] docs: remove obsolete browser session restriction --- apps/figcraft-web/src/main.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/apps/figcraft-web/src/main.rs b/apps/figcraft-web/src/main.rs index b65a82772..36d37ed39 100644 --- a/apps/figcraft-web/src/main.rs +++ b/apps/figcraft-web/src/main.rs @@ -22,8 +22,6 @@ //! - host mode: `?host=parent` (a same-origin page embedding FigCraft in an `