From fceb606314c4cecd01dd8bf35efb424c43715d79 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 23:55:45 -0500 Subject: [PATCH 01/12] M8: Zoom to selection leaves Figma's 40 pt margin and clears the bottom toolbar Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all sides, centred in that area (measured in Figma's web app, 2026-11-09). ViewState gains an unsaved bottom_inset, set by the UI each frame from the toolbar pill and by view.set bottomInset. Zoom to fit is unchanged. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove and briefed; Sonnet 5.5 measured and wrote at medium --- crates/engine/src/cmd/view.rs | 39 +++++++++++------- crates/engine/src/view_behaviour_tests.rs | 50 ++++++++++++++++++++++- crates/engine/src/view_state.rs | 23 +++++++++++ crates/ui-egui/src/app.rs | 6 +++ crates/ui-egui/src/shortcuts_tests.rs | 5 ++- docs/ui-parity.md | 5 ++- 6 files changed, 108 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index c33878066..d620e9129 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -259,25 +259,34 @@ pub fn specs() -> Vec { spec!("view.zoomSelection", "Zoom to selection", "{}", false, |s, _| { let ds = s.ds_mut()?; if let Some(b) = ds.doc.bounds_of(&ds.selection) { - ds.view.fit(b, 256.0); + ds.view.fit_selection(b, 256.0); } Ok(json!({"zoom": ds.view.zoom})) }), - spec!("view.set", "Set view", "{zoom?, cx?, cy? (page coordinate at the centre), vw?, vh? (viewport size)}", false, |s, p| { - let v = view(s)?; - if let Some(z) = num(p, "zoom") { - v.zoom = z.clamp(ViewState::MIN_ZOOM, ViewState::MAX_ZOOM); + spec!( + "view.set", + "Set view", + "{zoom?, cx?, cy? (page coordinate at the centre), vw?, vh? (viewport size), bottomInset? (height of the strip the bottom toolbar covers)}", + false, + |s, p| { + let v = view(s)?; + if let Some(z) = num(p, "zoom") { + v.zoom = z.clamp(ViewState::MIN_ZOOM, ViewState::MAX_ZOOM); + } + v.cx = num_or(p, "cx", v.cx); + v.cy = num_or(p, "cy", v.cy); + if let Some(w) = num(p, "vw") { + v.vw = w.clamp(10.0, 20000.0); + } + if let Some(h) = num(p, "vh") { + v.vh = h.clamp(10.0, 20000.0); + } + if let Some(i) = num(p, "bottomInset") { + v.bottom_inset = i.clamp(0.0, 20000.0); + } + Ok(serde_json::to_value(&*v).unwrap_or(Value::Null)) } - v.cx = num_or(p, "cx", v.cx); - v.cy = num_or(p, "cy", v.cy); - if let Some(w) = num(p, "vw") { - v.vw = w.clamp(10.0, 20000.0); - } - if let Some(h) = num(p, "vh") { - v.vh = h.clamp(10.0, 20000.0); - } - Ok(serde_json::to_value(&*v).unwrap_or(Value::Null)) - }), + ), spec!( "view.zoomAt", "Zoom tool", diff --git a/crates/engine/src/view_behaviour_tests.rs b/crates/engine/src/view_behaviour_tests.rs index 7f9e5a844..974c9f44f 100644 --- a/crates/engine/src/view_behaviour_tests.rs +++ b/crates/engine/src/view_behaviour_tests.rs @@ -131,7 +131,7 @@ fn zoom_to_fit_selection_and_frames() { // (command, selection before, zoom, centre, selection after, derivation) let rows: Vec<(&str, Vec, f64, (f64, f64), Vec, &str)> = vec![ ("view.zoomFit", vec![], fit(content), (470.0, 300.0), vec![], "Shift+1 fits everything on the page into the view"), - ("view.zoomSelection", vec![r], fit(Rect::new(0.0, 0.0, 40.0, 40.0)), (920.0, 20.0), vec![r], "Shift+2 zooms to the selection"), + ("view.zoomSelection", vec![r], (800.0 - 80.0) / 40.0, (920.0, 20.0), vec![r], "Shift+2 zooms to the selection, with a 40-point margin"), ( "view.nextFrame", vec![], @@ -225,7 +225,7 @@ fn view_shortcuts_follow_the_documented_keys() { (Platform::Other, "-", m(true, false, false, false), "view.zoomOut", "Shift and - zooms out"), (Platform::Mac, "0", m(true, false, false, false), "view.zoom100", "Shift+0 zooms to 100%"), (Platform::Other, "1", m(true, false, false, false), "view.zoomFit", "Shift+1 zooms to fit"), - (Platform::Mac, "2", m(true, false, false, false), "view.zoomSelection", "Shift+2 zooms to the selection"), + (Platform::Mac, "2", m(true, false, false, false), "view.zoomSelection", "Shift+2 zooms to the selection, with a 40-point margin"), (Platform::Mac, "N", m(false, false, false, false), "view.nextFrame", "N zooms to the next frame"), (Platform::Other, "N", m(true, false, false, false), "view.prevFrame", "Shift+N zooms to the previous frame"), (Platform::Mac, "R", m(true, false, false, false), "view.rulers", "Shift+R shows and hides the rulers"), @@ -771,3 +771,49 @@ fn view_toggles_are_kept_for_the_next_launch() { } assert!(!view.outlines && !view.outlines_selection && !view.proof_srgb, "{view:?}"); } + +/// Select a fresh rectangle at the origin, set the view and run `cmd`; the rect's screen box is +/// returned as (left, top, right, bottom). +fn zoom_on(cmd: &str, inset: f64, w: f64, h: f64) -> (ViewState, (f64, f64, f64, f64)) { + let mut s = Session::new(); + let r = rect(&mut s, 0.0, 0.0, w, h, None); + ex(&mut s, "view.set", json!({"vw": 1389, "vh": 903, "bottomInset": inset})); + ex(&mut s, "select.set", json!({"ids": [r]})); + ex(&mut s, cmd, json!({})); + let v = view(&s); + let (l, t) = v.page_to_screen(0.0, 0.0); + let (rr, b) = v.page_to_screen(w, h); + (v, (l, t, rr, b)) +} + +#[test] +fn zoom_to_selection_leaves_forty_points_and_clears_the_toolbar() { + // Measured in Figma's web app, 2026-11-09: 40 points on every side of the canvas above the toolbar. + let (v, (l, t, r, b)) = zoom_on("view.zoomSelection", 58.0, 100.0, 100.0); + assert!((v.zoom - 7.65).abs() < 0.01, "{}", v.zoom); + assert!((t - 40.0).abs() < 0.5 && (b - (845.0 - 40.0)).abs() < 0.5, "top {t}, bottom {b}"); + assert!((l - (1389.0 - r)).abs() < 0.5, "left {l}, right {r}"); +} + +#[test] +fn zoom_to_selection_on_a_wide_layer_is_limited_by_the_width() { + let (v, (l, _, r, _)) = zoom_on("view.zoomSelection", 58.0, 1000.0, 200.0); + assert!((v.zoom - (1389.0 - 80.0) / 1000.0).abs() < 0.001, "{}", v.zoom); + assert!((l - 40.0).abs() < 0.5 && ((1389.0 - r) - 40.0).abs() < 0.5, "left {l}, right {r}"); +} + +#[test] +fn zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height() { + let (v, _) = zoom_on("view.zoomSelection", 0.0, 100.0, 100.0); + assert!((v.zoom - (903.0 - 80.0) / 100.0).abs() < 1e-6, "{}", v.zoom); +} + +#[test] +fn zoom_to_fit_is_unchanged() { + // Left alone on purpose: its 64-point margin is not measured against Figma yet. + let mut s = Session::new(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0, None); + ex(&mut s, "view.set", json!({"vw": 1389, "vh": 903, "bottomInset": 58})); + ex(&mut s, "view.zoomFit", json!({})); + assert!((view(&s).zoom - (903.0 - 128.0) / 100.0).abs() < 1e-6); +} diff --git a/crates/engine/src/view_state.rs b/crates/engine/src/view_state.rs index fd70b4b11..bfbb36f66 100644 --- a/crates/engine/src/view_state.rs +++ b/crates/engine/src/view_state.rs @@ -12,6 +12,10 @@ pub struct ViewState { /// Viewport size in logical pixels (set by the UI; used by zoom-to-fit). pub vw: f64, pub vh: f64, + /// Height in screen points of the strip the floating bottom toolbar covers (from its top edge to + /// the canvas's bottom edge); set by the UI every frame, 0 when it's hidden. Never saved. + #[serde(skip)] + pub bottom_inset: f64, pub pixel_grid: bool, pub layout_grids: bool, pub rulers: bool, @@ -51,6 +55,7 @@ impl Default for ViewState { zoom: 1.0, vw: 1200.0, vh: 800.0, + bottom_inset: 0.0, pixel_grid: true, layout_grids: true, rulers: false, @@ -105,6 +110,24 @@ impl ViewState { self.cx = r.center().x; self.cy = r.center().y; } + /// Fit a page rectangle for Zoom to selection: a 40 point margin on all four sides of the area + /// above the bottom toolbar (`vw` by `vh - bottom_inset`), centred in that area. + pub fn fit_selection(&mut self, r: figcraft_geom::Rect, max_zoom: f64) { + if !(r.width() > 0.0 || r.height() > 0.0) || !r.x0.is_finite() { + self.cx = r.center().x; + self.cy = r.center().y; + return; + } + let margin = 40.0; + let inset = if self.bottom_inset.is_finite() { self.bottom_inset.clamp(0.0, (self.vh - 100.0).max(0.0)) } else { 0.0 }; + let area_h = self.vh - inset; + let zx = (self.vw - margin * 2.0).max(50.0) / r.width().max(1e-6); + let zy = (area_h - margin * 2.0).max(50.0) / r.height().max(1e-6); + self.zoom = zx.min(zy).clamp(Self::MIN_ZOOM, max_zoom); + // The rect's centre lands at screen y = area_h / 2, the page centre `(vh - area_h) / 2` below it. + self.cx = r.center().x; + self.cy = r.center().y + (self.vh - area_h) / 2.0 / self.zoom; + } /// The zoom from which the pixel grid shows (400%). pub const PIXEL_GRID_ZOOM: f64 = 4.0; /// Whether the pixel grid draws: it's on and the canvas is zoomed in to 400% or more. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 1290f4d5b..f2e85e194 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -371,6 +371,12 @@ impl FigApp { let worker = self.worker.take(); let mut worker = worker.unwrap_or_else(|| render_worker::Worker::new(ctx.clone())); canvas::show(self, ui, &mut worker); + // The strip the floating bottom toolbar covers, for Zoom to selection (0 when it's hidden). + let inset = + if !hidden && mobile.is_none() { f64::from(self.canvas.rect.max.y - toolbar::pill_rect(self.canvas.rect, 0.0).min.y) } else { 0.0 }; + if let Ok(ds) = self.session.ds_mut() { + ds.view.bottom_inset = inset; + } self.worker = Some(worker); if !hidden && mobile.is_none() { ui.scope_builder(egui::UiBuilder::new().id_salt("toolbar"), |ui| { diff --git a/crates/ui-egui/src/shortcuts_tests.rs b/crates/ui-egui/src/shortcuts_tests.rs index 4b223b211..e9c822c2b 100644 --- a/crates/ui-egui/src/shortcuts_tests.rs +++ b/crates/ui-egui/src/shortcuts_tests.rs @@ -90,7 +90,10 @@ fn shift_digits_zoom() { press(&mut u, Key::Num2, Modifiers::SHIFT); assert!(zoom(&u) > fit, "Shift+2 fits the smaller selection"); let v = &u.app.session.ds().unwrap().view; - assert_eq!((v.cx, v.cy), (110.0, 40.0), "centred on it"); + // Centred in the canvas above the bottom toolbar: the page centre sits half the toolbar's strip lower. + let expect_cy = 40.0 + v.bottom_inset / 2.0 / v.zoom; + assert_eq!(v.cx, 110.0, "centred on it"); + assert!((v.cy - expect_cy).abs() < 1e-9, "centred above the toolbar: {} vs {expect_cy}", v.cy); // `+` and `-` step the zoom. let z = zoom(&u); press(&mut u, Key::Minus, Modifiers::NONE); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index aa0ef25bd..0674a3359 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; 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: @@ -109,7 +109,7 @@ interaction feel not yet compared. | Item | Status | Notes | |---|---|---| -| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`) | +| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`); Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all four sides, centred in that area, at a continuous zoom (measured in Figma's web app, 2026-11-09; `zoom_to_selection_leaves_forty_points_and_clears_the_toolbar`, `zoom_to_selection_on_a_wide_layer_is_limited_by_the_width`, `zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height`); Zoom to fit (Shift+1) keeps its 64 pt margin, margin not measured yet (`zoom_to_fit_is_unchanged`) | | Rulers and guides (drag out, move, remove; rotated frames; frame guides) | done | guides belong to the page or a top-level frame (a frame moved into another keeps its guides but they stop applying); a click selects one for Delete, the arrows or the context menu's Remove guide; Alt-drag drops a copy; Alt while dragging measures to the layers in the frame it crosses; ruler numbering checked by eye only | | Frame labels (rotated, right-to-left), size badge | done | | | Outline mode | done | Outlines, outlines for the selection, mask outlines, frame outlines; shapes are clicked on their outlines, reaching layers behind; View ▸ Outlines ▸ Include hidden layers (`view.outlinesHiddenLayers`) outlines hidden layers too and Include object bounds (`view.outlinesObjectBounds`) draws the box of every layer whose outline isn't its box (groups, text, ellipses, vectors); what either draws can be clicked there (a hidden layer on its outline, a group on its box) and nothing else can; both are view settings like the other outline flags (per file, off in a new one, checked in the menu); the lines are light on a dark page (`outline_options_tests`). The main menu now shows a check mark beside every View toggle that is on | @@ -187,6 +187,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | Zoom to selection: the selection is fitted with a 40 pt margin into the canvas above the floating bottom toolbar (`ViewState::bottom_inset`, set by the UI each frame, never saved; `view.set` takes `bottomInset`) and centred in that area, as measured in Figma's web app on 2026-11-09. Zoom to fit is unchanged (margin not measured yet). Numbers unchanged. | | 2026-11-02 | patch | Shortcuts: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides, in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. A documented gesture row: 134 documented, 133 bound. Test: `padding_individual_tests` | | 2026-11-01 | patch | Number fields: dragging the field itself with Alt held scrubs it ("You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option Windows: Alt", Adjust alignment, rotation, position, and dimensions), with the resize cursor and the label's rates (Alt is the enabler there, so it isn't the fine rate); a click with Alt doesn't open the editor. Found by a documentation audit of the ui-parity rows. Test: `field_tests::alt_held_over_a_field_scrubs_it`. Counts unchanged | | 2026-11-02 | patch | M6, #1839: with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it by the nudge amounts (`tool.crosshair`), Enter places the object there (`tool.place`), Escape or a tool change takes it away; the canvas draws the crosshair and `ui.inspect` reports it (`tool.crosshair`), the Keyboard shortcuts panel lists the gesture ("Use the arrow keys to activate the crosshair cursor...", Accessibility at Figma). The board Shapes tool places on it too (its 160 px shape centred, as the tool centres a press), and the view pans by the overshoot when the crosshair is nudged past its edge. Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | From 5d529269ceaeeb8c5f7cc13a063508fab66ee8e5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 00:33:53 -0500 Subject: [PATCH 02/12] M8: Zoom to selection in a short canvas keeps the selection above the toolbar (#2139 review) The inset was clamped to leave 100 points and the fit kept at least 50, so in a canvas 130 points high the selection ended behind the toolbar. The real inset is kept and the margin shrinks to a quarter of the area when 40 points a side does not fit. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/engine/src/view_behaviour_tests.rs | 16 ++++++++++++++++ crates/engine/src/view_state.rs | 13 ++++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/view_behaviour_tests.rs b/crates/engine/src/view_behaviour_tests.rs index 974c9f44f..9c77314e0 100644 --- a/crates/engine/src/view_behaviour_tests.rs +++ b/crates/engine/src/view_behaviour_tests.rs @@ -808,6 +808,22 @@ fn zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height() { assert!((v.zoom - (903.0 - 80.0) / 100.0).abs() < 1e-6, "{}", v.zoom); } +#[test] +fn zoom_to_selection_in_a_short_canvas_still_ends_above_the_toolbar() { + // A canvas 130 points high with the 60-point toolbar strip leaves 70 above it: too short for + // 40 points a side, so the margin shrinks and the selection stays clear of the toolbar. + let mut s = Session::new(); + let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0, None); + ex(&mut s, "view.set", json!({"vw": 1389, "vh": 130, "bottomInset": 60})); + ex(&mut s, "select.set", json!({"ids": [r]})); + ex(&mut s, "view.zoomSelection", json!({})); + let v = view(&s); + let (_, top) = v.page_to_screen(0.0, 0.0); + let (_, bottom) = v.page_to_screen(100.0, 100.0); + assert!(top >= 0.0 && bottom <= 70.0 + 1e-6, "top {top}, bottom {bottom}"); + assert!((top - (70.0 - bottom)).abs() < 1e-6, "centred above the toolbar: top {top}, bottom {bottom}"); +} + #[test] fn zoom_to_fit_is_unchanged() { // Left alone on purpose: its 64-point margin is not measured against Figma yet. diff --git a/crates/engine/src/view_state.rs b/crates/engine/src/view_state.rs index bfbb36f66..212bb93b4 100644 --- a/crates/engine/src/view_state.rs +++ b/crates/engine/src/view_state.rs @@ -118,11 +118,14 @@ impl ViewState { self.cy = r.center().y; return; } - let margin = 40.0; - let inset = if self.bottom_inset.is_finite() { self.bottom_inset.clamp(0.0, (self.vh - 100.0).max(0.0)) } else { 0.0 }; - let area_h = self.vh - inset; - let zx = (self.vw - margin * 2.0).max(50.0) / r.width().max(1e-6); - let zy = (area_h - margin * 2.0).max(50.0) / r.height().max(1e-6); + let inset = if self.bottom_inset.is_finite() { self.bottom_inset.clamp(0.0, (self.vh - 1.0).max(0.0)) } else { 0.0 }; + let area_h = (self.vh - inset).max(1.0); + // 40 points as measured; a canvas too small for that keeps a quarter of its size on each + // side instead, so the selection still ends above the toolbar. + let mx = (self.vw / 4.0).clamp(0.0, 40.0); + let my = (area_h / 4.0).clamp(0.0, 40.0); + let zx = (self.vw - mx * 2.0).max(1.0) / r.width().max(1e-6); + let zy = (area_h - my * 2.0).max(1.0) / r.height().max(1e-6); self.zoom = zx.min(zy).clamp(Self::MIN_ZOOM, max_zoom); // The rect's centre lands at screen y = area_h / 2, the page centre `(vh - area_h) / 2` below it. self.cx = r.center().x; From 53bf0a40d9a5bbe6c9b8aef9c19454dfbb201bfa Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 15:09:23 -0500 Subject: [PATCH 03/12] M8: Zoom to selection centres a point above the toolbar and ignores non-finite rectangles; tests pin the margins (#2139 review) fit_selection checks every coordinate is finite (a NaN y or x1 left a NaN centre) and leaves the view as it is for such a rectangle. A point selection is centred in the area above the toolbar at its zoom, not in the whole viewport. Tests pin the exact short-canvas and no-inset positions, the narrow-canvas margins, lines, tiny and huge rectangles, the bottomInset clamp and that it is never saved, the unchanged Zoom to fit centre, the pill strip the app hands the engine (shown and hidden), and the Shift+2 centre without reading the inset back. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 triaged and briefed; Sonnet 5.5 verified and wrote at medium --- crates/engine/src/view_behaviour_tests.rs | 88 ++++++++++++++++++++++- crates/engine/src/view_state.rs | 11 ++- crates/ui-egui/src/shortcuts_tests.rs | 19 ++++- 3 files changed, 113 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/view_behaviour_tests.rs b/crates/engine/src/view_behaviour_tests.rs index 9c77314e0..c470afe18 100644 --- a/crates/engine/src/view_behaviour_tests.rs +++ b/crates/engine/src/view_behaviour_tests.rs @@ -806,6 +806,9 @@ fn zoom_to_selection_on_a_wide_layer_is_limited_by_the_width() { fn zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height() { let (v, _) = zoom_on("view.zoomSelection", 0.0, 100.0, 100.0); assert!((v.zoom - (903.0 - 80.0) / 100.0).abs() < 1e-6, "{}", v.zoom); + let (_, top) = v.page_to_screen(0.0, 0.0); + let (_, bottom) = v.page_to_screen(100.0, 100.0); + assert!((top - 40.0).abs() < 1e-6 && (bottom - 863.0).abs() < 1e-6, "top {top}, bottom {bottom}"); } #[test] @@ -822,6 +825,86 @@ fn zoom_to_selection_in_a_short_canvas_still_ends_above_the_toolbar() { let (_, bottom) = v.page_to_screen(100.0, 100.0); assert!(top >= 0.0 && bottom <= 70.0 + 1e-6, "top {top}, bottom {bottom}"); assert!((top - (70.0 - bottom)).abs() < 1e-6, "centred above the toolbar: top {top}, bottom {bottom}"); + // The margin shrinks to a quarter of the 70 points (17.5) and the zoom is the exact fit, not the floor. + assert!((v.zoom - 0.35).abs() < 1e-9, "{}", v.zoom); + assert!((top - 17.5).abs() < 1e-6 && (bottom - 52.5).abs() < 1e-6, "top {top}, bottom {bottom}"); +} + +/// A canvas narrower than 160 points keeps a quarter of its width on each side. +#[test] +fn zoom_to_selection_in_a_narrow_canvas_shrinks_the_side_margins() { + let mut s = Session::new(); + let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0, None); + ex(&mut s, "view.set", json!({"vw": 100, "vh": 903, "bottomInset": 0})); + ex(&mut s, "select.set", json!({"ids": [r]})); + ex(&mut s, "view.zoomSelection", json!({})); + let v = view(&s); + let (left, _) = v.page_to_screen(0.0, 0.0); + let (right, _) = v.page_to_screen(100.0, 100.0); + assert!((v.zoom - 0.5).abs() < 1e-9, "{}", v.zoom); + assert!((left - 25.0).abs() < 1e-6 && (right - 75.0).abs() < 1e-6, "left {left}, right {right}"); +} + +/// A view 1000 by 800 with a 100-point toolbar strip, for the edge cases of the fit. +fn strip_view() -> ViewState { + ViewState { vw: 1000.0, vh: 800.0, bottom_inset: 100.0, ..ViewState::default() } +} + +#[test] +fn fitting_a_selection_survives_points_lines_extremes_and_junk() { + // A point: the zoom stays, and it lands in the middle of the area above the toolbar (y = 350). + let mut v = strip_view(); + v.zoom = 2.0; + v.fit_selection(Rect::new(10.0, 20.0, 10.0, 20.0), 32.0); + assert_eq!(v.zoom, 2.0); + let (x, y) = v.page_to_screen(10.0, 20.0); + assert!((x - 500.0).abs() < 1e-9 && (y - 350.0).abs() < 1e-9, "{x}, {y}"); + // A zero-width line is limited by its height, a zero-height one by its width. + let mut v = strip_view(); + v.fit_selection(Rect::new(0.0, 0.0, 0.0, 100.0), 32.0); + assert!((v.zoom - (700.0 - 80.0) / 100.0).abs() < 1e-9, "{}", v.zoom); + let mut v = strip_view(); + v.fit_selection(Rect::new(0.0, 0.0, 100.0, 0.0), 32.0); + assert!((v.zoom - (1000.0 - 80.0) / 100.0).abs() < 1e-9, "{}", v.zoom); + // A tiny one stops at the maximum zoom, a huge one at the minimum. + let mut v = strip_view(); + v.fit_selection(Rect::new(0.0, 0.0, 0.001, 0.001), 32.0); + assert_eq!(v.zoom, 32.0); + v.fit_selection(Rect::new(0.0, 0.0, 1e12, 1e12), 32.0); + assert_eq!(v.zoom, ViewState::MIN_ZOOM); + // A rectangle with any coordinate that is not a finite number changes nothing. + for bad in [ + Rect::new(0.0, f64::NAN, 10.0, 10.0), + Rect::new(0.0, 0.0, f64::INFINITY, 10.0), + Rect::new(0.0, 0.0, 10.0, f64::NAN), + Rect::new(f64::NAN, 0.0, 10.0, 10.0), + ] { + let mut v = strip_view(); + let before = (v.zoom, v.cx, v.cy); + v.fit_selection(bad, 32.0); + assert_eq!((v.zoom, v.cx, v.cy), before, "{bad:?}"); + } +} + +#[test] +fn the_bottom_inset_is_clamped_and_never_saved() { + let mut s = Session::new(); + ex(&mut s, "view.set", json!({"bottomInset": -5})); + assert_eq!(view(&s).bottom_inset, 0.0); + ex(&mut s, "view.set", json!({"bottomInset": 1e12})); + assert_eq!(view(&s).bottom_inset, 20000.0); + // Larger than the viewport: the fit still leaves a sliver of canvas and a finite centre. + ex(&mut s, "view.set", json!({"vw": 400, "vh": 300, "bottomInset": 5000})); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0, None); + ex(&mut s, "select.set", json!({"ids": [r]})); + ex(&mut s, "view.zoomSelection", json!({})); + let v = view(&s); + assert!(v.zoom.is_finite() && v.cx.is_finite() && v.cy.is_finite(), "{v:?}"); + // It is not part of what the view saves. + let saved = serde_json::to_string(&v).unwrap(); + assert!(!saved.to_lowercase().contains("inset"), "{saved}"); + let back: ViewState = serde_json::from_str(&saved).unwrap(); + assert_eq!(back.bottom_inset, 0.0); } #[test] @@ -831,5 +914,8 @@ fn zoom_to_fit_is_unchanged() { rect(&mut s, 0.0, 0.0, 100.0, 100.0, None); ex(&mut s, "view.set", json!({"vw": 1389, "vh": 903, "bottomInset": 58})); ex(&mut s, "view.zoomFit", json!({})); - assert!((view(&s).zoom - (903.0 - 128.0) / 100.0).abs() < 1e-6); + let v = view(&s); + assert!((v.zoom - (903.0 - 128.0) / 100.0).abs() < 1e-6); + // No toolbar offset: the rectangle's own centre stays in the middle of the whole viewport. + assert_eq!((v.cx, v.cy), (50.0, 50.0)); } diff --git a/crates/engine/src/view_state.rs b/crates/engine/src/view_state.rs index 212bb93b4..8a8cc8a01 100644 --- a/crates/engine/src/view_state.rs +++ b/crates/engine/src/view_state.rs @@ -113,13 +113,18 @@ impl ViewState { /// Fit a page rectangle for Zoom to selection: a 40 point margin on all four sides of the area /// above the bottom toolbar (`vw` by `vh - bottom_inset`), centred in that area. pub fn fit_selection(&mut self, r: figcraft_geom::Rect, max_zoom: f64) { - if !(r.width() > 0.0 || r.height() > 0.0) || !r.x0.is_finite() { - self.cx = r.center().x; - self.cy = r.center().y; + // A rectangle that isn't all finite numbers leaves the view as it is. + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { return; } let inset = if self.bottom_inset.is_finite() { self.bottom_inset.clamp(0.0, (self.vh - 1.0).max(0.0)) } else { 0.0 }; let area_h = (self.vh - inset).max(1.0); + // A point (nothing to fit) is centred in the area above the toolbar at the zoom it has. + if !(r.width() > 0.0 || r.height() > 0.0) { + self.cx = r.center().x; + self.cy = r.center().y + (self.vh - area_h) / 2.0 / self.zoom.max(1e-6); + return; + } // 40 points as measured; a canvas too small for that keeps a quarter of its size on each // side instead, so the selection still ends above the toolbar. let mx = (self.vw / 4.0).clamp(0.0, 40.0); diff --git a/crates/ui-egui/src/shortcuts_tests.rs b/crates/ui-egui/src/shortcuts_tests.rs index e9c822c2b..fea6f21cd 100644 --- a/crates/ui-egui/src/shortcuts_tests.rs +++ b/crates/ui-egui/src/shortcuts_tests.rs @@ -91,7 +91,11 @@ fn shift_digits_zoom() { assert!(zoom(&u) > fit, "Shift+2 fits the smaller selection"); let v = &u.app.session.ds().unwrap().view; // Centred in the canvas above the bottom toolbar: the page centre sits half the toolbar's strip lower. - let expect_cy = 40.0 + v.bottom_inset / 2.0 / v.zoom; + // The strip is the canvas's bottom edge less the pill's top, worked out here, not read back. + let strip = f64::from(u.app.canvas.rect.max.y - crate::toolbar::pill_rect(u.app.canvas.rect, 0.0).min.y); + assert!(strip > 20.0 && strip < 200.0, "the pill is a toolbar's height: {strip}"); + assert!((v.bottom_inset - strip).abs() < 1e-3, "the app gives the engine the pill's strip: {} vs {strip}", v.bottom_inset); + let expect_cy = 40.0 + strip / 2.0 / v.zoom; assert_eq!(v.cx, 110.0, "centred on it"); assert!((v.cy - expect_cy).abs() < 1e-9, "centred above the toolbar: {} vs {expect_cy}", v.cy); // `+` and `-` step the zoom. @@ -204,3 +208,16 @@ fn shortcuts_panel_does_not_show_on_the_home_screen() { u.frame(vec![]); assert!(!u.app.ui.shortcuts_panel, "the panel closes on the home screen"); } + +/// The strip the bottom toolbar covers is given to the engine while the toolbar shows and is zero +/// when the interface is hidden. +#[test] +fn the_toolbar_strip_is_zero_when_the_interface_is_hidden() { + let (mut u, _, _) = setup(); + u.frame(vec![]); + u.frame(vec![]); + assert!(u.app.session.ds().unwrap().view.bottom_inset > 0.0, "shown"); + u.app.session.ds_mut().unwrap().view.ui_hidden = true; + u.frame(vec![]); + assert_eq!(u.app.session.ds().unwrap().view.bottom_inset, 0.0, "hidden"); +} From 100a6b7e6f42e5e7aeaf1329f29ee2fa8ffb979f Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 03:12:41 -0500 Subject: [PATCH 04/12] M9: .jam import: shapes with text come in as native board shapes (#1808) On a whiteboard, a FigJam shape with text whose generated records are complete becomes a native board shape for the 23 kinds FigCraft draws: an empty centred frame holding FigCraft's own outline (the file's paints, weight and dashes kept) and the text. The 7 kinds without an outline, and shapes with damaged records, keep the generated layers; the former warn with the kind's name. Stickies and shapes share one native-board hook in the layer mapper. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/format/src/fig/board_import_tests.rs | 139 +++++++++++++++++++- crates/format/src/fig/map.rs | 3 + crates/format/src/fig/map/board.rs | 118 +++++++++++++++++ crates/format/src/fig/map/layer.rs | 9 +- crates/ui-egui/locales/en.toml | 1 + docs/boards-parity.md | 5 +- docs/file-format-parity.md | 5 +- 7 files changed, 269 insertions(+), 11 deletions(-) diff --git a/crates/format/src/fig/board_import_tests.rs b/crates/format/src/fig/board_import_tests.rs index 89c6cba83..b1b1e30c7 100644 --- a/crates/format/src/fig/board_import_tests.rs +++ b/crates/format/src/fig/board_import_tests.rs @@ -9,7 +9,7 @@ fn board_schema() -> Schema { /// [`board_schema`] over another base schema. fn board_schema_of(base: &str) -> Schema { - Schema::parse(&base.replace( + Schema::parse(&base.replace("enum ShapeWithTextType SQUARE ELLIPSE", "enum ShapeWithTextType SQUARE ROUNDED_RECTANGLE ELLIPSE DIAMOND TRIANGLE_UP TRIANGLE_DOWN PARALLELOGRAM_RIGHT PARALLELOGRAM_LEFT TRAPEZOID PENTAGON HEXAGON OCTAGON STAR PLUS ARROW_LEFT ARROW_RIGHT CHEVRON SPEECH_BUBBLE ENG_DATABASE DOCUMENT_SINGLE PREDEFINED_PROCESS MANUAL_INPUT INTERNAL_STORAGE ENG_QUEUE ENG_FILE ENG_FOLDER SHIELD DOCUMENT_MULTIPLE SUMMING_JUNCTION OR").replace( "\nmessage Blob ", ", GeneratedData nodeGenerationData, GeneratedData derivedImmutableFrameData, string textAlignHorizontal, string textAlignVertical\nmessage GeneratedData NodeChange[] overrides, uint version\nmessage Blob ", )) @@ -549,3 +549,140 @@ fn a_fig_sticky_stays_a_design_frame() { assert!(frame.board.is_none()); assert_eq!(frame.children.len(), 3); } + +/// `board_node("SHAPE_WITH_TEXT")` of one FigJam kind. +fn shape_node(kind: &'static str) -> Kv<'static> { + let mut layer = board_node("SHAPE_WITH_TEXT"); + set(&mut layer, "shapeWithTextType", e(kind)); + layer +} + +/// On a whiteboard a diamond is a native shape: FigCraft draws its outline and its text sits inside. +#[test] +fn a_jam_diamond_is_a_native_shape_drawn_by_figcraft() { + let (doc, warnings) = jam(shape_node("DIAMOND")); + let frame = named(&doc, "Board object"); + assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Diamond })); + assert!(frame.fills.is_empty()); + assert_eq!((frame.width, frame.height), (240.0, 240.0)); + assert_eq!(frame.layout.as_ref().expect("shape auto layout").padding, [0.25 * 240.0; 4]); + assert_eq!(frame.children.len(), 2, "the outline and the text: {warnings:?}"); + let outline = doc.node(frame.children[0]).unwrap(); + let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) }; + assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(240.0, 240.0))); + assert_eq!(outline.fills[0].solid_color().unwrap().to_rgba8(), [255, 191, 64, 255]); + assert!(outline.child_layout.absolute); + assert_eq!(outline.constraints.horizontal, figcraft_doc::HConstraint::Scale); + assert_eq!(outline.constraints.vertical, figcraft_doc::VConstraint::Scale); + let label = doc.node(frame.children[1]).unwrap().kind.text().unwrap(); + assert_eq!(label.characters, "Olá\nIdea"); + assert_eq!(label.align_h, figcraft_doc::TextAlignH::Center); +} + +/// 23 of FigJam's 30 shape kinds have a FigCraft outline; the other 7 stay frames and say which. +#[test] +fn every_figjam_shape_kind_maps_or_stays_a_frame() { + let kinds = [ + "SQUARE", + "ROUNDED_RECTANGLE", + "ELLIPSE", + "DIAMOND", + "TRIANGLE_UP", + "TRIANGLE_DOWN", + "PARALLELOGRAM_RIGHT", + "PARALLELOGRAM_LEFT", + "TRAPEZOID", + "PENTAGON", + "HEXAGON", + "OCTAGON", + "STAR", + "PLUS", + "ARROW_LEFT", + "ARROW_RIGHT", + "CHEVRON", + "SPEECH_BUBBLE", + "ENG_DATABASE", + "DOCUMENT_SINGLE", + "PREDEFINED_PROCESS", + "MANUAL_INPUT", + "INTERNAL_STORAGE", + "ENG_QUEUE", + "ENG_FILE", + "ENG_FOLDER", + "SHIELD", + "DOCUMENT_MULTIPLE", + "SUMMING_JUNCTION", + "OR", + ]; + assert_eq!(kinds.len(), 30); + let mut mapped = 0; + for kind in kinds { + let table = super::map::board_shape(kind); + let (doc, warnings) = jam(shape_node(kind)); + let frame = named(&doc, "Board object"); + if let Some(shape) = table { + mapped += 1; + assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape }), "{kind}"); + } else { + assert!(frame.board.is_none(), "{kind}"); + assert!(warnings.iter().any(|w| w.contains(kind) && w.contains("no FigCraft outline")), "{kind}: {warnings:?}"); + } + } + assert_eq!(mapped, 23); +} + +/// A square keeps the paints and weight the file gave it, as read. +#[test] +fn a_square_keeps_its_paints_and_weight() { + let mut layer = shape_node("SQUARE"); + let background = + record(0, vec![("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)])), ("strokePaints", arr(vec![solid(0.5, 0.5, 0.5)])), ("strokeWeight", f(4.0))]); + set(&mut layer, "nodeGenerationData", o(vec![("overrides", arr(vec![background, record(1, text("Olá", 16.0))]))])); + let (doc, _) = jam(layer); + let frame = named(&doc, "Board object"); + assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Rectangle })); + let outline = doc.node(frame.children[0]).unwrap(); + assert_eq!(outline.fills[0].solid_color().unwrap().to_rgba8(), [255, 255, 255, 255]); + assert_eq!(outline.strokes[0].solid_color().unwrap().to_rgba8(), [128, 128, 128, 255]); + assert_eq!(outline.stroke.weight, 4.0); +} + +/// A shape record that isn't complete keeps today's generated layers and no board item. +#[test] +fn a_damaged_shape_record_keeps_the_generated_layers() { + let mut cases = Vec::new(); + let mut a = shape_node("DIAMOND"); + set(&mut a, "derivedImmutableFrameData", o(vec![("version", u(2))])); + cases.push(a); + let mut b = shape_node("DIAMOND"); + set(&mut b, "nodeGenerationData", o(vec![("overrides", arr(vec![record(1, text("Olá", 16.0))]))])); + cases.push(b); + let mut c = shape_node("DIAMOND"); + let background = record(0, vec![("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)]))]); + set(&mut c, "nodeGenerationData", o(vec![("overrides", arr(vec![background]))])); + cases.push(c); + for (i, layer) in cases.into_iter().enumerate() { + let (as_fig, fig_warnings) = imported(layer.clone()); + let (doc, warnings) = jam(layer); + let frame = named(&doc, "Board object"); + assert!(frame.board.is_none(), "case {i}"); + assert_eq!(frame.children.len(), named(&as_fig, "Board object").children.len(), "case {i}: the generated layers, as in a .fig"); + let sorted = |mut w: Vec| { + w.sort(); + w + }; + assert_eq!(sorted(warnings), sorted(fig_warnings), "case {i}: today's warnings"); + } +} + +/// A shape with no text yet is still a native shape (an empty one). +#[test] +fn a_jam_shape_without_text_is_still_a_native_shape() { + let mut layer = shape_node("SQUARE"); + let background = record(0, vec![("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)]))]); + set(&mut layer, "nodeGenerationData", o(vec![("overrides", arr(vec![background, record(1, text("", 16.0))]))])); + let (doc, _) = jam(layer); + let frame = named(&doc, "Board object"); + assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Rectangle })); + assert_eq!(doc.node(frame.children[1]).unwrap().kind.text().unwrap().characters, ""); +} diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index d150e5c63..5e4ab7e9d 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -28,6 +28,9 @@ mod proto; mod text; mod variables; +#[cfg(test)] +pub(super) use board::board_shape; + use component::OverrideScope; #[cfg(test)] use paint::paint; diff --git a/crates/format/src/fig/map/board.rs b/crates/format/src/fig/map/board.rs index 7dcf57cfe..5b885f060 100644 --- a/crates/format/src/fig/map/board.rs +++ b/crates/format/src/fig/map/board.rs @@ -5,6 +5,7 @@ use super::layer::{own_text, valid_size}; use super::paint::paint; use super::{Affine, Kv, MAX_DEPTH, Mapper, Obj, Value, View, generated_record, json, num}; +use figcraft_doc::BoardShape; impl<'a> Mapper<'a> { /// A sticky as a native board sticky: its frame (size, place, opacity and shadows as saved, @@ -86,3 +87,120 @@ impl<'a> Mapper<'a> { Some(kids) } } + +impl<'a> Mapper<'a> { + /// A sticky or shape with text as a native board item, or `None` with the note that it is + /// a frame with its generated layers. + pub(super) fn native_board_item(&mut self, own: &str, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option> { + let native = if own == "STICKY" { self.native_sticky(o, v, rest_id, depth) } else { self.native_shape(o, v, rest_id, depth) }; + if native.is_none() && own == "STICKY" { + self.warn("sticky layers import as frames with their text"); + } else if native.is_none() { + self.warn("shape with text layers import as frames with their text"); + } + native + } +} + +impl<'a> Mapper<'a> { + /// A shape with text as a native board shape: an empty frame holding FigCraft's own outline + /// (the file's paints and weight) and the text, centred. `None` (nothing changed) when the kind + /// has no FigCraft outline or a generated record is damaged: then the caller keeps the + /// generated layers. + pub(super) fn native_shape(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option> { + let kind = v.str("shapeWithTextType").unwrap_or("SQUARE"); + let Some(shape) = board_shape(kind) else { + self.warn(format!("shape with text kind {kind} has no FigCraft outline; kept as a frame")); + return None; + }; + if v.get("nodeGenerationData").is_none() || v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) { + return None; + } + let record = |id: u32| { + let (style, bounds) = (generated_record(v, "nodeGenerationData", id)?, generated_record(v, "derivedImmutableFrameData", id)?); + let view = View::of(style).with([(bounds, 1.0)]); + (valid_size(view.get("size")).is_some() && view.transform().is_some()).then_some(view) + }; + let background = record(0)?; + let body = record(1)?; + if depth >= MAX_DEPTH || self.count.saturating_add(2) > self.budget() { + return None; + } + let (w, h) = v.size().or_else(|| o.get("size").and_then(|s| Some((s.get("x")?.as_f64()?, s.get("y")?.as_f64()?))))?; + if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + return None; + } + // Everything is valid: build the outline from the record's paints, then the frame. + let mut outline = Obj::new(); + outline.insert("id".into(), json!(format!("{rest_id};generated0"))); + outline.insert("type".into(), json!("VECTOR")); + outline.insert("name".into(), json!("Outline")); + self.common(&mut outline, &background, "VECTOR", Affine::IDENTITY, None); + outline.insert("size".into(), json!({"x": w, "y": h})); + outline.insert("relativeTransform".into(), json!([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])); + outline.insert("vectorNetwork".into(), serde_json::to_value(figcraft_doc::VectorNetwork::from_path(&shape.path(w, h))).ok()?); + outline.insert("layoutPositioning".into(), json!("ABSOLUTE")); + outline.insert("constraints".into(), json!({"horizontal": "SCALE", "vertical": "SCALE"})); + outline.remove("cornerRadius"); + let mut label = Obj::new(); + label.insert("id".into(), json!(format!("{rest_id};generated1"))); + label.insert("type".into(), json!("TEXT")); + label.insert("name".into(), json!(own_text(&body).map_or_else(|| "Text".to_string(), |c| c.chars().take(40).collect()))); + self.common(&mut label, &body, "TEXT", Affine::IDENTITY, None); + self.text(&mut label, &body); + if let Some(Value::Object(style)) = label.get_mut("style") { + style.insert("textAutoResize".into(), json!("HEIGHT")); + style.insert("textAlignHorizontal".into(), json!("CENTER")); + } + label.insert("layoutSizingHorizontal".into(), json!("FILL")); + o.insert("fills".into(), json!([])); + o.insert("strokes".into(), json!([])); + o.insert("clipsContent".into(), json!(false)); + o.remove("cornerRadius"); + let [top, right, bottom, left] = shape.text_insets(); + for (k, val) in [ + ("layoutMode", json!("VERTICAL")), + ("primaryAxisAlignItems", json!("CENTER")), + ("counterAxisAlignItems", json!("CENTER")), + ("paddingTop", json!(top * h)), + ("paddingRight", json!(right * w)), + ("paddingBottom", json!(bottom * h)), + ("paddingLeft", json!(left * w)), + ] { + o.insert(k.into(), val); + } + self.count += 2; + o.insert("board".into(), json!({"type": "shape", "shape": shape.id()})); + Some(vec![Value::Object(outline), Value::Object(label)]) + } +} + +/// FigJam's `shapeWithTextType` as the outline FigCraft draws for it; `None` for the kinds it has none for. +pub(in crate::fig) fn board_shape(kind: &str) -> Option { + Some(match kind { + "SQUARE" => BoardShape::Rectangle, + "ROUNDED_RECTANGLE" => BoardShape::RoundedRectangle, + "ELLIPSE" => BoardShape::Ellipse, + "DIAMOND" => BoardShape::Diamond, + "TRIANGLE_UP" => BoardShape::Triangle, + "TRIANGLE_DOWN" => BoardShape::TriangleDown, + "PARALLELOGRAM_RIGHT" => BoardShape::ParallelogramRight, + "PARALLELOGRAM_LEFT" => BoardShape::ParallelogramLeft, + "TRAPEZOID" => BoardShape::Trapezoid, + "PENTAGON" => BoardShape::Pentagon, + "HEXAGON" => BoardShape::Hexagon, + "OCTAGON" => BoardShape::Octagon, + "STAR" => BoardShape::Star, + "PLUS" => BoardShape::Plus, + "ARROW_LEFT" => BoardShape::ArrowLeft, + "ARROW_RIGHT" => BoardShape::ArrowRight, + "CHEVRON" => BoardShape::Chevron, + "SPEECH_BUBBLE" => BoardShape::SpeechBubble, + "ENG_DATABASE" => BoardShape::Database, + "DOCUMENT_SINGLE" => BoardShape::Document, + "PREDEFINED_PROCESS" => BoardShape::PredefinedProcess, + "MANUAL_INPUT" => BoardShape::ManualInput, + "INTERNAL_STORAGE" => BoardShape::InternalStorage, + _ => return None, + }) +} diff --git a/crates/format/src/fig/map/layer.rs b/crates/format/src/fig/map/layer.rs index 869686537..f30279b0f 100644 --- a/crates/format/src/fig/map/layer.rs +++ b/crates/format/src/fig/map/layer.rs @@ -175,8 +175,8 @@ impl<'a> Mapper<'a> { let connector_label = own == "CONNECTOR" && !connector_snapshot && self.connector_label_fits(&view, depth); let ty = if connector_label { "FRAME" } else { Self::mapped_type(own, &view, connector_snapshot, connector_terminal, stand)? }; // A whiteboard's sticky says it imports as a frame only when it can't be a native one. - let native_sticky = self.board && own == "STICKY"; - if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH" && !native_sticky) { + let native_board = self.board && matches!(own, "STICKY" | "SHAPE_WITH_TEXT"); + if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH" && !native_board) { self.warn(format!("{} layers import as {what}", own.to_ascii_lowercase().replace('_', " "))); } if connector_snapshot { @@ -264,7 +264,7 @@ impl<'a> Mapper<'a> { }); kids.splice(0..0, connector_kids); if stand.is_some_and(|s| s.0 == "FRAME") { - let native = if native_sticky { self.native_sticky(&mut o, &view, &rest_id, depth) } else { None }; + let native = if native_board { self.native_board_item(own, &mut o, &view, &rest_id, depth) } else { None }; if let Some(native) = native { kids.splice(0..0, native); } else if let Some(snapshot) = self.board_snapshot(&mut o, &view, own, &rest_id, depth) { @@ -273,9 +273,6 @@ impl<'a> Mapper<'a> { kids.splice(0..0, self.shape_with_text(&mut o, &view, own, &rest_id)); kids.extend(self.inner_text(&o, &view, &rest_id, own == "STICKY")); } - if native_sticky && !o.contains_key("board") { - self.warn("sticky layers import as frames with their text"); - } } if !kids.is_empty() { o.insert("children".into(), Value::Array(kids)); diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 71e6ff010..b1d9fb928 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1891,6 +1891,7 @@ name = "English" "stale or invalid grid track sizing entries were ignored" = "stale or invalid grid track sizing entries were ignored" "stars and polygons without point counts or geometry use the default point count" = "stars and polygons without point counts or geometry use the default point count" "sticky layers import as frames with their text" = "sticky layers import as frames with their text" +"shape with text layers import as frames with their text" = "shape with text layers import as frames with their text" "style settings of some vector segments aren't supported; those segments use the layer's stroke" = "style settings of some vector segments aren't supported; those segments use the layer's stroke" "text path underline or strikethrough decoration is not rendered" = "text path underline or strikethrough decoration is not rendered" "text style overrides refer to missing table entries" = "text style overrides refer to missing table entries" diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 04cb832bc..9489e51a3 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) **Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that @@ -66,7 +66,7 @@ all end with the same geometry. | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | | Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots stay about a point and a half across on screen (1 to 3 points), scaled by the size setting. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none | -| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies come in as native stickies (their colour, text and author kept; size as saved), its shapes with text as frames with their generated layers and its connectors as vectors, not yet as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) | +| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies come in as native stickies (their colour, text and author kept; size as saved), its shapes with text as native shapes for the 23 kinds FigCraft draws (the file's paints and weight kept, the outline FigCraft's own; the 7 others stay frames with their generated layers) and its connectors as vectors, not yet as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) | ## Revision history @@ -76,6 +76,7 @@ all end with the same geometry. | 2026-11-09 | patch | M12, #2157: a sticky's text is 18 and stays 18 (measured in FigJam's web app: ten lines, then a long paragraph, never changed it; the note kept its width and grew taller). The normalize pass no longer resets a sticky's text to a size by its length (24 down to 11 before), so stickies in saved files keep their size. Size presets (Small to Huge) are still missing. Tests: `a_new_sticky_starts_at_18`, `a_sticky_keeps_its_text_size_as_text_is_added`, `a_sticky_saved_with_another_text_size_keeps_it` | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. A mind map node is a board object of its own (`BoardItem::MindNode`: text with no box) and a branch is a connector marked `branch`; the map's shape is read from its branches. `board.mindMap` places a first node with three children and `board.mindMapAdd` adds a child or a sibling, each one undo step. The normalize pass lays a touched map out again from its first node (`board::settle_mind_maps`, `figcraft_doc::mind_layout`): 88 between columns, 48 between siblings, each stack centred on its parent, numbers from a FigJam file saved and decoded. Tests: `board_mindmap_tests` in doc (five) and engine (eight). Numbers unchanged (no toolbar entry yet). | | 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. | +| 2026-11-12 | minor | M9, #1808: `.jam` import: a FigJam shape with text comes in as a native board shape (`BoardItem::Shape`) for the 23 kinds FigCraft draws (square, rounded rectangle, ellipse, diamond, triangles, parallelograms, trapezoid, pentagon, hexagon, octagon, star, plus, arrows, chevron, speech bubble, database, document, predefined process, manual input, internal storage). The frame is empty with centred auto layout and the kind's text insets; it holds an `Outline` vector drawn by FigCraft (`BoardShape::path`, so FigJam's 3 pt corner on a square is lost, and `board.setShape` and resizing treat it as FigCraft's own) with the file's paints, weight and dashes as read, and the text, centred. The 7 kinds FigCraft has no outline for (ENG_QUEUE, ENG_FILE, ENG_FOLDER, SHIELD, DOCUMENT_MULTIPLE, SUMMING_JUNCTION, OR) stay frames with their generated layers and a warning naming the kind; so does a shape whose generated records are damaged (a shape with no text yet is still native, with an empty text layer), and the same shape in a `.fig`. Tests: `board_import_tests.rs` (five). Numbers unchanged. | | 2026-11-10 | minor | M9, #1808: a `.jam` sticky imports as a native board sticky (`BoardItem::Sticky`): its frame keeps the saved size (240 pt, not FigCraft's 200), place, opacity and shadows, the saved colour is kept as it is (not snapped to the board colours), the note and the author line are its text layers, and it lays out like one made here (vertical, space between, hugging the height down to the saved size, the saved inset as padding). The importer reads a `board` field on the REST JSON (a FigCraft extension) for this; a sticky whose generated records are damaged, or the same sticky in a `.fig`, keeps the generated layers as before. Shapes, connectors, stamps and tables are unchanged; the note's text keeps the file's size until it is edited. Tests: `board_import_tests.rs` (native sticky, no author, damaged records, `.fig` unchanged), `import_regression_tests.rs` (the `board` field and junk values). Numbers unchanged. | | 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. | | 2026-11-04 | patch | M6, #1910: a `.jam` elbowed connector saved with its path (FigJam's `connectorControlPoints`) keeps it on import: the points become the `ConnectorPath::Runs` a connector reshaped by hand has and the line is walked along them, so a connector drawn around a layer stays around it; one whose points don't make a path from its ends' sides is routed as before. Still a vector, not a native board object. Details in [`file-format-parity.md`](file-format-parity.md). | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 56de5f480..e690394bc 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-10 · **Change:** minor (`.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.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 (`.jam` import: shapes with text come in as native board shapes (#1808); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.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 @@ -20,7 +20,7 @@ and prototype interactions are still unchecked there. | `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations (with their corner radius and smoothing, #2222), components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides; an instance scaled with the Scale tool, which stores `symbolData.uniformScaleFactor`, draws its layers at the main's lengths times that factor, composed through nested instances: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent, except where an override or derived row gives the value, which is already at the instance's scale; per-point vector corner radii also take their vector-data row's factor; the vector outline paths a layer carries (a network's points follow the layer's size), fixed grid tracks, image tile scales and glass effects are not scaled by the factor, #2091), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234), and the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; ZIP image reads have a separate total budget of 4 GiB (1 GiB on 32-bit targets) of decompressed ZIP-member bytes containing encoded images, with the 256 MiB per-image cap kept: a member that cannot fit is skipped before its output buffer is allocated, and the import report names the budget and counts skipped images (#1076). Failed reads and invalid image contents still consume the bytes read; a reference used by several layers is read once. This is not a limit on decoded pixels or total import memory; images carried inside the message are unchanged. The file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Elbowed and curved connectors without a saved path are routed as FigCraft's board connectors are (right angles, or one curve, from the sides of the layers they join); an elbowed one saved with its path (`connectorControlPoints`: a point and an axis per run between the first and the last) keeps that path when it leaves and arrives by the ends' sides (#1910), and a curved one's saved `connectorBezierControlPoints` are not read; a connector routed here takes its line's paint, weight, cap and dashes from the file's generated line record, as one with a saved snapshot does (#1807). A connector's label without a saved snapshot is kept as text centred on its line, without its background. Not read: table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | | `.penpot` (Penpot 2.x ZIP export) | — | **yes, offline** (open, import, drop, CLI, MCP) | **yes, offline** (export, CLI convert) | Editable layers, supported flex/grid layout, components, tokens and prototypes using the existing model. Unsupported layouts retain saved positions and bounded metadata; toggle-overlay and embedded font binaries are reported. Font references remain editable; no downloads. Synthetic regression coverage; live Penpot and cross-platform QA remain open. See [Penpot reference](penpot.md). | further live Penpot and cross-platform QA | | `.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 stickies as native board stickies (their colour, text and author kept, size as saved, #1808) and generated 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 | — | +| `.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 stickies as native board stickies (their colour, text and author kept, size as saved, #1808), shapes with text as native board shapes for the 23 kinds FigCraft draws (their paints and weight kept, the outline FigCraft's own; the 7 others keep their generated backgrounds and text, #1341, as ordinary layers) (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` | — | | `.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) | — | @@ -203,6 +203,7 @@ scales and empty-style clears; they have not been checked in other software. | 2026-11-07 | minor | `.fig` import, #2091 item 1: an instance scaled with the Scale tool stores `symbolData.uniformScaleFactor`, which the import never read, so the layers of a 128 px instance of a 256 px component came in at 256 px with the main's radii, strokes and spacing. The layers of an instance now take the main's lengths times the factor (composed through nested instances, so 0.5 inside 0.5 is 0.25 for the inner layers), the lengths the Scale tool scales: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent. A value an override or derived row gives is taken as written, already at the instance's scale; the instance's own size is the file's; a missing, non-finite, non-positive or out-of-range factor (outside 0.001 to 1000) changes nothing. Not scaled: vector outline paths (a network's points follow the layer's size), per-point corner radii, fixed grid tracks, image tile scales and glass effects. Tests: `fig::tests::a_scaled_instance_draws_its_layers_at_the_factor` and `fig::scale_factor_tests`. Numbers unchanged | | 2026-11-03 | patch | M6, #1909: `.jam` import: a connector end whose magnet is `AUTO` (FigJam picks the side when it draws) or `CENTER` (the end aims at the layer's middle) left the side its stale `relativePosition` named, the left one in the reporter's file, so the connectors looped behind their shape or crossed it. It now leaves the side facing the other end, as a board connector drawn here does (`Side::Auto`), for straight, elbowed and curved connectors alike; a named magnet (`TOP`, `RIGHT`, `BOTTOM`, `LEFT`) is unchanged, and an end without a magnet still takes the edge its point lies on. The Plugin API lists the magnets (`ConnectorEndpoint.magnet`: "Which side of the node it attaches to"; NONE, AUTO, TOP, LEFT, BOTTOM, RIGHT, CENTER; "Straight connectors may use only CENTER or NONE magnets"). Test: `connectors_with_an_automatic_side_leave_the_side_facing_the_target`. Numbers unchanged. | | 2026-11-04 | minor | JPG export: `quality` (1 to 100, default 90) on `file.export`, `export.add` / `export.update` and MCP `export`, kept in the export setting; an sRGB file's JPGs embed the sRGB ICC profile, as Display P3 files' JPGs already embedded theirs, since an untagged JPG is only assumed to be sRGB (#2004). | +| 2026-11-12 | minor | M9, #1808: `.jam` import: a FigJam shape with text comes in as a native board shape (`BoardItem::Shape`) for the 23 kinds FigCraft draws (square, rounded rectangle, ellipse, diamond, triangles, parallelograms, trapezoid, pentagon, hexagon, octagon, star, plus, arrows, chevron, speech bubble, database, document, predefined process, manual input, internal storage). The frame is empty with centred auto layout and the kind's text insets; it holds an `Outline` vector drawn by FigCraft (`BoardShape::path`, so FigJam's 3 pt corner on a square is lost, and `board.setShape` and resizing treat it as FigCraft's own) with the file's paints, weight and dashes as read, and the text, centred. The 7 kinds FigCraft has no outline for (ENG_QUEUE, ENG_FILE, ENG_FOLDER, SHIELD, DOCUMENT_MULTIPLE, SUMMING_JUNCTION, OR) stay frames with their generated layers and a warning naming the kind; so does a shape whose generated records are damaged or whose text is blank, and the same shape in a `.fig`. Tests: `board_import_tests.rs` (four). Numbers unchanged. | | 2026-11-10 | minor | M9, #1808: `.jam` import: a FigJam sticky comes in as a native board sticky. The mapper knows the canvas header (`fig-jam.`) and, for a whiteboard only, writes a `board` field (`{"type": "sticky", "author": ..}`, a FigCraft extension of the REST JSON) on a sticky whose generated records are complete (layout version 1, one visible solid background paint without strokes, a non-blank note), with the background's colour and corner radius, the file's size, place, opacity and shadows, the note and the author line as text layers and no background vector; the REST importer sets it as the layer's board item and ignores a junk `board` value with a warning. A sticky that isn't complete, or any sticky in a `.fig`, keeps the generated layers and the old note. Shapes with text, connectors, stamps and tables are unchanged. Tests: `fig::tests::board` (four), `rest::import_regression_tests` (two). | | 2026-11-04 | minor | `.fig` and `.jam` import, #1910: an elbowed connector saved with its path keeps it. FigJam stores `connectorControlPoints`, one per run between the first and the last, each a point on its run (in the connector's parent's coordinates) with the run's axis; the first run leaves the start's side and the last arrives at the end's. They become the `ConnectorPath::Runs` a board connector reshaped by hand has (`figcraft_doc::route_along`), so a connector drawn around a layer in FigJam stays around it instead of being routed through it. Points that don't make such a path (off both axes, two runs in a row the same way, a first or last run sideways to its side or going back into its object, more runs than a hand could make) leave the connector to the router as before, and only connectors routed here count in the "follow FigCraft's own routing" note. A curved connector's `connectorBezierControlPoints` are still not read. Tests: `tail_tests::an_elbow_connector_saved_with_its_path_keeps_it`, `tail_tests::an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here`. | | 2026-11-01 | patch | `.fig` and `.jam` import: a connector without a saved snapshot (elbowed and curved ones are routed here) took no stroke, so it was invisible (#1807); its line's paint, weight, cap and dashes now come from the file's generated line record, as a saved snapshot's do, and the connector's own values, when it has any, win. Test: `fig::connector_label_tests::a_routed_connector_takes_its_line_style_from_the_generated_record`. Numbers unchanged | From 9e22cc7bc3bbeed335ffed5866cc99b2f8b7a27f Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 03:30:43 -0500 Subject: [PATCH 05/12] M9: .jam shapes keep their fixed size and a blank record's outer text (#1808) A native shape frame now writes fixed sizing on both axes, as a shape made here has, so the first edit no longer shrinks it to hug its text. A shape whose generated text is blank while the outer layer still carries text keeps the generated layers (#1397). The kind name in the no-outline note is clipped, the docs rows match the code, and the new key sits in order. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/format/src/fig/board_import_tests.rs | 19 +++++++++++++++++++ crates/format/src/fig/map/board.rs | 9 ++++++++- crates/format/src/fig/map/layer.rs | 2 +- crates/ui-egui/locales/en.toml | 2 +- docs/boards-parity.md | 4 ++-- docs/file-format-parity.md | 4 ++-- 6 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/format/src/fig/board_import_tests.rs b/crates/format/src/fig/board_import_tests.rs index b1b1e30c7..efbabde05 100644 --- a/crates/format/src/fig/board_import_tests.rs +++ b/crates/format/src/fig/board_import_tests.rs @@ -566,6 +566,11 @@ fn a_jam_diamond_is_a_native_shape_drawn_by_figcraft() { assert!(frame.fills.is_empty()); assert_eq!((frame.width, frame.height), (240.0, 240.0)); assert_eq!(frame.layout.as_ref().expect("shape auto layout").padding, [0.25 * 240.0; 4]); + assert_eq!( + (frame.child_layout.sizing_h, frame.child_layout.sizing_v), + (figcraft_doc::Sizing::Fixed, figcraft_doc::Sizing::Fixed), + "a fixed box, as a shape made here: it must not hug its text" + ); assert_eq!(frame.children.len(), 2, "the outline and the text: {warnings:?}"); let outline = doc.node(frame.children[0]).unwrap(); let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) }; @@ -686,3 +691,17 @@ fn a_jam_shape_without_text_is_still_a_native_shape() { assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Rectangle })); assert_eq!(doc.node(frame.children[1]).unwrap().kind.text().unwrap().characters, ""); } + +/// Blank generated text must not hide text the outer node still carries (#1397): on a whiteboard +/// too, such a shape keeps the generated layers. +#[test] +fn a_jam_shape_whose_text_only_the_outer_node_carries_keeps_it() { + let mut layer = shape_node("SQUARE"); + set(&mut layer, "textData", o(vec![("characters", s("Outer saved text"))])); + let background = record(0, vec![("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)]))]); + set(&mut layer, "nodeGenerationData", o(vec![("overrides", arr(vec![background, record(1, text(" ", 24.0))]))])); + let (doc, _) = jam(layer); + let frame = named(&doc, "Board object"); + assert!(frame.board.is_none(), "the generated layers keep the outer text"); + assert!(frame.children.iter().filter_map(|id| doc.node(*id)?.kind.text()).any(|t| t.characters == "Outer saved text")); +} diff --git a/crates/format/src/fig/map/board.rs b/crates/format/src/fig/map/board.rs index 5b885f060..7ea2de801 100644 --- a/crates/format/src/fig/map/board.rs +++ b/crates/format/src/fig/map/board.rs @@ -110,7 +110,7 @@ impl<'a> Mapper<'a> { pub(super) fn native_shape(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option> { let kind = v.str("shapeWithTextType").unwrap_or("SQUARE"); let Some(shape) = board_shape(kind) else { - self.warn(format!("shape with text kind {kind} has no FigCraft outline; kept as a frame")); + self.warn(format!("shape with text kind {} has no FigCraft outline; kept as a frame", crate::rest::props::clip_str(kind))); return None; }; if v.get("nodeGenerationData").is_none() || v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) { @@ -123,6 +123,11 @@ impl<'a> Mapper<'a> { }; let background = record(0)?; let body = record(1)?; + // Blank generated text must not hide text the outer node still carries (#1397): the + // generated layers keep it. + if own_text(&body).is_none() && own_text(v).is_some() { + return None; + } if depth >= MAX_DEPTH || self.count.saturating_add(2) > self.budget() { return None; } @@ -162,6 +167,8 @@ impl<'a> Mapper<'a> { ("layoutMode", json!("VERTICAL")), ("primaryAxisAlignItems", json!("CENTER")), ("counterAxisAlignItems", json!("CENTER")), + ("primaryAxisSizingMode", json!("FIXED")), + ("counterAxisSizingMode", json!("FIXED")), ("paddingTop", json!(top * h)), ("paddingRight", json!(right * w)), ("paddingBottom", json!(bottom * h)), diff --git a/crates/format/src/fig/map/layer.rs b/crates/format/src/fig/map/layer.rs index f30279b0f..a2bc20ad0 100644 --- a/crates/format/src/fig/map/layer.rs +++ b/crates/format/src/fig/map/layer.rs @@ -174,7 +174,7 @@ impl<'a> Mapper<'a> { // A label without a snapshot: the connector becomes a frame holding its line and its label. let connector_label = own == "CONNECTOR" && !connector_snapshot && self.connector_label_fits(&view, depth); let ty = if connector_label { "FRAME" } else { Self::mapped_type(own, &view, connector_snapshot, connector_terminal, stand)? }; - // A whiteboard's sticky says it imports as a frame only when it can't be a native one. + // A whiteboard's sticky or shape with text says it imports as a frame only when it can't be a native one. let native_board = self.board && matches!(own, "STICKY" | "SHAPE_WITH_TEXT"); if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH" && !native_board) { self.warn(format!("{} layers import as {what}", own.to_ascii_lowercase().replace('_', " "))); diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index b1d9fb928..c916ccd0f 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1883,6 +1883,7 @@ name = "English" "set-variable actions without a value were skipped" = "set-variable actions without a value were skipped" "set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" = "set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" "shape generated outline is missing or damaged; using its rectangle" = "shape generated outline is missing or damaged; using its rectangle" +"shape with text layers import as frames with their text" = "shape with text layers import as frames with their text" "slot content assignment target is missing or is not slot content" = "slot content assignment target is missing or is not slot content" "slot content assignment uses the empty GUID sentinel and was skipped" = "slot content assignment uses the empty GUID sentinel and was skipped" "slot layers without a matching slot property were imported as frames" = "slot layers without a matching slot property were imported as frames" @@ -1891,7 +1892,6 @@ name = "English" "stale or invalid grid track sizing entries were ignored" = "stale or invalid grid track sizing entries were ignored" "stars and polygons without point counts or geometry use the default point count" = "stars and polygons without point counts or geometry use the default point count" "sticky layers import as frames with their text" = "sticky layers import as frames with their text" -"shape with text layers import as frames with their text" = "shape with text layers import as frames with their text" "style settings of some vector segments aren't supported; those segments use the layer's stroke" = "style settings of some vector segments aren't supported; those segments use the layer's stroke" "text path underline or strikethrough decoration is not rendered" = "text path underline or strikethrough decoration is not rendered" "text style overrides refer to missing table entries" = "text style overrides refer to missing table entries" diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 9489e51a3..9b1972be9 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** minor (a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) **Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that @@ -76,7 +76,7 @@ all end with the same geometry. | 2026-11-09 | patch | M12, #2157: a sticky's text is 18 and stays 18 (measured in FigJam's web app: ten lines, then a long paragraph, never changed it; the note kept its width and grew taller). The normalize pass no longer resets a sticky's text to a size by its length (24 down to 11 before), so stickies in saved files keep their size. Size presets (Small to Huge) are still missing. Tests: `a_new_sticky_starts_at_18`, `a_sticky_keeps_its_text_size_as_text_is_added`, `a_sticky_saved_with_another_text_size_keeps_it` | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. A mind map node is a board object of its own (`BoardItem::MindNode`: text with no box) and a branch is a connector marked `branch`; the map's shape is read from its branches. `board.mindMap` places a first node with three children and `board.mindMapAdd` adds a child or a sibling, each one undo step. The normalize pass lays a touched map out again from its first node (`board::settle_mind_maps`, `figcraft_doc::mind_layout`): 88 between columns, 48 between siblings, each stack centred on its parent, numbers from a FigJam file saved and decoded. Tests: `board_mindmap_tests` in doc (five) and engine (eight). Numbers unchanged (no toolbar entry yet). | | 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. | -| 2026-11-12 | minor | M9, #1808: `.jam` import: a FigJam shape with text comes in as a native board shape (`BoardItem::Shape`) for the 23 kinds FigCraft draws (square, rounded rectangle, ellipse, diamond, triangles, parallelograms, trapezoid, pentagon, hexagon, octagon, star, plus, arrows, chevron, speech bubble, database, document, predefined process, manual input, internal storage). The frame is empty with centred auto layout and the kind's text insets; it holds an `Outline` vector drawn by FigCraft (`BoardShape::path`, so FigJam's 3 pt corner on a square is lost, and `board.setShape` and resizing treat it as FigCraft's own) with the file's paints, weight and dashes as read, and the text, centred. The 7 kinds FigCraft has no outline for (ENG_QUEUE, ENG_FILE, ENG_FOLDER, SHIELD, DOCUMENT_MULTIPLE, SUMMING_JUNCTION, OR) stay frames with their generated layers and a warning naming the kind; so does a shape whose generated records are damaged (a shape with no text yet is still native, with an empty text layer), and the same shape in a `.fig`. Tests: `board_import_tests.rs` (five). Numbers unchanged. | +| 2026-11-12 | minor | M9, #1808: `.jam` import: a FigJam shape with text comes in as a native board shape (`BoardItem::Shape`) for the 23 kinds FigCraft draws (square, rounded rectangle, ellipse, diamond, triangles, parallelograms, trapezoid, pentagon, hexagon, octagon, star, plus, arrows, chevron, speech bubble, database, document, predefined process, manual input, internal storage). The frame is empty and a fixed size, as a shape made here, with centred auto layout and the kind's text insets; it holds an `Outline` vector drawn by FigCraft (`BoardShape::path`, so FigJam's 3 pt corner on a square is lost, and `board.setShape` and resizing treat it as FigCraft's own) with the file's paints, weight and dashes as read, and the text, centred. The 7 kinds FigCraft has no outline for (ENG_QUEUE, ENG_FILE, ENG_FOLDER, SHIELD, DOCUMENT_MULTIPLE, SUMMING_JUNCTION, OR) stay frames with their generated layers and a warning naming the kind; so does a shape whose generated records are damaged, or whose generated text is blank while the outer layer still carries text (#1397), and the same shape in a `.fig`; a shape with no text at all is still native, with an empty text layer. Tests: `board_import_tests.rs` (six). Numbers unchanged. | | 2026-11-10 | minor | M9, #1808: a `.jam` sticky imports as a native board sticky (`BoardItem::Sticky`): its frame keeps the saved size (240 pt, not FigCraft's 200), place, opacity and shadows, the saved colour is kept as it is (not snapped to the board colours), the note and the author line are its text layers, and it lays out like one made here (vertical, space between, hugging the height down to the saved size, the saved inset as padding). The importer reads a `board` field on the REST JSON (a FigCraft extension) for this; a sticky whose generated records are damaged, or the same sticky in a `.fig`, keeps the generated layers as before. Shapes, connectors, stamps and tables are unchanged; the note's text keeps the file's size until it is edited. Tests: `board_import_tests.rs` (native sticky, no author, damaged records, `.fig` unchanged), `import_regression_tests.rs` (the `board` field and junk values). Numbers unchanged. | | 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. | | 2026-11-04 | patch | M6, #1910: a `.jam` elbowed connector saved with its path (FigJam's `connectorControlPoints`) keeps it on import: the points become the `ConnectorPath::Runs` a connector reshaped by hand has and the line is walked along them, so a connector drawn around a layer stays around it; one whose points don't make a path from its ends' sides is routed as before. Still a vector, not a native board object. Details in [`file-format-parity.md`](file-format-parity.md). | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index e690394bc..57132c32a 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-10 · **Change:** minor (`.jam` import: shapes with text come in as native board shapes (#1808); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.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-12 · **Change:** minor (`.jam` import: shapes with text come in as native board shapes (#1808); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.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 @@ -203,7 +203,7 @@ scales and empty-style clears; they have not been checked in other software. | 2026-11-07 | minor | `.fig` import, #2091 item 1: an instance scaled with the Scale tool stores `symbolData.uniformScaleFactor`, which the import never read, so the layers of a 128 px instance of a 256 px component came in at 256 px with the main's radii, strokes and spacing. The layers of an instance now take the main's lengths times the factor (composed through nested instances, so 0.5 inside 0.5 is 0.25 for the inner layers), the lengths the Scale tool scales: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent. A value an override or derived row gives is taken as written, already at the instance's scale; the instance's own size is the file's; a missing, non-finite, non-positive or out-of-range factor (outside 0.001 to 1000) changes nothing. Not scaled: vector outline paths (a network's points follow the layer's size), per-point corner radii, fixed grid tracks, image tile scales and glass effects. Tests: `fig::tests::a_scaled_instance_draws_its_layers_at_the_factor` and `fig::scale_factor_tests`. Numbers unchanged | | 2026-11-03 | patch | M6, #1909: `.jam` import: a connector end whose magnet is `AUTO` (FigJam picks the side when it draws) or `CENTER` (the end aims at the layer's middle) left the side its stale `relativePosition` named, the left one in the reporter's file, so the connectors looped behind their shape or crossed it. It now leaves the side facing the other end, as a board connector drawn here does (`Side::Auto`), for straight, elbowed and curved connectors alike; a named magnet (`TOP`, `RIGHT`, `BOTTOM`, `LEFT`) is unchanged, and an end without a magnet still takes the edge its point lies on. The Plugin API lists the magnets (`ConnectorEndpoint.magnet`: "Which side of the node it attaches to"; NONE, AUTO, TOP, LEFT, BOTTOM, RIGHT, CENTER; "Straight connectors may use only CENTER or NONE magnets"). Test: `connectors_with_an_automatic_side_leave_the_side_facing_the_target`. Numbers unchanged. | | 2026-11-04 | minor | JPG export: `quality` (1 to 100, default 90) on `file.export`, `export.add` / `export.update` and MCP `export`, kept in the export setting; an sRGB file's JPGs embed the sRGB ICC profile, as Display P3 files' JPGs already embedded theirs, since an untagged JPG is only assumed to be sRGB (#2004). | -| 2026-11-12 | minor | M9, #1808: `.jam` import: a FigJam shape with text comes in as a native board shape (`BoardItem::Shape`) for the 23 kinds FigCraft draws (square, rounded rectangle, ellipse, diamond, triangles, parallelograms, trapezoid, pentagon, hexagon, octagon, star, plus, arrows, chevron, speech bubble, database, document, predefined process, manual input, internal storage). The frame is empty with centred auto layout and the kind's text insets; it holds an `Outline` vector drawn by FigCraft (`BoardShape::path`, so FigJam's 3 pt corner on a square is lost, and `board.setShape` and resizing treat it as FigCraft's own) with the file's paints, weight and dashes as read, and the text, centred. The 7 kinds FigCraft has no outline for (ENG_QUEUE, ENG_FILE, ENG_FOLDER, SHIELD, DOCUMENT_MULTIPLE, SUMMING_JUNCTION, OR) stay frames with their generated layers and a warning naming the kind; so does a shape whose generated records are damaged or whose text is blank, and the same shape in a `.fig`. Tests: `board_import_tests.rs` (four). Numbers unchanged. | +| 2026-11-12 | minor | M9, #1808: `.jam` import: a FigJam shape with text comes in as a native board shape (`BoardItem::Shape`) for the 23 kinds FigCraft draws (square, rounded rectangle, ellipse, diamond, triangles, parallelograms, trapezoid, pentagon, hexagon, octagon, star, plus, arrows, chevron, speech bubble, database, document, predefined process, manual input, internal storage). The frame is empty and a fixed size, as a shape made here, with centred auto layout and the kind's text insets; it holds an `Outline` vector drawn by FigCraft (`BoardShape::path`, so FigJam's 3 pt corner on a square is lost, and `board.setShape` and resizing treat it as FigCraft's own) with the file's paints, weight and dashes as read, and the text, centred. The 7 kinds FigCraft has no outline for (ENG_QUEUE, ENG_FILE, ENG_FOLDER, SHIELD, DOCUMENT_MULTIPLE, SUMMING_JUNCTION, OR) stay frames with their generated layers and a warning naming the kind; so does a shape whose generated records are damaged, or whose generated text is blank while the outer layer still carries text (#1397), and the same shape in a `.fig`; a shape with no text at all is still native, with an empty text layer. Tests: `board_import_tests.rs` (six). Numbers unchanged. | | 2026-11-10 | minor | M9, #1808: `.jam` import: a FigJam sticky comes in as a native board sticky. The mapper knows the canvas header (`fig-jam.`) and, for a whiteboard only, writes a `board` field (`{"type": "sticky", "author": ..}`, a FigCraft extension of the REST JSON) on a sticky whose generated records are complete (layout version 1, one visible solid background paint without strokes, a non-blank note), with the background's colour and corner radius, the file's size, place, opacity and shadows, the note and the author line as text layers and no background vector; the REST importer sets it as the layer's board item and ignores a junk `board` value with a warning. A sticky that isn't complete, or any sticky in a `.fig`, keeps the generated layers and the old note. Shapes with text, connectors, stamps and tables are unchanged. Tests: `fig::tests::board` (four), `rest::import_regression_tests` (two). | | 2026-11-04 | minor | `.fig` and `.jam` import, #1910: an elbowed connector saved with its path keeps it. FigJam stores `connectorControlPoints`, one per run between the first and the last, each a point on its run (in the connector's parent's coordinates) with the run's axis; the first run leaves the start's side and the last arrives at the end's. They become the `ConnectorPath::Runs` a board connector reshaped by hand has (`figcraft_doc::route_along`), so a connector drawn around a layer in FigJam stays around it instead of being routed through it. Points that don't make such a path (off both axes, two runs in a row the same way, a first or last run sideways to its side or going back into its object, more runs than a hand could make) leave the connector to the router as before, and only connectors routed here count in the "follow FigCraft's own routing" note. A curved connector's `connectorBezierControlPoints` are still not read. Tests: `tail_tests::an_elbow_connector_saved_with_its_path_keeps_it`, `tail_tests::an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here`. | | 2026-11-01 | patch | `.fig` and `.jam` import: a connector without a saved snapshot (elbowed and curved ones are routed here) took no stroke, so it was invisible (#1807); its line's paint, weight, cap and dashes now come from the file's generated line record, as a saved snapshot's do, and the connector's own values, when it has any, win. Test: `fig::connector_label_tests::a_routed_connector_takes_its_line_style_from_the_generated_record`. Numbers unchanged | From 7cb5af017d566a232f8018149d77e3277f452b74 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 05:46:11 -0500 Subject: [PATCH 06/12] M9: a .jam shape past the size cap draws its outline at the cap (#1808) The REST reader caps every size at 1,000,000; the native outline was built from the uncapped size, so it reached past its frame. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and fixed --- crates/format/src/fig/board_import_tests.rs | 15 +++++++++++++++ crates/format/src/fig/map/board.rs | 3 +++ crates/format/src/rest/props.rs | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/format/src/fig/board_import_tests.rs b/crates/format/src/fig/board_import_tests.rs index efbabde05..fb4d4ba30 100644 --- a/crates/format/src/fig/board_import_tests.rs +++ b/crates/format/src/fig/board_import_tests.rs @@ -584,6 +584,21 @@ fn a_jam_diamond_is_a_native_shape_drawn_by_figcraft() { assert_eq!(label.align_h, figcraft_doc::TextAlignH::Center); } +/// A shape past the importer's size cap is drawn at the capped size, so its outline stays inside +/// its frame. +#[test] +fn a_jam_shape_past_the_size_cap_draws_its_outline_at_the_cap() { + let mut layer = shape_node("DIAMOND"); + set(&mut layer, "size", xy(2_000_000.0, 2_000_000.0)); + let (doc, warnings) = jam(layer); + let frame = named(&doc, "Board object"); + assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Diamond }), "{warnings:?}"); + assert_eq!((frame.width, frame.height), (1e6, 1e6)); + let outline = doc.node(frame.children[0]).unwrap(); + let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) }; + assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(1e6, 1e6))); +} + /// 23 of FigJam's 30 shape kinds have a FigCraft outline; the other 7 stay frames and say which. #[test] fn every_figjam_shape_kind_maps_or_stays_a_frame() { diff --git a/crates/format/src/fig/map/board.rs b/crates/format/src/fig/map/board.rs index 7ea2de801..723c490bd 100644 --- a/crates/format/src/fig/map/board.rs +++ b/crates/format/src/fig/map/board.rs @@ -135,6 +135,9 @@ impl<'a> Mapper<'a> { if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { return None; } + // The REST reader caps every size; the outline is drawn at the capped size too, so it + // stays inside its frame. + let (w, h) = (w.min(crate::rest::props::MAX_SIZE), h.min(crate::rest::props::MAX_SIZE)); // Everything is valid: build the outline from the record's paints, then the frame. let mut outline = Obj::new(); outline.insert("id".into(), json!(format!("{rest_id};generated0"))); diff --git a/crates/format/src/rest/props.rs b/crates/format/src/rest/props.rs index f5be3d279..e68af9d88 100644 --- a/crates/format/src/rest/props.rs +++ b/crates/format/src/rest/props.rs @@ -13,7 +13,7 @@ use serde_json::Value; use super::Ctx; /// Largest width/height/stroke/radius/spacing value taken from the file. -pub(super) const MAX_SIZE: f64 = 1e6; +pub(crate) const MAX_SIZE: f64 = 1e6; /// Largest coordinate taken from the file. pub(super) const MAX_COORD: f64 = 1e7; /// Most entries read from any one list (paints, effects, dashes, grids…). From 88b63d1eb92b1a83bd6165e523b9ca8b9b903114 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 22:41:39 -0500 Subject: [PATCH 07/12] M6: .fig export writes text on a path (#2323) Text on a path was written as an ordinary text layer under the warning "text on a path was written as plain text", so the path, where the text starts and its side were gone when the file was opened again. It is now written as the format's own layer kind (TEXT_PATH): the first part of its path as a vector network of one open or closed chain with the segment the text starts on marked, the start as that segment's own parameter (textPathStart.tValue, found by inverse arc length) and the side as forward. Vertical alignment is written as top, which is how text on a path draws. More than one line and paths the format can't hold stay plain text, the parts of a path after the first are left out, and text on a path in an instance but not in its main component (or the other way round) is written as the main has it, each with its own warning. The field numbers come from the schema of a synthetic file saved from Figma's web app. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.2 briefed; Sonnet 5.5 wrote at medium --- crates/format/src/fig/export.rs | 5 +- crates/format/src/fig/export/layer.rs | 17 +- crates/format/src/fig/export/shape.rs | 227 ++++++++++++++++- crates/format/src/fig/text_path_tests.rs | 304 ++++++++++++++++++++++- docs/file-format-parity.md | 7 +- 5 files changed, 550 insertions(+), 10 deletions(-) diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index ac8612b9c..90bf8ecb2 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -72,7 +72,7 @@ const AUX: u32 = 2; pub(super) const SCHEMA: &str = " enum MessageType JOIN_START=0 NODE_CHANGES=1 enum NodePhase CREATED=0 REMOVED=1 -enum NodeType NONE=0 DOCUMENT=1 CANVAS=2 GROUP=3 FRAME=4 BOOLEAN_OPERATION=5 VECTOR=6 STAR=7 LINE=8 ELLIPSE=9 RECTANGLE=10 REGULAR_POLYGON=11 ROUNDED_RECTANGLE=12 TEXT=13 SLICE=14 SYMBOL=15 INSTANCE=16 SECTION=25 VARIABLE=28 VARIABLE_SET=31 +enum NodeType NONE=0 DOCUMENT=1 CANVAS=2 GROUP=3 FRAME=4 BOOLEAN_OPERATION=5 VECTOR=6 STAR=7 LINE=8 ELLIPSE=9 RECTANGLE=10 REGULAR_POLYGON=11 ROUNDED_RECTANGLE=12 TEXT=13 SLICE=14 SYMBOL=15 INSTANCE=16 SECTION=25 VARIABLE=28 VARIABLE_SET=31 TEXT_PATH=41 enum BlendMode PASS_THROUGH=0 NORMAL=1 DARKEN=2 MULTIPLY=3 LINEAR_BURN=4 COLOR_BURN=5 LIGHTEN=6 SCREEN=7 LINEAR_DODGE=8 COLOR_DODGE=9 OVERLAY=10 SOFT_LIGHT=11 HARD_LIGHT=12 DIFFERENCE=13 EXCLUSION=14 HUE=15 SATURATION=16 COLOR=17 LUMINOSITY=18 enum PaintType SOLID=0 GRADIENT_LINEAR=1 GRADIENT_RADIAL=2 GRADIENT_ANGULAR=3 GRADIENT_DIAMOND=4 IMAGE=5 enum ImageScaleMode STRETCH=0 FIT=1 FILL=2 TILE=3 @@ -151,6 +151,7 @@ message TextLineData LineType lineType=1, int styleId=10, int indentationLevel=2 message TextData string characters=1, uint[] characterStyleIDs=2, NodeChange[] styleOverrideTable=3, TextLineData[] lines=12 message Path WindingRule windingRule=1, uint commandsBlob=2, uint styleID=3 message VectorData uint vectorNetworkBlob=1, Vector normalizedSize=2, NodeChange[] styleOverrideTable=3 +message TextPathStart float tValue=1, bool forward=2 message ArcData float startingAngle=1, float endingAngle=2, float innerRadius=3 message OptionalVector Vector value=1 message LayoutGrid LayoutGridType type=1, Axis axis=2, bool visible=3, int numSections=4, float offset=5, float sectionSize=6, float gutterSize=7, Color color=8, LayoutGridPattern pattern=9, VariableData numSectionsVar=10, VariableData offsetVar=11, VariableData sectionSizeVar=12, VariableData gutterSizeVar=13 @@ -190,7 +191,7 @@ message GridTrackSizingFunction GridTrackSizingType type=1, float value=2 message GridTrackSize GridTrackSizingFunction minSizing=1, GridTrackSizingFunction maxSizing=2 message GUIDGridTrackSizeMapEntry GUID id=1, GridTrackSize trackSize=2 message GUIDGridTrackSizeMap GUIDGridTrackSizeMapEntry[] entries=1 -message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201 +message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201 struct Blob byte[] bytes message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4, Blob[] blobs=6 "; diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index bebd09059..6a9d0f1a0 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -66,6 +66,11 @@ impl<'d> Exporter<'d> { } _ => None, }; + // A text on a path is its own layer kind, written only when its path fields were built. + let on_path = match &n.kind { + NodeKind::Text(td) => self.text_path(n, td, nested), + _ => None, + }; let ty = match &n.kind { NodeKind::Page { .. } | NodeKind::Frame | NodeKind::Group | NodeKind::ComponentSet { .. } => "FRAME", NodeKind::Instance { .. } if main.is_none() => "FRAME", @@ -76,6 +81,7 @@ impl<'d> Exporter<'d> { NodeKind::Star { .. } => "STAR", NodeKind::Line => "LINE", NodeKind::Vector { .. } => "VECTOR", + NodeKind::Text(_) if on_path.is_some() => "TEXT_PATH", NodeKind::Text(_) => "TEXT", NodeKind::BooleanOp { .. } => "BOOLEAN_OPERATION", NodeKind::Component { .. } => "SYMBOL", @@ -99,7 +105,16 @@ impl<'d> Exporter<'d> { NodeKind::Polygon { count } => f.push(("count", u(*count))), NodeKind::Star { count, inner_ratio } => f.extend([("count", u(*count)), ("starInnerScale", fl(*inner_ratio))]), NodeKind::Vector { network } => self.vector(n, network, f), - NodeKind::Text(td) => self.text(td, &n.fills, f), + NodeKind::Text(td) => { + self.text(td, &n.fills, f); + if let Some(path) = on_path { + // Text on a path has no box to align in: it is written as top, which is how it draws. + if let Some(entry) = f.iter_mut().find(|(k, _)| *k == "textAlignVertical") { + entry.1 = e("TOP"); + } + f.extend(path); + } + } NodeKind::BooleanOp { op } => { let name = match op { BoolOp::Union => "UNION", diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index 119777367..f298e663f 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -173,9 +173,6 @@ impl<'d> Exporter<'d> { if styles.clone().any(|st| unsupported_decoration_look(st) || !st.variations.is_empty()) { self.warn("text decoration looks and variable font settings were left out"); } - if td.path.is_some() { - self.warn("text on a path was written as plain text"); - } if !td.features.is_empty() { self.warn("OpenType features were left out"); } @@ -374,4 +371,228 @@ impl<'d> Exporter<'d> { self.blobs.insert(bytes, i); Some(i) } + + /// The fields of a text on a path (its start and its path as a vector network), or `None` when the text stays plain text + /// (with the warning that says why). `nested`: for an instance's override row, which follows its main's layer. + pub(super) fn text_path(&mut self, n: &Node, td: &TextData, nested: bool) -> Option { + let doc = self.doc; + let own = text_path_net(td, n.width, n.height); + let main = if nested { n.source.and_then(|s| doc.node(s)) } else { None }; + if let Some(main) = main { + let main_ok = matches!(&main.kind, NodeKind::Text(m) if text_path_net(m, main.width, main.height).is_ok()); + if main_ok != own.is_ok() { + self.warn(TEXT_PATH_INSTANCE); + return None; + } + } + let tp = td.path.as_deref()?; + let made = match own { + Ok(made) => made, + Err(why) => { + self.warn(why); + return None; + } + }; + let Some(index) = self.blob(network::encode(&made.net)) else { + self.warn(TEXT_PATH_CANT); + return None; + }; + if made.later_parts { + self.warn(TEXT_PATH_PARTS); + } + Some(vec![ + ("textPathStart", o(vec![("tValue", fl(made.t)), ("forward", b(!tp.flip))])), + ("vectorData", o(vec![("vectorNetworkBlob", u(index)), ("normalizedSize", xy(n.width, n.height))])), + ]) + } +} + +/// The style id the format gives the segment a text on a path starts on. +const TEXT_PATH_MARK: u32 = 0x01ff_ffff; +const TEXT_PATH_LINES: &str = "text on a path with more than one line was written as plain text"; +const TEXT_PATH_CANT: &str = "text on a path the format can't hold was written as plain text"; +const TEXT_PATH_PARTS: &str = "the parts of a text's path after the first were left out"; +const TEXT_PATH_INSTANCE: &str = + "text on a path in an instance but not in its main component, or the other way round, was written as the main has it"; + +/// A text's path as the format holds it: one chain (or cycle) of a vector network with the +/// segment the text starts on marked, and the start as that segment's own parameter. +struct PathNet { + net: network::Network, + t: f64, + later_parts: bool, +} + +/// The tangent-to-control-point cubic of a network segment, as the import reads it. +fn net_cubic(net: &network::Network, s: &network::Segment) -> Option<(figcraft_doc::geom::kurbo::CubicBez, bool)> { + use figcraft_doc::geom::kurbo::CubicBez; + let (a, b) = (net.vertices.get(s.a)?, net.vertices.get(s.b)?); + let line = s.ta == (0.0, 0.0) && s.tb == (0.0, 0.0); + let cubic = CubicBez::new((a.x, a.y), (a.x + s.ta.0, a.y + s.ta.1), (b.x + s.tb.0, b.y + s.tb.1), (b.x, b.y)); + Some((cubic, line)) +} + +/// The length of a segment, as the import measures it. +fn net_length(net: &network::Network, s: &network::Segment) -> f64 { + use figcraft_doc::geom::kurbo::{Line, ParamCurveArclen}; + match net_cubic(net, s) { + Some((c, true)) => Line::new(c.p0, c.p3).arclen(1e-9), + Some((c, false)) => c.arclen(1e-9), + None => 0.0, + } +} + +/// The part of a path (a move and what follows it) as a chain of the network, and whether it is +/// a cycle; `None` without a segment longer than a billionth. +fn path_chain(part: &[figcraft_doc::geom::kurbo::PathEl]) -> Option<(network::Network, bool)> { + use figcraft_doc::geom::kurbo::{PathEl, Point, QuadBez}; + let r = |x: f64| f64::from(finite(x) as f32); + let rp = |p: Point| (r(p.x), r(p.y)); + let mut net = network::Network::default(); + let mut closed = false; + let mut cur = (0.0, 0.0); + let add = |net: &mut network::Network, c1: Option<(f64, f64)>, c2: Option<(f64, f64)>, end: (f64, f64)| { + let Some(last) = net.vertices.last() else { return }; + let (a, index) = ((last.x, last.y), net.vertices.len() - 1); + let tangent = |c: Option<(f64, f64)>, from: (f64, f64)| c.map_or((0.0, 0.0), |c| (r(c.0 - from.0), r(c.1 - from.1))); + let seg = network::Segment { style: 0, a: index, ta: tangent(c1, a), b: index + 1, tb: tangent(c2, end) }; + net.vertices.push(network::Vertex { style: 0, x: end.0, y: end.1 }); + if net_length(net, &seg) > 1e-9 { + net.segments.push(seg); + } else { + net.vertices.pop(); + } + }; + for el in part { + match el { + PathEl::MoveTo(p) => { + cur = rp(*p); + net.vertices.push(network::Vertex { style: 0, x: cur.0, y: cur.1 }); + } + PathEl::LineTo(p) => { + cur = rp(*p); + add(&mut net, None, None, cur); + } + PathEl::QuadTo(c, p) => { + let q = QuadBez::new(Point::new(cur.0, cur.1), Point::new(r(c.x), r(c.y)), Point::new(r(p.x), r(p.y))).raise(); + cur = rp(*p); + add(&mut net, Some((q.p1.x, q.p1.y)), Some((q.p2.x, q.p2.y)), cur); + } + PathEl::CurveTo(a, b, p) => { + cur = rp(*p); + add(&mut net, Some(rp(*a)), Some(rp(*b)), cur); + } + PathEl::ClosePath => closed = true, + } + } + if net.segments.is_empty() { + return None; + } + let first = net.vertices.first().map(|v| (v.x, v.y))?; + let last = net.vertices.last().map(|v| (v.x, v.y))?; + let near = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).hypot(p.1 - q.1) <= 1e-6; + let mut cycle = false; + if closed || near(last, first) { + if near(last, first) { + // The last segment ends on the first vertex. A single segment stays an open chain of + // two vertices at one place: the import refuses a segment from a vertex to itself. + if net.segments.len() > 1 { + net.vertices.pop(); + if let Some(s) = net.segments.last_mut() { + s.b = 0; + s.tb = (r(last.0 + s.tb.0 - first.0), r(last.1 + s.tb.1 - first.1)); + cycle = true; + } + } + } else { + net.segments.push(network::Segment { style: 0, a: net.vertices.len() - 1, ta: (0.0, 0.0), b: 0, tb: (0.0, 0.0) }); + cycle = true; + } + } + Some((net, cycle)) +} + +/// A text on a path as the format holds it, or the warning for why it stays plain text. +fn text_path_net(td: &TextData, w: f64, h: f64) -> Result { + use figcraft_doc::geom::kurbo::{ParamCurveArclen, PathEl}; + let Some(tp) = td.path.as_deref() else { return Err(TEXT_PATH_CANT) }; + if td.characters.contains(['\n', '\r']) { + return Err(TEXT_PATH_LINES); + } + let path = tp.path(); + let mut parts: Vec> = Vec::new(); + for el in path.elements() { + if matches!(el, PathEl::MoveTo(_)) { + parts.push(Vec::new()); + } + if let Some(part) = parts.last_mut() { + part.push(*el); + } + } + let mut chains = parts.iter().filter_map(|p| path_chain(p)); + let (mut net, cycle) = chains.next().ok_or(TEXT_PATH_CANT)?; + let later_parts = chains.next().is_some(); + if net.vertices.len() + net.segments.len() > MAX_NETWORK { + return Err(TEXT_PATH_CANT); + } + // The import scales the coordinates by size over normalized size, which are the same number + // here; an axis of no extent holds nothing but zeros. + let size = |x: f64| f64::from(finite(x) as f32); + for (extent, axis) in [(size(w), 0), (size(h), 1)] { + let at = |p: (f64, f64)| if axis == 0 { p.0 } else { p.1 }; + let flat = net.vertices.iter().all(|v| at((v.x, v.y)) == 0.0) && net.segments.iter().all(|s| at(s.ta) == 0.0 && at(s.tb) == 0.0); + if extent < 0.0 || (extent <= 1e-9 && (extent != 0.0 || !flat)) { + return Err(TEXT_PATH_CANT); + } + } + let lengths: Vec = net.segments.iter().map(|s| net_length(&net, s)).collect(); + let total: f64 = lengths.iter().sum(); + if !total.is_finite() || total <= 1e-10 { + return Err(TEXT_PATH_CANT); + } + // The path the import builds from it must be one the text renderer can measure. + let mut shape = figcraft_doc::geom::BezPath::new(); + for (i, s) in net.segments.iter().enumerate() { + let Some((c, line)) = net_cubic(&net, s) else { return Err(TEXT_PATH_CANT) }; + if i == 0 { + shape.move_to(c.p0); + } + if line { + shape.line_to(c.p3); + } else { + shape.curve_to(c.p1, c.p2, c.p3); + } + } + if cycle { + shape.close_path(); + } + let measured = figcraft_doc::geom::measure::polylines(&shape); + if measured.as_ref().and_then(|l| l.first()).is_none_or(|l| l.length() <= 1e-9) { + return Err(TEXT_PATH_CANT); + } + // The start, by length, as a parameter of the segment it falls on. + let start = tp.start(); + let at = (if tp.flip { 1.0 - start } else { start }) * total; + let mut before = 0.0; + let mut k = lengths.len().saturating_sub(1); + for (i, len) in lengths.iter().enumerate() { + if before + len >= at { + k = i; + break; + } + before += len; + } + if k + 1 == lengths.len() && before + lengths[k] < at { + before = total - lengths[k]; + } + let local = (at - before).clamp(0.0, lengths[k]); + let t = match net.segments.get(k).and_then(|s| net_cubic(&net, s)) { + Some((_, true)) | None => local / lengths[k], + Some((c, false)) => c.inv_arclen(local, 1e-9), + }; + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + if let Some(s) = net.segments.get_mut(k) { + s.style = TEXT_PATH_MARK; + } + Ok(PathNet { net, t, later_parts }) } diff --git a/crates/format/src/fig/text_path_tests.rs b/crates/format/src/fig/text_path_tests.rs index 8f7b46f43..0e9d0e0e8 100644 --- a/crates/format/src/fig/text_path_tests.rs +++ b/crates/format/src/fig/text_path_tests.rs @@ -83,8 +83,11 @@ fn blob() -> Vec { } fn canvas() -> Vec { + canvas_of(message(true)) +} + +fn canvas_of(message: Kv<'static>) -> Vec { let schema = super::kiwi::Schema::parse(SCHEMA).unwrap(); - let message = message(true); let message = super::kiwi::encode::message(&schema, schema.find("Message").unwrap(), &message).unwrap(); let mut out = b"fig-kiwi\0\0\0\0".to_vec(); for raw in [super::kiwi::encode::schema(&schema), message] { @@ -262,3 +265,302 @@ fn a_text_on_a_path_in_a_scaled_instance_has_its_path_scaled() { assert_eq!(path_of("Main"), "M0,0 L100,0"); assert_eq!(path_of("Half"), "M0,0 L50,0"); } + +// The `.fig` export writes text on a path. + +use figcraft_doc::geom::kurbo::PathEl; +use figcraft_doc::{Document, NodeId, TextAlignV}; + +const W1: &str = "text on a path with more than one line was written as plain text"; +const W2: &str = "text on a path the format can't hold was written as plain text"; +const W3: &str = "the parts of a text's path after the first were left out"; +const W4: &str = "text on a path in an instance but not in its main component, or the other way round, was written as the main has it"; +const MARK: u32 = 0x01ff_ffff; + +/// What an export wrote: its warnings, the layer records and the blobs. +struct Written { + warnings: Vec, + records: Vec>, + blobs: Vec>, +} + +impl Written { + fn of(doc: &Document) -> (Vec, Written) { + let (bytes, warnings) = super::export(doc, None).unwrap(); + let archive = super::Archive::open(&bytes).unwrap(); + let (schema, message) = super::decode_canvas(&archive.canvas).unwrap(); + let schema: &'static super::kiwi::Schema = Box::leak(Box::new(schema)); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let records = msg.get("nodeChanges").unwrap().list().to_vec(); + let blobs = msg + .get("blobs") + .map(|b| b.list().iter().filter_map(|x| x.get("bytes").and_then(Kv::bytes).map(<[u8]>::to_vec)).collect()) + .unwrap_or_default(); + (bytes, Written { warnings, records, blobs }) + } + + fn record(&self, name: &str) -> &Kv<'static> { + self.records.iter().find(|r| r.get("name").and_then(Kv::str) == Some(name)).unwrap_or_else(|| panic!("no record {name}")) + } + + /// The network in the blob a record's `vectorData` names. + fn network(&self, record: &Kv<'static>) -> super::network::Network { + let i = record.get("vectorData").unwrap().get("vectorNetworkBlob").and_then(Kv::f64).unwrap() as usize; + super::network::decode(self.blobs.get(i).unwrap()).unwrap() + } + + fn warned(&self, text: &str) -> bool { + self.warnings.iter().any(|w| w == text) + } +} + +fn ty<'a>(r: &'a Kv<'static>) -> &'a str { + r.get("type").and_then(Kv::str).unwrap() +} + +fn start_of(r: &Kv<'static>) -> (f64, bool) { + let s = r.get("textPathStart").unwrap_or_else(|| panic!("no textPathStart")); + (s.get("tValue").and_then(Kv::f64).unwrap(), s.get("forward").and_then(Kv::bool).unwrap()) +} + +/// A page holding one text per `(name, characters, d, start, flip, width, height)`. +fn doc_of(texts: &[(&str, &str, &str, f64, bool, f64, f64)]) -> Document { + let mut doc = Document::new("paths"); + let page = doc.first_page().unwrap(); + for (name, chars, d, start, flip, w, h) in texts { + let id = doc.create(page, NodeKind::Text(Default::default()), name, 0.0, 0.0, *w, *h).unwrap(); + let td = doc.node_mut(id).unwrap().kind.text_mut().unwrap(); + td.characters = (*chars).into(); + if !d.is_empty() || !chars.is_empty() { + td.path = Some(Box::new(TextPath { d: (*d).into(), start: *start, flip: *flip })); + } + } + doc +} + +fn text_of<'a>(doc: &'a Document, name: &str) -> &'a figcraft_doc::TextData { + let node = doc.nodes().find(|n| n.name == name).unwrap_or_else(|| panic!("no layer {name}")); + let NodeKind::Text(td) = &node.kind else { panic!("{name} is not text") }; + td +} + +fn elements(d: &str) -> Vec<(char, Vec<(f64, f64)>)> { + figcraft_doc::geom::svg_path(d) + .unwrap() + .elements() + .iter() + .map(|el| match el { + PathEl::MoveTo(p) => ('M', vec![(p.x, p.y)]), + PathEl::LineTo(p) => ('L', vec![(p.x, p.y)]), + PathEl::QuadTo(a, b) => ('Q', vec![(a.x, a.y), (b.x, b.y)]), + PathEl::CurveTo(a, b, c) => ('C', vec![(a.x, a.y), (b.x, b.y), (c.x, c.y)]), + PathEl::ClosePath => ('Z', vec![]), + }) + .collect() +} + +fn same_path(a: &str, b: &str) { + let (x, y) = (elements(a), elements(b)); + assert_eq!(x.len(), y.len(), "{a} / {b}"); + for ((ka, pa), (kb, pb)) in x.iter().zip(&y) { + assert_eq!(ka, kb, "{a} / {b}"); + for (p, q) in pa.iter().zip(pb) { + assert!((p.0 - q.0).abs() < 1e-3 && (p.1 - q.1).abs() < 1e-3, "{a} / {b}"); + } + } +} + +fn no_text_path_warning(warnings: &[String]) { + assert!(!warnings.iter().any(|w| w.contains("text path") || w.contains("text off its path")), "{warnings:?}"); +} + +#[test] +fn a_text_on_a_path_survives_a_fig_export() { + let (doc, _) = super::import(&canvas(), "Text path").unwrap(); + let (bytes, warnings) = super::export(&doc, None).unwrap(); + assert!(!warnings.iter().any(|w| w.contains("text on a path")), "{warnings:?}"); + let (_, w) = Written::of(&doc); + let r = w.record("alpha path"); + assert_eq!(ty(r), "TEXT_PATH"); + assert_eq!(start_of(r), (0.5, true)); + assert_eq!(r.get("textAlignVertical").and_then(Kv::str), Some("TOP")); + let normalized = r.get("vectorData").unwrap().get("normalizedSize").unwrap(); + let size = r.get("size").unwrap(); + for k in ["x", "y"] { + assert_eq!(normalized.get(k).and_then(Kv::f64), size.get(k).and_then(Kv::f64)); + } + assert_eq!((size.get("x").and_then(Kv::f64), size.get("y").and_then(Kv::f64)), (Some(100.0), Some(0.0))); + let net = w.network(r); + assert_eq!(net.vertices.iter().map(|v| (v.x, v.y)).collect::>(), [(0.0, 0.0), (100.0, 0.0)]); + assert_eq!(net.segments.len(), 1); + assert_eq!((net.segments[0].style, net.segments[0].ta, net.segments[0].tb), (MARK, (0.0, 0.0), (0.0, 0.0))); + assert!(net.regions.is_empty()); + let (back, import_warnings) = super::import(&bytes, "Back").unwrap(); + no_text_path_warning(&import_warnings); + let td = text_of(&back, "alpha path"); + assert_eq!(td.path.as_deref(), Some(&TextPath { d: "M0,0 L100,0".into(), start: 0.5, flip: false })); + assert_eq!(td.characters, "alpha"); + assert_eq!((td.runs.len(), td.runs[0].start, td.runs[0].end), (1, 3, 5)); +} + +#[test] +fn the_start_is_written_by_length_from_either_side() { + const CURVE: &str = "M0,82.5 C70,-27.5 230,-27.5 300,82.5 C370,192.5 530,192.5 600,82.5"; + let mut doc = doc_of(&[ + ("far", "alpha", CURVE, 0.7490379757, false, 600.0, 165.0), + ("near", "alpha", CURVE, 0.004744078, false, 600.0, 165.0), + ("flipped", "alpha", "M0,0 L600,0", 0.16013986, true, 600.0, 0.0), + ]); + let page = doc.first_page().unwrap(); + doc.create(page, NodeKind::Text(Default::default()), "plain", 0.0, 0.0, 50.0, 20.0).unwrap(); + let (bytes, w) = Written::of(&doc); + let marked = |name: &str| -> (usize, f64, bool) { + let r = w.record(name); + let net = w.network(r); + let at: Vec = net.segments.iter().enumerate().filter(|(_, s)| s.style == MARK).map(|(i, _)| i).collect(); + assert_eq!(at.len(), 1, "{name}"); + let (t, forward) = start_of(r); + (at[0], t, forward) + }; + let (i, t, forward) = marked("far"); + assert_eq!((i, forward), (1, true)); + assert!((t - 0.49800667).abs() < 1e-5, "{t}"); + let (i, t, forward) = marked("near"); + assert_eq!((i, forward), (0, true)); + assert!((t - 0.0086954795).abs() < 1e-5, "{t}"); + assert!((t - 0.009488156).abs() > 5e-4, "{t}"); + let (i, t, forward) = marked("flipped"); + assert_eq!((i, forward), (0, false)); + assert!((t - 0.83986014).abs() < 1e-6, "{t}"); + let plain = w.record("plain"); + assert_eq!(ty(plain), "TEXT"); + assert!(plain.get("textPathStart").is_none() && plain.get("vectorData").is_none()); + let (back, _) = super::import(&bytes, "Back").unwrap(); + for (name, d, start, flip) in + [("far", CURVE, 0.7490379757, false), ("near", CURVE, 0.004744078, false), ("flipped", "M0,0 L600,0", 0.16013986, true)] + { + let path = text_of(&back, name).path.as_deref().unwrap_or_else(|| panic!("{name} lost its path")); + same_path(&path.d, d); + assert!((path.start - start).abs() < 1e-6, "{name}: {}", path.start); + assert_eq!(path.flip, flip, "{name}"); + } +} + +#[test] +fn a_closed_path_is_written_as_a_cycle() { + let doc = doc_of(&[("square", "alpha", "M0,0 L100,0 L100,100 L0,100 Z", 0.3, false, 100.0, 100.0)]); + let (bytes, w) = Written::of(&doc); + let r = w.record("square"); + let net = w.network(r); + assert_eq!((net.vertices.len(), net.segments.len()), (4, 4)); + assert_eq!(net.segments.iter().map(|s| (s.a, s.b)).collect::>(), [(0, 1), (1, 2), (2, 3), (3, 0)]); + assert_eq!(net.segments.iter().map(|s| s.style).collect::>(), [0, MARK, 0, 0]); + assert!((start_of(r).0 - 0.2).abs() < 1e-6); + let come_back = |bytes: &[u8]| { + let (back, warnings) = super::import(bytes, "Back").unwrap(); + no_text_path_warning(&warnings); + text_of(&back, "square").path.as_deref().unwrap().clone() + }; + let once = come_back(&bytes); + same_path(&once.d, "M100,0 L100,100 L0,100 L0,0 L100,0 Z"); + assert!((once.start - 0.05).abs() < 1e-6, "{}", once.start); + let (back, _) = super::import(&bytes, "Back").unwrap(); + let (again, _) = super::export(&back, None).unwrap(); + let twice = come_back(&again); + same_path(&twice.d, &once.d); + assert!((twice.start - once.start).abs() < 1e-6); + + let open_end = doc_of(&[("tri", "alpha", "M0,0 L100,0 L100,100 L0,0", 0.5, false, 100.0, 100.0)]); + let (_, w) = Written::of(&open_end); + let net = w.network(w.record("tri")); + assert_eq!(net.vertices.len(), 3); + assert_eq!(net.segments.iter().map(|s| (s.a, s.b)).collect::>(), [(0, 1), (1, 2), (2, 0)]); +} + +#[test] +fn paths_the_format_cant_hold_fall_back_with_their_own_warning() { + let plain = |doc: &Document, warning: &str| { + let (bytes, w) = Written::of(doc); + assert!(w.warned(warning), "{:?}", w.warnings); + let r = w.record("t"); + assert_eq!(ty(r), "TEXT"); + assert!(r.get("textPathStart").is_none() && r.get("vectorData").is_none()); + let (back, warnings) = super::import(&bytes, "Back").unwrap(); + assert!(text_of(&back, "t").path.is_none()); + assert!(!warnings.iter().any(|x| x.contains("text path")), "{warnings:?}"); + }; + plain(&doc_of(&[("t", "al\npha", "M0,0 L100,0", 0.5, false, 100.0, 0.0)]), W1); + plain(&doc_of(&[("t", "alpha", "M0,5 L100,5", 0.5, false, 100.0, 0.0)]), W2); + let mut empty = doc_of(&[("t", "alpha", "", 0.5, false, 100.0, 20.0)]); + let id = empty.nodes().find(|n| n.name == "t").unwrap().id; + empty.node_mut(id).unwrap().kind.text_mut().unwrap().path = Some(Box::new(TextPath { d: String::new(), start: 0.5, flip: false })); + plain(&empty, W2); + + // Vertical alignment: written as top, still on its path. + let mut middle = doc_of(&[("t", "alpha", "M0,0 L100,0", 0.5, false, 100.0, 0.0)]); + let id = middle.nodes().find(|n| n.name == "t").unwrap().id; + middle.node_mut(id).unwrap().kind.text_mut().unwrap().align_v = TextAlignV::Middle; + let (bytes, w) = Written::of(&middle); + assert!(!w.warnings.iter().any(|x| x.contains("text on a path")), "{:?}", w.warnings); + assert_eq!(w.record("t").get("textAlignVertical").and_then(Kv::str), Some("TOP")); + let (back, _) = super::import(&bytes, "Back").unwrap(); + assert!(text_of(&back, "t").path.is_some()); + + // Several parts: the first. + let (bytes, w) = Written::of(&doc_of(&[("t", "alpha", "M0,0 L100,0 M0,50 L100,50", 0.5, false, 100.0, 50.0)])); + assert!(w.warned(W3), "{:?}", w.warnings); + let (back, _) = super::import(&bytes, "Back").unwrap(); + let path = text_of(&back, "t").path.as_deref().unwrap(); + same_path(&path.d, "M0,0 L100,0"); + assert!((path.start - 0.5).abs() < 1e-6); + + // A zero-length segment is dropped. + let (bytes, w) = Written::of(&doc_of(&[("t", "alpha", "M0,0 L0,0 L100,0", 0.5, false, 100.0, 0.0)])); + assert!(!w.warnings.iter().any(|x| x.contains("text on a path")), "{:?}", w.warnings); + let (back, _) = super::import(&bytes, "Back").unwrap(); + same_path(&text_of(&back, "t").path.as_deref().unwrap().d, "M0,0 L100,0"); + + // A closed path of one segment. + let (bytes, w) = Written::of(&doc_of(&[("t", "alpha", "M0,0 C100,-100 -100,-100 0,0 Z", 0.5, false, 100.0, 100.0)])); + assert!(!w.warnings.iter().any(|x| x.contains("text on a path")), "{:?}", w.warnings); + let (back, _) = super::import(&bytes, "Back").unwrap(); + let els = elements(&text_of(&back, "t").path.as_deref().unwrap().d); + assert_eq!(els.first().map(|e| e.1[0]), Some((0.0, 0.0))); + let last = els.iter().rev().find(|e| e.0 != 'Z').unwrap(); + assert_eq!(last.1.last().copied(), Some((0.0, 0.0))); +} + +#[test] +fn an_instance_layer_on_a_path_survives_a_fig_export() { + let (doc, _) = super::import(&canvas_of(scaled_instance_message()), "Scaled path").unwrap(); + let (bytes, warnings) = super::export(&doc, None).unwrap(); + assert!(!warnings.iter().any(|w| w.contains("text on a path")), "{warnings:?}"); + let (back, _) = super::import(&bytes, "Back").unwrap(); + let path_of = |doc: &Document, parent: &str| { + let parent = doc.nodes().find(|n| n.name == parent).unwrap(); + let node = doc.node(parent.children[0]).unwrap(); + let NodeKind::Text(text) = &node.kind else { panic!("expected text") }; + text.path.as_deref().map(|p| p.d.clone()) + }; + assert_eq!(path_of(&back, "Main").as_deref(), Some("M0,0 L100,0")); + assert_eq!(path_of(&back, "Half").as_deref(), Some("M0,0 L50,0")); + + // A layer in an instance that isn't on a path where its main's layer is. + let mut cleared = doc; + let half: NodeId = cleared.nodes().find(|n| n.name == "Half").unwrap().children[0]; + cleared.node_mut(half).unwrap().kind.text_mut().unwrap().path = None; + let (_, w) = Written::of(&cleared); + assert!(w.warned(W4), "{:?}", w.warnings); +} + +#[test] +fn the_schema_numbers_text_on_a_path() { + let s = super::kiwi::Schema::parse(super::export::SCHEMA).unwrap(); + let def = |n: &str| s.defs.iter().find(|d| d.name == n).unwrap(); + assert_eq!(def("NodeType").fields.iter().find(|x| x.name == "TEXT_PATH").map(|x| x.value), Some(41)); + assert_eq!(def("NodeChange").fields.iter().find(|x| x.name == "textPathStart").map(|x| x.value), Some(432)); + let start = def("TextPathStart"); + assert!(matches!(start.kind, super::kiwi::Kind::Message)); + let fields: Vec<_> = start.fields.iter().map(|x| (x.name.as_str(), x.value)).collect(); + assert_eq!(fields, [("tValue", 1), ("forward", 2)]); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2d62d68d5..e14e05eae 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-12 · **Change:** minor (`.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.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-12 · **Change:** minor (`.fig` export writes text on a path (#2323); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.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 @@ -94,7 +94,7 @@ scales and empty-style clears; they have not been checked in other software. - **Written:** pages (name, background); frames, groups, sections, rectangles (as rounded rectangles, with their four radii), ellipses (arcs), polygons, stars, lines, vectors (editable network blobs with per-point corner radius, handle mirroring, caps and joins, plus the outline of - their filled areas), text, boolean groups, slices; the fill outline of frames and shapes and the + their filled areas), text, text on a path (the first part of its path, where the text starts and its side), boolean groups, slices; the fill outline of frames and shapes and the stroke outline of plain strokes (a ring around boxes and whole ellipses, the widened path of other centred strokes); solid, gradient (handles as the paint transform) and image paints (the image bytes, named by their SHA-1, scale mode, @@ -141,7 +141,7 @@ scales and empty-style clears; they have not been checked in other software. with the width on both sides when the shape has a fill too), pattern fills, WebP export settings (written as PNG), image adjustments, glass settings other than frost, springs other than Gentle (written as ease out), set-variable, set-variable-mode and conditional actions, scroll-to offsets, text decoration - looks, variable font axes, text on a path, nested list levels, OpenType features, per-layer operations inside boolean groups, different stroke ends + looks, variable font axes, text on a path with more than one line or on a path the format can't hold (written as plain text), the parts of a text's path after the first, text on a path in an instance but not in its main or the other way round (written as the main has it), nested list levels, OpenType features, per-layer operations inside boolean groups, different stroke ends on lines, the Dash cap (no public name for it). Not written at all: stroke outlines of dashed and per-side strokes and of inside or outside strokes on polygons, stars and vectors, glyph outlines of text (a reader lays text out with its own fonts), version history and branches. @@ -195,6 +195,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | M6, #2323: the `.fig` export writes text on a path as the format's own layer kind (`TEXT_PATH`): the first part of its path as a vector network of one open or closed chain with the segment the text starts on marked, the start as that segment's own parameter (`textPathStart.tValue`, found by inverse arc length) and the side as `forward`. Vertical alignment is written as top, which is how text on a path draws. The importer already read all of it; a closed path comes back starting at the marked segment, the same curve and start point. Text with more than one line and paths the format can't hold stay plain text, the parts of a path after the first are left out, and text on a path in an instance but not in its main component (or the other way round) is written as the main has it, each with its own warning. The field numbers come from the schema of a synthetic file saved from Figma's web app. Checked through the importer only, not in other software | | 2026-11-12 | minor | M6, #2305: the `.fig` export writes a text's list spacing (`listSpacing`), hanging punctuation (`hangingPunctuation`), hanging lists (`hangingList`) and vertical trim (`leadingTrim`: none or cap height), which the importer already read. A field is written only when it differs from its default (in a design file saved by Figma, a text at the defaults carries none of the four), and an instance override that goes back to the default clears it. The warning narrows to OpenType features, which the importer does not read from a `.fig`. Checked through the importer only, not in other software. | | 2026-11-10 | minor | M4, #2222: a boolean group's corner radius and smoothing are read and written by the `.fig` importer and exporter, and by the REST importer | | 2026-11-07 | patch | Fonts, #2092: a font loaded with `text.loadFont` is the counterpart of a font uploaded to the organization, which Figma's help center ("Manage conflicting fonts") ranks first, ahead of installed fonts and the web fonts. FigCraft chose the first face added for a family and style, so the built-in Inter 4.x kept Regular, SemiBold and Bold after Inter 3.19 was loaded and only Medium refitted. A loaded face now wins over the other faces of its family and style, the latest load over earlier ones; style matching and fallbacks are unchanged, and `refitted` lists the text whose size changes. Installed versus built-in order is not changed here. Test: `fontdb::tests::a_loaded_face_wins_over_the_built_in_one_of_its_family_and_style`. Numbers unchanged. | From a243f0b81dbc237abffd82c320b231dce1001db1 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 00:11:55 -0500 Subject: [PATCH 08/12] M6: the .fig export keeps a text path's curves exact, and its instance test checks both ways round (#2323) A curve's control points are no longer rounded on their own before their offsets from the end points are taken, so a curve read from a file is written back with the offsets it had. The instance test now reads both cases of the instance warning back. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.2 reviewed; Sonnet 5.5 wrote at medium --- crates/format/src/fig/export/shape.rs | 4 +- crates/format/src/fig/text_path_tests.rs | 76 ++++++++++++++++++++++-- 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index f298e663f..6b70b6c62 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -480,7 +480,9 @@ fn path_chain(part: &[figcraft_doc::geom::kurbo::PathEl]) -> Option<(network::Ne } PathEl::CurveTo(a, b, p) => { cur = rp(*p); - add(&mut net, Some(rp(*a)), Some(rp(*b)), cur); + // The control points are not rounded on their own: the format holds each as its offset from the end + // point, and taken from the point as read that is the offset the file had. + add(&mut net, Some((finite(a.x), finite(a.y))), Some((finite(b.x), finite(b.y))), cur); } PathEl::ClosePath => closed = true, } diff --git a/crates/format/src/fig/text_path_tests.rs b/crates/format/src/fig/text_path_tests.rs index 0e9d0e0e8..154b9015d 100644 --- a/crates/format/src/fig/text_path_tests.rs +++ b/crates/format/src/fig/text_path_tests.rs @@ -545,12 +545,24 @@ fn an_instance_layer_on_a_path_survives_a_fig_export() { assert_eq!(path_of(&back, "Main").as_deref(), Some("M0,0 L100,0")); assert_eq!(path_of(&back, "Half").as_deref(), Some("M0,0 L50,0")); - // A layer in an instance that isn't on a path where its main's layer is. - let mut cleared = doc; - let half: NodeId = cleared.nodes().find(|n| n.name == "Half").unwrap().children[0]; - cleared.node_mut(half).unwrap().kind.text_mut().unwrap().path = None; - let (_, w) = Written::of(&cleared); + // A layer in an instance that isn't on a path where its main's layer is: it comes back on the main's path. + let off = |parent: &str| { + let mut doc = doc.clone(); + let id: NodeId = doc.nodes().find(|n| n.name == parent).unwrap().children[0]; + doc.node_mut(id).unwrap().kind.text_mut().unwrap().path = None; + doc + }; + let (bytes, w) = Written::of(&off("Half")); assert!(w.warned(W4), "{:?}", w.warnings); + let (back, _) = super::import(&bytes, "Back").unwrap(); + assert_eq!(path_of(&back, "Half").as_deref(), Some("M0,0 L50,0")); + + // The other way round: the main's layer is plain text, and so is the instance's. + let (bytes, w) = Written::of(&off("Main")); + assert!(w.warned(W4), "{:?}", w.warnings); + assert_eq!(ty(w.record("arc")), "TEXT"); + let (back, _) = super::import(&bytes, "Back").unwrap(); + assert_eq!((path_of(&back, "Main"), path_of(&back, "Half")), (None, None)); } #[test] @@ -564,3 +576,57 @@ fn the_schema_numbers_text_on_a_path() { let fields: Vec<_> = start.fields.iter().map(|x| (x.name.as_str(), x.value)).collect(); assert_eq!(fields, [("tValue", 1), ("forward", 2)]); } + +/// A text on a path of two curves whose coordinates 32-bit floats hold while their control points (a point plus its +/// tangent) need more digits, as the curves of a saved file do. +fn uneven_curve_canvas() -> Vec { + let mut blob = Vec::new(); + let u32le = |out: &mut Vec, n: u32| out.extend_from_slice(&n.to_le_bytes()); + let f32le = |out: &mut Vec, n: f32| out.extend_from_slice(&n.to_le_bytes()); + for n in [3, 2, 0] { + u32le(&mut blob, n); + } + for (x, y) in [(0.1, 82.3), (300.7, 82.9), (600.3, 81.7)] { + u32le(&mut blob, 0); + f32le(&mut blob, x); + f32le(&mut blob, y); + } + for (style, a, ta, b, tb) in [(0, 0, (70.7, -110.3), 1, (-70.9, -110.1)), (MARK, 1, (70.3, 110.7), 2, (-70.1, 110.9))] { + u32le(&mut blob, style); + u32le(&mut blob, a); + f32le(&mut blob, ta.0); + f32le(&mut blob, ta.1); + u32le(&mut blob, b); + f32le(&mut blob, tb.0); + f32le(&mut blob, tb.1); + } + let identity = o(vec![("m00", f(1.0)), ("m01", f(0.0)), ("m02", f(0.0)), ("m10", f(0.0)), ("m11", f(1.0)), ("m12", f(0.0))]); + let text = node( + 2, + Some(1), + "TEXT_PATH", + vec![ + ("name", s("curve")), + ("size", point(600.5, 221.25)), + ("transform", identity), + ("textData", o(vec![("characters", s("alpha"))])), + ("fontSize", f(24.0)), + ("fontName", o(vec![("family", s("Inter")), ("style", s("Regular"))])), + ("textPathStart", o(vec![("tValue", f(0.4)), ("forward", Kv::Bool(true))])), + ("vectorData", o(vec![("vectorNetworkBlob", u(0)), ("normalizedSize", point(600.5, 221.25))])), + ], + ); + let nodes = vec![node(0, None, "DOCUMENT", vec![]), node(1, Some(0), "CANVAS", vec![]), text]; + canvas_of(o(vec![("nodeChanges", a(nodes)), ("blobs", a(vec![o(vec![("bytes", Kv::Bytes(blob))])]))])) +} + +#[test] +fn a_curve_read_from_a_file_is_written_back_as_it_was() { + let (doc, _) = super::import(&uneven_curve_canvas(), "Curve").unwrap(); + let read = text_of(&doc, "curve").path.as_deref().unwrap().clone(); + let (bytes, _) = super::export(&doc, None).unwrap(); + let (back, warnings) = super::import(&bytes, "Back").unwrap(); + no_text_path_warning(&warnings); + // The file holds a control point as its offset from the end point: taken from the point as read, it is the same offset. + assert_eq!(text_of(&back, "curve").path.as_deref(), Some(&read)); +} From c74bcd0b0ecb6df317771fbbfecc07657c0d6236 Mon Sep 17 00:00:00 2001 From: Denis Gomes <6731020+denisg0mes@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:41:48 -0500 Subject: [PATCH 09/12] M1: Paste over selection puts the copies just above the selected layer Shift+Cmd/Ctrl+V pasted into the selected layer's parent at its top-left, but appended the copies, so they went to the top of the parent's layers whatever was selected. In an auto layout frame that put them at the end of the flow, away from the layer they were pasted over. They now go just above the selected layer, in the copied order: in the Layers panel the row above it, in an auto layout frame the item after it. A section pasted over a layer in a frame still goes on the page, on top of its layers, as before. Paste to replace already kept the replaced layer's place. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/edit/clipboard.rs | 14 +++++++++++--- crates/engine/src/tests.rs | 18 ++++++++++++++++++ docs/ui-parity.md | 3 ++- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index a04bfcb5c..dbf4ec180 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -329,14 +329,22 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { let sel = s.selection(); let page = s.page()?; let doc = s.doc()?; - let (parent, at) = match sel.first() { + let (parent, at, above) = match sel.first() { Some(i) => { let parent = doc.node(*i).and_then(|n| n.parent).unwrap_or(page); - (parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0))) + (parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)), doc.index_in_parent(*i).map(|ix| ix + 1)) } - None => (page, None), + None => (page, None, None), }; let ids = paste_into(s, parent, at)?; + if let Some(above) = above { + let doc = s.doc_mut()?; + for (k, i) in + ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::>().into_iter().enumerate() + { + doc.reorder(i, above + k)?; + } + } s.set_selection(ids.clone()); Ok(json!({"ids": ids})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e983d6064..2862f3541 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -345,6 +345,24 @@ fn copy_paste_and_duplicate() { assert_eq!(d["ids"].as_array().unwrap().len(), 1); } +#[test] +fn paste_over_puts_the_copies_just_above_the_selected_layer() { + let mut s = sess(); + let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()); + let layer = + |s: &mut Session, x: f64| id(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 10, "height": 10, "parent": frame})).unwrap()); + let (a, b, c) = (layer(&mut s, 10.0), layer(&mut s, 30.0), layer(&mut s, 50.0)); + let kids = |s: &Session| s.doc().unwrap().node(frame).unwrap().children.clone(); + assert_eq!(kids(&s), vec![a, b, c]); + s.execute("edit.copy", &json!({"ids": [b, c]})).unwrap(); + s.set_selection(vec![a]); + let pasted: Vec = s.execute("edit.pasteOver", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(params::id_of).collect(); + assert_eq!(pasted.len(), 2); + assert_eq!(kids(&s), vec![a, pasted[0], pasted[1], b, c], "in the selected layer's frame, just above it, in the copied order"); + assert_eq!(s.doc().unwrap().world_bounds(pasted[0]).unwrap().x0, 10.0, "at the selected layer's position"); + assert_eq!(s.selection(), pasted); +} + #[test] fn boolean_and_flatten() { let mut s = sess(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e928b4c12..f5215a134 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-10 · **Change:** minor (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-13 · **Change:** minor (M1: Paste over selection puts the pasted layers just above the selected layer; 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: @@ -215,6 +215,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | M1: Shift+Cmd/Ctrl+V (Paste over selection) puts the pasted layers just above the selected layer, in its parent and in the copied order, at its position; they went to the top of the parent's layers, so in an auto layout frame they ended the flow instead of following the selected layer. | | 2026-11-12 | patch | M8: Tab while renaming the last layer in the Layers panel commits and opens the first row's rename, as measured in Figma's web app on 2026-11-12 (it ended the rename before); Shift+Tab on the first row is unchanged, not measured; Tab and Shift+Tab now move only the rename and leave the selection on the layer first renamed, as measured in Figma's web app on 2026-11-12 (it followed the rename before) (`tab_on_the_last_row_commits_and_wraps_to_the_first`, `tab_while_renaming_leaves_the_selection_on_the_first_layer`), Rename row | | 2026-11-09 | patch | M3, #2156: the text caret takes the text's solid fill colour (red text, red caret; light grey on a dark frame, light grey, one colour and no inversion), measured in Figma's web app: the fill of the character before the caret (the first one's at the start); FigCraft draws it opaque (how Figma treats a translucent fill was not measured); gradient, image and hidden fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour (white in the dark theme, invisible on the default light page, #2190). Width and height unchanged; collaborators' carets unchanged. Tests: `caret_tests` | | 2026-11-10 | minor | The Rotation field shows and sets the layer's rotation on the page (its own angle plus its parents' when no ancestor is flipped; with a flipped ancestor FigCraft reads the composed angle, which flips the sign of the layer's own angle, and Figma's behaviour there was not measured), in frames and groups alike, as measured in Figma's web app for rotated, unflipped parents (#2196) | From 193c3a3591685fd95ad1ff60d23fe00bfbbd4319 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 05:40:27 -0500 Subject: [PATCH 10/12] M6: the .fig export names the case of a multi-line instance text on its main's text path (#2323) An override can't take its layer off the main component's text path, so an instance text of more than one line, whose main is on a path, stays on that path in the file. The export warned the general instance mismatch for it. It now says exactly that case: "an instance's text of more than one line stays on its main component's text path in the file, as an override can't take it off". FigCraft's own import reads such a layer as plain text. The docs' Left out list names the case. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/format/src/fig/export/shape.rs | 8 +++++++- crates/format/src/fig/text_path_tests.rs | 11 +++++++++++ docs/file-format-parity.md | 2 +- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index 6b70b6c62..9ef7b2077 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -381,7 +381,11 @@ impl<'d> Exporter<'d> { if let Some(main) = main { let main_ok = matches!(&main.kind, NodeKind::Text(m) if text_path_net(m, main.width, main.height).is_ok()); if main_ok != own.is_ok() { - self.warn(TEXT_PATH_INSTANCE); + // An override can't take its layer off the main's path. So an instance text of + // more than one line, on a main that is on a path, stays on that path in the file: + // say so rather than the general mismatch (FigCraft's import reads it as plain text). + let lines = main_ok && matches!(own, Err(TEXT_PATH_LINES)); + self.warn(if lines { TEXT_PATH_INSTANCE_LINES } else { TEXT_PATH_INSTANCE }); return None; } } @@ -414,6 +418,8 @@ const TEXT_PATH_CANT: &str = "text on a path the format can't hold was written a const TEXT_PATH_PARTS: &str = "the parts of a text's path after the first were left out"; const TEXT_PATH_INSTANCE: &str = "text on a path in an instance but not in its main component, or the other way round, was written as the main has it"; +const TEXT_PATH_INSTANCE_LINES: &str = + "an instance's text of more than one line stays on its main component's text path in the file, as an override can't take it off"; /// A text's path as the format holds it: one chain (or cycle) of a vector network with the /// segment the text starts on marked, and the start as that segment's own parameter. diff --git a/crates/format/src/fig/text_path_tests.rs b/crates/format/src/fig/text_path_tests.rs index 154b9015d..ec1e20bdd 100644 --- a/crates/format/src/fig/text_path_tests.rs +++ b/crates/format/src/fig/text_path_tests.rs @@ -275,6 +275,8 @@ const W1: &str = "text on a path with more than one line was written as plain te const W2: &str = "text on a path the format can't hold was written as plain text"; const W3: &str = "the parts of a text's path after the first were left out"; const W4: &str = "text on a path in an instance but not in its main component, or the other way round, was written as the main has it"; +const W4_LINES: &str = + "an instance's text of more than one line stays on its main component's text path in the file, as an override can't take it off"; const MARK: u32 = 0x01ff_ffff; /// What an export wrote: its warnings, the layer records and the blobs. @@ -557,6 +559,15 @@ fn an_instance_layer_on_a_path_survives_a_fig_export() { let (back, _) = super::import(&bytes, "Back").unwrap(); assert_eq!(path_of(&back, "Half").as_deref(), Some("M0,0 L50,0")); + // An instance's text of two lines on a main that is on a path: the override can't leave the + // path, so the warning names that case, not the general mismatch. + let mut two = doc.clone(); + let id: NodeId = two.nodes().find(|n| n.name == "Half").unwrap().children[0]; + two.node_mut(id).unwrap().kind.text_mut().unwrap().characters = "al\npha".into(); + let (_, w) = Written::of(&two); + assert!(w.warned(W4_LINES), "{:?}", w.warnings); + assert!(!w.warned(W4), "{:?}", w.warnings); + // The other way round: the main's layer is plain text, and so is the instance's. let (bytes, w) = Written::of(&off("Main")); assert!(w.warned(W4), "{:?}", w.warnings); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 47bab36b7..2dc0e240b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -141,7 +141,7 @@ scales and empty-style clears; they have not been checked in other software. with the width on both sides when the shape has a fill too), pattern fills, WebP export settings (written as PNG), image adjustments, glass settings other than frost, springs other than Gentle (written as ease out), set-variable, set-variable-mode and conditional actions, scroll-to offsets, text decoration - looks, variable font axes, text on a path with more than one line or on a path the format can't hold (written as plain text), the parts of a text's path after the first, text on a path in an instance but not in its main or the other way round (written as the main has it), nested list levels, OpenType features, per-layer operations inside boolean groups, different stroke ends + looks, variable font axes, text on a path with more than one line or on a path the format can't hold (written as plain text), the parts of a text's path after the first, text on a path in an instance but not in its main or the other way round (written as the main has it), an instance's text of more than one line on a main on a path (it stays on that path, as an override can't take it off), nested list levels, OpenType features, per-layer operations inside boolean groups, different stroke ends on lines, the Dash cap (no public name for it). Not written at all: stroke outlines of dashed and per-side strokes and of inside or outside strokes on polygons, stars and vectors, glyph outlines of text (a reader lays text out with its own fonts), version history and branches. From 34ccbc83b6c0e4c7b1b777a5cadaa6f28a780bdc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 14:57:10 +0000 Subject: [PATCH 11/12] ci: prefetch dependencies before Sonar coverage --- .github/workflows/sonarcloud.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 50616c871..a8872386f 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -16,8 +16,8 @@ concurrency: jobs: sonarcloud: - # Pin the coverage setup that checks out this repo's pinned craft-i18n data. - uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@ea24c9c24e1997238334182160f60e602e5bce32 + # Pin the coverage setup that provisions test data and fetches locked dependencies before offline metadata tests. + uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@5008f8cd1b011b35eed223a7d058d7a8e9075ef6 with: # The shared coverage archive's shards omit the CLI executable used by integration tests. # Run this repository's suite in one instrumented job and provide its pinned test data. From d5cdba8d3b7f5270f918f398cb9b2be2a668e44e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 15:56:31 +0000 Subject: [PATCH 12/12] Isolate concurrent font integration tests --- apps/figcraft-cli/tests/it/fonts.rs | 25 ++++++++++++++++++++++--- crates/text/src/fontdb_tests.rs | 14 ++++++++++++-- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/apps/figcraft-cli/tests/it/fonts.rs b/apps/figcraft-cli/tests/it/fonts.rs index 998665c48..a42fd9ce5 100644 --- a/apps/figcraft-cli/tests/it/fonts.rs +++ b/apps/figcraft-cli/tests/it/fonts.rs @@ -2,15 +2,21 @@ //! `--no-system-fonts` or `FIGCRAFT_NO_SYSTEM_FONTS=1` opts out. use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; use serde_json::{Value, json}; /// The result of one `figcraft-cli run` step (script file `name`); `opt_out` sets the environment /// variable. fn run_one(name: &str, step: Value, args: &[&str], opt_out: bool) -> Value { + static NEXT_SCRIPT: AtomicU64 = AtomicU64::new(0); let d = std::env::temp_dir().join(format!("figcraft-cli-fonts-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); - let script = d.join(format!("{name}.json")); + // Tests in this binary run concurrently. `sketch_imports_keep_to_no_system_fonts` also calls + // `families`, so a shared `families.json` could be truncated while another child reads it; + // an empty script is valid and makes the CLI exit successfully without printing result JSON. + let sequence = NEXT_SCRIPT.fetch_add(1, Ordering::Relaxed); + let script = d.join(format!("{name}-{sequence}.json")); std::fs::write(&script, json!([step]).to_string()).unwrap(); let mut cmd = Command::new(env!("CARGO_BIN_EXE_figcraft-cli")); cmd.arg("run").arg(&script).args(args); @@ -20,8 +26,21 @@ fn run_one(name: &str, step: Value, args: &[&str], opt_out: bool) -> Value { cmd.env_remove("FIGCRAFT_NO_SYSTEM_FONTS"); } let out = cmd.output().unwrap(); - assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); - let line: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert!( + out.status.success(), + "{name}: CLI status {:?}; stdout={:?}; stderr={}", + out.status.code(), + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + let line: Value = serde_json::from_slice(&out.stdout).unwrap_or_else(|error| { + panic!( + "{name} {:?}: CLI returned success without JSON: {error}; stdout={:?}; stderr={}", + args, + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ) + }); line["result"].clone() } diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index a3dd15396..bf459fe06 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -376,9 +376,19 @@ fn font_bytes_load_into_the_db() { let families = load_font_bytes(f.bytes.to_vec()); assert_eq!(families.len(), 1); assert!(families.iter().all(|f| has_family(f))); - let faces = db().read().unwrap().face_count(); + // The global face count can grow here when another test finishes the concurrent system + // font scan. Count explicitly loaded faces from this family so the idempotency assertion + // stays isolated from unrelated installed fonts. + let loaded_faces = || { + let db = db().read().unwrap(); + families + .iter() + .map(|family| db.faces.iter().filter(|face| face.loaded > 0 && face.family.eq_ignore_ascii_case(family)).count()) + .collect::>() + }; + let faces = loaded_faces(); assert_eq!(load_font_bytes(f.bytes.to_vec()), families); - assert_eq!(db().read().unwrap().face_count(), faces); + assert_eq!(loaded_faces(), faces); } }