From 143067f2d59f5b901d86d0e58a397495bcfe187f Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 13:47:19 -0500 Subject: [PATCH 01/15] M7: Variables JSON: export and import text styles (#2173) variable.export {format: "json"} now writes a top-level textStyles array beside meta: each own text style as style.list returns it, with bound holding the ids meta.variables is keyed by. variable.import reads it back: styles merge by name, bindings are re-pointed to the imported variables (one naming a variable the JSON lacks is dropped with a warning), junk entries are skipped with warnings, and the result gains styles {added, updated}. A shared text_kind helper now serves style.create, style.update and the new upsert_text_style. CSS, Tailwind and Dart stay variables-only. 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 | 1 + crates/engine/src/cmd/styles.rs | 39 ++++++++++++- crates/engine/src/cmd/variables_io.rs | 77 +++++++++++++++++++++++-- crates/engine/src/variables_io_tests.rs | 74 ++++++++++++++++++++++++ docs/components-parity.md | 2 + docs/file-format-parity.md | 2 +- docs/gaps.md | 2 +- docs/mcp.md | 4 +- 8 files changed, 190 insertions(+), 11 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index dc6204b44..c05574114 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 | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it, `bound` holding the ids `meta.variables` is keyed by), and `variable.import` reads it back (styles merged by name, bindings re-pointed, a binding to a variable the JSON lacks dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | | 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/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 9ba420c43..e50f5589d 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -256,6 +256,41 @@ fn text_style_json(cmd: &str, v: &Value) -> Result { serde_json::from_value::(v).map(|t| t.as_text_style()).map_err(|e| bad(cmd, e.to_string())) } +/// A text style value from JSON: the character values from `style`, the paragraph values from +/// `paragraph` (the same object for the flat `value` of `style.create`). +fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result { + Ok(StyleKind::Text { style: text_style_json(cmd, style)?, paragraph: Box::new(paragraph_style_json(cmd, paragraph)?) }) +} + +/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]), with `bound` as its +/// variable bindings (those that name no field of the value are dropped). True when a style of +/// that name existed and was redefined (with the style's id); the caller settles and propagates. +pub(crate) fn upsert_text_style( + doc: &mut Document, + name: &str, + description: &str, + style: &Value, + paragraph: &Value, + bound: BTreeMap, +) -> Result<(StyleId, bool)> { + let cmd = "variable.import"; + let kind = text_kind(cmd, style, paragraph)?; + let same = + doc.styles.iter().position(|x| x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id)); + let updated = same.is_some(); + let mut st = match same.and_then(|i| doc.styles.get(i)) { + Some(x) => Style { kind, bound, ..x.clone() }, + None => Style { id: doc.new_style_id(), name: name.to_string(), description: description.to_string(), kind, bound }, + }; + crate::style_vars::prune(&mut st); + let sid = st.id.clone(); + match same.and_then(|i| doc.styles.get_mut(i)) { + Some(slot) => *slot = st, + None => doc.styles.push(st), + } + Ok((sid, updated)) +} + /// The text style definition a layer's chars from `at` (None = its base style) show. fn text_style_of(n: &Node, at: Option) -> Option { let t = n.kind.text()?; @@ -353,7 +388,7 @@ fn create(s: &mut Session, p: &Value) -> Result { let kind = if let Some(v) = get(p, "value") { match t.as_str() { "paint" | "color" | "fill" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, + "text" => text_kind(cmd, v, v)?, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, "grid" => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => return Err(bad(cmd, "type: paint|text|effect|grid")), @@ -550,7 +585,7 @@ fn update(s: &mut Session, p: &Value) -> Result { let cur = doc.styles.get(idx).map(|x| x.kind.type_name()).unwrap_or("paint"); Some(match cur { "paint" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, + "text" => text_kind(cmd, v, v)?, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, }) diff --git a/crates/engine/src/cmd/variables_io.rs b/crates/engine/src/cmd/variables_io.rs index 1b3b4ee29..e59027a11 100644 --- a/crates/engine/src/cmd/variables_io.rs +++ b/crates/engine/src/cmd/variables_io.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, Variable, VariableId, VariableValue, Variables, trim_num}; +use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, StyleKind, Variable, VariableId, VariableValue, Variables, trim_num}; use serde_json::{Value, json}; use super::CommandSpec; @@ -25,7 +25,7 @@ pub fn specs() -> Vec { spec!( "variable.import", "Import variables", - "{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, warnings (also when it holds no variables, or fewer than its collections list)}", + "{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level; a top-level `textStyles` array, a FigCraft extension, adds this file's text styles by name with their variable bindings re-pointed)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, warnings (also when it holds no variables, or fewer than its collections list)}", true, import ), @@ -44,8 +44,13 @@ fn export(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "collections: [collection ids or names]")), }; let text = match string(p, "format").as_deref().unwrap_or("json") { - "json" => serde_json::to_string_pretty(&figcraft_format::rest::export_variables(&doc.variables, &colls)) - .map_err(|e| EngineError::Other(e.to_string()))?, + "json" => { + let mut out = figcraft_format::rest::export_variables(&doc.variables, &colls); + if let Value::Object(m) = &mut out { + m.insert("textStyles".into(), text_styles(doc)); + } + serde_json::to_string_pretty(&out).map_err(|e| EngineError::Other(e.to_string()))? + } "css" => css(doc, &colls, false), "tailwind" => css(doc, &colls, true), "dart" => dart(&doc.variables, &colls), @@ -60,6 +65,61 @@ fn export(s: &mut Session, p: &Value) -> Result { } } +/// This file's own text styles as `style.list {type: "text"}` returns them (values and `bound`, +/// the variable ids being those `meta.variables` is keyed by): the `textStyles` of the variables +/// JSON, a FigCraft extension beside the REST-compatible `meta`. +fn text_styles(doc: &Document) -> Value { + let own = |st: &&figcraft_doc::Style| matches!(st.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &st.id); + Value::Array(doc.styles.iter().filter(own).filter_map(|st| serde_json::to_value(st).ok()).collect()) +} + +/// Read `entries` (the `textStyles` of a variables JSON) into this file: a style joins this file's +/// text style of the same name, others are added; bindings follow `ids` (imported variable id to +/// this file's). Returns (added, updated); what can't be read is a warning. +fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap, warnings: &mut Vec) -> (usize, usize) { + let Value::Array(list) = entries else { + warnings.push("`textStyles` should be an array of text styles: skipped".to_string()); + return (0, 0); + }; + let (mut added, mut updated) = (0, 0); + let mut touched = Vec::new(); + for (i, e) in list.iter().enumerate() { + let name = e.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); + let (Some(name), Some(style)) = (name, e.get("style").filter(|x| x.is_object())) else { + warnings.push(format!("`textStyles` entry {i} needs a `name` and a `style` object: skipped")); + continue; + }; + let mut bound = BTreeMap::new(); + if let Some(Value::Object(m)) = e.get("bound") { + for (field, id) in m { + match id.as_str().and_then(|v| ids.get(v)) { + Some(local) => { + bound.insert(field.clone(), local.clone()); + } + None => warnings.push(format!("text style `{name}`: `{field}` is bound to a variable the JSON doesn't hold: left unbound")), + } + } + } + let description = e.get("description").and_then(Value::as_str).unwrap_or_default(); + match super::styles::upsert_text_style(doc, name, description, style, e.get("paragraph").unwrap_or(&Value::Null), bound) { + Ok((sid, was)) => { + touched.push(sid); + if was { + updated += 1; + } else { + added += 1; + } + } + Err(err) => warnings.push(format!("text style `{name}`: {err}")), + } + } + crate::style_vars::settle(doc); + for sid in touched { + super::styles::propagate_style(doc, &sid); + } + (added, updated) +} + /// `text` as a CSS comment or quoted string body. fn css_safe(text: &str) -> String { text.replace("*/", "* /").replace(['"', '\\', '\n', '\r', '\u{c}'], " ") @@ -362,5 +422,12 @@ fn import(s: &mut Session, p: &Value) -> Result { } } } - Ok(json!({"collections": added_colls, "variables": added, "updated": updated, "warnings": warnings})) + let (styles_added, styles_updated) = match v.get("textStyles") { + Some(entries) => import_text_styles(doc, entries, &ids, &mut warnings), + None => (0, 0), + }; + Ok(json!({ + "collections": added_colls, "variables": added, "updated": updated, + "styles": {"added": styles_added, "updated": styles_updated}, "warnings": warnings + })) } diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index eba692802..1d459207f 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -302,6 +302,80 @@ fn variables_import_checks_what_it_reads() { let (a, b) = (vars.get("a").unwrap(), vars.get("b").unwrap()); assert!(!a.values.values().chain(b.values.values()).all(|v| matches!(v, VariableValue::Alias(_))), "no loop"); healthy(&s); + // Junk `textStyles` entries are skipped with a warning, never an internal error. + let long = "n".repeat(200); + let empty = json!({"variableCollections": {}, "variables": {}}); + for junk in [json!(5), json!([3]), json!([{"name": 3}]), json!([{"name": "x", "style": "nope"}]), json!([{"name": long, "style": 7}])] { + let mut file = empty.clone(); + file["textStyles"] = junk.clone(); + match s.execute("variable.import", &json!({"variables": file})) { + Ok(r) => assert!(r["warnings"].to_string().contains("text style") || r["warnings"].to_string().contains("textStyles"), "{junk}: {r}"), + Err(e) => assert!(!matches!(e, crate::EngineError::Internal { .. }), "{junk}: {e}"), + } + } + assert!(s.doc().unwrap().styles.is_empty(), "no junk style got in"); +} + +/// A file with a "Body" text style whose size, line height and style name follow variables. +fn body_session() -> Session { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Type", "modes": ["Base"]})); + ex(&mut s, "variable.create", json!({"collection": "Type", "name": "size", "type": "number", "value": 16})); + ex(&mut s, "variable.create", json!({"collection": "Type", "name": "lh", "type": "number", "value": 24})); + ex(&mut s, "variable.create", json!({"collection": "Type", "name": "face", "type": "string", "value": "Bold"})); + ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 12, "lineHeight": "150%"}})); + for (field, v) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] { + ex(&mut s, "style.bind", json!({"style": "Body", "field": field, "variable": v})); + } + s +} + +#[test] +fn variables_export_carries_text_styles_with_their_bindings() { + let mut s = body_session(); + let out = ex(&mut s, "variable.export", json!({})); + let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); + let styles = file["textStyles"].as_array().unwrap(); + assert_eq!(styles.len(), 1, "{file}"); + assert_eq!(styles[0]["name"], "Body"); + assert_eq!(styles[0]["style"]["font_size"], 16.0); + assert_eq!(styles[0]["style"]["font_style"], "Bold"); + assert_eq!(styles[0], ex(&mut s, "style.list", json!({"type": "text"}))[0], "what style.list returns"); + for field in ["fontSize", "lineHeight", "fontStyle"] { + let id = styles[0]["bound"][field].as_str().unwrap(); + assert!(file["meta"]["variables"].get(id).is_some(), "{field} -> {id}"); + } + let css = ex(&mut s, "variable.export", json!({"format": "css"})); + assert!(!css["text"].as_str().unwrap().contains("Body"), "{css}"); +} + +#[test] +fn text_styles_round_trip_through_variables_import() { + let mut s = body_session(); + let out = ex(&mut s, "variable.export", json!({})); + let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); + let mut t = Session::new(); + let r = ex(&mut t, "variable.import", json!({"variables": file})); + assert_eq!(r["styles"], json!({"added": 1, "updated": 0}), "{r}"); + let doc = t.doc().unwrap(); + let body = doc.styles.iter().find(|x| x.name == "Body").unwrap(); + let ids: Vec<&str> = body.bound.values().map(|v| v.as_str()).collect(); + assert_eq!(body.bound.len(), 3, "{body:?}"); + assert!(ids.iter().all(|i| doc.variables.get(i).is_some()), "bindings point at this file's variables"); + let StyleKind::Text { style, .. } = &body.kind else { panic!("{body:?}") }; + assert_eq!((style.font_style.as_str(), style.font_size), ("Bold", 16.0)); + // Again: the style is updated, not duplicated. + let r = ex(&mut t, "variable.import", json!({"variables": file})); + assert_eq!(r["styles"], json!({"added": 0, "updated": 1}), "{r}"); + assert_eq!(t.doc().unwrap().styles.len(), 1); + // A binding to a variable the JSON lacks is dropped with a warning naming the style. + let mut u = Session::new(); + let mut lone = file.clone(); + lone["meta"] = json!({"variableCollections": {}, "variables": {}}); + let r = ex(&mut u, "variable.import", json!({"variables": lone})); + assert_eq!(r["styles"]["added"], 1, "{r}"); + assert!(u.doc().unwrap().styles[0].bound.is_empty()); + assert!(r["warnings"].to_string().contains("Body"), "{r}"); } #[test] diff --git a/docs/components-parity.md b/docs/components-parity.md index 8fcaea78a..726fabeed 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -67,6 +67,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once | | 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 | +| Text styles in the Variables JSON export and import (`textStyles`, a FigCraft extension: the REST `styles` metadata has no values) | done | `variable.export {format: "json"}` adds a top-level `textStyles` array (values and `bound`, ids matching `meta.variables`); `variable.import` merges it by style name and re-points bindings; CSS, Tailwind and Dart are variables only | | 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) | | 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 | @@ -79,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it, `bound` holding the ids `meta.variables` is keyed by), and `variable.import` reads it back (styles merged by name, bindings re-pointed, a binding to a variable the JSON lacks dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | | 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/file-format-parity.md b/docs/file-format-parity.md index dd04fdf75..5031f1151 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -22,7 +22,7 @@ and prototype interactions are still unchecked there. | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | | `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with generated sticky and shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | -| REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | +| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array on export and import) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Developer Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — | | Local library files | team libraries in the cloud | yes (enable a `.figcraft` as a library) | yes (publish) | per-asset versions, updates with overrides kept | see [collaboration-parity](collaboration-parity.md) | diff --git a/docs/gaps.md b/docs/gaps.md index f42b97e4e..f31c41183 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -408,7 +408,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Landed:** extended collections (`library.extendCollection`: a library collection's modes and variables in a collection of this file, values overridden per mode with reset, following library updates, variables of its own), variables import/export (`variable.export` / `variable.import`: - the REST local variables JSON, merged by name; CSS custom properties), gradient stops and variant + the REST local variables JSON, merged by name, with the file's text styles under `textStyles`; CSS custom properties), gradient stops and variant properties bound to variables. - **Landed (2026-10-12):** variables a library adds to a collection this file extends are a library update of their own (`library.updates` lists them by name, without an `id` until they have a diff --git a/docs/mcp.md b/docs/mcp.md index 04b37e1f0..3f19b8379 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1232,13 +1232,13 @@ Dart constants for Flutter (`format: "dart"`: an `abstract final class` per coll default mode's named after the collection and the others after the collection and the mode, with a `static const` `Color`, `double`, `String` or `bool` per variable; names become camelCase Dart identifiers kept apart, aliases are resolved to their value in that mode), and -returns `{text}` (or writes `path` and returns `{path}`). `variable.import {variables}` (an object, +returns `{text}` (or writes `path` and returns `{path}`). The JSON format also carries a top-level `textStyles` array beside `meta`, a FigCraft extension (the REST `styles` metadata has no values): each entry is what `style.list {type: "text"}` returns (`name`, `style`, `paragraph`, and `bound` holding the same variable ids `meta.variables` is keyed by); CSS, Tailwind and Dart are variables only. `variable.import {variables}` (an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level) reads one back: a collection joins this file's collection of the same name (values matched by mode name, new modes and variables added, a same-named variable of another type skipped with a warning; library copies and extended collections are never targets), others are -added; aliases are checked for loops; it returns `{collections, variables, updated, warnings}`, +added; aliases are checked for loops; a `textStyles` array is read too (a style joins this file's text style of the same name, others are added; bindings follow the imported variables, one to a variable the JSON lacks is dropped with a warning); it returns `{collections, variables, updated, styles: {added, updated}, warnings}`, with a warning when the JSON holds no variables (`no variables found: expected meta.variables …`) or fewer than its collections list in `variableIds`. The Variables editor's Import… and Export… buttons do the same through file dialogs. From 355caa79dcd18bd4c7dfabef2690e9d988b04bd2 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 14:07:44 -0500 Subject: [PATCH 02/15] M7: Variables JSON text styles: a file's own export round-trips, caps, binding checks (#2173) Importing a file's own export keeps the bindings of the text styles it replaces (ids the import doesn't carry), and same-named styles match one by one instead of all hitting the first. Entries (10,000), names (500), descriptions (10,000) and bindings (32 per style) are capped; a binding to a field the style lacks or a variable of another type is dropped with a warning. Warnings no longer name the command. The spec strings, status lines and docs/mcp.md describe the format. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 reviewed; Sonnet 5.5 wrote at medium --- ROADMAP.md | 2 +- crates/engine/src/cmd/styles.rs | 19 +++--- crates/engine/src/cmd/variables_io.rs | 84 +++++++++++++++++++------ crates/engine/src/variables_io_tests.rs | 78 ++++++++++++++++++++++- docs/components-parity.md | 2 +- docs/file-format-parity.md | 2 +- docs/gaps.md | 2 +- docs/mcp.md | 4 +- 8 files changed, 157 insertions(+), 36 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c05574114..0a7ca6c78 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 (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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 diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index e50f5589d..a61f4f18c 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -262,22 +262,25 @@ fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result { Ok(StyleKind::Text { style: text_style_json(cmd, style)?, paragraph: Box::new(paragraph_style_json(cmd, paragraph)?) }) } -/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]), with `bound` as its -/// variable bindings (those that name no field of the value are dropped). True when a style of -/// that name existed and was redefined (with the style's id); the caller settles and propagates. +/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]). `bind` gives its +/// variable bindings from the document, the new value and the style it replaces. The style +/// redefined is the first local text style of that name not in `touched`. True when one existed +/// (with the style's id); the caller settles and propagates. pub(crate) fn upsert_text_style( doc: &mut Document, name: &str, description: &str, style: &Value, paragraph: &Value, - bound: BTreeMap, + touched: &[StyleId], + bind: impl FnOnce(&Document, &StyleKind, Option<&Style>) -> BTreeMap, ) -> Result<(StyleId, bool)> { - let cmd = "variable.import"; - let kind = text_kind(cmd, style, paragraph)?; - let same = - doc.styles.iter().position(|x| x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id)); + let kind = text_kind("variable.import", style, paragraph)?; + let same = doc.styles.iter().position(|x| { + x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id) && !touched.contains(&x.id) + }); let updated = same.is_some(); + let bound = bind(doc, &kind, same.and_then(|i| doc.styles.get(i))); let mut st = match same.and_then(|i| doc.styles.get(i)) { Some(x) => Style { kind, bound, ..x.clone() }, None => Style { id: doc.new_style_id(), name: name.to_string(), description: description.to_string(), kind, bound }, diff --git a/crates/engine/src/cmd/variables_io.rs b/crates/engine/src/cmd/variables_io.rs index e59027a11..5816ea44b 100644 --- a/crates/engine/src/cmd/variables_io.rs +++ b/crates/engine/src/cmd/variables_io.rs @@ -18,14 +18,14 @@ pub fn specs() -> Vec { spec!( "variable.export", "Export variables", - "{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-=\"\"], colour calculations as the colour they show in that mode with other collections in their default modes; numbers in px unless layers or scopes use them as opacity or font weight | tailwind: a Tailwind CSS v4 stylesheet, the default mode as an @theme block named the way inspect.code's tailwind utilities read them: --color-*, --radius-*, --text-*, --spacing-*, --font-*, unique per file; each other mode as in css; colour calculations as the colour they show in that mode, other collections in their default modes) | dart: a Dart file for Flutter, a class of constants per collection and mode (Color, double, String, bool), aliases and colour calculations resolved), path? (write it there)} → {text}, or {path} when written", + "{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-=\"\"], colour calculations as the colour they show in that mode with other collections in their default modes; numbers in px unless layers or scopes use them as opacity or font weight | tailwind: a Tailwind CSS v4 stylesheet, the default mode as an @theme block named the way inspect.code's tailwind utilities read them: --color-*, --radius-*, --text-*, --spacing-*, --font-*, unique per file; each other mode as in css; colour calculations as the colour they show in that mode, other collections in their default modes) | dart: a Dart file for Flutter, a class of constants per collection and mode (Color, double, String, bool), aliases and colour calculations resolved), path? (write it there)} → {text}, or {path} when written; the json format adds a top-level `textStyles` array (this file's text styles as style.list returns them, `bound` holding the ids `meta.variables` is keyed by), a FigCraft extension beside the REST-compatible `meta`", false, export ), spec!( "variable.import", "Import variables", - "{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level; a top-level `textStyles` array, a FigCraft extension, adds this file's text styles by name with their variable bindings re-pointed)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, warnings (also when it holds no variables, or fewer than its collections list)}", + "{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level; a top-level `textStyles` array, a FigCraft extension, adds this file's text styles by name with their variable bindings re-pointed)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, styles {added, updated}, warnings (also when it holds no variables, or fewer than its collections list)}", true, import ), @@ -73,35 +73,38 @@ fn text_styles(doc: &Document) -> Value { Value::Array(doc.styles.iter().filter(own).filter_map(|st| serde_json::to_value(st).ok()).collect()) } +/// At most this many text styles are read from a variables JSON, this many bindings per style, and +/// this many chars of a description. +const MAX_TEXT_STYLES: usize = 10_000; +const MAX_STYLE_BINDINGS: usize = 32; +const MAX_STYLE_DESCRIPTION: usize = 10_000; + /// Read `entries` (the `textStyles` of a variables JSON) into this file: a style joins this file's -/// text style of the same name, others are added; bindings follow `ids` (imported variable id to -/// this file's). Returns (added, updated); what can't be read is a warning. +/// text style of the same name (the first one this import hasn't touched yet), others are added; +/// bindings follow `ids` (imported variable id to this file's). Returns (added, updated); what +/// can't be read is a warning. fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap, warnings: &mut Vec) -> (usize, usize) { let Value::Array(list) = entries else { warnings.push("`textStyles` should be an array of text styles: skipped".to_string()); return (0, 0); }; + if list.len() > MAX_TEXT_STYLES { + warnings.push(format!("`textStyles` holds {} entries: only the first {MAX_TEXT_STYLES} are read", list.len())); + } let (mut added, mut updated) = (0, 0); let mut touched = Vec::new(); - for (i, e) in list.iter().enumerate() { - let name = e.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); + for (i, e) in list.iter().take(MAX_TEXT_STYLES).enumerate() { + let name = e.get("name").and_then(Value::as_str).and_then(super::variables::clean_name); let (Some(name), Some(style)) = (name, e.get("style").filter(|x| x.is_object())) else { warnings.push(format!("`textStyles` entry {i} needs a `name` and a `style` object: skipped")); continue; }; - let mut bound = BTreeMap::new(); - if let Some(Value::Object(m)) = e.get("bound") { - for (field, id) in m { - match id.as_str().and_then(|v| ids.get(v)) { - Some(local) => { - bound.insert(field.clone(), local.clone()); - } - None => warnings.push(format!("text style `{name}`: `{field}` is bound to a variable the JSON doesn't hold: left unbound")), - } - } - } - let description = e.get("description").and_then(Value::as_str).unwrap_or_default(); - match super::styles::upsert_text_style(doc, name, description, style, e.get("paragraph").unwrap_or(&Value::Null), bound) { + let description: String = e.get("description").and_then(Value::as_str).unwrap_or_default().chars().take(MAX_STYLE_DESCRIPTION).collect(); + let wanted = e.get("bound"); + let bind = |doc: &Document, kind: &StyleKind, current: Option<&figcraft_doc::Style>| { + text_style_bindings(&name, wanted, ids, doc, kind, current, warnings) + }; + match super::styles::upsert_text_style(doc, &name, &description, style, e.get("paragraph").unwrap_or(&Value::Null), &touched, bind) { Ok((sid, was)) => { touched.push(sid); if was { @@ -110,6 +113,7 @@ fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap warnings.push(format!("text style `{name}`: {msg}")), Err(err) => warnings.push(format!("text style `{name}`: {err}")), } } @@ -120,6 +124,48 @@ fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap, + ids: &BTreeMap, + doc: &Document, + kind: &StyleKind, + current: Option<&figcraft_doc::Style>, + warnings: &mut Vec, +) -> BTreeMap { + let mut bound = BTreeMap::new(); + let Some(Value::Object(m)) = wanted else { return bound }; + if m.len() > MAX_STYLE_BINDINGS { + warnings.push(format!("text style `{name}`: {} bindings: only the first {MAX_STYLE_BINDINGS} are read", m.len())); + } + for (field, id) in m.iter().take(MAX_STYLE_BINDINGS) { + let held = current.and_then(|c| c.bound.get(field)).filter(|h| id.as_str() == Some(h.as_str())); + let local = id.as_str().and_then(|v| ids.get(v)).or(held); + match checked_binding(doc, kind, field, local) { + Ok(local) => { + bound.insert(field.clone(), local.clone()); + } + Err(why) => warnings.push(format!("text style `{name}`: {why}: left unbound")), + } + } + bound +} + +/// `local` when it is a variable of this file of the type a text style's `field` takes. +fn checked_binding<'a>(doc: &Document, kind: &StyleKind, field: &str, local: Option<&'a VariableId>) -> std::result::Result<&'a VariableId, String> { + let local = local.ok_or_else(|| format!("`{field}` is bound to a variable the JSON doesn't hold"))?; + let want = crate::style_vars::field_type(kind, field).ok_or_else(|| format!("no field `{field}` to bind"))?; + match doc.variables.get_by_id(local).map(|v| v.kind) { + Some(k) if k == want => Ok(local), + Some(k) => Err(format!("`{field}` takes a {} variable, not a {} one", want.id(), k.id())), + None => Err(format!("`{field}` is bound to a variable this file lacks")), + } +} + /// `text` as a CSS comment or quoted string body. fn css_safe(text: &str) -> String { text.replace("*/", "* /").replace(['"', '\\', '\n', '\r', '\u{c}'], " ") diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index 1d459207f..5ac6654a3 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -302,10 +302,17 @@ fn variables_import_checks_what_it_reads() { let (a, b) = (vars.get("a").unwrap(), vars.get("b").unwrap()); assert!(!a.values.values().chain(b.values.values()).all(|v| matches!(v, VariableValue::Alias(_))), "no loop"); healthy(&s); +} + +#[test] +fn text_styles_in_a_variables_json_are_checked_and_capped() { + let mut s = Session::new(); + let mode = json!([{"modeId": "m", "name": "Mode 1"}]); // Junk `textStyles` entries are skipped with a warning, never an internal error. - let long = "n".repeat(200); let empty = json!({"variableCollections": {}, "variables": {}}); - for junk in [json!(5), json!([3]), json!([{"name": 3}]), json!([{"name": "x", "style": "nope"}]), json!([{"name": long, "style": 7}])] { + for junk in + [json!(5), json!([3]), json!([{"name": 3}]), json!([{"name": "x", "style": "nope"}]), json!([{"name": "x", "style": {"font_size": "big"}}])] + { let mut file = empty.clone(); file["textStyles"] = junk.clone(); match s.execute("variable.import", &json!({"variables": file})) { @@ -313,7 +320,35 @@ fn variables_import_checks_what_it_reads() { Err(e) => assert!(!matches!(e, crate::EngineError::Internal { .. }), "{junk}: {e}"), } } + let mut file = empty.clone(); + file["textStyles"] = json!([{"name": "x", "style": {"font_size": "big"}}]); + let r = ex(&mut s, "variable.import", json!({"variables": file})); + assert!(r["warnings"].to_string().contains("text style `x`"), "{r}"); assert!(s.doc().unwrap().styles.is_empty(), "no junk style got in"); + // A name is cut to 500 chars, a description to 10,000, and only the first 10,000 entries are read. + let mut file = empty.clone(); + file["textStyles"] = json!([{"name": "n".repeat(100_000), "description": "d".repeat(100_000), "style": {}}]); + ex(&mut s, "variable.import", json!({"variables": file})); + let styles = &s.doc().unwrap().styles; + assert_eq!(styles.len(), 1); + assert!(styles[0].name.chars().count() <= 500 && styles[0].description.chars().count() <= 10_000, "{}", styles[0].name.len()); + let mut file = empty.clone(); + file["textStyles"] = Value::Array((0..10_050).map(|i| json!({"name": format!("s{i}"), "style": {}})).collect()); + let r = ex(&mut s, "variable.import", json!({"variables": file})); + assert_eq!(r["styles"]["added"], 10_000, "{}", r["styles"]); + assert!(r["warnings"].to_string().contains("10000") || r["warnings"].to_string().contains("10,000"), "{}", r["warnings"]); + // A binding to a field the style lacks, or to a variable of another type, is dropped with a warning. + let mut t = Session::new(); + let file = json!({ + "meta": {"variableCollections": {"c": {"id": "c", "name": "T", "modes": mode}}, + "variables": {"s": {"id": "s", "name": "s", "variableCollectionId": "c", "resolvedType": "STRING", "valuesByMode": {"m": "x"}}}}, + "textStyles": [{"name": "t", "style": {}, "bound": {"fontSize": "s", "nope": "s"}}] + }); + let r = ex(&mut t, "variable.import", json!({"variables": file})); + assert_eq!(r["styles"]["added"], 1, "{r}"); + assert!(t.doc().unwrap().styles[0].bound.is_empty(), "{r}"); + let w = r["warnings"].as_array().unwrap().iter().filter_map(|x| x.as_str()).filter(|x| x.contains("text style `t`")).collect::>(); + assert!(w.len() == 2 && w.iter().any(|x| x.contains("fontSize")) && w.iter().any(|x| x.contains("nope")), "{r}"); } /// A file with a "Body" text style whose size, line height and style name follow variables. @@ -323,7 +358,11 @@ fn body_session() -> Session { ex(&mut s, "variable.create", json!({"collection": "Type", "name": "size", "type": "number", "value": 16})); ex(&mut s, "variable.create", json!({"collection": "Type", "name": "lh", "type": "number", "value": 24})); ex(&mut s, "variable.create", json!({"collection": "Type", "name": "face", "type": "string", "value": "Bold"})); - ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 12, "lineHeight": "150%"}})); + ex( + &mut s, + "style.create", + json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 12, "lineHeight": "150%", "paragraphSpacing": 8, "listStyle": "bulleted"}}), + ); for (field, v) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] { ex(&mut s, "style.bind", json!({"style": "Body", "field": field, "variable": v})); } @@ -340,6 +379,11 @@ fn variables_export_carries_text_styles_with_their_bindings() { assert_eq!(styles[0]["name"], "Body"); assert_eq!(styles[0]["style"]["font_size"], 16.0); assert_eq!(styles[0]["style"]["font_style"], "Bold"); + assert_eq!(styles[0]["paragraph"]["paragraph_spacing"], 8.0, "{file}"); + assert_eq!(styles[0]["paragraph"]["list"], "bulleted", "{file}"); + let mut keys: Vec<&str> = styles[0].as_object().unwrap().keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!(keys, ["bound", "description", "id", "name", "paragraph", "style", "type"], "the entry's shape is public: {file}"); assert_eq!(styles[0], ex(&mut s, "style.list", json!({"type": "text"}))[0], "what style.list returns"); for field in ["fontSize", "lineHeight", "fontStyle"] { let id = styles[0]["bound"][field].as_str().unwrap(); @@ -355,19 +399,31 @@ fn text_styles_round_trip_through_variables_import() { let out = ex(&mut s, "variable.export", json!({})); let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); let mut t = Session::new(); + ex(&mut t, "variable.createCollection", json!({"name": "Type", "modes": ["Base"]})); + for (name, v) in [("gap", 4), ("pad", 6), ("lh", 30)] { + ex(&mut t, "variable.create", json!({"collection": "Type", "name": name, "type": "number", "value": v})); + } let r = ex(&mut t, "variable.import", json!({"variables": file})); assert_eq!(r["styles"], json!({"added": 1, "updated": 0}), "{r}"); + assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}"); let doc = t.doc().unwrap(); let body = doc.styles.iter().find(|x| x.name == "Body").unwrap(); let ids: Vec<&str> = body.bound.values().map(|v| v.as_str()).collect(); assert_eq!(body.bound.len(), 3, "{body:?}"); assert!(ids.iter().all(|i| doc.variables.get(i).is_some()), "bindings point at this file's variables"); + for (field, name) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] { + assert_eq!(doc.variables.get(&body.bound[field]).unwrap().name, name, "{field}"); + } + let StyleKind::Text { paragraph, .. } = &body.kind else { panic!("{body:?}") }; + assert_eq!((paragraph.paragraph_spacing, paragraph.list), (8.0, ListStyle::Bulleted)); let StyleKind::Text { style, .. } = &body.kind else { panic!("{body:?}") }; assert_eq!((style.font_style.as_str(), style.font_size), ("Bold", 16.0)); // Again: the style is updated, not duplicated. let r = ex(&mut t, "variable.import", json!({"variables": file})); assert_eq!(r["styles"], json!({"added": 0, "updated": 1}), "{r}"); assert_eq!(t.doc().unwrap().styles.len(), 1); + assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(t.doc().unwrap().styles[0].bound.len(), 3); // A binding to a variable the JSON lacks is dropped with a warning naming the style. let mut u = Session::new(); let mut lone = file.clone(); @@ -378,6 +434,22 @@ fn text_styles_round_trip_through_variables_import() { assert!(r["warnings"].to_string().contains("Body"), "{r}"); } +#[test] +fn a_files_own_export_leaves_its_text_styles_alone() { + let mut s = body_session(); + ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 20}})); + ex(&mut s, "variable.createCollection", json!({"name": "Other", "modes": ["Base"]})); + ex(&mut s, "variable.create", json!({"collection": "Other", "name": "o", "type": "number", "value": 1})); + let out = ex(&mut s, "variable.export", json!({"collections": ["Other"]})); + let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); + let before = s.doc().unwrap().styles.clone(); + assert_eq!(before.len(), 2); + let r = ex(&mut s, "variable.import", json!({"variables": file})); + assert_eq!(s.doc().unwrap().styles, before, "{r}"); + assert_eq!(r["styles"], json!({"added": 0, "updated": 2}), "{r}"); + assert!(!r["warnings"].to_string().contains("left unbound"), "{r}"); +} + #[test] fn variables_import_caps_the_file_it_reads() { let dir = std::env::temp_dir().join(format!("figcraft-vars-io-cap-{}", std::process::id())); diff --git a/docs/components-parity.md b/docs/components-parity.md index 726fabeed..879dd7e31 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-10 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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/file-format-parity.md b/docs/file-format-parity.md index 5031f1151..e0fc1c4c4 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (`.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; 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); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); 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; folders, devices and pipes are refused before anything is read (#1114); 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); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); 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); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; 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); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); 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; folders, devices and pipes are refused before anything is read (#1114); 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); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); 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); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's diff --git a/docs/gaps.md b/docs/gaps.md index f31c41183..f60e83afe 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 (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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 diff --git a/docs/mcp.md b/docs/mcp.md index 3f19b8379..2b548b704 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1232,13 +1232,13 @@ Dart constants for Flutter (`format: "dart"`: an `abstract final class` per coll default mode's named after the collection and the others after the collection and the mode, with a `static const` `Color`, `double`, `String` or `bool` per variable; names become camelCase Dart identifiers kept apart, aliases are resolved to their value in that mode), and -returns `{text}` (or writes `path` and returns `{path}`). The JSON format also carries a top-level `textStyles` array beside `meta`, a FigCraft extension (the REST `styles` metadata has no values): each entry is what `style.list {type: "text"}` returns (`name`, `style`, `paragraph`, and `bound` holding the same variable ids `meta.variables` is keyed by); CSS, Tailwind and Dart are variables only. `variable.import {variables}` (an object, +returns `{text}` (or writes `path` and returns `{path}`). The JSON format also carries a top-level `textStyles` array beside `meta`, a FigCraft extension (the REST `styles` metadata has no values): each entry is what `style.list {type: "text"}` returns (`name`, `style`, `paragraph`, and `bound` holding the ids `meta.variables` is keyed by, which it holds only for the variables of the exported local collections, so a file's own export with `collections` left out of it names variables its `meta` lacks, and an import keeps such a binding on the style it replaces; an entry's `style` keys are snake_case and its `bound` keys camelCase, `bound.fontSize` binding `style.font_size`); CSS, Tailwind and Dart are variables only. `variable.import {variables}` (an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level) reads one back: a collection joins this file's collection of the same name (values matched by mode name, new modes and variables added, a same-named variable of another type skipped with a warning; library copies and extended collections are never targets), others are -added; aliases are checked for loops; a `textStyles` array is read too (a style joins this file's text style of the same name, others are added; bindings follow the imported variables, one to a variable the JSON lacks is dropped with a warning); it returns `{collections, variables, updated, styles: {added, updated}, warnings}`, +added; aliases are checked for loops; a `textStyles` array is read too (a style joins this file's text style of the same name, others are added; bindings follow the imported variables; one to a variable the JSON lacks (unless the style it replaces already holds that id), to a field the style lacks or to a variable of another type is dropped with a warning; at most 10,000 styles and 32 bindings each are read); it returns `{collections, variables, updated, styles: {added, updated}, warnings}`, with a warning when the JSON holds no variables (`no variables found: expected meta.variables …`) or fewer than its collections list in `variableIds`. The Variables editor's Import… and Export… buttons do the same through file dialogs. From 81c3cc6369b0f738efb5a0708745fdcc3c5da1e9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 15:37:27 -0500 Subject: [PATCH 03/15] M7: Docs: who reads textStyles, the kept binding, filtered exports (#2173) The file-format row says only variable.import reads textStyles (file.open and file.import read the variables but not the text styles). The ROADMAP row says a binding is kept without a warning when the existing style already holds that variable, and that an export filtered by collections can name variables meta.variables doesn't include, as docs/mcp.md already does. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- ROADMAP.md | 2 +- docs/file-format-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 0a7ca6c78..953aca9ba 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -365,7 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| -| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it, `bound` holding the ids `meta.variables` is keyed by), and `variable.import` reads it back (styles merged by name, bindings re-pointed, a binding to a variable the JSON lacks dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | +| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it; `bound` holds the ids `meta.variables` is keyed by for variables of the exported collections, so an export filtered by `collections` can name variables it doesn't include), and `variable.import` reads it back (styles merged by name, bindings re-pointed; a binding to a variable the JSON lacks is kept without a warning when the existing style already holds that same variable, and otherwise dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | | 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/file-format-parity.md b/docs/file-format-parity.md index e0fc1c4c4..8b9b3bdab 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -22,7 +22,7 @@ and prototype interactions are still unchecked there. | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | | `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with generated sticky and shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | -| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array on export and import) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | +| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array, written by `variable.export` and read only by `variable.import`: `file.open` and `file.import` read the variables but not `textStyles`) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Developer Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — | | Local library files | team libraries in the cloud | yes (enable a `.figcraft` as a library) | yes (publish) | per-asset versions, updates with overrides kept | see [collaboration-parity](collaboration-parity.md) | From 737df567a32e0736f1472097af4eeab5a66a62c9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 16:41:17 -0500 Subject: [PATCH 04/15] M7: Variables JSON import: a re-imported style keeps its identity (#2173) Two text styles sharing a name and reordered after the export swapped their values on re-import, because each entry took the first untouched style of its name. An entry now takes the local text style with its exported id and name first, and falls back to the name, so a file's own export round-trips and another file's still matches by name. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/engine/src/cmd/styles.rs | 12 ++++++++---- crates/engine/src/cmd/variables_io.rs | 3 ++- crates/engine/src/variables_io_tests.rs | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index a61f4f18c..76c953bc6 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -264,11 +264,14 @@ fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result { /// Make or redefine this file's text style `name` from JSON (see [`text_kind`]). `bind` gives its /// variable bindings from the document, the new value and the style it replaces. The style -/// redefined is the first local text style of that name not in `touched`. True when one existed -/// (with the style's id); the caller settles and propagates. +/// redefined is the local text style of that name with the exported `id` (so a file re-importing +/// its own export keeps each style's identity when two share a name), else the first of that +/// name; never one in `touched`. True when one existed (with the style's id); the caller settles +/// and propagates. pub(crate) fn upsert_text_style( doc: &mut Document, name: &str, + id: Option<&str>, description: &str, style: &Value, paragraph: &Value, @@ -276,9 +279,10 @@ pub(crate) fn upsert_text_style( bind: impl FnOnce(&Document, &StyleKind, Option<&Style>) -> BTreeMap, ) -> Result<(StyleId, bool)> { let kind = text_kind("variable.import", style, paragraph)?; - let same = doc.styles.iter().position(|x| { + let eligible = |x: &Style| { x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id) && !touched.contains(&x.id) - }); + }; + let same = id.and_then(|id| doc.styles.iter().position(|x| x.id == id && eligible(x))).or_else(|| doc.styles.iter().position(&eligible)); let updated = same.is_some(); let bound = bind(doc, &kind, same.and_then(|i| doc.styles.get(i))); let mut st = match same.and_then(|i| doc.styles.get(i)) { diff --git a/crates/engine/src/cmd/variables_io.rs b/crates/engine/src/cmd/variables_io.rs index 5816ea44b..93133edba 100644 --- a/crates/engine/src/cmd/variables_io.rs +++ b/crates/engine/src/cmd/variables_io.rs @@ -104,7 +104,8 @@ fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap| { text_style_bindings(&name, wanted, ids, doc, kind, current, warnings) }; - match super::styles::upsert_text_style(doc, &name, &description, style, e.get("paragraph").unwrap_or(&Value::Null), &touched, bind) { + let id = e.get("id").and_then(Value::as_str); + match super::styles::upsert_text_style(doc, &name, id, &description, style, e.get("paragraph").unwrap_or(&Value::Null), &touched, bind) { Ok((sid, was)) => { touched.push(sid); if was { diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index 5ac6654a3..2225f12a3 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -450,6 +450,20 @@ fn a_files_own_export_leaves_its_text_styles_alone() { assert!(!r["warnings"].to_string().contains("left unbound"), "{r}"); } +/// Two text styles share a name and are reordered after the export: re-importing it gives each +/// style its own values back (matched by the exported id), not its namesake's. +#[test] +fn a_files_own_export_keeps_each_same_named_style_after_a_reorder() { + let mut s = body_session(); + ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 20}})); + let out = ex(&mut s, "variable.export", json!({})); + let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap(); + s.doc_mut().unwrap().styles.reverse(); + let before = s.doc().unwrap().styles.clone(); + let r = ex(&mut s, "variable.import", json!({"variables": file})); + assert_eq!(s.doc().unwrap().styles, before, "{r}"); +} + #[test] fn variables_import_caps_the_file_it_reads() { let dir = std::env::temp_dir().join(format!("figcraft-vars-io-cap-{}", std::process::id())); From b3da0ef69f21f6a483fc60c41bf24b753f9d9c4d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 16 Nov 2026 04:37:42 -0500 Subject: [PATCH 05/15] docs: status lines are main's summary with this PR's entry in front The main merge kept the old summary in front of main's rewritten one; this takes main's line and puts back only the PR's own entry. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 87c1e76da..46e9f4843 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-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); 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); M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **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 From a228a4a171b3c72d557eaf007902cf20993960bb Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:36:47 +0530 Subject: [PATCH 06/15] M4: commit number field edits on canvas click and clear stale drafts on selection change (#2392, #2433) - Resolves #2392 and #2433. - When deselecting or changing selection while editing a design panel field, the widget unmounted before focus loss could be processed, leaving a stale editing draft in UI memory that reappeared with a green outline upon reselecting. - Track selection ownership (`owner_sel`) for field drafts and clear stale drafts when selection changes or focus is surrendered. - When clicking the canvas while editing a panel field, defer the canvas pointer press by one frame to allow the field to process focus loss and commit its value before the canvas tool processes the click. - Add regression tests in field_tests for deselecting while editing and clicking the canvas while editing. --- crates/ui-egui/src/app.rs | 3 + crates/ui-egui/src/canvas.rs | 3 + crates/ui-egui/src/canvas/input.rs | 54 ++++++++++++----- crates/ui-egui/src/field_tests.rs | 36 ++++++++++++ crates/ui-egui/src/widgets.rs | 94 +++++++++++++++++++++++------- 5 files changed, 153 insertions(+), 37 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 10a82ed5c..17b908f51 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -240,6 +240,9 @@ impl FigApp { crate::control::drain(self, &ctx); windows::requests(self, &ctx); selection_spacing::sync(self, &ctx); + let cur_sel = self.session.selection().to_vec(); + let sel_id = egui::Id::unique("app_current_selection"); + ctx.data_mut(|d| d.insert_temp(sel_id, cur_sel)); // Before any widget: the navigation keys (F6, Tab, arrows, Escape) move the keyboard. a11y::begin(self, &ctx, ui.scope_id()); if self.ui.title_bar == TitleBar::Custom { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5de28c832..8badd282e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -97,6 +97,8 @@ pub struct CanvasState { pressure: Option, /// The latest scroll came from a mouse wheel rather than a trackpad (Scroll wheel zoom). wheel_is_mouse: bool, + /// A pointer press on the canvas deferred by one frame to let a focused panel field blur and commit. + deferred_down: Option<(Pos2, bool, Pos2, egui::Modifiers)>, } impl Default for CanvasState { @@ -128,6 +130,7 @@ impl Default for CanvasState { preedit: None, pressure: None, wheel_is_mouse: false, + deferred_down: None, } } } diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 1b177693e..2e02f66f6 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -322,35 +322,29 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo app.canvas.dragging = false; return true; } + deliver_deferred_down(app); let primary_pressed = ctx.input(|i| i.pointer.button_pressed(egui::PointerButton::Primary)); let primary_down = ctx.input(|i| i.pointer.primary_down()); let primary_released = ctx.input(|i| i.pointer.button_released(egui::PointerButton::Primary)); - // The press and the release carry their own positions: both in one frame (a quick click or a - // slow frame) would otherwise send the press from the hover position the pointer ended at. - let (press_pos, release_pos) = ctx.input(|i| { - let (mut press, mut release) = (None, None); - for e in &i.events { - if let egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } = e { - if *pressed { - press = Some(*pos); - } else { - release = Some(*pos); - } - } - } - (press, release) - }); + let (press_pos, release_pos) = pointer_press_release_positions(&ctx); let kind = if primary_pressed && resp.hovered() { app.canvas.dragging = true; app.ui.context_menu = None; app.ui.tool_flyout = None; // Clicking the canvas takes focus from panel fields. + let had_field_focus = ctx.memory(|m| m.focused()).is_some(); ctx.memory_mut(|m| { if let Some(f) = m.focused() { m.surrender_focus(f); } }); - Some(PointerKind::Down) + if had_field_focus { + app.canvas.deferred_down = Some((press_pos.unwrap_or(pos), primary_released, release_pos.unwrap_or(pos), mods)); + ctx.request_repaint(); + None + } else { + Some(PointerKind::Down) + } } else if app.canvas.dragging && primary_released { app.canvas.dragging = false; Some(PointerKind::Up) @@ -397,6 +391,34 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo } } +/// Send a pointer down/up sequence deferred from the previous frame to let a focused field blur and commit. +fn deliver_deferred_down(app: &mut FigApp) { + if let Some((press_at, deferred_released, release_at, deferred_mods)) = app.canvas.deferred_down.take() { + send(app, PointerKind::Down, press_at, &deferred_mods); + if deferred_released { + app.canvas.dragging = false; + send(app, PointerKind::Up, release_at, &deferred_mods); + } + } +} + +/// The press and release positions from raw pointer events in this batch. +fn pointer_press_release_positions(ctx: &egui::Context) -> (Option, Option) { + ctx.input(|i| { + let (mut press, mut release) = (None, None); + for e in &i.events { + if let egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } = e { + if *pressed { + press = Some(*pos); + } else { + release = Some(*pos); + } + } + } + (press, release) + }) +} + /// Pointer event `kind` at screen point `pos`, to the tools. fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) { let ev = pointer_event(app, kind, pos, m); diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 4d8b5cf62..562fc45ec 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1765,3 +1765,39 @@ fn a_boolean_groups_field_shows_the_radius_it_draws() { type_into(&mut u, "Corner radius", "+10", Key::Enter); assert_eq!(u.app.session.doc().unwrap().node(g).unwrap().corners.radii, [10.0; 4], "0 + 10, not 30 + 10"); } + +#[test] +fn deselecting_while_editing_number_field_retains_stale_value_on_reselect() { + let (mut u, _a, b) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + u.frame(vec![Event::Text("23".into())]); + + // Deselect (clear selection) while field is in editing state + u.app.run("select.clear", json!({})); + u.frame(vec![]); + + // Now select b (which has height 20) + u.app.run("select.set", json!({"ids": [b]})); + u.frame(vec![]); + + // Verify height field does NOT stay stuck in editing state + let h_editing = u.ctx.data(|d| d.get_temp::(Id::unique("lay_h").with("editing"))); + assert_eq!(h_editing, None, "Height field must not be stuck in editing state after deselect and reselect"); + assert_eq!(field(&mut u, "Height").1, "20", "Height field must show layer b's height"); +} + +#[test] +fn clicking_canvas_while_editing_number_field_commits_value() { + let (mut u, a, _) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + u.frame(vec![Event::Text("50".into())]); + + // Click on empty canvas (outside the layers and panels) + let canvas_click = pos2(500.0, 500.0); + click(&mut u, canvas_click); + + let doc = u.app.session.doc().unwrap(); + assert_eq!(doc.node(a).unwrap().height, 50.0, "Clicking canvas must commit the edited field value"); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index c1f8614b4..552f8fb62 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -294,6 +294,56 @@ fn cancel_retargeted_field_save(ui: &mut Ui, id: Id) { ui.memory_mut(|m| m.surrender_focus(editor)); } +/// Drop a field draft when the active selection has changed since the edit began. +fn sync_field_owner(ui: &mut Ui, id: Id) -> (Option, Option>) { + let editing_id = id.with("editing"); + let owner_id = id.with("owner_sel"); + let sel_id = egui::Id::unique("app_current_selection"); + let cur_sel: Option> = ui.data(|d| d.get_temp(sel_id)); + let owner: Option> = ui.data(|d| d.get_temp(owner_id)); + let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); + if editing.is_some() && cur_sel.is_some() && owner.is_some() && owner != cur_sel { + ui.data_mut(|d| { + d.remove::(editing_id); + d.remove::(id.with("kept")); + d.remove::>(owner_id); + d.remove::(id.with("selectall")); + d.remove::(id.with("cmdstart")); + d.remove::(id.with("edited")); + }); + ui.memory_mut(|m| m.surrender_focus(id.with("te"))); + editing = None; + } + (editing, cur_sel) +} + +/// Discard an editor's active draft and surrender focus. +fn clear_field_editor(ui: &mut Ui, id: Id) { + ui.data_mut(|d| { + d.remove::(id.with("editing")); + d.remove::>(id.with("owner_sel")); + }); + ui.memory_mut(|m| m.surrender_focus(id.with("te"))); +} + +/// Paint a lead label or icon for a number field. +fn paint_number_field_lead(ui: &mut Ui, lead: &Lead, lead_rect: Rect, rect: Rect, lead_w: f32, lead_resp: &egui::Response, t: &Tokens) { + match lead { + Lead::Text(s) => { + let galley = crate::bidi::name_galley(ui.painter(), s, regular(11.0), t.text_secondary, lead_w - 12.0); + // A label cut short shows whole on hover. + if galley.elided { + lead_resp.clone().on_hover_text(*s); + } + ui.painter().galley(pos2(lead_rect.min.x + 8.0, rect.center().y - galley.size().y / 2.0), galley, t.text_secondary); + } + Lead::Icon(i, _) => { + icons::paint(ui.painter(), Rect::from_center_size(lead_rect.center() + vec2(1.0, 0.0), vec2(14.0, 14.0)), *i, t.icon_secondary) + } + Lead::None | Lead::Named(_) => {} + } +} + /// Implement the shared number field: label/icon lead, scrubbing, keyboard stepping and /// typing, select-all when a click starts editing, bindable values and deferred-save /// cancellation; returns an edit and/or bind event. @@ -323,7 +373,8 @@ fn number_field_impl( let lead_rect = Rect::from_min_size(rect.min, vec2(lead_w, FIELD_H)); let edit_rect = Rect::from_min_max(pos2(rect.min.x + lead_w, rect.min.y), rect.max); let editing_id = id.with("editing"); - let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); + let owner_id = id.with("owner_sel"); + let (mut editing, cur_sel) = sync_field_owner(ui, id); // Alt held over the field scrubs it too, as the label always does: "hover the input field // itself and hold down the modifier key" (Adjust alignment, rotation, position, and // dimensions). The field senses drags only while Alt is held, or while a scrub begun that way @@ -349,20 +400,7 @@ fn number_field_impl( } else if hovered { ui.painter().rect_stroke(rect, CornerRadius::same(5), Stroke::new(1.0, t.field_hover_border), StrokeKind::Inside); } - match lead { - Lead::Text(s) => { - let galley = crate::bidi::name_galley(ui.painter(), s, regular(11.0), t.text_secondary, lead_w - 12.0); - // A label cut short shows whole on hover. - if galley.elided { - lead_resp.clone().on_hover_text(s); - } - ui.painter().galley(pos2(lead_rect.min.x + 8.0, rect.center().y - galley.size().y / 2.0), galley, t.text_secondary); - } - Lead::Icon(i, _) => { - icons::paint(ui.painter(), Rect::from_center_size(lead_rect.center() + vec2(1.0, 0.0), vec2(14.0, 14.0)), i, t.icon_secondary) - } - Lead::None | Lead::Named(_) => {} - } + paint_number_field_lead(ui, &lead, lead_rect, rect, lead_w, &lead_resp, &t); if lead_resp.hovered() || lead_resp.dragged() || (alt_now && editing.is_none() && field_resp.hovered()) || (alt_scrub && field_resp.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } @@ -434,6 +472,9 @@ fn number_field_impl( ui.data_mut(|d| { d.insert_temp(editing_id, editing.clone().unwrap_or_default()); d.insert_temp(kept_id, value.map(fmt_num).unwrap_or_default()); + if let Some(ref s) = cur_sel { + d.insert_temp(owner_id, s.clone()); + } d.insert_temp(id.with("selectall"), !typed_now); d.insert_temp(id.with("cmdstart"), with_command); d.remove::(id.with("edited")); @@ -496,8 +537,7 @@ fn number_field_impl( } if esc { // Back to what it was: nothing is committed. - ui.data_mut(|d| d.remove::(editing_id)); - ui.memory_mut(|m| m.surrender_focus(id.with("te"))); + clear_field_editor(ui, id); } else if r.lost_focus() || enter { // Enter, Tab or a click elsewhere commits what was typed (a field left as it was // commits nothing: no undo step, and a rounded display isn't written back). @@ -511,7 +551,9 @@ fn number_field_impl( { out = Some(e); } - ui.data_mut(|d| d.remove::(editing_id)); + clear_field_editor(ui, id); + } else if !r.has_focus() && !started { + clear_field_editor(ui, id); } else { ui.data_mut(|d| d.insert_temp(editing_id, text)); } @@ -682,7 +724,8 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str cancel_retargeted_field_save(ui, id); let t = Tokens::get(ui.ctx()); let editing_id = id.with("editing"); - let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); + let owner_id = id.with("owner_sel"); + let (mut editing, cur_sel) = sync_field_owner(ui, id); let resp = ui.interact(rect, id.with("click"), Sense::click()); let shown = if secret { std::borrow::Cow::Owned("•".repeat(value.chars().count())) } else { std::borrow::Cow::Borrowed(value) }; a11y::text(&resp, name, &shown); @@ -695,6 +738,9 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str let started = editing.is_none() && resp.clicked(); if started { editing = Some(value.to_string()); + if let Some(ref s) = cur_sel { + ui.data_mut(|d| d.insert_temp(owner_id, s.clone())); + } ui.memory_mut(|m| m.request_focus(id.with("te"))); select_all_next(ui, id.with("te"), value); } @@ -708,10 +754,12 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str let enter = !started && ui.input(|i| i.key_pressed(egui::Key::Enter)); let esc = ui.input(|i| i.key_pressed(egui::Key::Escape)); if esc { - ui.data_mut(|d| d.remove::(editing_id)); + clear_field_editor(ui, id); } else if r.lost_focus() || enter { out = Some(text); - ui.data_mut(|d| d.remove::(editing_id)); + clear_field_editor(ui, id); + } else if !r.has_focus() && !started { + clear_field_editor(ui, id); } else { ui.data_mut(|d| d.insert_temp(editing_id, text)); } @@ -1412,6 +1460,10 @@ pub fn text_field_inline(ui: &mut Ui, id: Id, value: &str, rect: Rect, font: egu ui.data_mut(|d| d.remove::(buf_id)); ui.memory_mut(|m| m.surrender_focus(te_id)); (text != value && !text.trim().is_empty()).then_some(text) + } else if !r.has_focus() && !started { + ui.data_mut(|d| d.remove::(buf_id)); + ui.memory_mut(|m| m.surrender_focus(te_id)); + None } else { ui.data_mut(|d| d.insert_temp(buf_id, text)); None From 4dbcf0dff652175235f7b2cefc5ccf871c8ac773 Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:40:52 +0530 Subject: [PATCH 07/15] M4: rename field test and update UI parity docs (#2392, #2433) - Rename `deselecting_while_editing_number_field_retains_stale_value_on_reselect` to `a_draft_is_dropped_when_the_selection_changes` to reflect what is asserted. - Update `docs/ui-parity.md` header status line and add a revision row for #2392 and #2433 with test names. --- crates/ui-egui/src/field_tests.rs | 2 +- docs/ui-parity.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 562fc45ec..8c20a541d 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1767,7 +1767,7 @@ fn a_boolean_groups_field_shows_the_radius_it_draws() { } #[test] -fn deselecting_while_editing_number_field_retains_stale_value_on_reselect() { +fn a_draft_is_dropped_when_the_selection_changes() { let (mut u, _a, b) = setup(); let (h_pos, _) = field(&mut u, "Height"); click(&mut u, h_pos); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6a9d101fd..b69f7cfa0 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-19 · **Change:** minor (M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two 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) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `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`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); 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-19 · **Change:** minor (M4: design and layout panel field edits commit on canvas click by deferring pointer press by one frame, and stale drafts are dropped when selection changes so green outlines do not persist on reselect (#2392, #2433; `a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two 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) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `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`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); 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: @@ -345,3 +345,4 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | 2026-11-12 | minor | M8: a selected polygon or star has a Count handle on the canvas (hover label Count N), measured in Figma's web app on 2026-11-12: it sits on the first vertex clockwise from the top (a star's first outer point, not inset), and a drag sets the count to round(360 / the pointer's clockwise angle from the top point about the centre), so 90 degrees gives 4, 72 gives 5 and 45 gives 8, with the step shrinking as the count grows; one drag is one undo step. The count is clamped to 3 to 60 (the help center's range for a star; a polygon's maximum was not read). Tests: `a_polygon_has_a_count_handle_on_its_first_vertex_clockwise_from_the_top`, `dragging_the_count_handle_sets_the_count_by_the_angle_about_the_centre`, `a_count_drag_is_one_undo_step` | | 2026-10-10 | major | Created from the ROADMAP's look-and-feel and interaction items, the keymap and the canvas code | | 2026-11-12 | minor | M8, #2293: Duplicate repeats the last copy's move and rotation, not only the shift of its bounds' corner. The step is the move of the copies' centre in the page frame (not turned by the accumulated rotation) plus the turn each copy has over its source, applied about the new copy's centre, or the selection's centre for several layers; size is not stepped; a deselect forgets the step. Measured in Figma's web app on 2026-11-12 (typed and dragged moves and turns, one layer and two). | +| 2026-11-19 | patch | Panel fields (#2392, #2433): editing drafts in design and layout number and text fields record their owning selection and are dropped on selection change, preventing stale values and green outlines from persisting across deselects; clicking the canvas while editing defers the canvas pointer press by one frame to let the field blur and commit its value before the tool clears or changes selection (`a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`) | From 802808a17a93fc986ec4133605b835879ff46063 Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:57:55 +0530 Subject: [PATCH 08/15] M4: preserve field drafts across window deactivation and refresh selection snapshot (#2392, #2433) - Check widget focus directly (`r.ctx.memory(|m| m.has_focus(r.id))`) instead of `r.has_focus()` so uncommitted drafts are not cleared when the window loses focus (e.g. application switching). - Refresh the active selection snapshot in `ctx.data` before rendering the right panel so draft ownership reflects any selection updates from the layers panel in the same frame. - Add regression tests in `field_tests` and update parity docs. --- crates/ui-egui/src/app.rs | 3 +++ crates/ui-egui/src/field_tests.rs | 32 +++++++++++++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 6 +++--- docs/ui-parity.md | 4 ++-- 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 17b908f51..c63d688c6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -375,6 +375,9 @@ impl FigApp { .show(ui, |ui| { let label = right_tab_label(self.ui.right_tab); a11y::region(&mut self.ui.nav, ui, a11y::Region::Properties, egui::accesskit::Role::Pane, label); + let cur_sel = self.session.selection().to_vec(); + let sel_id = egui::Id::unique("app_current_selection"); + ui.ctx().data_mut(|d| d.insert_temp(sel_id, cur_sel)); right::right_panel(self, ui) }); } diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 8c20a541d..8de277a09 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1801,3 +1801,35 @@ fn clicking_canvas_while_editing_number_field_commits_value() { let doc = u.app.session.doc().unwrap(); assert_eq!(doc.node(a).unwrap().height, 50.0, "Clicking canvas must commit the edited field value"); } + +#[test] +fn field_draft_is_retained_when_window_loses_focus() { + let (mut u, _a, _) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + u.frame(vec![Event::Text("55".into())]); + + // Simulate window deactivation (e.g. user switching windows/applications) + u.frame_raw(egui::RawInput { focused: false, ..Default::default() }); + + // Verify draft is still present + let h_editing = u.ctx.data(|d| d.get_temp::(Id::unique("lay_h").with("editing"))); + assert_eq!(h_editing.as_deref(), Some("55"), "field draft must be retained when window loses focus"); +} + +#[test] +fn selecting_different_layer_in_layers_panel_drops_draft() { + let (mut u, _a, b) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + u.frame(vec![Event::Text("99".into())]); + + // Switch selection to B via session (as layers panel does when clicked) + u.app.run("select.set", json!({"ids": [b]})); + u.frame(vec![]); + + // Verify draft was dropped and b's height is shown, not 99 + let h_editing = u.ctx.data(|d| d.get_temp::(Id::unique("lay_h").with("editing"))); + assert_eq!(h_editing, None, "stale draft must not leak into newly selected layer"); + assert_eq!(field(&mut u, "Height").1, "20", "Height field must show layer b's height"); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 552f8fb62..eb7ba2ef6 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -552,7 +552,7 @@ fn number_field_impl( out = Some(e); } clear_field_editor(ui, id); - } else if !r.has_focus() && !started { + } else if !r.ctx.memory(|m| m.has_focus(r.id)) && !started { clear_field_editor(ui, id); } else { ui.data_mut(|d| d.insert_temp(editing_id, text)); @@ -758,7 +758,7 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str } else if r.lost_focus() || enter { out = Some(text); clear_field_editor(ui, id); - } else if !r.has_focus() && !started { + } else if !r.ctx.memory(|m| m.has_focus(r.id)) && !started { clear_field_editor(ui, id); } else { ui.data_mut(|d| d.insert_temp(editing_id, text)); @@ -1460,7 +1460,7 @@ pub fn text_field_inline(ui: &mut Ui, id: Id, value: &str, rect: Rect, font: egu ui.data_mut(|d| d.remove::(buf_id)); ui.memory_mut(|m| m.surrender_focus(te_id)); (text != value && !text.trim().is_empty()).then_some(text) - } else if !r.has_focus() && !started { + } else if !r.ctx.memory(|m| m.has_focus(te_id)) && !started { ui.data_mut(|d| d.remove::(buf_id)); ui.memory_mut(|m| m.surrender_focus(te_id)); None diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b69f7cfa0..3d9c53d4e 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-19 · **Change:** minor (M4: design and layout panel field edits commit on canvas click by deferring pointer press by one frame, and stale drafts are dropped when selection changes so green outlines do not persist on reselect (#2392, #2433; `a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two 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) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `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`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); 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-19 · **Change:** minor (M4: design and layout panel field edits commit on canvas click by deferring pointer press by one frame, and stale drafts are dropped when selection changes so green outlines do not persist on reselect (#2392, #2433; `a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`, `field_draft_is_retained_when_window_loses_focus`, `selecting_different_layer_in_layers_panel_drops_draft`); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two 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) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `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`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); 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: @@ -345,4 +345,4 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | 2026-11-12 | minor | M8: a selected polygon or star has a Count handle on the canvas (hover label Count N), measured in Figma's web app on 2026-11-12: it sits on the first vertex clockwise from the top (a star's first outer point, not inset), and a drag sets the count to round(360 / the pointer's clockwise angle from the top point about the centre), so 90 degrees gives 4, 72 gives 5 and 45 gives 8, with the step shrinking as the count grows; one drag is one undo step. The count is clamped to 3 to 60 (the help center's range for a star; a polygon's maximum was not read). Tests: `a_polygon_has_a_count_handle_on_its_first_vertex_clockwise_from_the_top`, `dragging_the_count_handle_sets_the_count_by_the_angle_about_the_centre`, `a_count_drag_is_one_undo_step` | | 2026-10-10 | major | Created from the ROADMAP's look-and-feel and interaction items, the keymap and the canvas code | | 2026-11-12 | minor | M8, #2293: Duplicate repeats the last copy's move and rotation, not only the shift of its bounds' corner. The step is the move of the copies' centre in the page frame (not turned by the accumulated rotation) plus the turn each copy has over its source, applied about the new copy's centre, or the selection's centre for several layers; size is not stepped; a deselect forgets the step. Measured in Figma's web app on 2026-11-12 (typed and dragged moves and turns, one layer and two). | -| 2026-11-19 | patch | Panel fields (#2392, #2433): editing drafts in design and layout number and text fields record their owning selection and are dropped on selection change, preventing stale values and green outlines from persisting across deselects; clicking the canvas while editing defers the canvas pointer press by one frame to let the field blur and commit its value before the tool clears or changes selection (`a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`) | +| 2026-11-19 | patch | Panel fields (#2392, #2433): editing drafts in design and layout number and text fields record their owning selection and are dropped on selection change, preventing stale values and green outlines from persisting across deselects; window blur retains field drafts while widget focus is kept; clicking the canvas while editing defers the canvas pointer press by one frame to let the field blur and commit its value before the tool clears or changes selection (`a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`, `field_draft_is_retained_when_window_loses_focus`, `selecting_different_layer_in_layers_panel_drops_draft`) | From 9448c7f16c8b67ed3d0357364fa867fdae11c38a Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:11:00 +0530 Subject: [PATCH 09/15] M4: exercise UI layer row click in same-frame selection test (#2392, #2433) - Click layer B via `u.row_at(b)` in the Layers panel during the frame instead of directly updating the session selection. --- crates/ui-egui/src/field_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 8de277a09..16bddf154 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1824,9 +1824,9 @@ fn selecting_different_layer_in_layers_panel_drops_draft() { click(&mut u, h_pos); u.frame(vec![Event::Text("99".into())]); - // Switch selection to B via session (as layers panel does when clicked) - u.app.run("select.set", json!({"ids": [b]})); - u.frame(vec![]); + // Click layer B in the Layers panel (sending press and release in the same frame) + let b_row = u.row_at(b); + click(&mut u, b_row); // Verify draft was dropped and b's height is shown, not 99 let h_editing = u.ctx.data(|d| d.get_temp::(Id::unique("lay_h").with("editing"))); From b71204ca4eaf14936d36dd26143c740d2c76a16a Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:48:40 +0530 Subject: [PATCH 10/15] M4: simplify canvas input primary pointer kind dispatch (#2392, #2433) - Extract primary_pointer_kind helper to keep input cognitive complexity within limits. --- crates/ui-egui/src/canvas/input.rs | 82 ++++++++++++++++++------------ 1 file changed, 49 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 462a6af80..7bc62f6d5 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -328,39 +328,7 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo let primary_down = ctx.input(|i| i.pointer.primary_down()); let primary_released = ctx.input(|i| i.pointer.button_released(egui::PointerButton::Primary)); let (press_pos, release_pos) = pointer_press_release_positions(&ctx); - let kind = if primary_pressed && resp.hovered() { - app.canvas.dragging = true; - app.ui.context_menu = None; - app.ui.tool_flyout = None; - // Clicking the canvas takes focus from panel fields. - let had_field_focus = ctx.memory(|m| m.focused()).is_some(); - ctx.memory_mut(|m| { - if let Some(f) = m.focused() { - m.surrender_focus(f); - } - }); - if had_field_focus { - app.canvas.deferred_down = Some((press_pos.unwrap_or(pos), primary_released, release_pos.unwrap_or(pos), mods)); - ctx.request_repaint(); - None - } else { - Some(PointerKind::Down) - } - } else if app.canvas.dragging && primary_released { - app.canvas.dragging = false; - Some(PointerKind::Up) - } else if app.canvas.dragging && primary_down { - Some(PointerKind::Move) - } else if resp.hovered() { - app.canvas.hovering = true; - Some(PointerKind::Hover) - } else { - // Something over the canvas took the pointer. - if std::mem::take(&mut app.canvas.hovering) { - left(app); - } - None - }; + let kind = primary_pointer_kind(app, &ctx, resp, pos, mods, press_pos, release_pos, primary_pressed, primary_down, primary_released); // Pen pressure comes with touch events (a pen on Windows, a stylus in a browser); a mouse, // macOS and Linux tablets report none and draw at the stroke weight. let force = ctx.input(|i| { @@ -397,6 +365,54 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo } } +/// Decide the primary pointer event kind (Down, Up, Move, Hover, or deferred). +fn primary_pointer_kind( + app: &mut FigApp, + ctx: &egui::Context, + resp: &egui::Response, + pos: Pos2, + mods: egui::Modifiers, + press_pos: Option, + release_pos: Option, + primary_pressed: bool, + primary_down: bool, + primary_released: bool, +) -> Option { + if primary_pressed && resp.hovered() { + app.canvas.dragging = true; + app.ui.context_menu = None; + app.ui.tool_flyout = None; + // Clicking the canvas takes focus from panel fields. + let had_field_focus = ctx.memory(|m| m.focused()).is_some(); + ctx.memory_mut(|m| { + if let Some(f) = m.focused() { + m.surrender_focus(f); + } + }); + if had_field_focus { + app.canvas.deferred_down = Some((press_pos.unwrap_or(pos), primary_released, release_pos.unwrap_or(pos), mods)); + ctx.request_repaint(); + None + } else { + Some(PointerKind::Down) + } + } else if app.canvas.dragging && primary_released { + app.canvas.dragging = false; + Some(PointerKind::Up) + } else if app.canvas.dragging && primary_down { + Some(PointerKind::Move) + } else if resp.hovered() { + app.canvas.hovering = true; + Some(PointerKind::Hover) + } else { + // Something over the canvas took the pointer. + if std::mem::take(&mut app.canvas.hovering) { + left(app); + } + None + } +} + /// Send a pointer down/up sequence deferred from the previous frame to let a focused field blur and commit. fn deliver_deferred_down(app: &mut FigApp) { if let Some((press_at, deferred_released, release_at, deferred_mods)) = app.canvas.deferred_down.take() { From b8fca1ab6da4de11339ca4aad5b02797323fe673 Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:22:38 +0530 Subject: [PATCH 11/15] M4, #2392: track field draft generation and document identity, preserve canvas coordinates across deferred delivery --- crates/ui-egui/src/app.rs | 8 +- crates/ui-egui/src/canvas.rs | 19 +++- crates/ui-egui/src/canvas/input.rs | 77 +++++++++++++--- crates/ui-egui/src/field_tests.rs | 141 ++++++++++++++++++++++++++++- crates/ui-egui/src/widgets.rs | 97 +++++++++++++++++--- docs/ui-parity.md | 2 +- 6 files changed, 309 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index c63d688c6..ad45c5347 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -240,9 +240,9 @@ impl FigApp { crate::control::drain(self, &ctx); windows::requests(self, &ctx); selection_spacing::sync(self, &ctx); + let doc_uid = self.session.ds().ok().map(|d| d.uid); let cur_sel = self.session.selection().to_vec(); - let sel_id = egui::Id::unique("app_current_selection"); - ctx.data_mut(|d| d.insert_temp(sel_id, cur_sel)); + widgets::update_selection_snapshot(&ctx, doc_uid, cur_sel); // Before any widget: the navigation keys (F6, Tab, arrows, Escape) move the keyboard. a11y::begin(self, &ctx, ui.scope_id()); if self.ui.title_bar == TitleBar::Custom { @@ -375,9 +375,9 @@ impl FigApp { .show(ui, |ui| { let label = right_tab_label(self.ui.right_tab); a11y::region(&mut self.ui.nav, ui, a11y::Region::Properties, egui::accesskit::Role::Pane, label); + let doc_uid = self.session.ds().ok().map(|d| d.uid); let cur_sel = self.session.selection().to_vec(); - let sel_id = egui::Id::unique("app_current_selection"); - ui.ctx().data_mut(|d| d.insert_temp(sel_id, cur_sel)); + widgets::update_selection_snapshot(ui.ctx(), doc_uid, cur_sel); right::right_panel(self, ui) }); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 9ce36667b..d46f759f6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -48,6 +48,19 @@ pub mod render_worker; pub(crate) mod selection_spacing; pub mod widget_bar; +/// A pointer press on the canvas deferred by one frame to let a focused panel field blur and commit. +#[derive(Clone, Debug)] +pub(crate) struct DeferredDown { + pub(crate) doc_uid: u64, + pub(crate) page: NodeId, + pub(crate) page_pos: Point, + pub(crate) screen_pos: Pos2, + pub(crate) released: bool, + pub(crate) release_page_pos: Point, + pub(crate) release_screen_pos: Pos2, + pub(crate) mods: egui::Modifiers, +} + pub struct CanvasState { pub rect: Rect, texture: Option, @@ -77,13 +90,14 @@ pub struct CanvasState { pub refine_latency_ms: Option, /// The share of the canvas no render covered last frame: the page background showed there. pub uncovered: f32, - dragging: bool, + pub(crate) dragging: bool, space_pan: bool, middle_pan: Option<(Pos2, f64, f64)>, /// The zoom tool (Z held): zooming out (Alt) or in, and where its drag started. zoom_tool: Option, zoom_drag: Option, pub last_pointer: Option, + pub last_down: Option, /// The real pointer was over the canvas last frame (leaving it clears what it hovered). hovering: bool, /// The hover last sent to the tools and the state it was found in ([`input::HoverKey`]): the @@ -99,7 +113,7 @@ pub struct CanvasState { /// The latest scroll came from a mouse wheel rather than a trackpad (Scroll wheel zoom). wheel_is_mouse: bool, /// A pointer press on the canvas deferred by one frame to let a focused panel field blur and commit. - deferred_down: Option<(Pos2, bool, Pos2, egui::Modifiers)>, + pub(crate) deferred_down: Option, } impl Default for CanvasState { @@ -126,6 +140,7 @@ impl Default for CanvasState { zoom_tool: None, zoom_drag: None, last_pointer: None, + last_down: None, hovering: false, last_hover: None, preedit: None, diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 7bc62f6d5..f1c0bc795 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -1,4 +1,4 @@ -use super::{FigApp, Point, PointerKind, Pos2, Rect, Ui, json, pointer_event}; +use super::{FigApp, Point, PointerEvent, PointerKind, Pos2, Rect, Ui, json, pointer_event}; /// What a hover was found in: the event (where, the modifiers, the zoom) and what decides what it /// hits (the file and page, their revision, the selection, the tool and modes). The same again finds @@ -208,6 +208,7 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo }); let (wheel, zoom_delta) = wheel_zoom(app, &ctx, zoom_delta, mods.shift); let scroll = wheel + pan; + deliver_deferred_down(app, &ctx); let editing_text = app.session.ds().map(|d| d.text_edit.is_some()).unwrap_or(false); let typing_elsewhere = crate::a11y::field_focused(&ctx); app.canvas.space_pan = space && !editing_text && !typing_elsewhere; @@ -323,7 +324,6 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo app.canvas.dragging = false; return true; } - deliver_deferred_down(app); let primary_pressed = ctx.input(|i| i.pointer.button_pressed(egui::PointerButton::Primary)); let primary_down = ctx.input(|i| i.pointer.primary_down()); let primary_released = ctx.input(|i| i.pointer.button_released(egui::PointerButton::Primary)); @@ -390,7 +390,22 @@ fn primary_pointer_kind( } }); if had_field_focus { - app.canvas.deferred_down = Some((press_pos.unwrap_or(pos), primary_released, release_pos.unwrap_or(pos), mods)); + if let Ok(ds) = app.session.ds() { + let press_screen = press_pos.unwrap_or(pos); + let press_page = app.to_page(press_screen); + let release_screen = release_pos.unwrap_or(pos); + let release_page = app.to_page(release_screen); + app.canvas.deferred_down = Some(crate::canvas::DeferredDown { + doc_uid: ds.uid, + page: ds.page, + page_pos: press_page, + screen_pos: press_screen, + released: primary_released, + release_page_pos: release_page, + release_screen_pos: release_screen, + mods, + }); + } ctx.request_repaint(); None } else { @@ -414,13 +429,28 @@ fn primary_pointer_kind( } /// Send a pointer down/up sequence deferred from the previous frame to let a focused field blur and commit. -fn deliver_deferred_down(app: &mut FigApp) { - if let Some((press_at, deferred_released, release_at, deferred_mods)) = app.canvas.deferred_down.take() { - send(app, PointerKind::Down, press_at, &deferred_mods); - if deferred_released { - app.canvas.dragging = false; - send(app, PointerKind::Up, release_at, &deferred_mods); - } +fn deliver_deferred_down(app: &mut FigApp, ctx: &egui::Context) { + let Some(deferred) = app.canvas.deferred_down.take() else { + return; + }; + let Ok(ds) = app.session.ds() else { + app.canvas.dragging = false; + return; + }; + if ds.uid != deferred.doc_uid || ds.page != deferred.page { + app.canvas.dragging = false; + return; + } + let released_now = !ctx.input(|i| i.pointer.primary_down()); + if deferred.released || released_now { + send_at_page(app, PointerKind::Down, deferred.page_pos, deferred.screen_pos, &deferred.mods); + app.canvas.dragging = false; + let up_page = if deferred.released { deferred.release_page_pos } else { deferred.page_pos }; + let up_screen = if deferred.released { deferred.release_screen_pos } else { deferred.screen_pos }; + send_at_page(app, PointerKind::Up, up_page, up_screen, &deferred.mods); + } else { + app.canvas.dragging = true; + send_at_page(app, PointerKind::Down, deferred.page_pos, deferred.screen_pos, &deferred.mods); } } @@ -453,7 +483,29 @@ fn pan_past_edge(app: &mut FigApp, ctx: &egui::Context, mods: &egui::Modifiers) } fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) { - let ev = pointer_event(app, kind, pos, m); + let page_pos = app.to_page(pos); + send_at_page(app, kind, page_pos, pos, m); +} + +fn send_at_page(app: &mut FigApp, kind: PointerKind, page_pos: Point, screen_pos: Pos2, m: &egui::Modifiers) { + let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0); + let ev = PointerEvent { + kind, + x: page_pos.x, + y: page_pos.y, + sx: f64::from(screen_pos.x), + sy: f64::from(screen_pos.y), + shift: m.shift, + alt: m.alt, + cmd: m.command || app.ui.crop.is_some(), + ctrl: m.ctrl, + zoom, + pressure: app.canvas.pressure, + }; + send_pointer_event(app, ev, kind); +} + +fn send_pointer_event(app: &mut FigApp, ev: PointerEvent, kind: PointerKind) { // A hover where nothing changed since the last one finds what that one found (the state is // taken after it ran: what it set, such as the hovered layer, is part of it). let hover = kind == PointerKind::Hover; @@ -463,6 +515,9 @@ fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) { if kind == PointerKind::Up { app.canvas.pressure = None; } + if kind == PointerKind::Down { + app.canvas.last_down = Some(Point::new(ev.x, ev.y)); + } app.canvas.last_pointer = Some(Point::new(ev.x, ev.y)); // A gesture something else committed under the held button (a colour picker closing on this // press) leaves the rest of its drag with nothing to edit: that is not worth saying. diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 16bddf154..8d30f950b 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1819,17 +1819,150 @@ fn field_draft_is_retained_when_window_loses_focus() { #[test] fn selecting_different_layer_in_layers_panel_drops_draft() { - let (mut u, _a, b) = setup(); + let (mut u, a, b) = setup(); let (h_pos, _) = field(&mut u, "Height"); click(&mut u, h_pos); u.frame(vec![Event::Text("99".into())]); - // Click layer B in the Layers panel (sending press and release in the same frame) + // Click layer B in the Layers panel with press and release in the same frame let b_row = u.row_at(b); - click(&mut u, b_row); + u.frame(vec![ + Event::PointerButton { pos: b_row, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + Event::PointerButton { pos: b_row, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + ]); + u.frame(vec![]); - // Verify draft was dropped and b's height is shown, not 99 + // Verify draft was dropped, A was not committed with 99, and B retains its height + let doc = u.app.session.doc().unwrap(); + assert_eq!(doc.node(a).unwrap().height, 30.0, "Layer A must retain its original height and not commit the draft"); + assert_eq!(doc.node(b).unwrap().height, 20.0, "Layer B must retain its original height"); let h_editing = u.ctx.data(|d| d.get_temp::(Id::unique("lay_h").with("editing"))); assert_eq!(h_editing, None, "stale draft must not leak into newly selected layer"); assert_eq!(field(&mut u, "Height").1, "20", "Height field must show layer b's height"); } + +#[test] +fn draft_is_dropped_across_empty_selection_transition() { + let (mut u, a, _) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + u.frame(vec![Event::Text("23".into())]); + + // Clear selection for one frame (Design panel will not render Height during this frame) + u.app.session.execute("select.set", &json!({"ids": []})).unwrap(); + u.frame(vec![]); + + // Update A's height externally while deselected + u.app.session.execute("node.set", &json!({"id": a, "props": {"height": 60.0}})).unwrap(); + + // Reselect A + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.frame(vec![]); + + // Draft must have been invalidated across the hidden selection transition + let h_editing = u.ctx.data(|d| d.get_temp::(Id::unique("lay_h").with("editing"))); + assert_eq!(h_editing, None, "draft must be invalidated across empty selection transition"); + assert_eq!(field(&mut u, "Height").1, "60", "Height field must display A's updated height"); + let doc = u.app.session.doc().unwrap(); + assert_eq!(doc.node(a).unwrap().height, 60.0, "Layer A height must remain 60"); +} + +#[test] +fn draft_is_dropped_when_layer_value_changes_externally() { + let (mut u, a, _) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + u.frame(vec![Event::Text("23".into())]); + + // Change A's height externally through node.set while selection remains unchanged + u.app.session.execute("node.set", &json!({"id": a, "props": {"height": 75.0}})).unwrap(); + u.frame(vec![]); + + // Draft must be dropped and field must show the new size 75 + let h_editing = u.ctx.data(|d| d.get_temp::(Id::unique("lay_h").with("editing"))); + assert_eq!(h_editing, None, "draft must be dropped when layer size changes"); + assert_eq!(field(&mut u, "Height").1, "75", "Height field must show the new layer size"); +} + +#[test] +fn deferred_canvas_press_preserves_page_coordinates_across_view_change() { + let (mut u, _a, _) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + u.frame(vec![Event::Text("50".into())]); + + // Press on canvas while Height is focused; deferred_down captures current page coordinates + let canvas_click = pos2(500.0, 300.0); + let original_page_pos = u.app.to_page(canvas_click); + + // Frame with click on canvas (queues deferred down and release) + u.frame(vec![ + Event::PointerMoved(canvas_click), + Event::PointerButton { pos: canvas_click, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + Event::PointerButton { pos: canvas_click, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + ]); + + // Simulate view change (e.g. scrolling or panning) before delivery + if let Ok(ds) = u.app.session.ds_mut() { + ds.view.scroll(100.0, 50.0, false); + } + + // Deliver deferred down in the next frame + u.frame(vec![]); + + // Verify pointer down delivered to engine matches original page coordinates, not shifted by scroll + let last = u.app.canvas.last_down.expect("pointer down event delivered"); + assert!((last.x - original_page_pos.x).abs() < 1e-4, "deferred press must preserve original page x coordinate"); + assert!((last.y - original_page_pos.y).abs() < 1e-4, "deferred press must preserve original page y coordinate"); +} + +#[test] +fn deferred_press_released_off_canvas_delivers_cleanly_without_orphan_down() { + let (mut u, _a, _) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + + // Press inside focused field / canvas to queue deferred down + let canvas_pos = pos2(500.0, 300.0); + u.button(canvas_pos, true); + + // Release off canvas (e.g. outside window/canvas rect) before the next frame + let off_canvas = pos2(-50.0, -50.0); + u.frame_with( + vec![ + Event::PointerMoved(off_canvas), + Event::PointerButton { pos: off_canvas, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + ], + Modifiers::NONE, + ); + + // Re-enter canvas + u.frame_with(vec![Event::PointerMoved(canvas_pos)], Modifiers::NONE); + + // Verify no dragging or orphan Down is stuck + assert!(!u.app.canvas.dragging, "canvas must not be left in dragging state"); + assert!(u.app.canvas.deferred_down.is_none(), "deferred down must be cleared"); +} + +#[test] +fn deferred_press_discarded_on_doc_or_page_switch() { + let (mut u, _a, _) = setup(); + let (h_pos, _) = field(&mut u, "Height"); + click(&mut u, h_pos); + + // Press on canvas to queue deferred down + let canvas_pos = pos2(500.0, 300.0); + u.button(canvas_pos, true); + assert!(u.app.canvas.deferred_down.is_some(), "deferred down should be queued"); + + // Create and switch to a new page + let new_page = u.app.session.execute("page.add", &json!({"name": "Page 2"})).unwrap(); + let page_id = id(new_page); + u.app.session.execute("page.select", &json!({"id": page_id})).unwrap(); + + // Run next frame + u.frame(vec![]); + + // Deferred down must have been discarded because page changed + assert!(u.app.canvas.deferred_down.is_none(), "deferred down must be discarded on page switch"); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 71868278d..3d27f45dc 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -294,19 +294,52 @@ fn cancel_retargeted_field_save(ui: &mut Ui, id: Id) { ui.memory_mut(|m| m.surrender_focus(editor)); } -/// Drop a field draft when the active selection has changed since the edit began. -fn sync_field_owner(ui: &mut Ui, id: Id) -> (Option, Option>) { +/// A snapshot of the active document and selection generation. +#[derive(Clone, PartialEq, Eq, Debug)] +pub(crate) struct SelectionSnapshot { + pub(crate) doc_uid: Option, + pub(crate) selection: Vec, + pub(crate) generation: u64, +} + +pub(crate) fn update_selection_snapshot(ctx: &egui::Context, doc_uid: Option, selection: Vec) { + let sel_id = egui::Id::unique("app_current_selection"); + let prev: Option = ctx.data(|d| d.get_temp(sel_id)); + let generation = match prev { + Some(ref p) if p.doc_uid == doc_uid && p.selection == selection => p.generation, + Some(ref p) => p.generation.wrapping_add(1), + None => 1, + }; + ctx.data_mut(|d| { + d.insert_temp(sel_id, SelectionSnapshot { doc_uid, selection, generation }); + }); +} + +/// Drop a field draft when the active selection, document, or layer value has changed since the edit began. +fn sync_field_owner(ui: &mut Ui, id: Id, current_val: Option) -> (Option, Option) { let editing_id = id.with("editing"); let owner_id = id.with("owner_sel"); + let owner_val_id = id.with("owner_val"); let sel_id = egui::Id::unique("app_current_selection"); - let cur_sel: Option> = ui.data(|d| d.get_temp(sel_id)); - let owner: Option> = ui.data(|d| d.get_temp(owner_id)); + let cur_snap: Option = ui.data(|d| d.get_temp(sel_id)); + let owner_snap: Option = ui.data(|d| d.get_temp(owner_id)); + let owner_val: Option> = ui.data(|d| d.get_temp(owner_val_id)); let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); - if editing.is_some() && cur_sel.is_some() && owner.is_some() && owner != cur_sel { + + let selection_changed = editing.is_some() + && (cur_snap.is_none() + || owner_snap.is_none() + || owner_snap.as_ref().map(|s| (&s.doc_uid, &s.selection, s.generation)) + != cur_snap.as_ref().map(|s| (&s.doc_uid, &s.selection, s.generation))); + + let value_changed = editing.is_some() && owner_val.is_some() && owner_val != Some(current_val); + + if selection_changed || value_changed { ui.data_mut(|d| { d.remove::(editing_id); d.remove::(id.with("kept")); - d.remove::>(owner_id); + d.remove::(owner_id); + d.remove::>(owner_val_id); d.remove::(id.with("selectall")); d.remove::(id.with("cmdstart")); d.remove::(id.with("edited")); @@ -314,14 +347,47 @@ fn sync_field_owner(ui: &mut Ui, id: Id) -> (Option, Option (Option, Option) { + let editing_id = id.with("editing"); + let owner_id = id.with("owner_sel"); + let owner_text_id = id.with("owner_text"); + let sel_id = egui::Id::unique("app_current_selection"); + let cur_snap: Option = ui.data(|d| d.get_temp(sel_id)); + let owner_snap: Option = ui.data(|d| d.get_temp(owner_id)); + let owner_text: Option = ui.data(|d| d.get_temp(owner_text_id)); + let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); + + let selection_changed = editing.is_some() + && (cur_snap.is_none() + || owner_snap.is_none() + || owner_snap.as_ref().map(|s| (&s.doc_uid, &s.selection, s.generation)) + != cur_snap.as_ref().map(|s| (&s.doc_uid, &s.selection, s.generation))); + + let value_changed = editing.is_some() && owner_text.as_deref().is_some_and(|t| t != current_val); + + if selection_changed || value_changed { + ui.data_mut(|d| { + d.remove::(editing_id); + d.remove::(owner_id); + d.remove::(owner_text_id); + }); + ui.memory_mut(|m| m.surrender_focus(id.with("te"))); + editing = None; + } + (editing, cur_snap) } /// Discard an editor's active draft and surrender focus. fn clear_field_editor(ui: &mut Ui, id: Id) { ui.data_mut(|d| { d.remove::(id.with("editing")); - d.remove::>(id.with("owner_sel")); + d.remove::(id.with("owner_sel")); + d.remove::>(id.with("owner_val")); + d.remove::(id.with("owner_text")); }); ui.memory_mut(|m| m.surrender_focus(id.with("te"))); } @@ -374,7 +440,7 @@ fn number_field_impl( let edit_rect = Rect::from_min_max(pos2(rect.min.x + lead_w, rect.min.y), rect.max); let editing_id = id.with("editing"); let owner_id = id.with("owner_sel"); - let (mut editing, cur_sel) = sync_field_owner(ui, id); + let (mut editing, cur_snap) = sync_field_owner(ui, id, value); // Alt held over the field scrubs it too, as the label always does: "hover the input field // itself and hold down the modifier key" (Adjust alignment, rotation, position, and // dimensions). The field senses drags only while Alt is held, or while a scrub begun that way @@ -472,9 +538,10 @@ fn number_field_impl( ui.data_mut(|d| { d.insert_temp(editing_id, editing.clone().unwrap_or_default()); d.insert_temp(kept_id, value.map(fmt_num).unwrap_or_default()); - if let Some(ref s) = cur_sel { + if let Some(ref s) = cur_snap { d.insert_temp(owner_id, s.clone()); } + d.insert_temp(id.with("owner_val"), value); d.insert_temp(id.with("selectall"), !typed_now); d.insert_temp(id.with("cmdstart"), with_command); d.remove::(id.with("edited")); @@ -526,6 +593,7 @@ fn number_field_impl( // The stepped value stays selected: typing replaces it. ui.data_mut(|d| { d.insert_temp(kept_id, text.clone()); + d.insert_temp(id.with("owner_val"), Some(nv)); d.insert_temp(id.with("selectall"), true); d.insert_temp(id.with("edited"), true); }); @@ -725,7 +793,7 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str let t = Tokens::get(ui.ctx()); let editing_id = id.with("editing"); let owner_id = id.with("owner_sel"); - let (mut editing, cur_sel) = sync_field_owner(ui, id); + let (mut editing, cur_snap) = sync_text_field_owner(ui, id, value); let resp = ui.interact(rect, id.with("click"), Sense::click()); let shown = if secret { std::borrow::Cow::Owned("•".repeat(value.chars().count())) } else { std::borrow::Cow::Borrowed(value) }; a11y::text(&resp, name, &shown); @@ -738,8 +806,11 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str let started = editing.is_none() && resp.clicked(); if started { editing = Some(value.to_string()); - if let Some(ref s) = cur_sel { - ui.data_mut(|d| d.insert_temp(owner_id, s.clone())); + if let Some(ref s) = cur_snap { + ui.data_mut(|d| { + d.insert_temp(owner_id, s.clone()); + d.insert_temp(id.with("owner_text"), value.to_string()); + }); } ui.memory_mut(|m| m.request_focus(id.with("te"))); select_all_next(ui, id.with("te"), value); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b3d941f6f..602e5bf74 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -350,4 +350,4 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | 2026-11-12 | minor | M8: a selected polygon or star has a Count handle on the canvas (hover label Count N), measured in Figma's web app on 2026-11-12: it sits on the first vertex clockwise from the top (a star's first outer point, not inset), and a drag sets the count to round(360 / the pointer's clockwise angle from the top point about the centre), so 90 degrees gives 4, 72 gives 5 and 45 gives 8, with the step shrinking as the count grows; one drag is one undo step. The count is clamped to 3 to 60 (the help center's range for a star; a polygon's maximum was not read). Tests: `a_polygon_has_a_count_handle_on_its_first_vertex_clockwise_from_the_top`, `dragging_the_count_handle_sets_the_count_by_the_angle_about_the_centre`, `a_count_drag_is_one_undo_step` | | 2026-10-10 | major | Created from the ROADMAP's look-and-feel and interaction items, the keymap and the canvas code | | 2026-11-12 | minor | M8, #2293: Duplicate repeats the last copy's move and rotation, not only the shift of its bounds' corner. The step is the move of the copies' centre in the page frame (not turned by the accumulated rotation) plus the turn each copy has over its source, applied about the new copy's centre, or the selection's centre for several layers; size is not stepped; a deselect forgets the step. Measured in Figma's web app on 2026-11-12 (typed and dragged moves and turns, one layer and two). | -| 2026-11-19 | patch | Panel fields (#2392, #2433): editing drafts in design and layout number and text fields record their owning selection and are dropped on selection change, preventing stale values and green outlines from persisting across deselects; window blur retains field drafts while widget focus is kept; clicking the canvas while editing defers the canvas pointer press by one frame to let the field blur and commit its value before the tool clears or changes selection (`a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`, `field_draft_is_retained_when_window_loses_focus`, `selecting_different_layer_in_layers_panel_drops_draft`) | +| 2026-11-19 | patch | Panel fields (#2392, #2433): editing drafts in design and layout number and text fields track document identity, selection generation, and layer value; drafts are dropped when the selection changes, across deselections, or when the underlying layer value or size changes, preventing stale values and green outlines from persisting; window blur retains field drafts while widget focus is kept; clicking the canvas while editing defers the canvas pointer press by one frame (preserving page coordinates and document ownership) to let the field blur and commit its value before the tool clears or changes selection (`a_draft_is_dropped_when_the_selection_changes`, `clicking_canvas_while_editing_number_field_commits_value`, `field_draft_is_retained_when_window_loses_focus`, `selecting_different_layer_in_layers_panel_drops_draft`, `draft_is_dropped_across_empty_selection_transition`, `draft_is_dropped_when_layer_value_changes_externally`, `deferred_canvas_press_preserves_page_coordinates_across_view_change`, `deferred_press_released_off_canvas_delivers_cleanly_without_orphan_down`, `deferred_press_discarded_on_doc_or_page_switch`) | From 29d39933423271d40cf28976ba6fd3aa45d50098 Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:48:15 +0530 Subject: [PATCH 12/15] ui: only compare selection snapshot when present to preserve draft in isolated panels --- crates/ui-egui/src/widgets.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 3d27f45dc..59243d154 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -327,10 +327,10 @@ fn sync_field_owner(ui: &mut Ui, id: Id, current_val: Option) -> (Option = ui.data(|d| d.get_temp(editing_id)); let selection_changed = editing.is_some() - && (cur_snap.is_none() - || owner_snap.is_none() - || owner_snap.as_ref().map(|s| (&s.doc_uid, &s.selection, s.generation)) - != cur_snap.as_ref().map(|s| (&s.doc_uid, &s.selection, s.generation))); + && match (&cur_snap, &owner_snap) { + (Some(cur), Some(owner)) => cur != owner, + _ => false, + }; let value_changed = editing.is_some() && owner_val.is_some() && owner_val != Some(current_val); @@ -362,10 +362,10 @@ fn sync_text_field_owner(ui: &mut Ui, id: Id, current_val: &str) -> (Option = ui.data(|d| d.get_temp(editing_id)); let selection_changed = editing.is_some() - && (cur_snap.is_none() - || owner_snap.is_none() - || owner_snap.as_ref().map(|s| (&s.doc_uid, &s.selection, s.generation)) - != cur_snap.as_ref().map(|s| (&s.doc_uid, &s.selection, s.generation))); + && match (&cur_snap, &owner_snap) { + (Some(cur), Some(owner)) => cur != owner, + _ => false, + }; let value_changed = editing.is_some() && owner_text.as_deref().is_some_and(|t| t != current_val); From c3165679e7c14406fc35fbfb58018e7fa929ba5c Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:40:38 +0530 Subject: [PATCH 13/15] M4, #2433: keep stale-draft clearing on selection change and drop superseded deferred canvas press --- crates/ui-egui/src/field_tests.rs | 85 +++++++++++++------------------ crates/ui-egui/src/widgets.rs | 35 +++++++------ 2 files changed, 55 insertions(+), 65 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 73140dcdf..1c575cac9 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -554,6 +554,14 @@ fn arithmetic_commits_tab_moves_on_and_escape_restores() { // With the keyboard on a field and nothing typed, the arrows step it. key(&mut u, Key::ArrowUp, Modifiers::NONE); assert_eq!(geom(&u, a).0, 78.0); + // An editor opened from the keyboard is the same one Tab stop in both directions. + for (first, mods) in [("X", Modifiers::NONE), ("Y", Modifiers::SHIFT)] { + assert_eq!(focused_name(&u.ctx), first); + key(&mut u, Key::Enter, Modifiers::NONE); + assert!(u.ctx.text_edit_focused(), "Enter opens the editor of {first}"); + key(&mut u, Key::Tab, mods); + assert_eq!(focused_name(&u.ctx), if first == "X" { "Y" } else { "X" }, "one Tab from the editor of {first}"); + } } /// Answers a Save as dialog with `path`, once, and counts the dialogs asked for. @@ -1350,43 +1358,37 @@ fn a_deferred_field_save_does_not_retarget_a_closed_moved_or_foreign_owner() { } /// A save prepared for A must not force its cached X editor into B when routing changes the -/// presented document before the fields draw, even though both panels use the same widget ID. +/// presented document before the fields draw, even though both panels use the same widget ID. The +/// control channel is the route that presents B in the save's pass: a click on B's tab cannot, as +/// the runtime ends a pass at a pointer press and the click lands in the next one. #[test] fn a_prepared_field_save_cannot_commit_into_a_same_pass_replacement_document() { - for route in ["control", "tab"] { - for save_as in [false, true] { - for discard in [false, true] { - prepared_save_cannot_enter_a_replacement(route, save_as, discard); - } + for save_as in [false, true] { + for discard in [false, true] { + prepared_save_cannot_enter_a_replacement(save_as, discard); } } } -/// The save shortcut's key events (and, routing by tab, a click on the tab at `tab_at`), with the modifiers held. -fn save_events(route: &str, save_as: bool, tab_at: egui::Pos2) -> (Vec, Modifiers) { +/// The save shortcut's key events, with the modifiers held. +fn save_events(save_as: bool) -> (Vec, Modifiers) { let mut modifiers = if cfg!(target_os = "macos") { Modifiers::COMMAND } else { Modifiers::COMMAND.plus(Modifiers::CTRL) }; if save_as { modifiers = modifiers.plus(Modifiers::SHIFT); } - let mut events = vec![ + let events = vec![ Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: true, repeat: false, modifiers }, Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers }, ]; - if route == "tab" { - events.push(Event::PointerMoved(tab_at)); - for pressed in [true, false] { - events.push(Event::PointerButton { pos: tab_at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); - } - } (events, modifiers) } -/// One route/save-as/discard combination of the same-pass replacement test: a save prepared for A -/// must not commit A's cached X editor into B when routing presents B before the fields draw, -/// even though both panels use the same widget ID. -fn prepared_save_cannot_enter_a_replacement(route: &str, save_as: bool, discard: bool) { +/// One save-as/discard combination of the same-pass replacement test: a save prepared for A must +/// not commit A's cached X editor into B when routing presents B before the fields draw, even +/// though both panels use the same widget ID. +fn prepared_save_cannot_enter_a_replacement(save_as: bool, discard: bool) { let (mut u, a, _) = setup(); - let dir = std::env::temp_dir().join(format!("figcraft-field-save-owner-{}-{route}-{save_as}-{discard}", std::process::id())); + let dir = std::env::temp_dir().join(format!("figcraft-field-save-owner-{}-{save_as}-{discard}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let (path, other, copy) = (dir.join("a.figcraft"), dir.join("b.figcraft"), dir.join("copy.figcraft")); u.app.session.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); @@ -1399,7 +1401,6 @@ fn prepared_save_cannot_enter_a_replacement(route: &str, save_as: bool, discard: u.app.session.execute("select.set", &json!({"ids": [b]})).unwrap(); let other_index = u.app.session.active; let other_uid = u.app.session.ds().unwrap().uid; - let other_name = u.app.session.doc().unwrap().name.clone(); let other_model = u.app.session.ds().unwrap().doc.clone(); let before_switch_revision = u.app.session.ds().unwrap().revision; let other_history = u.app.session.undo_depth(); @@ -1414,15 +1415,7 @@ fn prepared_save_cannot_enter_a_replacement(route: &str, save_as: bool, discard: assert_eq!(other_revision, before_switch_revision + 1, "the setup switch advances only B's command revision"); let asked = std::rc::Rc::new(std::cell::Cell::new(0)); u.app.services = Box::new(SaveAsPicker { path: Some(copy.clone()), asked: asked.clone() }); - let output = u.frame_output(vec![]); - let nodes = output.platform_output.accesskit_update.unwrap().nodes; - let tab = nodes - .iter() - .map(|(_, node)| node) - .find(|node| node.role() == Role::Tab && node.label() == Some(other_name.as_str())) - .expect("the actual B tab"); - let bounds = tab.bounds().unwrap(); - let tab_at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + u.frame(vec![]); let (at, _) = field(&mut u, "X"); click(&mut u, at); assert_eq!(u.ctx.memory(|m| m.focused()), Some(Id::unique("pos_x").with("te"))); @@ -1431,20 +1424,15 @@ fn prepared_save_cannot_enter_a_replacement(route: &str, save_as: bool, discard: assert_eq!(u.ctx.data(|d| d.get_temp::(Id::unique("pos_x").with("editing"))), Some("77".into())); assert_eq!(geom(&u, a).0, 10.0, "A's raw draft is not committed yet"); assert_eq!(u.app.session.ds().unwrap().uid, owner, "the save begins with A presented"); - let reply = if route == "control" { - let (reply, rx) = std::sync::mpsc::channel(); - u.app.control_queue.push(crate::ControlRequest { - id: json!("same-pass-switch"), - method: "engine.execute".into(), - params: json!({"command": "doc.switch", "params": {"index": other_index}, "window": 0}), - reply, - state: Default::default(), - }); - Some(rx) - } else { - None - }; - let (events, modifiers) = save_events(route, save_as, tab_at); + let (reply, rx) = std::sync::mpsc::channel(); + u.app.control_queue.push(crate::ControlRequest { + id: json!("same-pass-switch"), + method: "engine.execute".into(), + params: json!({"command": "doc.switch", "params": {"index": other_index}, "window": 0}), + reply, + state: Default::default(), + }); + let (events, modifiers) = save_events(save_as); if discard { let mut events = events; events.insert(0, Event::ModifiersChanged(modifiers)); @@ -1452,13 +1440,11 @@ fn prepared_save_cannot_enter_a_replacement(route: &str, save_as: bool, discard: } else { u.frame_with(events, modifiers); } - if let Some(reply) = reply { - let reply = reply.try_recv().expect("real control::drain acknowledged doc.switch in this pass"); - assert!(reply.result.is_ok(), "{:?}", reply.result); - } + let reply = rx.try_recv().expect("real control::drain acknowledged doc.switch in this pass"); + assert!(reply.result.is_ok(), "{:?}", reply.result); let unchanged = |u: &Ui| { assert_eq!(u.app.session.ds().unwrap().uid, other_uid, "the real same-pass route presents B"); - assert_eq!(geom(u, b), (200.0, 40.0, 30.0, 30.0), "A's draft cannot enter B's field: route={route}, save_as={save_as}, discard={discard}"); + assert_eq!(geom(u, b), (200.0, 40.0, 30.0, 30.0), "A's draft cannot enter B's field: save_as={save_as}, discard={discard}"); assert!(std::sync::Arc::ptr_eq(&u.app.session.ds().unwrap().doc, &other_model), "B's model is untouched"); assert_eq!(u.app.session.ds().unwrap().revision, other_revision); assert_eq!(u.app.session.undo_depth(), other_history, "B's undo/redo history is unchanged"); @@ -1883,4 +1869,3 @@ fn draft_is_dropped_when_layer_value_changes_externally() { assert_eq!(h_editing, None, "draft must be dropped when layer size changes"); assert_eq!(field(&mut u, "Height").1, "75", "Height field must show the new layer size"); } - diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 47c88888e..d5c3a2f1e 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -392,6 +392,25 @@ fn clear_field_editor(ui: &mut Ui, id: Id) { ui.memory_mut(|m| m.surrender_focus(id.with("te"))); } +/// Paint a lead label or icon for a number field. +fn paint_number_field_lead(ui: &mut Ui, lead: &Lead, lead_rect: Rect, rect: Rect, lead_w: f32, lead_resp: &egui::Response, t: &Tokens) { + match lead { + Lead::Text(s) => { + // Whole points: egui rounds wrap width to GUI_ROUNDING, which wraps a fractional label column. + let galley = crate::bidi::name_galley(ui.painter(), s, regular(11.0), t.text_secondary, (lead_w - 12.0).ceil()); + // A label cut short shows whole on hover. + if galley.elided { + lead_resp.clone().on_hover_text(*s); + } + ui.painter().galley(pos2(lead_rect.min.x + 8.0, rect.center().y - galley.size().y / 2.0), galley, t.text_secondary); + } + Lead::Icon(i, _) => { + icons::paint(ui.painter(), Rect::from_center_size(lead_rect.center() + vec2(1.0, 0.0), vec2(14.0, 14.0)), *i, t.icon_secondary); + } + Lead::None | Lead::Named(_) => {} + } +} + /// Implement the shared number field: label/icon lead, scrubbing, keyboard stepping and /// typing, select-all when a click starts editing, bindable values and deferred-save /// cancellation; returns an edit and/or bind event. @@ -448,21 +467,7 @@ fn number_field_impl( } else if hovered { ui.painter().rect_stroke(rect, CornerRadius::same(5), Stroke::new(1.0, t.field_hover_border), StrokeKind::Inside); } - match lead { - Lead::Text(s) => { - // Whole points: egui rounds wrap width to GUI_ROUNDING, which wraps a fractional label column. - let galley = crate::bidi::name_galley(ui.painter(), s, regular(11.0), t.text_secondary, (lead_w - 12.0).ceil()); - // A label cut short shows whole on hover. - if galley.elided { - lead_resp.clone().on_hover_text(s); - } - ui.painter().galley(pos2(lead_rect.min.x + 8.0, rect.center().y - galley.size().y / 2.0), galley, t.text_secondary); - } - Lead::Icon(i, _) => { - icons::paint(ui.painter(), Rect::from_center_size(lead_rect.center() + vec2(1.0, 0.0), vec2(14.0, 14.0)), i, t.icon_secondary) - } - Lead::None | Lead::Named(_) => {} - } + paint_number_field_lead(ui, &lead, lead_rect, rect, lead_w, &lead_resp, &t); if lead_resp.hovered() || lead_resp.dragged() || (alt_now && editing.is_none() && field_resp.hovered()) || (alt_scrub && field_resp.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } From e5060d0f55329c18d63508a56d1222a14b2e8f22 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 13:17:55 +0700 Subject: [PATCH 14/15] M8: control channel: requests queued behind an applied ui.input batch run in the next frame, so a doc.switch can't send the batch into another file (#1503) --- crates/ui-egui/src/control.rs | 12 +++++- crates/ui-egui/src/control/capture_tests.rs | 48 +++++++++++++++++++++ crates/ui-egui/src/windows.rs | 9 ++++ docs/control-protocol.md | 4 +- 4 files changed, 70 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 4ece981aa..21f6a8eae 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -548,8 +548,9 @@ pub fn background(app: &mut FigApp, ctx: &Context) { app.control_queue.push(r); continue; } - if r.method == "ui.input" { - // Keep one synthetic batch until a real UI pass consumes it. + if r.method == "ui.input" || app.applied_frame == Some(crate::windows::viewport(target)) { + // Keep one synthetic batch until a real UI pass consumes it, and what was queued behind + // a batch already taken until the pass that applies it has presented. app.control_queue.push(r); continue; } @@ -777,6 +778,13 @@ fn route_queued(app: &mut FigApp, ctx: &Context, viewport: egui::ViewportId, now admit(app, r, target, now); return; } + if app.applied_frame == Some(viewport) { + // This pass applies an injected batch: what was queued behind it runs next frame, so a + // file switch can't send the batch's keys or pointer into another document (#1503). + ctx.request_repaint(); + app.control_queue.push(r); + return; + } if !r.begin() { return; } diff --git a/crates/ui-egui/src/control/capture_tests.rs b/crates/ui-egui/src/control/capture_tests.rs index 6289e1dc3..86298727c 100644 --- a/crates/ui-egui/src/control/capture_tests.rs +++ b/crates/ui-egui/src/control/capture_tests.rs @@ -576,6 +576,54 @@ fn injected_input_is_acknowledged_only_after_the_pass_that_applies_it() { assert!(!u.app.control_synthetic, "the fence ends with the frame"); } +/// Asserts a document switch that reaches the frame applying a batch waits for the next frame: +/// the batch's Delete edits the file it was sent for, never the one switched to (#1503). +#[test] +fn a_switch_queued_behind_an_applied_batch_never_takes_its_input() { + let mut s = Session::empty(); + let rect = |s: &mut Session, name: &str| { + s.execute("file.new", &json!({"name": name})).unwrap(); + let id = NodeId( + s.execute("node.create", &json!({"type": "rectangle", "x": 0, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(), + ); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + id + }; + let (a, b) = (rect(&mut s, "A"), rect(&mut s, "B")); + let index = |s: &Session, name: &str| s.docs.iter().position(|d| d.doc.name == name).expect("file"); + s.active = index(&s, "A"); + let mut u = Ui::new(s); + let (tx, input) = std::sync::mpsc::channel(); + u.app.control_queue.push(ControlRequest { + id: json!(30), + method: "ui.input".into(), + params: json!({"events": [{"move": [700.0, 450.0]}, {"key": "Delete"}]}), + reply: tx, + state: Default::default(), + }); + u.frame(vec![]); + // The window takes A's batch; the switch to B arrives before that frame's control drain. + let events = crate::windows::take_input(&mut u.app, egui::ViewportId::ROOT); + assert!(!events.is_empty(), "A's batch is in the frame"); + let (tx, switch) = std::sync::mpsc::channel(); + u.app.control_queue.push(ControlRequest { + id: json!(31), + method: "engine.execute".into(), + params: json!({"command": "doc.switch", "params": {"index": index(&u.app.session, "B")}}), + reply: tx, + state: Default::default(), + }); + u.frame(events); + assert!(input.try_recv().expect("the batch is acknowledged").result.is_ok()); + assert!(switch.try_recv().is_err(), "the switch waits for the frame after the batch"); + u.frame(vec![]); + assert!(switch.try_recv().expect("the switch runs next").result.is_ok()); + let file = |u: &Ui, name: &str| u.app.session.docs[index(&u.app.session, name)].doc.clone(); + assert_eq!(u.app.session.active, index(&u.app.session, "B")); + assert!(!file(&u, "A").contains(a), "the batch edited the file it was sent for"); + assert!(file(&u, "B").contains(b), "and left the file switched to alone"); +} + /// Asserts a discarded pass neither acknowledges nor replays an injected batch; the presented /// pass acknowledges once. #[test] diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 7ff34de64..ef05dc9ac 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -135,6 +135,15 @@ pub fn guard(app: &mut FigApp, ctx: &Context, f: impl FnOnce(&mut FigApp)) { let msg = e.downcast_ref::<&str>().map(ToString::to_string).or_else(|| e.downcast_ref::().cloned()).unwrap_or_else(|| "panic".into()); log::error!("UI panic: {msg}"); app.toast(format!("Internal error (please report): {msg}")); + // A pass that panicked never reached `end_input_frame`: its batch's replies say so, and + // neither the control queue nor the clipboard fence waits for it. + if app.applied_frame.take().is_some() { + for ack in app.applied_acks.drain(..) { + let _ = ack.tx.send(crate::ControlReply { id: ack.reply.id, result: Err(format!("the frame applying the input failed: {msg}")) }); + } + app.applied_input = None; + app.control_synthetic = false; + } ctx.request_repaint(); app.services.emergency_save(&app.session); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4e7e9e818..c34fbdf94 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -340,7 +340,9 @@ controller button pressed in the prototype playing, the presenter's or else the short name, a key/gamepad trigger's name or a standard layout index 0–16; an error when no prototype plays); positions are window points. Events of one call arrive in the same frame, so send a press and its release (or a double-click's two clicks) as -separate calls. Returns `{queued}`. +separate calls. Returns `{queued}`. Requests sent after a batch that a frame has already taken run +in the frame after it, so a `doc.switch` (or any other request) never sends the batch into another +file; a batch whose file changed before a frame took it is not applied, and its reply is an error. ```json {"id":6,"method":"ui.input","params":{"events":[{"move":[1000,315]}]}} From 02b7b9981846a3b4d8af5f0317feb92b6d2a382e Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 00:03:30 -0700 Subject: [PATCH 15/15] perf(collab): add capability-gated delta snapshots for mirrored layers (#1819) --- crates/collab-net/src/loopback_tests.rs | 27 +- crates/collab/src/client.rs | 65 ++-- crates/collab/src/delta_dst_tests.rs | 216 +++++++++++ crates/collab/src/delta_snapshot/decode.rs | 393 +++++++++++++++++++++ crates/collab/src/delta_snapshot/encode.rs | 222 ++++++++++++ crates/collab/src/delta_snapshot/fields.rs | 284 +++++++++++++++ crates/collab/src/delta_snapshot/mod.rs | 146 ++++++++ crates/collab/src/delta_snapshot_tests.rs | 350 ++++++++++++++++++ crates/collab/src/docprops.rs | 71 ++-- crates/collab/src/journal_tests.rs | 4 +- crates/collab/src/lib.rs | 5 + crates/collab/src/message.rs | 46 ++- crates/collab/src/packed_welcome_tests.rs | 4 +- crates/collab/src/reconnect_tests.rs | 38 +- crates/collab/src/server.rs | 32 +- crates/collab/src/server_tests.rs | 8 +- crates/collab/src/sim.rs | 4 +- docs/collab-protocol.md | 13 +- 18 files changed, 1847 insertions(+), 81 deletions(-) create mode 100644 crates/collab/src/delta_dst_tests.rs create mode 100644 crates/collab/src/delta_snapshot/decode.rs create mode 100644 crates/collab/src/delta_snapshot/encode.rs create mode 100644 crates/collab/src/delta_snapshot/fields.rs create mode 100644 crates/collab/src/delta_snapshot/mod.rs create mode 100644 crates/collab/src/delta_snapshot_tests.rs diff --git a/crates/collab-net/src/loopback_tests.rs b/crates/collab-net/src/loopback_tests.rs index 7af598bf9..48b19549d 100644 --- a/crates/collab-net/src/loopback_tests.rs +++ b/crates/collab-net/src/loopback_tests.rs @@ -189,9 +189,13 @@ fn guests_join_and_see_each_other() { let Some(Event::Welcome { info, peers }) = ap.events.iter().rev().find(|e| matches!(e, Event::Welcome { .. })) else { panic!("no welcome") }; assert_eq!(info.name, "Ada"); assert!( - ap.events.iter().any( - |e| matches!(e, Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::Snapshot(snapshot), .. }) if !snapshot.is_empty()) - ), + ap.events.iter().any(|e| matches!( + e, + Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::Snapshot(snapshot), .. }) if !snapshot.is_empty() + ) || matches!( + e, + Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::DeltaSnapshot(bytes), .. }) if !bytes.is_empty() + )), "the welcome carries the document for the sync client" ); assert_eq!(peers.iter().map(|p| p.name.as_str()).collect::>(), ["Hana"], "the host is already here"); @@ -670,12 +674,21 @@ fn welcomes_are_packed_only_for_clients_that_read_them() { let addr: SocketAddr = invite.server.host.parse().unwrap(); let mut old = Raw::connect(addr); let ClientMsg::Hello(h) = Client::hello(FILE, TOKEN, "Old", "") else { panic!("not a hello") }; - assert!(old.send(&ClientMsg::Hello(Hello { client_version: "0.12.1 signals hosting comments".into(), ..h }))); + assert!(old.send(&ClientMsg::Hello(Hello { client_version: "0.12.1 signals hosting comments".into(), ..h.clone() }))); let Some(ServerMsg::Welcome { catch_up: CatchUp::Snapshot(plain), .. }) = old.next() else { panic!("no plain welcome") }; + let mut mid = Raw::connect(addr); + assert!(mid.send(&ClientMsg::Hello(Hello { client_version: "0.18.1 signals hosting comments packed design-review branches".into(), ..h }))); + let Some(mut packed_welcome @ ServerMsg::Welcome { catch_up: CatchUp::Packed(_), .. }) = mid.next() else { panic!("no packed welcome") }; + message::unpack(&mut packed_welcome, 64 << 20).unwrap(); + assert!(matches!(packed_welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(s), .. } if s == plain), "the same document"); let mut new = Raw::hello(addr, TOKEN); - let Some(mut welcome @ ServerMsg::Welcome { catch_up: CatchUp::Packed(_), .. }) = new.next() else { panic!("no packed welcome") }; - message::unpack(&mut welcome, 64 << 20).unwrap(); - assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(s), .. } if s == plain), "the same document"); + let Some(mut delta_welcome @ ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. }) = new.next() else { + panic!("no delta snapshot welcome") + }; + message::unpack(&mut delta_welcome, 64 << 20).unwrap(); + let delta_doc = Client::join(delta_welcome).unwrap().document().clone(); + let plain_doc = figcraft_collab::Replica::from_snapshot(&plain).unwrap().document().clone(); + assert_eq!(delta_doc, plain_doc, "delta snapshot opens the exact same document"); host.stop(); } diff --git a/crates/collab/src/client.rs b/crates/collab/src/client.rs index da83aca84..ba1c3b44c 100644 --- a/crates/collab/src/client.rs +++ b/crates/collab/src/client.rs @@ -86,10 +86,19 @@ impl Client { /// Start from the server's `Welcome` (which must carry a snapshot). pub fn join(welcome: ServerMsg) -> Result { - let ServerMsg::Welcome { session, client_id, seq, catch_up: CatchUp::Snapshot(snapshot), processed, peers, access, secret } = welcome else { + let ServerMsg::Welcome { session, client_id, seq, catch_up, processed, peers, access, secret } = welcome else { return Err(Error::Protocol("expected a welcome with the document".into())); }; - let mut confirmed = Replica::from_snapshot(&snapshot)?; + let mut confirmed = match catch_up { + CatchUp::Snapshot(snapshot) => Replica::from_snapshot(&snapshot)?, + CatchUp::DeltaSnapshot(bytes) => { + let limits = crate::Limits::default(); + crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)? + } + CatchUp::Delta(_) | CatchUp::Packed(_) => { + return Err(Error::Protocol("expected a welcome with the document".into())); + } + }; confirmed.document_mut().set_client_id(client_id); let next_id = confirmed.document().next_id(); Ok(Client { @@ -597,26 +606,13 @@ impl Client { CatchUp::Snapshot(snapshot) => { let mut confirmed = Replica::from_snapshot(&snapshot)?; confirmed.document_mut().set_client_id(self.id); - self.confirmed = confirmed; - self.seq = seq; - // What the server accepted meanwhile is in the snapshot. Which of the batches since - // were others' isn't known, so the steps check every value they wrote below. - while let Some(p) = self.pending.front().filter(|p| p.batch_id <= last_batch).cloned() { - self.pending.pop_front(); - if processed.refused.contains(&p.batch_id) { - self.refused(&p, offline()); - } else if p.kind != BatchKind::FollowUp - && let Some(s) = p.step.and_then(|id| find_step(&mut self.undo, &mut self.redo, id)) - { - s.settle(p.kind); - } - } - for s in self.undo.iter_mut().chain(self.redo.iter_mut()).filter(|s| s.confirmed) { - s.verify(&self.confirmed)?; - } - for p in &mut self.pending { - p.rebased = true; - } + self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?; + } + CatchUp::DeltaSnapshot(bytes) => { + let limits = crate::Limits::default(); + let mut confirmed = crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?; + confirmed.document_mut().set_client_id(self.id); + self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?; } } if self.seq != seq { @@ -636,6 +632,31 @@ impl Client { Ok(self.flush(recompute)) } + fn rejoin_with_confirmed(&mut self, confirmed: Replica, seq: u64, last_batch: u64, processed: &Processed) -> Result<(), Error> { + let offline = || "it no longer applied when the connection came back".to_string(); + self.confirmed = confirmed; + self.seq = seq; + // What the server accepted meanwhile is in the snapshot. Which of the batches since + // were others' isn't known, so the steps check every value they wrote below. + while let Some(p) = self.pending.front().filter(|p| p.batch_id <= last_batch).cloned() { + self.pending.pop_front(); + if processed.refused.contains(&p.batch_id) { + self.refused(&p, offline()); + } else if p.kind != BatchKind::FollowUp + && let Some(s) = p.step.and_then(|id| find_step(&mut self.undo, &mut self.redo, id)) + { + s.settle(p.kind); + } + } + for s in self.undo.iter_mut().chain(self.redo.iter_mut()).filter(|s| s.confirmed) { + s.verify(&self.confirmed)?; + } + for p in &mut self.pending { + p.rebased = true; + } + Ok(()) + } + /// A session that doesn't know this client (it restarted without its saved state) welcomed /// it as new: start over from its document; unconfirmed work and the undo history are gone. fn restart(&mut self, welcome: ServerMsg) -> Result, Error> { diff --git a/crates/collab/src/delta_dst_tests.rs b/crates/collab/src/delta_dst_tests.rs new file mode 100644 index 000000000..2a0a08a0e --- /dev/null +++ b/crates/collab/src/delta_dst_tests.rs @@ -0,0 +1,216 @@ +//! Multi-seed mixed-version DST for `CatchUp::DeltaSnapshot`. + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Document, NodeId}; +use figcraft_geom::Affine; + +use crate::delta_snapshot::{decode_delta_snapshot, encode_delta_snapshot}; +use crate::delta_snapshot_tests::{LEGACY_CLIENT_VERSION, assert_docs_json_eq, design_system_doc}; +use crate::message::{CatchUp, ClientMsg, Hello, ServerMsg}; +use crate::sim::Rng; +use crate::{Client, Limits, NoRecompute, Outgoing, Server}; + +fn deliver_outgoing(clients: &mut [(Client, Hello, bool)], outs: Vec) { + for out in outs { + match out { + Outgoing::All(m) => { + for (c, _, _) in clients.iter_mut() { + if c.is_online() { + let _ = c.receive(m.clone(), &NoRecompute).unwrap(); + } + } + } + Outgoing::To(target, m) => { + for (c, _, _) in clients.iter_mut() { + if c.is_online() && c.id() == target { + let _ = c.receive(m.clone(), &NoRecompute).unwrap(); + } + } + } + Outgoing::Others(skip, m) => { + for (c, _, _) in clients.iter_mut() { + if c.is_online() && c.id() != skip { + let _ = c.receive(m.clone(), &NoRecompute).unwrap(); + } + } + } + } + } +} + +fn reconnect_dst_client(server: &mut Server, clients: &mut [(Client, Hello, bool)], idx: usize) -> (bool, bool) { + let (c, base_h, delta_capable) = &mut clients[idx]; + let ClientMsg::Hello(mut rh) = c.reconnect(base_h.clone()) else { panic!("expected Hello") }; + if !*delta_capable { + rh.client_version = base_h.client_version.clone(); + } + let (id, outs) = server.join(rh).unwrap(); + let welcome = outs + .into_iter() + .find_map(|o| match o { + Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m), + _ => None, + }) + .unwrap(); + let is_delta_snap = matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. }); + let is_legacy_snap = matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }); + let follow = c.receive(welcome, &NoRecompute).unwrap(); + let cid = c.id(); + for msg in follow { + let rep = server.receive(cid, msg); + deliver_outgoing(clients, rep); + } + (is_delta_snap, is_legacy_snap) +} + +fn apply_random_dst_edit(edited: &mut Document, rng: &mut Rng, comp: NodeId, main_children: &[NodeId], seed: u64, step: usize) { + let all_ids: Vec = edited.ids().filter(|id| !edited.node(*id).unwrap().is_page()).collect(); + match rng.below(4) { + 0 => { + let target = *rng.pick(main_children).unwrap(); + if let Some(n) = edited.node_mut(target) { + n.fills = vec![Paint::solid(Color::from_rgb8_const(rng.below(255) as u8, 80, 140))]; + } + } + 1 => { + let text_mirrors: Vec = + all_ids.iter().copied().filter(|id| edited.node(*id).is_some_and(|n| n.source.is_some() && n.kind.text().is_some())).collect(); + if let Some(&target) = rng.pick(&text_mirrors) + && let Some(n) = edited.node_mut(target) + { + if let Some(t) = n.kind.text_mut() { + t.characters = format!("S{seed}-T{step}"); + } + if rng.chance(0.5) { + n.overrides.clear(); + } else { + n.overrides.insert("characters".to_string()); + } + } + } + 2 => { + let mirrors: Vec = all_ids.iter().copied().filter(|id| edited.node(*id).is_some_and(|n| n.source.is_some())).collect(); + if let Some(&target) = rng.pick(&mirrors) + && let Some(n) = edited.node_mut(target) + { + n.transform = Affine::translate((rng.below(400) as f64, rng.below(200) as f64)); + n.width = 20.0 + rng.below(120) as f64; + } + } + _ => { + if let Some(n) = edited.node_mut(comp) { + n.name = format!("Card-v{step}"); + } + } + } +} + +fn assert_dst_invariants(server: &Server, clients: &[(Client, Hello, bool)], seed: u64, step: usize) { + let decoded = decode_delta_snapshot(&encode_delta_snapshot(server.replica()).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap(); + assert_docs_json_eq(server.document(), decoded.document(), &format!("seed={seed} step={step} roundtrip")); + for (i, (c, _, _)) in clients.iter().enumerate() { + if c.is_online() { + assert_docs_json_eq(server.document(), c.document(), &format!("seed={seed} step={step} client {i}")); + } + } +} + +fn run_dst_seed(seed: u64) { + let mut rng = Rng::new(seed); + let (doc, comp, main_children) = design_system_doc(6); + let limits = Limits { max_log_batches: 2, ..Limits::default() }; + let mut server = Server::new(doc, "dst-secret", limits); + + let join_client = |srv: &mut Server, name: &str, delta_capable: bool| -> (Client, Hello) { + let ClientMsg::Hello(mut h) = Client::hello("dst", "dst-secret", name, "#2266EE") else { panic!() }; + if !delta_capable { + h.client_version = LEGACY_CLIENT_VERSION.into(); + } + let (id, outs) = srv.join(h.clone()).unwrap(); + let welcome = outs + .into_iter() + .find_map(|o| match o { + Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m), + _ => None, + }) + .unwrap(); + if delta_capable { + assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. })); + } else { + assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })); + } + (Client::join(welcome).unwrap(), h) + }; + + let (c0, h0) = join_client(&mut server, "Delta-A", true); + let (c1, h1) = join_client(&mut server, "Delta-B", true); + let (c2, h2) = join_client(&mut server, "Legacy-C", false); + let mut clients = vec![(c0, h0, true), (c1, h1, true), (c2, h2, false)]; + let (mut delta_snap_rejoins, mut legacy_snap_rejoins) = (0usize, 0usize); + + for step in 0..30usize { + if step == 15 { + let saved = server.state().unwrap(); + server = Server::restore(saved, "dst-secret", limits).unwrap(); + for (c, _, _) in &mut clients { + c.disconnect(); + } + for idx in 0..clients.len() { + let _ = reconnect_dst_client(&mut server, &mut clients, idx); + } + assert_dst_invariants(&server, &clients, seed, step); + continue; + } + + if step == 6 || step == 20 { + let victim = if step == 6 { 1 } else { 2 }; + clients[victim].0.disconnect(); + server.leave(clients[victim].0.id()); + + let mut off_doc = clients[victim].0.document().clone(); + if let Some(p) = off_doc.first_page() + && let Some(n) = off_doc.node_mut(p) + { + n.name = format!("Offline-{seed}-{step}"); + } + let _ = clients[victim].0.edit(&off_doc).unwrap(); + + for sub in 0..4 { + let mut edited = clients[0].0.document().clone(); + apply_random_dst_edit(&mut edited, &mut rng, comp, &main_children, seed, step * 10 + sub); + if let Some(msg) = clients[0].0.edit(&edited).unwrap() { + let outs = server.receive(clients[0].0.id(), msg); + deliver_outgoing(&mut clients, outs); + } + } + + let (was_delta, was_legacy) = reconnect_dst_client(&mut server, &mut clients, victim); + delta_snap_rejoins += usize::from(was_delta); + legacy_snap_rejoins += usize::from(was_legacy); + assert_dst_invariants(&server, &clients, seed, step); + continue; + } + + let actor_idx = rng.below(clients.len()); + let mut edited = clients[actor_idx].0.document().clone(); + apply_random_dst_edit(&mut edited, &mut rng, comp, &main_children, seed, step); + if let Some(msg) = clients[actor_idx].0.edit(&edited).unwrap() { + let outs = server.receive(clients[actor_idx].0.id(), msg); + deliver_outgoing(&mut clients, outs); + } + assert_dst_invariants(&server, &clients, seed, step); + } + + assert!(delta_snap_rejoins > 0 && legacy_snap_rejoins > 0, "seed={seed}: must exercise both snapshot rejoin paths"); +} + +#[test] +fn dst_mixed_delta_and_legacy_clients_converge_under_faults_and_restarts() { + let seeds: Vec = match std::env::var("FIGCRAFT_DST_SEED").ok().and_then(|s| s.parse::().ok()) { + Some(single) => vec![single], + None => vec![1, 7, 42, 1337, 2026], + }; + for seed in seeds { + run_dst_seed(seed); + } +} diff --git a/crates/collab/src/delta_snapshot/decode.rs b/crates/collab/src/delta_snapshot/decode.rs new file mode 100644 index 000000000..2579a12dc --- /dev/null +++ b/crates/collab/src/delta_snapshot/decode.rs @@ -0,0 +1,393 @@ +//! Streaming decode and memory-budget enforcement for `CatchUp::DeltaSnapshot`. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt; +use std::io::Read; +use std::mem::size_of; +use std::sync::Arc; + +use figcraft_doc::color::Paint; +use figcraft_doc::proto::Interaction; +use figcraft_doc::{ + Annotation, CodeLink, DevResource, Document, Effect, ExportSetting, Guide, LayoutGrid, Measurement, Node, NodeId, NodeKind, Region, Segment, + VectorNetwork, Vertex, +}; +use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor}; + +use super::fields::{FieldDelta, apply_field_delta}; +use super::{DEFAULT_MAX_MATERIALIZED_BYTES, HEADER_LEN, WireMeta, WireRecord, parse_header}; +use crate::Error; +use crate::docprops::{clamp_design_review_config, validate_image_base64}; +use crate::frac; +use crate::replica::{Positions, Replica}; + +/// Maximum ratio of estimated materialized bytes to declared uncompressed JSON bytes. +/// Heavy design-system files sit around 15x to 35x; amplification bombs exceed 1,000x. +const MAX_AMPLIFICATION_FACTOR: usize = 64; +const MIN_MATERIALIZED_FLOOR: usize = 16 << 20; + +/// Decode a compressed `CatchUp::DeltaSnapshot` payload into a validated [`Replica`]. +pub fn decode_delta_snapshot(bytes: &[u8], max_bytes: usize, max_nodes: usize) -> Result { + decode_delta_snapshot_with_budget(bytes, max_bytes, max_nodes, DEFAULT_MAX_MATERIALIZED_BYTES) +} + +/// Decode a compressed `CatchUp::DeltaSnapshot` with an explicit ceiling on estimated +/// materialized memory, also capped at `max(16 MiB, 64 * declared_bytes)`. +pub fn decode_delta_snapshot_with_budget(bytes: &[u8], max_bytes: usize, max_nodes: usize, max_materialized_bytes: usize) -> Result { + let declared = parse_header(bytes)?; + if declared > max_bytes { + return Err(Error::TooLarge(max_bytes)); + } + let body = bytes.get(HEADER_LEN..).ok_or_else(|| Error::Decode("delta snapshot body missing".into()))?; + // Stop inflating at `declared + 1` so a forged small length aborts immediately. + let limit = u64::try_from(declared).unwrap_or(u64::MAX).saturating_add(1); + let prealloc = declared.min(bytes.len().saturating_mul(8)).min(1 << 20); + let mut raw = Vec::with_capacity(prealloc); + flate2::read::DeflateDecoder::new(body).take(limit).read_to_end(&mut raw).map_err(|e| Error::Decode(format!("delta snapshot deflate: {e}")))?; + if raw.len() > declared { + return Err(Error::TooLarge(declared)); + } + if raw.len() != declared { + return Err(Error::Decode(format!("delta snapshot truncated: header declared {declared} bytes, inflated {}", raw.len()))); + } + + let cap = declared.saturating_mul(MAX_AMPLIFICATION_FACTOR).max(MIN_MATERIALIZED_FLOOR); + stream_decode_wire(&raw, max_nodes, max_materialized_bytes.min(cap)) +} + +fn est_str_map(m: &BTreeMap) -> usize { + m.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len()).saturating_add(48)) +} + +fn est_vector_bytes(net: &VectorNetwork) -> usize { + let regs = net.regions.iter().fold(0usize, |acc, r| { + let loops = r.loops.iter().fold(0usize, |a, l| a.saturating_add(l.len().saturating_mul(size_of::()))); + let fills = r.fills.as_ref().map_or(0, |f| f.len().saturating_mul(size_of::())); + acc.saturating_add(size_of::()).saturating_add(loops).saturating_add(fills) + }); + size_of::() + .saturating_add(net.vertices.len().saturating_mul(size_of::())) + .saturating_add(net.segments.len().saturating_mul(size_of::())) + .saturating_add(regs) +} + +fn est_kind_bytes(kind: &NodeKind) -> usize { + match kind { + NodeKind::Vector { network } => est_vector_bytes(network), + NodeKind::Text(t) => t.characters.len().saturating_add(t.runs.len().saturating_mul(64)), + NodeKind::Component { description, props, prop_order } => { + description.len().saturating_add(props.len().saturating_mul(96)).saturating_add(prop_order.len().saturating_mul(32)) + } + NodeKind::Instance { props, .. } => props.len().saturating_mul(96), + _ => 0, + } +} + +fn est_node_bytes(n: &Node) -> usize { + let ov: usize = n.overrides.iter().fold(0, |a, s| a.saturating_add(s.len()).saturating_add(24)); + size_of::() + .saturating_add(n.name.len()) + .saturating_add(n.dev_note.len()) + .saturating_add(n.fills.len().saturating_mul(size_of::())) + .saturating_add(n.strokes.len().saturating_mul(size_of::())) + .saturating_add(n.effects.len().saturating_mul(size_of::())) + .saturating_add(n.grids.len().saturating_mul(size_of::())) + .saturating_add(n.guides.len().saturating_mul(size_of::())) + .saturating_add(n.exports.len().saturating_mul(size_of::())) + .saturating_add(n.interactions.len().saturating_mul(size_of::())) + .saturating_add(n.annotations.len().saturating_mul(size_of::())) + .saturating_add(n.code_links.len().saturating_mul(size_of::())) + .saturating_add(n.dev_resources.len().saturating_mul(size_of::())) + .saturating_add(n.measurements.len().saturating_mul(size_of::())) + .saturating_add(est_kind_bytes(&n.kind)) + .saturating_add(ov) + .saturating_add(est_str_map(&n.plugin_data)) + .saturating_add(est_str_map(&n.prop_refs)) +} + +fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usize { + deltas.iter().fold(0usize, |acc, d| { + let extra = match d { + FieldDelta::Name(s) | FieldDelta::DevNote(s) => s.len(), + FieldDelta::Kind(k) => est_kind_bytes(k), + FieldDelta::VectorRef(idx) => usize::try_from(*idx).ok().and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0), + FieldDelta::Fills(v) | FieldDelta::Strokes(v) => v.len().saturating_mul(size_of::()), + FieldDelta::Effects(v) => v.len().saturating_mul(size_of::()), + FieldDelta::PluginData(m) | FieldDelta::PropRefs(m) => est_str_map(m), + FieldDelta::Annotations(v) => v.len().saturating_mul(size_of::()), + _ => 0, + }; + acc.saturating_add(extra) + }) +} + +struct DecodeState { + doc: Document, + positions: Positions, + touched: BTreeSet, + vectors: Vec, + vector_sizes: Vec, + node_sizes: HashMap, + meta: Option, + records_seen: usize, + max_nodes: usize, + materialized_bytes: usize, + max_materialized_bytes: usize, + abort: Option, +} + +impl DecodeState { + fn new(max_nodes: usize, max_materialized_bytes: usize) -> Self { + Self { + doc: Document::without_pages(""), + positions: Positions::new(), + touched: BTreeSet::new(), + vectors: Vec::new(), + vector_sizes: Vec::new(), + node_sizes: HashMap::new(), + meta: None, + records_seen: 0, + max_nodes, + materialized_bytes: 0, + max_materialized_bytes, + abort: None, + } + } + + fn charge(&mut self, bytes: usize) -> Result<(), Error> { + self.materialized_bytes = self.materialized_bytes.saturating_add(bytes); + if self.materialized_bytes > self.max_materialized_bytes { + return Err(Error::TooLarge(self.max_materialized_bytes)); + } + Ok(()) + } + + fn fail(&mut self, err: Error) -> E { + let msg = err.to_string(); + self.abort = Some(err); + E::custom(msg) + } + + fn ingest_record(&mut self, rec: WireRecord) -> Result<(), Error> { + let (node, pos, size) = match rec { + WireRecord::Full { pos, mut node, vref } => { + frac::validate(&pos).map_err(|e| Error::Invalid(e.to_string()))?; + if self.doc.contains(node.id) { + return Err(Error::Invalid(format!("node {} already exists", node.id))); + } + node.children.clear(); + let mut est = est_node_bytes(&node).saturating_add(pos.len()); + if let Some(idx) = vref { + let i = usize::try_from(idx).map_err(|_| Error::Decode(format!("invalid vector ref {idx}")))?; + let vsize = self.vector_sizes.get(i).copied().ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?; + est = est.saturating_add(vsize); + self.charge(est)?; + let net = self.vectors.get(i).ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?; + node.kind = NodeKind::Vector { network: net.clone() }; + } else { + self.charge(est)?; + } + (*node, pos, est) + } + WireRecord::Mirror(m) => { + frac::validate(&m.pos).map_err(|e| Error::Invalid(e.to_string()))?; + if self.doc.contains(m.id) { + return Err(Error::Invalid(format!("node {} already exists", m.id))); + } + let missing = || Error::Invalid(format!("mirror {} references missing or cyclic source {}", m.id, m.source)); + let src_size = self.node_sizes.get(&m.source).copied().ok_or_else(missing)?; + let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &self.vector_sizes)).saturating_add(m.pos.len()); + self.charge(est)?; + let src = self.doc.node(m.source).ok_or_else(missing)?; + let mut node = src.clone(); + node.id = m.id; + node.parent = m.parent; + node.children.clear(); + node.source = Some(m.source); + node.overrides = m.overrides; + for delta in m.deltas { + apply_field_delta(&mut node, delta, &self.vectors)?; + } + let actual = est_node_bytes(&node).saturating_add(m.pos.len()); + (node, m.pos, actual) + } + }; + + let id = node.id; + insert_decoded_node(&mut self.doc, &mut self.positions, node, pos)?; + self.touched.insert(id); + self.node_sizes.insert(id, size); + Ok(()) + } +} + +struct VectorsSeed<'a>(&'a mut DecodeState); +impl<'de> DeserializeSeed<'de> for VectorsSeed<'_> { + type Value = (); + fn deserialize>(self, d: D) -> Result<(), D::Error> { + d.deserialize_seq(self) + } +} +impl<'de> Visitor<'de> for VectorsSeed<'_> { + type Value = (); + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("vector networks") + } + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + while let Some(net) = seq.next_element::()? { + let size = est_vector_bytes(&net); + if let Err(err) = self.0.charge(size) { + return Err(self.0.fail(err)); + } + self.0.vector_sizes.push(size); + self.0.vectors.push(net); + } + Ok(()) + } +} + +struct RecordsSeed<'a>(&'a mut DecodeState); +impl<'de> DeserializeSeed<'de> for RecordsSeed<'_> { + type Value = (); + fn deserialize>(self, d: D) -> Result<(), D::Error> { + d.deserialize_seq(self) + } +} +impl<'de> Visitor<'de> for RecordsSeed<'_> { + type Value = (); + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("delta snapshot records") + } + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + loop { + if self.0.records_seen >= self.0.max_nodes { + if seq.next_element::()?.is_some() { + let max = self.0.max_nodes; + return Err(self.0.fail(Error::Invalid(format!("delta snapshot exceeds the {max}-node limit")))); + } + break; + } + let Some(rec) = seq.next_element::()? else { + break; + }; + self.0.records_seen += 1; + if let Err(err) = self.0.ingest_record(rec) { + return Err(self.0.fail(err)); + } + } + Ok(()) + } +} + +struct DeltaWireSeed<'a>(&'a mut DecodeState); +impl<'de> DeserializeSeed<'de> for DeltaWireSeed<'_> { + type Value = (); + fn deserialize>(self, d: D) -> Result<(), D::Error> { + d.deserialize_map(self) + } +} +impl<'de> Visitor<'de> for DeltaWireSeed<'_> { + type Value = (); + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("delta snapshot payload") + } + fn visit_map>(self, mut map: A) -> Result<(), A::Error> { + while let Some(key) = map.next_key::()? { + match key.as_str() { + "meta" => { + let meta: WireMeta = map.next_value()?; + let img_bytes = meta.images.iter().fold(0usize, |a, i| a.saturating_add(i.bytes.len())); + if let Err(err) = self.0.charge(img_bytes) { + return Err(self.0.fail(err)); + } + self.0.meta = Some(meta); + } + "vectors" => map.next_value_seed(VectorsSeed(self.0))?, + "records" => map.next_value_seed(RecordsSeed(self.0))?, + _ => { + let _ = map.next_value::()?; + } + } + } + Ok(()) + } +} + +fn stream_decode_wire(raw: &[u8], max_nodes: usize, max_materialized_bytes: usize) -> Result { + let mut state = DecodeState::new(max_nodes, max_materialized_bytes); + let mut de = serde_json::Deserializer::from_slice(raw); + let res = DeltaWireSeed(&mut state).deserialize(&mut de); + if let Some(err) = state.abort { + return Err(err); + } + res.map_err(|e| Error::Decode(format!("delta snapshot json: {e}")))?; + de.end().map_err(|e| Error::Decode(format!("delta snapshot trailing data: {e}")))?; + + let meta = state.meta.ok_or_else(|| Error::Decode("delta snapshot missing meta".into()))?; + apply_meta(&mut state.doc, meta); + relist_pages(&mut state.doc, &state.positions); + if state.doc.pages.is_empty() { + return Err(Error::Invalid("a snapshot needs a page".into())); + } + state.doc.published = None; + state.doc.take_dirty(); + let replica = Replica::from_parts(state.doc, state.positions); + replica.check(&state.touched)?; + Ok(replica) +} + +fn insert_decoded_node(doc: &mut Document, positions: &mut Positions, node: Node, pos: String) -> Result<(), Error> { + let (id, is_page, parent) = (node.id, node.is_page(), node.parent); + match (is_page, parent) { + (true, None) => { + doc.insert_page(node).map_err(|e| Error::Invalid(e.to_string()))?; + } + (false, Some(p)) => { + let siblings = &doc.get(p).map_err(|e| Error::Invalid(e.to_string()))?.children; + let at = siblings.partition_point(|c| (positions.get(c).map_or("", String::as_str), *c) < (pos.as_str(), id)); + doc.insert(node, p, Some(at)).map_err(|e| Error::Invalid(e.to_string()))?; + } + _ => return Err(Error::Invalid("pages, and only pages, have no parent".into())), + } + positions.insert(id, pos); + Ok(()) +} + +fn apply_meta(doc: &mut Document, mut meta: WireMeta) { + doc.name = meta.name; + doc.kind = meta.kind; + doc.styles = meta.styles; + doc.variables = meta.variables; + doc.current_page = meta.current_page; + doc.document_colors = meta.document_colors; + doc.comments = meta.comments; + doc.libraries = Arc::new(meta.libraries); + doc.color_profile = meta.color_profile; + doc.image_presets = meta.image_presets; + clamp_design_review_config(&mut meta.design_review); + doc.design_review = meta.design_review; + doc.annotation_categories = meta.annotation_categories; + doc.dev_snapshots = meta.dev_snapshots.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); + doc.timer = meta.timer; + doc.vote = meta.vote; + doc.votes = meta.votes; + doc.vote_history = meta.vote_history; + for wi in meta.images { + // Leave out images that fail validation or attempt to replace bytes under an existing + // key, matching legacy `Replica::from_snapshot_leaving_out`. + let Ok(img) = validate_image_base64(&wi.key, wi.width, wi.height, &wi.bytes) else { + continue; + }; + if doc.images.get(&wi.key).is_some_and(|old| old.bytes != img.bytes) { + continue; + } + doc.images.insert(wi.key, img); + } +} + +fn relist_pages(doc: &mut Document, positions: &Positions) { + let store = doc.libraries.store; + let mut pages: Vec = doc.nodes().filter(|n| n.is_page() && Some(n.id) != store).map(|n| n.id).collect(); + pages.sort_by(|a, b| (positions.get(a).map_or("", String::as_str), *a).cmp(&(positions.get(b).map_or("", String::as_str), *b))); + doc.pages = pages; +} diff --git a/crates/collab/src/delta_snapshot/encode.rs b/crates/collab/src/delta_snapshot/encode.rs new file mode 100644 index 000000000..474cea954 --- /dev/null +++ b/crates/collab/src/delta_snapshot/encode.rs @@ -0,0 +1,222 @@ +//! Topological ordering, vector interning and deflate framing for `CatchUp::DeltaSnapshot`. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::io::{BufWriter, Write}; + +use figcraft_doc::{Document, Node, NodeId, NodeKind, VectorNetwork}; +use sha2::{Digest as _, Sha256}; + +use super::fields::{diff_mirror_fields, exact_vector_network_eq}; +use super::{DELTA_MAGIC, DELTA_VERSION, DeltaWireRef, MirrorWire, WireImage, WireMeta, WireRecord}; +use crate::Error; +use crate::replica::Replica; + +/// Content-addressed deduplicator for `VectorNetwork`s within one snapshot. +#[derive(Default)] +pub(super) struct VectorInterner { + by_hash: HashMap<[u8; 32], Vec>, + table: Vec, +} + +impl VectorInterner { + pub(super) fn intern(&mut self, net: &VectorNetwork) -> Result { + let raw = serde_json::to_vec(net).map_err(|e| Error::Encode(e.to_string()))?; + let digest: [u8; 32] = Sha256::digest(&raw).into(); + if let Some(bucket) = self.by_hash.get(&digest) { + for &idx in bucket { + if usize::try_from(idx).ok().and_then(|i| self.table.get(i)).is_some_and(|existing| exact_vector_network_eq(existing, net)) { + return Ok(idx); + } + } + } + let idx = u32::try_from(self.table.len()).map_err(|_| Error::Encode("too many distinct vector networks".into()))?; + self.table.push(net.clone()); + self.by_hash.entry(digest).or_default().push(idx); + Ok(idx) + } +} + +/// Kahn topological order over `(parent, source)` edges (in-degree at most 2 per node). +/// +/// Every parent precedes its children and every acyclic source precedes its mirrors. Nodes +/// caught in a `source` cycle are appended in parent-first order and emitted as `Full`. +fn topo_order(doc: &Document) -> Vec { + let mut roots = doc.pages.clone(); + roots.extend(doc.nodes().filter(|n| n.parent.is_none() && !doc.pages.contains(&n.id)).map(|n| n.id)); + let mut parent_order = Vec::with_capacity(doc.node_count()); + for r in roots { + parent_order.extend(doc.subtree(r)); + } + + let present: HashSet = parent_order.iter().copied().collect(); + let mut indeg: HashMap = HashMap::with_capacity(present.len()); + let mut deps_of: HashMap> = HashMap::with_capacity(present.len()); + + for &id in &parent_order { + let Some(n) = doc.node(id) else { continue }; + let mut d: u8 = 0; + let p = n.parent.filter(|p| *p != id && present.contains(p)); + let s = n.source.filter(|s| *s != id && Some(*s) != p && present.contains(s)); + if let Some(pid) = p { + deps_of.entry(pid).or_default().push(id); + d += 1; + } + if let Some(sid) = s { + deps_of.entry(sid).or_default().push(id); + d += 1; + } + indeg.insert(id, d); + } + + let mut q: VecDeque = parent_order.iter().copied().filter(|id| indeg.get(id).copied() == Some(0)).collect(); + let mut ordered = Vec::with_capacity(parent_order.len()); + let mut placed: HashSet = HashSet::with_capacity(parent_order.len()); + + while let Some(u) = q.pop_front() { + if !placed.insert(u) { + continue; + } + ordered.push(u); + if let Some(nexts) = deps_of.get(&u) { + for &v in nexts { + if let Some(deg) = indeg.get_mut(&v) + && *deg > 0 + { + *deg -= 1; + if *deg == 0 { + q.push_back(v); + } + } + } + } + } + + if ordered.len() < parent_order.len() { + for id in parent_order { + if placed.insert(id) { + ordered.push(id); + } + } + } + ordered +} + +/// Encode `replica` as a compressed `CatchUp::DeltaSnapshot` payload. +pub fn encode_delta_snapshot(replica: &Replica) -> Result, Error> { + let doc = replica.document(); + let order = topo_order(doc); + let mut interner = VectorInterner::default(); + let mut seen: HashMap = HashMap::with_capacity(order.len()); + let mut records = Vec::with_capacity(order.len()); + + for id in order { + let Some(node) = doc.node(id) else { continue }; + let pos = replica.key(id).to_string(); + let rec = encode_one_node(node, pos, &seen, &mut interner)?; + records.push(rec); + seen.insert(id, node); + } + + let meta = build_meta(doc); + let wire = DeltaWireRef { meta: &meta, vectors: &interner.table, records: &records }; + compress_wire(&wire) +} + +fn encode_one_node(node: &Node, pos: String, seen: &HashMap, interner: &mut VectorInterner) -> Result { + if let Some(src_id) = node.source + && let Some(src) = seen.get(&src_id) + { + let deltas = diff_mirror_fields(src, node, interner)?; + return Ok(WireRecord::Mirror(Box::new(MirrorWire { + id: node.id, + parent: node.parent, + pos, + source: src_id, + overrides: node.overrides.clone(), + deltas, + }))); + } + + let mut stripped = node.clone(); + // Children are rebuilt from `(parent, pos)` on decode. + stripped.children.clear(); + let vref = match &mut stripped.kind { + NodeKind::Vector { network } if !network.vertices.is_empty() || !network.segments.is_empty() || !network.regions.is_empty() => { + let idx = interner.intern(network)?; + *network = VectorNetwork::default(); + Some(idx) + } + _ => None, + }; + Ok(WireRecord::Full { pos, node: Box::new(stripped), vref }) +} + +fn build_meta(doc: &Document) -> WireMeta { + use base64::Engine as _; + let images = doc + .images + .iter() + .map(|(key, img)| WireImage { + key: key.clone(), + width: img.width, + height: img.height, + bytes: base64::engine::general_purpose::STANDARD.encode(img.bytes.as_slice()), + }) + .collect(); + WireMeta { + name: doc.name.clone(), + kind: doc.kind, + styles: doc.styles.clone(), + variables: doc.variables.clone(), + current_page: doc.current_page, + document_colors: doc.document_colors.clone(), + comments: doc.comments.clone(), + libraries: (*doc.libraries).clone(), + color_profile: doc.color_profile, + image_presets: doc.image_presets.clone(), + design_review: doc.design_review.clone(), + annotation_categories: doc.annotation_categories.clone(), + dev_snapshots: doc.dev_snapshots.iter().map(|(k, v)| (*k, (**v).clone())).collect(), + timer: doc.timer, + vote: doc.vote.clone(), + votes: doc.votes.clone(), + vote_history: doc.vote_history.clone(), + images, + } +} + +struct CountingWriter { + inner: W, + written: usize, +} + +impl Write for CountingWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let n = self.inner.write(buf)?; + self.written = self.written.saturating_add(n); + Ok(n) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + +fn compress_wire(wire: &DeltaWireRef<'_>) -> Result, Error> { + let mut out = Vec::with_capacity(4096); + out.extend_from_slice(DELTA_MAGIC); + out.push(DELTA_VERSION); + out.extend_from_slice(&0u32.to_le_bytes()); + + // Buffer writes into 64 KiB chunks so serde_json's small token writes do not enter deflate individually. + let encoder = flate2::write::DeflateEncoder::new(out, flate2::Compression::fast()); + let mut buffered = BufWriter::with_capacity(64 * 1024, CountingWriter { inner: encoder, written: 0 }); + serde_json::to_writer(&mut buffered, wire).map_err(|e| Error::Encode(e.to_string()))?; + let counting = buffered.into_inner().map_err(|e| Error::Encode(e.into_error().to_string()))?; + let len_u32 = u32::try_from(counting.written).map_err(|_| Error::TooLarge(u32::MAX as usize))?; + let mut out = counting.inner.finish().map_err(|e| Error::Encode(e.to_string()))?; + if let Some(slot) = out.get_mut(5..9) { + slot.copy_from_slice(&len_u32.to_le_bytes()); + } + Ok(out) +} diff --git a/crates/collab/src/delta_snapshot/fields.rs b/crates/collab/src/delta_snapshot/fields.rs new file mode 100644 index 000000000..e3ebe097b --- /dev/null +++ b/crates/collab/src/delta_snapshot/fields.rs @@ -0,0 +1,284 @@ +//! Mirror field deltas and structural equality checks. +//! +//! `Paint` ignores `color_alpha` in `PartialEq`, and IEEE-754 equates `-0.0` with `0.0`. +//! Float and paint fields therefore compare bit-for-bit or via serialized JSON so mirror +//! encoding never drops data that legacy snapshots preserve. + +use std::collections::BTreeMap; + +use figcraft_doc::color::{BlendMode, Paint, PaintKind}; +use figcraft_doc::geom::Affine; +use figcraft_doc::proto::{Interaction, Overflow, ScrollPosition}; +use figcraft_doc::{ + Annotation, AutoLayout, BoardItem, BoolOp, ChildLayout, CodeLink, CollectionId, Constraints, Corners, DevResource, DevStatus, Effect, + ExportSetting, Guide, LayoutGrid, MaskType, Measurement, ModeId, Node, NodeKind, Region, Segment, StrokeProps, StyleRefs, VariableId, + VectorNetwork, Vertex, +}; +use serde::{Deserialize, Serialize}; + +use super::encode::VectorInterner; +use crate::Error; + +/// Defines `FieldDelta`, mirror diffing and delta application from one field table so adding +/// or editing a field keeps all three in lockstep. +/// +/// New variants must be appended and gated behind a version or capability bump because older +/// clients reject unknown variants during deserialization. +macro_rules! delta_fields { + ( + boxed: [ $( $bvar:ident ( $bty:ty ) => $bfield:ident via $beq:ident ),* $(,)? ], + value: [ $( $vvar:ident ( $vty:ty ) => $vfield:ident via $veq:ident ),* $(,)? ] + ) => { + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] + #[serde(rename_all = "camelCase")] + pub(super) enum FieldDelta { + Kind(Box), + VectorRef(u32), + $( $bvar(Box<$bty>), )* + $( $vvar($vty), )* + } + + fn diff_table_fields(src: &Node, node: &Node, out: &mut Vec) { + $( + if !$beq(&node.$bfield, &src.$bfield) { + out.push(FieldDelta::$bvar(Box::new(node.$bfield.clone()))); + } + )* + $( + if !$veq(&node.$vfield, &src.$vfield) { + out.push(FieldDelta::$vvar(node.$vfield.clone())); + } + )* + } + + pub(super) fn apply_field_delta(node: &mut Node, delta: FieldDelta, vectors: &[VectorNetwork]) -> Result<(), Error> { + match delta { + FieldDelta::Kind(v) => node.kind = *v, + FieldDelta::VectorRef(idx) => { + let net = usize::try_from(idx) + .ok() + .and_then(|i| vectors.get(i)) + .ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?; + node.kind = NodeKind::Vector { network: net.clone() }; + } + $( FieldDelta::$bvar(v) => node.$bfield = *v, )* + $( FieldDelta::$vvar(v) => node.$vfield = v, )* + } + Ok(()) + } + }; +} + +delta_fields! { + boxed: [ + Stroke(StrokeProps) => stroke via eq_exact, + ChildLayout(ChildLayout) => child_layout via eq_exact, + Styles(StyleRefs) => styles via eq_plain, + ], + value: [ + Name(String) => name via eq_plain, + Visible(bool) => visible via eq_plain, + Locked(bool) => locked via eq_plain, + Opacity(f32) => opacity via eq_f32, + Blend(BlendMode) => blend via eq_plain, + Transform(Affine) => transform via eq_affine, + Width(f64) => width via eq_f64, + Height(f64) => height via eq_f64, + Fills(Vec) => fills via eq_paint_vec, + Strokes(Vec) => strokes via eq_paint_vec, + Effects(Vec) => effects via eq_vec_exact, + Corners(Corners) => corners via eq_exact, + Constraints(Constraints) => constraints via eq_plain, + Layout(Option) => layout via eq_opt_exact, + Clip(bool) => clip via eq_plain, + IsMask(bool) => is_mask via eq_plain, + MaskType(MaskType) => mask_type via eq_plain, + Grids(Vec) => grids via eq_vec_exact, + Guides(Vec) => guides via eq_vec_exact, + Exports(Vec) => exports via eq_vec_exact, + Interactions(Vec) => interactions via eq_vec_exact, + Overflow(Overflow) => overflow via eq_plain, + ScrollPosition(ScrollPosition) => scroll_position via eq_exact, + Bound(BTreeMap) => bound via eq_plain, + VarModes(BTreeMap) => var_modes via eq_plain, + ScaleFactor(f64) => scale_factor via eq_f64, + BoolOp(Option) => bool_op via eq_plain, + ConstrainProportions(bool) => constrain_proportions via eq_plain, + Exposed(bool) => exposed via eq_plain, + DevStatus(DevStatus) => dev_status via eq_plain, + DevChanged(bool) => dev_changed via eq_plain, + DevNote(String) => dev_note via eq_plain, + PropRefs(BTreeMap) => prop_refs via eq_plain, + PluginData(BTreeMap) => plugin_data via eq_plain, + Annotations(Vec) => annotations via eq_vec_exact, + CodeLinks(Vec) => code_links via eq_plain, + DevResources(Vec) => dev_resources via eq_plain, + Measurements(Vec) => measurements via eq_vec_exact, + Board(Option) => board via eq_opt_exact, + ] +} + +/// Fails to compile if a new field is added to `figcraft_doc::Node` without updating `delta_fields!`. +#[allow(dead_code)] +fn every_node_field_visited(n: &Node) { + let Node { + id: _, + name: _, + kind: _, + parent: _, + children: _, + visible: _, + locked: _, + opacity: _, + blend: _, + transform: _, + width: _, + height: _, + fills: _, + strokes: _, + stroke: _, + effects: _, + corners: _, + constraints: _, + layout: _, + child_layout: _, + clip: _, + is_mask: _, + mask_type: _, + grids: _, + guides: _, + exports: _, + interactions: _, + overflow: _, + scroll_position: _, + styles: _, + bound: _, + var_modes: _, + scale_factor: _, + bool_op: _, + constrain_proportions: _, + source: _, + exposed: _, + dev_status: _, + dev_changed: _, + dev_note: _, + overrides: _, + prop_refs: _, + plugin_data: _, + annotations: _, + code_links: _, + dev_resources: _, + measurements: _, + board: _, + } = n; +} + +pub(super) fn diff_mirror_fields(src: &Node, node: &Node, interner: &mut VectorInterner) -> Result, Error> { + let mut deltas = Vec::new(); + if !exact_kind_eq(&node.kind, &src.kind) { + match &node.kind { + NodeKind::Vector { network } => deltas.push(FieldDelta::VectorRef(interner.intern(network)?)), + other => deltas.push(FieldDelta::Kind(Box::new(other.clone()))), + } + } + diff_table_fields(src, node, &mut deltas); + Ok(deltas) +} + +#[inline] +fn eq_plain(a: &T, b: &T) -> bool { + a == b +} + +#[inline] +fn eq_f64(a: &f64, b: &f64) -> bool { + a.to_bits() == b.to_bits() +} + +#[inline] +fn eq_f32(a: &f32, b: &f32) -> bool { + a.to_bits() == b.to_bits() +} + +#[inline] +fn eq_affine(a: &Affine, b: &Affine) -> bool { + a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| x.to_bits() == y.to_bits()) +} + +fn eq_json(a: &T, b: &T) -> bool { + matches!((serde_json::to_vec(a), serde_json::to_vec(b)), (Ok(x), Ok(y)) if x == y) +} + +fn eq_exact(a: &T, b: &T) -> bool { + a == b && eq_json(a, b) +} + +fn eq_vec_exact(a: &[T], b: &[T]) -> bool { + (a.is_empty() && b.is_empty()) || (a == b && eq_json(a, b)) +} + +fn eq_opt_exact(a: &Option, b: &Option) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => x == y && eq_json(x, y), + _ => false, + } +} + +fn eq_paint(a: &Paint, b: &Paint) -> bool { + if a.visible != b.visible || a.blend != b.blend || !eq_f32(&a.opacity, &b.opacity) || !eq_f32(&a.color_alpha, &b.color_alpha) { + return false; + } + match (&a.kind, &b.kind) { + (PaintKind::Solid { color: ca }, PaintKind::Solid { color: cb }) => { + eq_f32(&ca.r, &cb.r) && eq_f32(&ca.g, &cb.g) && eq_f32(&ca.b, &cb.b) && eq_f32(&ca.a, &cb.a) + } + _ => a.kind == b.kind && eq_json(&a.kind, &b.kind), + } +} + +fn eq_paint_vec(a: &[Paint], b: &[Paint]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| eq_paint(x, y)) +} + +fn eq_vertex(a: &Vertex, b: &Vertex) -> bool { + eq_f64(&a.x, &b.x) && eq_f64(&a.y, &b.y) && eq_f64(&a.radius, &b.radius) && a.mirror == b.mirror && a.cap == b.cap && a.join == b.join +} + +fn eq_segment(a: &Segment, b: &Segment) -> bool { + a.a == b.a && a.b == b.b && eq_f64(&a.ta.0, &b.ta.0) && eq_f64(&a.ta.1, &b.ta.1) && eq_f64(&a.tb.0, &b.tb.0) && eq_f64(&a.tb.1, &b.tb.1) +} + +fn eq_region(a: &Region, b: &Region) -> bool { + let fills_ok = match (&a.fills, &b.fills) { + (None, None) => true, + (Some(fa), Some(fb)) => eq_paint_vec(fa, fb), + _ => false, + }; + let space_ok = match (a.paint_space, b.paint_space) { + (None, None) => true, + (Some(pa), Some(pb)) => eq_f64(&pa.width, &pb.width) && eq_f64(&pa.height, &pb.height) && eq_affine(&pa.transform, &pb.transform), + _ => false, + }; + a.winding == b.winding && a.loops == b.loops && fills_ok && space_ok +} + +pub(super) fn exact_vector_network_eq(a: &VectorNetwork, b: &VectorNetwork) -> bool { + a.vertices.len() == b.vertices.len() + && a.segments.len() == b.segments.len() + && a.regions.len() == b.regions.len() + && a.vertices.iter().zip(&b.vertices).all(|(x, y)| eq_vertex(x, y)) + && a.segments.iter().zip(&b.segments).all(|(x, y)| eq_segment(x, y)) + && a.regions.iter().zip(&b.regions).all(|(x, y)| eq_region(x, y)) +} + +fn exact_kind_eq(a: &NodeKind, b: &NodeKind) -> bool { + match (a, b) { + (NodeKind::Frame, NodeKind::Frame) + | (NodeKind::Group, NodeKind::Group) + | (NodeKind::Rectangle, NodeKind::Rectangle) + | (NodeKind::Line, NodeKind::Line) => true, + (NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) => exact_vector_network_eq(na, nb), + _ => eq_exact(a, b), + } +} diff --git a/crates/collab/src/delta_snapshot/mod.rs b/crates/collab/src/delta_snapshot/mod.rs new file mode 100644 index 000000000..34c5dd25d --- /dev/null +++ b/crates/collab/src/delta_snapshot/mod.rs @@ -0,0 +1,146 @@ +//! Direct mirror-delta and deduplicated-vector snapshots (`CatchUp::DeltaSnapshot`). +//! +//! Used for clients whose hello announces `delta-snapshot` and `design-review`. +//! Nodes are ordered topologically over `(parent, source)` edges so parents precede +//! children and acyclic sources precede their mirrors. Mirrors diff field values +//! structurally instead of trusting `Node::overrides`. Decoding streams records +//! one at a time under inflated-byte, exact declared-length, node-count and +//! materialized-memory budgets. + +mod decode; +mod encode; +mod fields; + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_doc::color::{Color, ColorProfile}; +use figcraft_doc::{ + AnnotationCategory, Ballots, BoardTimer, Comment, DesignReview, DevSnapshot, FileKind, ImagePreset, Libraries, Node, NodeId, VectorNetwork, Vote, + VoteRecord, +}; +use serde::{Deserialize, Serialize}; + +use crate::Error; +use fields::FieldDelta; + +pub use decode::{decode_delta_snapshot, decode_delta_snapshot_with_budget}; +pub use encode::encode_delta_snapshot; + +/// Wire header magic for [`CatchUp::DeltaSnapshot`](crate::CatchUp::DeltaSnapshot). +pub const DELTA_MAGIC: &[u8; 4] = b"FCDS"; +/// Wire format version for [`CatchUp::DeltaSnapshot`](crate::CatchUp::DeltaSnapshot). +pub const DELTA_VERSION: u8 = 1; +/// Fixed header size: 4-byte magic, 1-byte version, 4-byte little-endian uncompressed length. +const HEADER_LEN: usize = 9; +/// Default ceiling on estimated materialized bytes during decode. +pub const DEFAULT_MAX_MATERIALIZED_BYTES: usize = 512 << 20; + +/// Check the fixed header and declared uncompressed length in O(1). +/// +/// Combined with [`decode_delta_snapshot_with_budget`] requiring `inflated.len() == declared`, +/// this prevents a client from inflating past `max_bytes`. +pub fn check_header_limit(bytes: &[u8], max_bytes: usize) -> Result<(), Error> { + let declared = parse_header(bytes)?; + if declared > max_bytes { + return Err(Error::TooLarge(max_bytes)); + } + Ok(()) +} + +fn parse_header(bytes: &[u8]) -> Result { + let header = bytes.get(..HEADER_LEN).ok_or_else(|| Error::Decode("delta snapshot header is truncated".into()))?; + if header.get(..4) != Some(DELTA_MAGIC.as_slice()) { + return Err(Error::Decode("delta snapshot magic mismatch".into())); + } + let version = header.get(4).copied().ok_or_else(|| Error::Decode("delta snapshot version missing".into()))?; + if version != DELTA_VERSION { + return Err(Error::Decode(format!("unsupported delta snapshot version {version}"))); + } + let len_slice = header.get(5..9).ok_or_else(|| Error::Decode("delta snapshot length missing".into()))?; + let len_bytes: [u8; 4] = len_slice.try_into().map_err(|_| Error::Decode("delta snapshot length".into()))?; + usize::try_from(u32::from_le_bytes(len_bytes)).map_err(|_| Error::TooLarge(usize::MAX)) +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "r", rename_all = "camelCase")] +enum WireRecord { + Full { + pos: String, + node: Box, + #[serde(default, skip_serializing_if = "Option::is_none")] + vref: Option, + }, + Mirror(Box), +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct MirrorWire { + id: NodeId, + #[serde(default, skip_serializing_if = "Option::is_none")] + parent: Option, + pos: String, + source: NodeId, + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + overrides: BTreeSet, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + deltas: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct WireImage { + key: String, + width: u32, + height: u32, + bytes: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct WireMeta { + name: String, + #[serde(default)] + kind: FileKind, + #[serde(default)] + styles: Vec, + #[serde(default)] + variables: figcraft_doc::Variables, + #[serde(default)] + current_page: Option, + #[serde(default)] + document_colors: Vec, + #[serde(default)] + comments: Vec, + #[serde(default)] + libraries: Libraries, + #[serde(default)] + color_profile: ColorProfile, + #[serde(default)] + image_presets: Vec, + #[serde(default)] + design_review: DesignReview, + #[serde(default)] + annotation_categories: Option>, + #[serde(default)] + dev_snapshots: BTreeMap, + #[serde(default)] + timer: Option, + #[serde(default)] + vote: Option, + #[serde(default)] + votes: Ballots, + #[serde(default)] + vote_history: Vec, + #[serde(default)] + images: Vec, +} + +/// Serialization envelope written in canonical order (`meta`, `vectors`, `records`). +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct DeltaWireRef<'a> { + meta: &'a WireMeta, + #[serde(skip_serializing_if = "<[VectorNetwork]>::is_empty")] + vectors: &'a [VectorNetwork], + records: &'a [WireRecord], +} diff --git a/crates/collab/src/delta_snapshot_tests.rs b/crates/collab/src/delta_snapshot_tests.rs new file mode 100644 index 000000000..ff6a369fc --- /dev/null +++ b/crates/collab/src/delta_snapshot_tests.rs @@ -0,0 +1,350 @@ +//! Parity, exact-equality and hostile-input tests for `CatchUp::DeltaSnapshot`. + +use std::collections::BTreeMap; +use std::io::Write; +use std::sync::Arc; + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{ + BoardTimer, Comment, DesignReview, DevSnapshot, Document, ImageData, ImagePreset, Libraries, NodeId, NodeKind, Segment, TextData, VectorNetwork, + Vertex, Vote, VoteRecord, +}; +use figcraft_geom::Affine; + +use crate::delta_snapshot::{DELTA_MAGIC, DELTA_VERSION, decode_delta_snapshot, decode_delta_snapshot_with_budget, encode_delta_snapshot}; +use crate::message::{self, CatchUp, ClientMsg, ServerMsg}; +use crate::{Client, Error, Limits, Outgoing, Replica, Server}; + +pub(crate) const LEGACY_CLIENT_VERSION: &str = "0.18.1 signals hosting comments packed design-review branches"; + +/// Compare two documents via serialized JSON (excluding per-client `next_id`) so +/// non-structural `PartialEq` cannot hide silent data loss. +pub(crate) fn assert_docs_json_eq(left: &Document, right: &Document, context: &str) { + let mut lj = serde_json::to_value(left).expect("serialize left doc"); + let mut rj = serde_json::to_value(right).expect("serialize right doc"); + if let Some(m) = lj.as_object_mut() { + m.remove("next_id"); + } + if let Some(m) = rj.as_object_mut() { + m.remove("next_id"); + } + assert_eq!(lj, rj, "{context}: serialized JSON mismatch"); +} + +fn make_raw_delta_payload(json: &str, declared_override: Option) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(DELTA_MAGIC); + out.push(DELTA_VERSION); + let len = declared_override.unwrap_or(u32::try_from(json.len()).unwrap()); + out.extend_from_slice(&len.to_le_bytes()); + let mut z = flate2::write::DeflateEncoder::new(out, flate2::Compression::fast()); + z.write_all(json.as_bytes()).unwrap(); + z.finish().unwrap() +} + +pub(crate) fn sample_vector_icon(seed: usize, vertex_count: usize) -> VectorNetwork { + let mut vertices = Vec::with_capacity(vertex_count); + let mut segments = Vec::with_capacity(vertex_count); + for i in 0..vertex_count { + let a = (i as f64) * std::f64::consts::TAU / (vertex_count as f64) + (seed as f64) * 0.1; + vertices.push(Vertex::new(16.0 + 12.0 * a.cos(), 16.0 + 12.0 * a.sin())); + segments.push(Segment { a: i, b: (i + 1) % vertex_count, ta: (1.5, -0.5), tb: (-1.5, 0.5) }); + } + VectorNetwork { vertices, segments, regions: Vec::new() } +} + +/// Build a document with cross-page instances (main component on page 2, instances on page 1), +/// depth-2 mirror chains, repeated vector icons and stale empty `overrides` (#1819). +pub(crate) fn design_system_doc(num_instances: usize) -> (Document, NodeId, Vec) { + let mut doc = Document::new("DesignSystemDST"); + let page1 = doc.first_page().unwrap(); + let page2 = doc.add_page("Components"); + + let comp = doc + .create( + page2, + NodeKind::Component { description: "Card".into(), props: BTreeMap::new(), prop_order: Vec::new() }, + "Card", + 0.0, + 0.0, + 320.0, + 200.0, + ) + .unwrap(); + + let icon_a = sample_vector_icon(1, 24); + let icon_b = sample_vector_icon(2, 24); + let mut main_children = Vec::new(); + for i in 0..6 { + let kind = match i { + 0 | 1 => NodeKind::Text(TextData::new(format!("Title {i}"))), + 2 => NodeKind::Vector { network: icon_a.clone() }, + 3 => NodeKind::Vector { network: icon_b.clone() }, + _ => NodeKind::Rectangle, + }; + let cid = doc.create(comp, kind, &format!("Part {i}"), i as f64 * 24.0, 8.0, 32.0, 32.0).unwrap(); + if let Some(n) = doc.node_mut(cid) { + n.fills = vec![Paint::solid(Color::from_rgb8_const(40, 100, (i * 30) as u8))]; + } + main_children.push(cid); + } + + let main_snapshots: Vec<_> = main_children.iter().map(|id| doc.node(*id).unwrap().clone()).collect(); + let mut prev_inst_children: Option> = None; + + for idx in 0..num_instances { + let mut root = doc.node(comp).unwrap().clone(); + let inst_id = doc.alloc_id(); + root.id = inst_id; + root.name = format!("Card #{idx}"); + root.kind = NodeKind::Instance { component: comp, props: BTreeMap::new() }; + root.children.clear(); + root.parent = None; + root.source = Some(comp); + root.transform = Affine::translate((idx as f64 * 340.0, 0.0)); + doc.insert(root, page1, None).unwrap(); + + let mut this_children = Vec::new(); + for (j, src) in main_snapshots.iter().enumerate() { + let mut child = src.clone(); + child.id = doc.alloc_id(); + child.parent = None; + child.children.clear(); + let chain_src = prev_inst_children.as_ref().filter(|_| idx % 3 == 2).map_or(src.id, |prev| prev[j]); + child.source = Some(chain_src); + + if j == 0 && idx % 2 == 0 { + if let NodeKind::Text(t) = &mut child.kind { + t.characters = format!("Overridden {idx}"); + } + if idx % 4 != 0 { + child.overrides.insert("characters".to_string()); + } + } + if j == 4 && idx % 5 == 0 { + child.width = 99.0; + child.transform = Affine::translate((12.0, 24.0)); + } + let child_id = child.id; + doc.insert(child, inst_id, None).unwrap(); + this_children.push(child_id); + } + prev_inst_children = Some(this_children); + } + + doc.take_dirty(); + (doc, comp, main_children) +} + +#[test] +fn mirror_delta_preserves_paint_color_alpha_and_signed_zero() { + let mut doc = Document::new("ExactEq"); + let page = doc.first_page().unwrap(); + let src = doc.create(page, NodeKind::Rectangle, "Src", 0.0, 0.0, 100.0, 50.0).unwrap(); + let mut src_paint = Paint::solid(Color::from_rgb8_const(20, 80, 200)); + src_paint.opacity = 0.5; + src_paint.color_alpha = 0.5; + if let Some(n) = doc.node_mut(src) { + n.fills = vec![src_paint.clone()]; + n.strokes = vec![src_paint]; + } + + let mut mirror = doc.node(src).unwrap().clone(); + mirror.id = doc.alloc_id(); + mirror.parent = None; + mirror.source = Some(src); + mirror.fills[0].color_alpha = 1.0; + mirror.strokes[0].color_alpha = 0.25; + mirror.width = -0.0; + mirror.transform = Affine::translate((-0.0, 0.0)); + assert_eq!(doc.node(src).unwrap().fills, mirror.fills, "Paint PartialEq ignores color_alpha"); + doc.insert(mirror, page, None).unwrap(); + doc.take_dirty(); + + let replica = Replica::new(doc); + let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 16 << 20, Limits::default().max_nodes).unwrap(); + let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap(); + assert_docs_json_eq(replica.document(), decoded.document(), "exact structural equality"); + assert_docs_json_eq(legacy.document(), decoded.document(), "legacy parity"); +} + +#[test] +fn corrupt_hash_image_matches_legacy_join_parity() { + let mut doc = Document::new("BadImage"); + let page = doc.first_page().unwrap(); + doc.create(page, NodeKind::Rectangle, "Box", 0.0, 0.0, 40.0, 40.0).unwrap(); + let bad_key = "0".repeat(64); + doc.images.insert(bad_key.clone(), ImageData { bytes: Arc::new(b"not-matching-sha256".to_vec()), width: 10, height: 10 }); + doc.images.insert("svg_icon_1".into(), ImageData { bytes: Arc::new(b"valid-bytes".to_vec()), width: 16, height: 16 }); + doc.take_dirty(); + + let mut srv = Server::new(doc, "tok", Limits::default()); + let join_with = |srv: &mut Server, ver: Option<&str>| -> Client { + let ClientMsg::Hello(mut h) = Client::hello("f", "tok", "u", "#111") else { panic!() }; + if let Some(v) = ver { + h.client_version = v.into(); + } + let (id, outs) = srv.join(h).unwrap(); + let w = outs + .into_iter() + .find_map(|o| match o { + Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m), + _ => None, + }) + .unwrap(); + Client::join(w).unwrap() + }; + + let legacy_client = join_with(&mut srv, Some(LEGACY_CLIENT_VERSION)); + let delta_client = join_with(&mut srv, None); + assert!(!delta_client.document().images.contains_key(&bad_key)); + assert!(delta_client.document().images.contains_key("svg_icon_1")); + assert_docs_json_eq(legacy_client.document(), delta_client.document(), "corrupt-image parity"); +} + +#[test] +fn forged_declared_length_cannot_bypass_unpack_limit() { + let huge_json = format!( + r#"{{"meta":{{"name":"Bomb"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"{}","type":"page","width":0,"height":0}}}}]}}"#, + "A".repeat(4 << 20) + ); + let mut welcome = ServerMsg::Welcome { + session: 1, + client_id: 1, + seq: 0, + catch_up: CatchUp::DeltaSnapshot(make_raw_delta_payload(&huge_json, Some(10))), + processed: message::Processed::default(), + peers: Vec::new(), + access: message::Access::Edit, + secret: 1, + }; + message::unpack(&mut welcome, 1 << 20).unwrap(); + let err = Client::join(welcome).unwrap_err(); + assert!(matches!(err, Error::TooLarge(10)), "forged length must abort at declared+1, got {err:?}"); +} + +#[test] +fn mirror_and_vref_amplification_bombs_are_rejected_within_memory_budget() { + let big_text = "X".repeat(256 * 1024); + let mut mirror_recs = String::from( + r#"{"meta":{"name":"MirrorBomb"},"records":[{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},"#, + ); + mirror_recs.push_str(&format!( + r#"{{"r":"full","pos":"a0","node":{{"id":2,"name":"Big","parent":1,"type":"text","characters":"{big_text}","width":10,"height":10}}}}"# + )); + for i in 3..2003u64 { + mirror_recs.push_str(&format!(r#",{{"r":"mirror","id":{i},"parent":1,"pos":"a{i:04}1","source":2}}"#)); + } + mirror_recs.push_str("]}"); + let err1 = decode_delta_snapshot(&make_raw_delta_payload(&mirror_recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err(); + assert!(matches!(err1, Error::TooLarge(_)), "mirror bomb must fail TooLarge, got {err1:?}"); + + let net_json = serde_json::to_string(&sample_vector_icon(1, 20_000)).unwrap(); + let mut vref_recs = format!( + r#"{{"meta":{{"name":"VrefBomb"}},"vectors":[{net_json}],"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}}"# + ); + for i in 2..3002u64 { + vref_recs.push_str(&format!( + r#",{{"r":"full","pos":"a{i:04}1","vref":0,"node":{{"id":{i},"name":"V","parent":1,"type":"vector","network":{{"vertices":[],"segments":[]}},"width":10,"height":10}}}}"# + )); + } + vref_recs.push_str("]}"); + let err2 = decode_delta_snapshot(&make_raw_delta_payload(&vref_recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err(); + assert!(matches!(err2, Error::TooLarge(_)), "vref bomb must fail TooLarge, got {err2:?}"); +} + +#[test] +fn streaming_node_budget_and_hostile_inputs_are_rejected_cleanly() { + let mut many = + String::from(r#"{"meta":{"name":"Many"},"records":[{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}}"#); + for i in 2..502u64 { + many.push_str(&format!( + r#",{{"r":"full","pos":"a{i:04}1","node":{{"id":{i},"name":"R","parent":1,"type":"rectangle","width":1,"height":1}}}}"# + )); + } + many.push_str("]}"); + let err = decode_delta_snapshot_with_budget(&make_raw_delta_payload(&many, None), 16 << 20, 10, 64 << 20).unwrap_err(); + assert!(matches!(&err, Error::Invalid(msg) if msg.contains("10-node limit")), "got {err:?}"); + + let cyclic = r#"{"meta":{"name":"Evil"},"records":[ + {"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}}, + {"r":"mirror","id":2,"parent":1,"pos":"a0","source":3}, + {"r":"mirror","id":3,"parent":1,"pos":"a1","source":2} + ]}"#; + let self_cycle = r#"{"meta":{"name":"Self"},"records":[ + {"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}}, + {"r":"mirror","id":2,"parent":1,"pos":"a0","source":2} + ]}"#; + assert!(matches!(decode_delta_snapshot(&make_raw_delta_payload(cyclic, None), 1 << 20, 100), Err(Error::Invalid(_)))); + assert!(matches!(decode_delta_snapshot(&make_raw_delta_payload(self_cycle, None), 1 << 20, 100), Err(Error::Invalid(_)))); + + for bad in [vec![], b"FCD".to_vec(), b"XXXX\x01\x00\x00\x00\x00".to_vec(), b"FCDS\x99\x00\x00\x00\x00".to_vec(), vec![0xFF; 64]] { + assert!(decode_delta_snapshot(&bad, 1 << 20, 1000).is_err()); + } +} + +#[test] +fn full_metadata_and_design_review_roundtrip_matches_legacy_json() { + let (mut doc, _, _) = design_system_doc(4); + let page = doc.first_page().unwrap(); + doc.comments.push(Comment { + id: 7, + page, + x: 10.0, + y: 20.0, + anchor: None, + first: figcraft_doc::Message::new("Alice", "Check contrast", 1_700_000_000), + resolved: false, + replies: Vec::new(), + read_by: None, + }); + doc.dev_snapshots.insert(page, Arc::new(DevSnapshot { nodes: vec![Arc::new(doc.node(page).unwrap().clone())] })); + doc.timer = Some(BoardTimer::Paused { left: 120_000 }); + let vote = Vote { per_person: 3, scope: Default::default(), ended: false, by: "Alice".into() }; + doc.vote = Some(vote.clone()); + doc.votes.entry("alice".into()).or_default().push(page); + doc.vote_history.push(VoteRecord { vote, ballots: doc.votes.clone(), names: BTreeMap::new(), ended: 1_700_000_000 }); + doc.libraries = Arc::new(Libraries::default()); + doc.image_presets.push(ImagePreset { name: "Warm".into(), filters: Default::default() }); + doc.images.insert("logo_1".into(), ImageData { bytes: Arc::new(b"png-bytes".to_vec()), width: 32, height: 32 }); + doc.design_review = DesignReview { radii: vec![4.0; figcraft_doc::MAX_RADII + 10], ..DesignReview::default() }; + doc.take_dirty(); + + let replica = Replica::new(doc); + let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap(); + let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap(); + assert_eq!(decoded.document().design_review.radii.len(), figcraft_doc::MAX_RADII); + assert_docs_json_eq(legacy.document(), decoded.document(), "full metadata parity"); +} + +#[test] +fn encoder_safely_roundtrips_cyclic_source_references_as_full_records() { + let mut doc = Document::new("CyclicInMemory"); + let page = doc.first_page().unwrap(); + let a = doc.create(page, NodeKind::Rectangle, "A", 0.0, 0.0, 50.0, 50.0).unwrap(); + let b = doc.create(page, NodeKind::Rectangle, "B", 60.0, 0.0, 50.0, 50.0).unwrap(); + doc.node_mut(a).unwrap().source = Some(b); + doc.node_mut(b).unwrap().source = Some(a); + doc.take_dirty(); + + let replica = Replica::new(doc); + let back = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 1 << 20, 100).unwrap(); + assert_docs_json_eq(replica.document(), back.document(), "cyclic source roundtrip"); +} + +#[test] +fn delta_snapshot_never_panics_when_truncated_or_bit_flipped() { + let (doc, _, _) = design_system_doc(2); + let valid = encode_delta_snapshot(&Replica::new(doc)).unwrap(); + // Truncations across header and compressed body. + for cut in [0, 1, 4, 8, 9, 10, valid.len() / 2, valid.len() - 1] { + assert!(decode_delta_snapshot(&valid[..cut], 16 << 20, 10_000).is_err()); + } + // Single-bit flips across header and body must either error cleanly or produce a valid Replica. + let stride = (valid.len() / 64).max(1); + for idx in (0..valid.len()).step_by(stride) { + let mut mutated = valid.clone(); + mutated[idx] ^= 0x80; + let _ = decode_delta_snapshot(&mutated, 16 << 20, 10_000); + } +} diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index ae7299511..6b50ffaea 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -290,27 +290,61 @@ fn image_of(key: &str, value: &Json) -> Result { image_within(key, value, ImageData::MAX_BYTES) } -/// [`image_of`] with `max_bytes` for the decoded size. -pub(crate) fn image_within(key: &str, value: &Json, max_bytes: u64) -> Result { +/// Validate raw image bytes and dimensions under the same security rules as [`image_of`] (#1086). +pub(crate) fn validate_image_raw_within(key: &str, width: u32, height: u32, bytes: Vec, max_bytes: u64) -> Result { if !ImageData::is_valid_key(key) { return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)"))); } - let v: ImageValue = value.read("image")?; - if v.width > MAX_IMAGE_SIDE || v.height > MAX_IMAGE_SIDE { - return Err(Error::Invalid(format!("image: {}×{} passes the {} a side may be", v.width, v.height, MAX_IMAGE_SIDE))); + if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE { + return Err(Error::Invalid(format!("image: {width}×{height} passes the {MAX_IMAGE_SIDE} a side may be"))); } - let max_encoded = (max_bytes / 3).saturating_mul(4).saturating_add(4); - if u64::try_from(v.bytes.len()).unwrap_or(u64::MAX) > max_encoded { - return Err(Error::Invalid(format!("image: base64 text longer than {max_encoded} bytes for {max_bytes} of bytes"))); - } - let bytes = base64::engine::general_purpose::STANDARD.decode(v.bytes.as_bytes()).map_err(|e| Error::Invalid(format!("image: {e}")))?; if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > max_bytes { return Err(Error::Invalid(format!("image: {} bytes pass the {max_bytes} an image may be", bytes.len()))); } if ImageData::claims_content_hash(key) && key != sha256_hex(&bytes) { return Err(Error::Invalid(format!("image: the bytes aren't what their key {key} hashes to"))); } - Ok(ImageData { bytes: Arc::new(bytes), width: v.width, height: v.height }) + Ok(ImageData { bytes: Arc::new(bytes), width, height }) +} + +/// Validate base64-encoded image bytes and dimensions under [`ImageData::MAX_BYTES`]. +pub(crate) fn validate_image_base64(key: &str, width: u32, height: u32, encoded: &str) -> Result { + validate_image_base64_within(key, width, height, encoded, ImageData::MAX_BYTES) +} + +fn validate_image_base64_within(key: &str, width: u32, height: u32, encoded: &str, max_bytes: u64) -> Result { + if !ImageData::is_valid_key(key) { + return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)"))); + } + if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE { + return Err(Error::Invalid(format!("image: {width}×{height} passes the {MAX_IMAGE_SIDE} a side may be"))); + } + let max_encoded = (max_bytes / 3).saturating_mul(4).saturating_add(4); + if u64::try_from(encoded.len()).unwrap_or(u64::MAX) > max_encoded { + return Err(Error::Invalid(format!("image: base64 text longer than {max_encoded} bytes for {max_bytes} of bytes"))); + } + let bytes = base64::engine::general_purpose::STANDARD.decode(encoded.as_bytes()).map_err(|e| Error::Invalid(format!("image: {e}")))?; + validate_image_raw_within(key, width, height, bytes, max_bytes) +} + +/// Clamp oversized review settings in place (matches [`clamp_snapshot_design_review`]). +pub(crate) fn clamp_design_review_config(config: &mut figcraft_doc::DesignReview) -> bool { + if config.over_limits().is_empty() { + return false; + } + config.radii.truncate(figcraft_doc::MAX_RADII); + config.brand.truncate(figcraft_doc::MAX_BRAND_COLORS); + config.disabled.truncate(figcraft_doc::MAX_DISABLED); + true +} + +/// [`image_of`] with `max_bytes` for the decoded size. +pub(crate) fn image_within(key: &str, value: &Json, max_bytes: u64) -> Result { + if !ImageData::is_valid_key(key) { + return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)"))); + } + let v: ImageValue = value.read("image")?; + validate_image_base64_within(key, v.width, v.height, &v.bytes, max_bytes) } macro_rules! doc_scalars { @@ -413,17 +447,12 @@ pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) -> bool { let mut clamped_any = false; for c in changes { if let Change::SetDoc { prop: DocProp::DesignReview, value } = c - && let Ok(config) = value.read::("design review") - && !config.over_limits().is_empty() + && let Ok(mut clamped) = value.read::("design review") + && clamp_design_review_config(&mut clamped) + && let Ok(v) = Json::of(&clamped) { - 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; - clamped_any = true; - } + *value = v; + clamped_any = true; } } clamped_any diff --git a/crates/collab/src/journal_tests.rs b/crates/collab/src/journal_tests.rs index a8a7c4c25..3562c81c4 100644 --- a/crates/collab/src/journal_tests.rs +++ b/crates/collab/src/journal_tests.rs @@ -303,7 +303,7 @@ fn a_resume_after_history_was_left_out_catches_up_with_the_snapshot() { let (key, bytes) = crate::image_tests::forged(); state.snapshot.push(crate::image_tests::put(&key, 2, 1, bytes)); let mut r = Server::restore(state, "", Limits::default()).unwrap(); - assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_)), "left out on restore"); + assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_) | message::CatchUp::DeltaSnapshot(_)), "left out on restore"); // Left out on replay. let mut s = Server::new(base(), "", Limits::default()); @@ -312,7 +312,7 @@ fn a_resume_after_history_was_left_out_catches_up_with_the_snapshot() { let mut r = Server::restore(state.clone(), "", Limits::default()).unwrap(); let batch = vec![crate::image_tests::put(&key, 2, 1, bytes)]; r.replay(Journal::Accepted(message::Accepted { seq: state.seq + 1, author: a.id(), batch_id: 90, changes: batch })).unwrap(); - assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_)), "left out on replay"); + assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_) | message::CatchUp::DeltaSnapshot(_)), "left out on replay"); } /// A restart that left nothing out keeps resuming clients on the cheaper delta. diff --git a/crates/collab/src/lib.rs b/crates/collab/src/lib.rs index 230e209b8..912af370f 100644 --- a/crates/collab/src/lib.rs +++ b/crates/collab/src/lib.rs @@ -24,6 +24,7 @@ pub mod change; pub mod client; pub mod code; +pub mod delta_snapshot; mod diff; mod docprops; pub mod frac; @@ -143,6 +144,10 @@ mod comment_access_tests; #[cfg(test)] mod deleted_cap_tests; #[cfg(test)] +mod delta_dst_tests; +#[cfg(test)] +mod delta_snapshot_tests; +#[cfg(test)] mod diff_tests; #[cfg(test)] mod entry_ids_tests; diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index a1bc84fba..36c691b85 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -44,9 +44,14 @@ pub const BRANCHES: &str = "branches"; /// (older ones couldn't decode the variant at all). pub const DESIGN_REVIEW: &str = "design-review"; +/// The word a client puts in its [`Hello::client_version`] when it reads +/// [`CatchUp::DeltaSnapshot`]: a server sends a direct value-checked mirror-delta + vector-dedup +/// compressed snapshot instead of `Vec` (#1819, #2041). +pub const DELTA_SNAPSHOT: &str = "delta-snapshot"; + /// 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} {DESIGN_REVIEW} {BRANCHES}", env!("CARGO_PKG_VERSION")) + format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW} {BRANCHES} {DELTA_SNAPSHOT}", env!("CARGO_PKG_VERSION")) } /// Whether `client_version` announces `word`. @@ -84,6 +89,11 @@ pub fn reads_branches(client_version: &str) -> bool { announces(client_version, BRANCHES) } +/// A [`Hello::client_version`] that announces [`DELTA_SNAPSHOT`]. +pub fn reads_delta_snapshot(client_version: &str) -> bool { + announces(client_version, DELTA_SNAPSHOT) +} + /// Join a file's session. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Hello { @@ -353,6 +363,10 @@ pub enum CatchUp { /// [`PACKED`]: a document's changes shrink several times over. The client reads it with /// [`unpack`] before anything else sees the welcome. Packed(Vec), + /// A direct compressed mirror-delta & vector-deduplicated snapshot + /// ([`crate::delta_snapshot`]), for a client whose hello announced [`DELTA_SNAPSHOT`]. + /// Appended last so earlier postcard discriminants remain unchanged. + DeltaSnapshot(Vec), } /// Opens a connection that manages a server's files (instead of [`Hello`]): the server's admin @@ -1175,19 +1189,25 @@ pub fn pack(msg: &mut ServerMsg) -> Result<(), Error> { /// past `max_bytes` (untrusted input: the limit an unpacked welcome would have had to fit). /// Anything else is left as it is. pub fn unpack(msg: &mut ServerMsg, max_bytes: usize) -> Result<(), Error> { - if let ServerMsg::Welcome { catch_up, .. } = msg - && let CatchUp::Packed(packed) = catch_up - { - let mut raw = Vec::new(); - let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1); - flate2::read::DeflateDecoder::new(packed.as_slice()) - .take(limit) - .read_to_end(&mut raw) - .map_err(|e| Error::Decode(format!("packed document: {e}")))?; - if raw.len() > max_bytes { - return Err(Error::TooLarge(max_bytes)); + if let ServerMsg::Welcome { catch_up, .. } = msg { + match catch_up { + CatchUp::Packed(packed) => { + let mut raw = Vec::new(); + let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1); + flate2::read::DeflateDecoder::new(packed.as_slice()) + .take(limit) + .read_to_end(&mut raw) + .map_err(|e| Error::Decode(format!("packed document: {e}")))?; + if raw.len() > max_bytes { + return Err(Error::TooLarge(max_bytes)); + } + *catch_up = CatchUp::Snapshot(from_postcard(&raw)?); + } + CatchUp::DeltaSnapshot(bytes) => { + crate::delta_snapshot::check_header_limit(bytes, max_bytes)?; + } + CatchUp::Snapshot(_) | CatchUp::Delta(_) => {} } - *catch_up = CatchUp::Snapshot(from_postcard(&raw)?); } Ok(()) } diff --git a/crates/collab/src/packed_welcome_tests.rs b/crates/collab/src/packed_welcome_tests.rs index c78208cc4..d8c48bcc7 100644 --- a/crates/collab/src/packed_welcome_tests.rs +++ b/crates/collab/src/packed_welcome_tests.rs @@ -23,7 +23,9 @@ fn welcome() -> ServerMsg { } doc.repair(); let mut s = Server::new(doc, "tok", Limits::default()); - let ClientMsg::Hello(h) = Client::hello("f", "tok", "Ada", "#FF8800") else { panic!("not a hello") }; + let ClientMsg::Hello(mut h) = Client::hello("f", "tok", "Ada", "#FF8800") else { panic!("not a hello") }; + // Test the legacy `packed` welcome path (a client from before `delta-snapshot`). + h.client_version = "0.18.1 signals hosting comments packed design-review branches".into(); let (_, out) = s.join(h).unwrap(); out.into_iter().find_map(|o| if let Outgoing::To(_, m @ ServerMsg::Welcome { .. }) = o { Some(m) } else { None }).unwrap() } diff --git a/crates/collab/src/reconnect_tests.rs b/crates/collab/src/reconnect_tests.rs index af13b5042..5489069ee 100644 --- a/crates/collab/src/reconnect_tests.rs +++ b/crates/collab/src/reconnect_tests.rs @@ -117,7 +117,7 @@ fn a_long_absence_catches_up_with_a_snapshot() { } let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() }; let (_, out) = s.join(h).unwrap(); - assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }))); + assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. }))); deliver(&mut a, &out); assert_eq!(a.view(), s.replica()); // A short absence gets the missed batches only. @@ -154,7 +154,7 @@ fn the_default_log_is_bounded_in_bytes_and_a_client_behind_it_catches_up_with_a_ assert!(s.log_bytes() > 0, "recent batches are still kept"); let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() }; let (_, out) = s.join(h).unwrap(); - assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }))); + assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. }))); deliver(&mut a, &out); assert_eq!(a.view(), s.replica()); // Within the log, a short absence still gets the missed batch only. @@ -195,7 +195,7 @@ fn after_a_snapshot_undo_leaves_what_others_changed_meanwhile() { } let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() }; let (_, out) = s.join(h).unwrap(); - assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }))); + assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. }))); deliver(&mut a, &out); // Undo: the page name goes back, the frame keeps b's later name. let msgs = a.undo(&NoRecompute).unwrap(); @@ -326,7 +326,7 @@ fn a_restored_session_with_clamped_settings_catches_up_by_snapshot() { let (id, out) = restored.join(h).unwrap(); assert_eq!(id, b.id(), "a reconnecting client keeps its id"); assert!( - matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })), + matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })), "a clamped session hands out the snapshot, not a batch past the limits: {out:?}" ); deliver(&mut b, &out); @@ -394,3 +394,33 @@ fn resume_needs_the_issued_secret() { let resend = come_back(&mut s, &mut host); assert!(resend.is_empty()); } + +#[test] +fn a_legacy_client_without_delta_snapshot_catches_up_with_a_legacy_snapshot() { + let mut s = Server::new(base(), "tok", Limits { max_log_batches: 2, ..Limits::default() }); + let legacy_hello = || Hello { client_version: "0.18.1 signals hosting comments packed design-review branches".into(), ..hello() }; + let (_, out) = s.join(legacy_hello()).unwrap(); + assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }))); + let Outgoing::To(_, w) = out.into_iter().next().unwrap() else { panic!() }; + let mut a = Client::join(w).unwrap(); + let mut b = join(&mut s); + let page = s.document().first_page().unwrap(); + + // Disconnect legacy client `a` and overflow the 2-batch server log so `a` must catch up via + // legacy `CatchUp::Snapshot` (never `DeltaSnapshot`). + a.disconnect(); + s.leave(a.id()); + for i in 0..4 { + let m = edit(&mut b, |d| d.node_mut(page).unwrap().name = format!("Legacy {i}")).unwrap(); + let out = s.receive(b.id(), m); + deliver(&mut b, &out); + } + let ClientMsg::Hello(h) = a.reconnect(legacy_hello()) else { panic!() }; + let (_, out) = s.join(h).unwrap(); + assert!( + matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })), + "legacy client without delta-snapshot must receive CatchUp::Snapshot on rejoin" + ); + deliver(&mut a, &out); + assert_eq!(a.view(), s.replica()); +} diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 99f0d6d6d..785650625 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; use crate::change::{Change, Entry, Family, Prop, Target}; use crate::message::{ Accepted, Access, BranchEvent, BranchReq, BranchStatus, CatchUp, ClientMsg, Hello, MAX_SHARED_BRANCHES, PROTOCOL, Peer, Presence, Processed, - Resume, ServerMsg, SharedBranch, Signal, reads_branches, reads_comments, reads_design_review, reads_signals, + Resume, ServerMsg, SharedBranch, Signal, reads_branches, reads_comments, reads_delta_snapshot, reads_design_review, reads_signals, }; use crate::replica::{Mode, Replica, create_change}; use crate::{Error, Limits, diff, docprops, same_secret}; @@ -126,6 +126,9 @@ pub struct Server { /// resuming client other bytes under a key it holds): every resuming client catches up with /// the snapshot, not the log. resync: bool, + /// Cached compressed [`CatchUp::DeltaSnapshot`] for `self.seq`, so repeated joins of large + /// files pay ~0 ms server CPU while no edit has arrived (#1819). + delta_cache: Option<(u64, Vec)>, } /// The most client ids a session remembers for reconnecting (the oldest disconnected ones go @@ -188,6 +191,7 @@ impl Server { design_review: BTreeSet::new(), spotlight: None, resync: false, + delta_cache: None, } } @@ -417,10 +421,18 @@ 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 reads_delta = reads_delta_snapshot(&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()) } + // Only send the cached delta snapshot to peers that also read `design-review`, since + // the compressed payload carries the document's review config without per-peer filtering. + // If delta encoding ever fails, fall back to the legacy snapshot instead of refusing join. + _ if reads_delta && reads_design_review => match self.cached_delta_snapshot() { + Ok(bytes) => CatchUp::DeltaSnapshot(bytes), + Err(_) => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?), + }, _ => 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 @@ -686,9 +698,27 @@ impl Server { } self.state = next; self.seq += 1; + self.delta_cache = None; Ok(()) } + /// Return the cached compressed delta snapshot for `self.seq`, building it once on cache miss. + /// Snapshots larger than 16 MiB compressed (e.g. files with large embedded images) are still + /// sent, but are not pinned in `self.delta_cache` so room memory stays bounded. + fn cached_delta_snapshot(&mut self) -> Result, Error> { + const MAX_DELTA_CACHE_BYTES: usize = 16 << 20; + if let Some((seq, bytes)) = &self.delta_cache + && *seq == self.seq + { + return Ok(bytes.clone()); + } + let bytes = crate::delta_snapshot::encode_delta_snapshot(&self.state)?; + if bytes.len() <= MAX_DELTA_CACHE_BYTES { + self.delta_cache = Some((self.seq, bytes.clone())); + } + Ok(bytes) + } + /// The document-level entries (styles, variables, collections, comments) a batch adds or /// removes, each with whether it is there afterwards. A new one is refused when its id lies in /// the space of another client this session gave an id to, or in a space at or above diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs index 8979cb213..758c075b3 100644 --- a/crates/collab/src/server_tests.rs +++ b/crates/collab/src/server_tests.rs @@ -417,15 +417,15 @@ fn a_review_edit_reaches_only_the_peers_that_read_it() { 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. + // A capable newcomer's catch-up (a fresh join, so a delta snapshot) carries the settings. let (_, out) = s.join(hello("tok")).unwrap(); - let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) = + let Some(Outgoing::To(_, welcome @ ServerMsg::Welcome { .. })) = 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:?}"); + let joined = Client::join(welcome).unwrap(); + assert!(!joined.document().design_review.is_default(), "capable newcomer carries design review settings"); // 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(); diff --git a/crates/collab/src/sim.rs b/crates/collab/src/sim.rs index d6129b10a..d539ace27 100644 --- a/crates/collab/src/sim.rs +++ b/crates/collab/src/sim.rs @@ -291,7 +291,9 @@ impl Sim { let ClientMsg::Hello(hello) = hello else { return Err(Error::Protocol("hello".into())) }; let seen = self.clients.get(i).map_or(0, Client::seq); let (id, out) = self.server.join(hello).map_err(|m| Error::Protocol(format!("{m:?}")))?; - if out.iter().any(|o| matches!(o, Outgoing::To(to, ServerMsg::Welcome { catch_up: crate::CatchUp::Snapshot(_), .. }) if *to == id)) { + if out.iter().any(|o| { + matches!(o, Outgoing::To(to, ServerMsg::Welcome { catch_up: crate::CatchUp::Snapshot(_) | crate::CatchUp::DeltaSnapshot(_), .. }) if *to == id) + }) { self.snapshots += 1; if let Some(g) = self.gaps.get_mut(i) { g.push((seen, self.server.seq())); diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 73afaad14..2cc15c005 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -288,7 +288,7 @@ Server → client: | Message | Meaning | |---|---| -| `Welcome {session, client_id, seq, catch_up: Snapshot, Delta or Packed, processed, peers, access}` | Join accepted: the full document, or for a reconnecting client the batches it missed; `Packed` is the full document compressed (deflate of the snapshot's postcard bytes), sent only to clients whose hello announced `packed`, which read it back within the size an uncompressed welcome could have had; what the server did with that client's batches (`processed {last_batch, refused}`); `access` is `edit`, `view` (a view link: every batch is refused) or `comment` (a comment link: a batch is refused unless every change in it is to comment threads: a thread's `put` or `remove`, their order or the whole list). | +| `Welcome {session, client_id, seq, catch_up: Snapshot, Delta, Packed or DeltaSnapshot, processed, peers, access}` | Join accepted: the full document, or for a reconnecting client the batches it missed; `Packed` is the full document compressed (deflate of the snapshot's postcard bytes), sent only to clients whose hello announced `packed`, which read it back within the size an uncompressed welcome could have had; `DeltaSnapshot` is a direct compressed mirror-delta and deduplicated-vector snapshot (`FCDS` header + version byte + exact inflated length + deflate), sent only to clients whose hello announced `delta-snapshot` (and `design-review`), enforcing inflated-byte, node-count and materialized-memory budgets during streaming decode; what the server did with that client's batches (`processed {last_batch, refused}`); `access` is `edit`, `view` (a view link: every batch is refused) or `comment` (a comment link: a batch is refused unless every change in it is to comment threads: a thread's `put` or `remove`, their order or the whole list). | | `Changes {seq, author, batch_id, changes}` | Accepted changes, in order, to everyone (the author gets its own back as confirmation). | | `Reject {batch_id, reason, fixes: [Change]}` | A batch (or part of it) was invalid: the current values to roll back to. | | `Presence {client_id, …}` / `PeerJoined` / `PeerLeft` | Other people's cursors, selections and arrivals. | @@ -958,10 +958,13 @@ Decisions, as built: 10 000, `max_log_changes`, default 1 000 000, and `max_log_bytes`, default 64 MiB, which a desktop host uses as they are and `figcraft-server` takes from its `max_log_mb`). If every batch after the client's sequence number is still in it, the welcome carries them (`CatchUp::Delta`); - otherwise the whole document (`CatchUp::Snapshot`), compressed for a client whose hello - announced `packed` (`CatchUp::Packed`, `message::pack` / `unpack`: deflate at its fastest level - on the hub's thread; a document's changes shrink about sevenfold, e.g. 397 KB to 53 KB for 4 040 - layers). Older clients, and servers from before, keep the uncompressed snapshot. + otherwise the whole document: `CatchUp::DeltaSnapshot` for clients whose hello announced + `delta-snapshot` and `design-review` (Kahn `(parent, source)` topological order, exact + value-checked mirror deltas, deduplicated `VectorNetwork` table, cached per `seq` on the server + up to 16 MiB compressed; breaking `FieldDelta` additions bump the version/capability word), + `CatchUp::Packed` (`message::pack` / `unpack`: deflate at its fastest level on the hub's thread) + for older clients that announced `packed`, and uncompressed `CatchUp::Snapshot` for the oldest + clients. - **What happened to the batches in flight.** The server remembers per client the last batch id it processed and the latest refused ids (at most 1 024). Batches up to that id that the catch-up doesn't confirm were refused (the user is told); the others are sent again, in order, keeping