From 9e3ab8e43d0428e552eb27fc7d92c1cbcaa49dfe Mon Sep 17 00:00:00 2001 From: mahmoud Date: Sat, 7 Nov 2026 12:55:45 +0330 Subject: [PATCH 001/129] M10: render Persian and Arabic in default web builds --- Cargo.lock | 1 + ROADMAP.md | 6 +- crates/text/Cargo.toml | 7 + crates/text/build.rs | 211 +++++++++++++++++----- crates/text/src/embedded.rs | 88 +++++++++ crates/text/src/fontdb.rs | 2 +- crates/text/src/lib.rs | 2 + crates/text/tests/support/web_fallback.rs | 82 +++++++++ docs/localization-parity.md | 20 +- docs/translating.md | 31 ++-- 10 files changed, 376 insertions(+), 74 deletions(-) create mode 100644 crates/text/src/embedded.rs create mode 100644 crates/text/tests/support/web_fallback.rs diff --git a/Cargo.lock b/Cargo.lock index 5fdb9e27b..4202fbee6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2084,6 +2084,7 @@ dependencies = [ "craft-font-catalog", "figcraft-doc", "figcraft-geom", + "flate2", "harfrust 0.13.3", "icu_segmenter", "log", diff --git a/ROADMAP.md b/ROADMAP.md index a574499c0..289d371e7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -104,7 +104,7 @@ native speakers' reviews of the nine language drafts need people. | Traditional Chinese (Taiwan) | zh-Hant | 2,647 / 2,647 entries (100%, counted 2026-11-03) | draft (needs native review) | | Spanish | es, es-419 | 100% (es-419: an overlay of 101 entries) | draft (needs native review) | | Hindi | hi | 0% | none | -| Arabic | ar | 2,508 / 2,508 entries (100%, counted 2026-10-28) | draft; the window mirrors (panels swap sides); native review and mirrored panel rows pending | +| Arabic | ar | 2,508 / 2,508 entries (100%, counted 2026-10-28) | draft; web builds with craft-fonts offer Arabic by default; the window mirrors (panels swap sides); native review and mirrored panel rows pending | | French | fr | 95% | draft (needs native review) | | Portuguese (Brazil) | pt-BR | 95% | draft (needs native review) | | Indonesian | id | 99% | draft (needs native review) | @@ -133,6 +133,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log +- **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. - **2026-11-05** · M2, #1823: Suggest auto layout is its own command. `layout.suggest` used to run `layout.add` and made one row of everything. It now splits a frame's layers into rows or columns by the gaps between them, wraps each band of several layers in a hugging frame without fill and repeats inside it, so the design gets as many auto layout frames as it needs and keeps its placement where the gaps are even (the frame keeps its size). Uneven gaps, bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes are reported as `warnings`, and instances and layers inside them are refused. `layout.add` is unchanged. Tests in `layout_suggest_tests.rs`. Numbers unchanged. - **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row. - **2026-11-05** · M10, #2014: the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each; Bengali and Thai keep `crate::cjk`'s choice), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`. @@ -364,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index aea3d3be5..23b658e9d 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -8,6 +8,12 @@ description = "FigCraft text: font database (embedded craft-fonts + system fonts [lints] workspace = true +[build-dependencies] +flate2 = { workspace = true } + +[dev-dependencies] +flate2 = { workspace = true } + [dependencies] figcraft-geom = { workspace = true } figcraft-doc = { workspace = true } @@ -34,6 +40,7 @@ craft-font-catalog = { workspace = true } # wasm) instead of its dictionaries (~1.8 MB, which would take the .wasm past the 24 MiB gate in # packaging/web/package.sh). [target.'cfg(target_arch = "wasm32")'.dependencies] +flate2 = { workspace = true } icu_segmenter = { workspace = true, features = ["lstm"] } [target.'cfg(target_os = "macos")'.dependencies] diff --git a/crates/text/build.rs b/crates/text/build.rs index 796079968..38851f316 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -1,11 +1,13 @@ //! Embeds the optional craft-fonts build input (`CRAFT_FONTS_DIR`): both `fonts/manifest.txt` and the //! opt-in Latin presentation fonts in `fonts/latin-manifest.txt` (Inter, Roboto, …). Unset or missing, //! `CRAFT_FONTS` is empty and native apps use system fonts. Required web releases enforce Inter -//! Regular/SemiBold and Noto Sans Georgian Regular after filtering. Recipe: craft-fonts `docs/integration.md`. +//! Regular/SemiBold, Noto Sans Georgian Regular and Noto Sans Arabic Regular after filtering. +//! Recipe: craft-fonts `docs/integration.md`. //! Noto Sans CJK only with `FIGCRAFT_EMBED_CJK` set (the web build's only way to show CJK UI text). -//! The other scripts' faces (Noto Sans Arabic, Hebrew, Thai, Devanagari…) stay out of web builds unless -//! `FIGCRAFT_EMBED_SCRIPTS` names their script tags (`Arab,Hebr,Thai,Deva`: one tag per script wanted, -//! as the manifest's scripts column lists them; #1902). +//! Noto Sans Arabic is included by default so Persian and Arabic remain readable without local fonts +//! (#1902). Other scripts' faces (Hebrew, Thai, Devanagari…) stay out of web builds unless +//! `FIGCRAFT_EMBED_SCRIPTS` names their script tags (`Hebr,Thai,Deva`: one tag per script wanted, +//! as the manifest's scripts column lists them). //! `FIGCRAFT_WEB_FONTS` (comma-separated families) adds manifest families to the web build. use std::fmt::Write as _; use std::path::PathBuf; @@ -20,19 +22,31 @@ fn main() { println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_CJK"); println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_SCRIPTS"); println!("cargo::rerun-if-env-changed=FIGCRAFT_WEB_FONTS"); - let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n"); let dir = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); let embed_cjk = std::env::var_os("FIGCRAFT_EMBED_CJK").is_some(); let embed_scripts = scripts_from(std::env::var("FIGCRAFT_EMBED_SCRIPTS").ok().as_deref()); let web_fonts = web_fonts(&std::env::var("FIGCRAFT_WEB_FONTS").unwrap_or_default()); - match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &embed_scripts, &web_fonts) { + let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()); + // Compress the complete web catalog so adding the Arabic fallback stays within the WASM + // size budget. Each face is restored once, byte-for-byte, before the existing font consumers. + let mut src = if wasm { + String::from( + "pub static CRAFT_FONTS: std::sync::LazyLock> = std::sync::LazyLock::new(|| {\n static PACKED: &[(&str, &str, &crate::embedded::PackedFont)] = &[\n", + ) + } else { + String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n") + }; + match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &embed_scripts, &web_fonts, wasm.then_some(out_dir.as_path())) { Ok(entries) => src.push_str(&entries), Err(e) => println!("cargo::error={e}"), } src.push_str("];\n"); - let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs"); + if wasm { + src.push_str(" PACKED.iter().filter_map(|(family, style, font)| Some(CraftFont { family, style, bytes: font.data()? })).collect()\n});\n"); + } + let out = out_dir.join("craft_fonts.rs"); if let Err(e) = std::fs::write(&out, src) { println!("cargo::error=writing {}: {e}", out.display()); } @@ -64,6 +78,7 @@ fn input_fonts( embed_cjk: bool, embed_scripts: &[String], web_fonts: &[String], + packed_dir: Option<&std::path::Path>, ) -> Result { let Some(dir) = dir else { for family in web_fonts { @@ -80,7 +95,7 @@ fn input_fonts( watch(&path); continue; } - match craft_fonts(dir, manifest, wasm, embed_cjk, embed_scripts, web_fonts) { + match craft_fonts(dir, manifest, wasm, embed_cjk, embed_scripts, web_fonts, packed_dir) { Ok(catalog) => { loaded = true; out.push_str(&catalog.entries); @@ -96,7 +111,7 @@ fn input_fonts( println!("cargo::warning=FIGCRAFT_WEB_FONTS: {family:?} isn't embedded: {why}"); } if required && wasm { - for (family, style) in [("Inter", "Regular"), ("Inter", "SemiBold"), ("Noto Sans Georgian", "Regular")] { + for (family, style) in [("Inter", "Regular"), ("Inter", "SemiBold"), ("Noto Sans Georgian", "Regular"), ("Noto Sans Arabic", "Regular")] { if !faces.iter().any(|(f, s)| f == family && s == style) { return Err(format!("required web font missing: {family} {style}; CRAFT_FONTS_DIR must include both Latin and core release faces")); } @@ -135,6 +150,7 @@ fn craft_fonts( embed_cjk: bool, embed_scripts: &[String], web_fonts: &[String], + packed_dir: Option<&std::path::Path>, ) -> Result { let manifest = dir.join(manifest_rel); watch(&manifest); @@ -155,25 +171,67 @@ fn craft_fonts( if cjk && !embed_cjk { continue; } - // Web builds have a size budget: Inter, Noto Sans Georgian (small, for the Georgian UI), only the - // SemiBold wordmark, optionally Noto Sans CJK (every CJK script, for CJK UI text), the faces - // of the scripts `FIGCRAFT_EMBED_SCRIPTS` names (an Arabic or Persian document needs Noto Sans - // Arabic, +0.8 MB; the browser has no system fonts to fall back on, #1902), and the + // Web builds have a size budget: Inter, Noto Sans Georgian (small, for the Georgian UI), + // Noto Sans Arabic (Persian/Arabic would otherwise show boxes without local fonts, #1902), + // only the SemiBold wordmark, optionally Noto Sans CJK (every CJK script, for CJK + // UI text), the faces of the scripts `FIGCRAFT_EMBED_SCRIPTS` names, and the // families a distribution names in `FIGCRAFT_WEB_FONTS` (a Thai face for Thai text, say). let wordmark = *family == "Archivo" && *style == "SemiBold"; let asked = scripts.split(',').map(str::trim).any(|s| embed_scripts.iter().any(|e| e.eq_ignore_ascii_case(s))); let added = web_fonts.iter().any(|f| f == family); - if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk && !asked && !added { + if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian" | "Noto Sans Arabic") && !wordmark && !cjk && !asked && !added { continue; } let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; println!("cargo::rerun-if-changed={}", path.display()); faces.push(((*family).to_owned(), (*style).to_owned())); - let _ = writeln!(out, " CraftFont {{ family: {family:?}, style: {style:?}, bytes: include_bytes!({:?}) }},", path.display().to_string()); + if let Some(packed_dir) = packed_dir.filter(|_| wasm) { + let (packed, len) = pack_font(&path, packed_dir)?; + let _ = writeln!( + out, + " ({family:?}, {style:?}, {{ static FONT: crate::embedded::PackedFont = crate::embedded::PackedFont::new(include_bytes!({:?}), {len}); &FONT }}),", + packed.display().to_string() + ); + } else { + let _ = + writeln!(out, " CraftFont {{ family: {family:?}, style: {style:?}, bytes: include_bytes!({:?}) }},", path.display().to_string()); + } } Ok(Catalog { entries: out, faces }) } +/// Write a lossless zlib copy under OUT_DIR, never into the font checkout. A path hash avoids +/// collisions between manifest entries without using their relative paths as output paths. +fn pack_font(path: &std::path::Path, out_dir: &std::path::Path) -> Result<(PathBuf, usize), String> { + use std::hash::{Hash, Hasher}; + use std::io::{Read as _, Write as _}; + // Keep this in step with embedded::unpack: a required face must not build successfully + // only to be discarded by the runtime decoder. Limit reads too, if the input changes. + const MAX_FONT_BYTES: u64 = 256 * 1024 * 1024; + let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let len = file.metadata().map_err(|e| format!("{}: {e}", path.display()))?.len(); + if len == 0 || len > MAX_FONT_BYTES { + return Err(format!("{}: embedded font size must be 1..={MAX_FONT_BYTES} bytes", path.display())); + } + let mut bytes = Vec::new(); + file.take(MAX_FONT_BYTES + 1).read_to_end(&mut bytes).map_err(|e| format!("{}: {e}", path.display()))?; + if bytes.is_empty() || bytes.len() as u64 > MAX_FONT_BYTES { + return Err(format!("{}: embedded font size changed outside the supported range", path.display())); + } + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + encoder.write_all(&bytes).map_err(|e| format!("compressing {}: {e}", path.display()))?; + let packed = encoder.finish().map_err(|e| format!("compressing {}: {e}", path.display()))?; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + path.hash(&mut hash); + let output = out_dir.join(format!("font-{:016x}.zlib", hash.finish())); + std::fs::write(&output, packed).map_err(|e| format!("{}: {e}", output.display()))?; + Ok((output, bytes.len())) +} + +#[cfg(test)] +#[path = "tests/support/web_fallback.rs"] +mod web_fallback; + #[cfg(test)] mod tests { use super::*; @@ -181,18 +239,18 @@ mod tests { static NEXT: AtomicU64 = AtomicU64::new(0); - struct Fixture(PathBuf); + pub(super) struct Fixture(pub(super) PathBuf); impl Fixture { /// Test fixture: create a unique temporary directory, write a synthetic face file and - /// install the default Georgian manifest. - fn new() -> Self { + /// install the default Georgian and Arabic manifest. + pub(super) fn new() -> Self { let dir = std::env::temp_dir().join(format!("fig-font-input-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); std::fs::create_dir_all(dir.join("fonts")).unwrap(); // The build script validates manifest/file presence; font bytes are checked centrally. std::fs::write(dir.join("fonts/face.ttf"), b"synthetic build-input fixture").unwrap(); let fixture = Self(dir); - fixture.manifest("manifest.txt", &[("Noto Sans Georgian", "Regular")]); + fixture.manifest("manifest.txt", &[("Noto Sans Georgian", "Regular"), ("Noto Sans Arabic", "Regular")]); fixture } @@ -210,6 +268,32 @@ mod tests { } } + /// Fail at build time for sizes the runtime decoder cannot accept. + #[test] + fn web_font_compression_rejects_empty_and_oversized_inputs() { + let f = Fixture::new(); + let path = f.0.join("invalid.ttf"); + let file = std::fs::File::create(&path).unwrap(); + assert!(pack_font(&path, &f.0).unwrap_err().contains("font size")); + file.set_len(256 * 1024 * 1024 + 1).unwrap(); + assert!(pack_font(&path, &f.0).unwrap_err().contains("font size")); + } + + /// Web catalog entries embed lossless packed files; native entries still reference raw fonts. + #[test] + fn web_catalog_packs_fonts_and_native_keeps_original_bytes() { + let f = Fixture::new(); + let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &[], Some(&f.0)).unwrap(); + assert_eq!(web.entries.matches("PackedFont::new").count(), 2); + let path = f.0.join("fonts/face.ttf").canonicalize().unwrap(); + let (packed, len) = pack_font(&path, &f.0).unwrap(); + assert!(web.entries.contains(&packed.display().to_string())); + assert_eq!(len, std::fs::read(&path).unwrap().len()); + let native = craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[], &[], Some(&f.0)).unwrap(); + assert!(native.entries.contains(&path.display().to_string())); + assert!(!native.entries.contains("PackedFont")); + } + /// Asserts the native Latin catalog keeps its 43 permitted presentation faces, the web /// catalog keeps only the four Inter faces, Adobe-authored families are absent, and /// permitted native faces remain. @@ -217,9 +301,9 @@ mod tests { fn restored_latin_catalog_preserves_permitted_native_faces_and_web_budget() { let f = Fixture::new(); std::fs::write(f.0.join("fonts/latin-manifest.txt"), include_str!("tests/fixtures/latin-families.txt")).unwrap(); - let native = craft_fonts(&f.0, "fonts/latin-manifest.txt", false, false, &[], &[]).unwrap(); + let native = craft_fonts(&f.0, "fonts/latin-manifest.txt", false, false, &[], &[], None).unwrap(); assert_eq!(native.faces.len(), 43, "all prior permitted presentation faces remain available"); - let web = craft_fonts(&f.0, "fonts/latin-manifest.txt", true, false, &[], &[]).unwrap(); + let web = craft_fonts(&f.0, "fonts/latin-manifest.txt", true, false, &[], &[], None).unwrap(); assert_eq!(web.faces.len(), 4, "the web catalog keeps only the four Inter faces"); for catalog in [&native, &web] { assert!(!catalog.entries.contains("Source Sans 3")); @@ -227,30 +311,31 @@ mod tests { } assert!(native.faces.iter().any(|(family, _)| family == "Carlito")); assert!(native.faces.iter().any(|(family, _)| family == "Liberation Serif")); - assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).is_ok()); + assert!(input_fonts(Some(&f.0), true, true, false, &[], &[], None).is_ok()); } /// Asserts required web input rejects a catalog missing Inter Regular or Inter SemiBold. #[test] fn required_web_rejects_core_only_and_partial_latin_catalogs() { let f = Fixture::new(); - assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap_err().contains("Inter Regular")); + assert!(input_fonts(Some(&f.0), true, true, false, &[], &[], None).unwrap_err().contains("Inter Regular")); f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Unrelated", "SemiBold")]); - assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap_err().contains("Inter SemiBold")); + assert!(input_fonts(Some(&f.0), true, true, false, &[], &[], None).unwrap_err().contains("Inter SemiBold")); } - /// Asserts required web input embeds the Inter and Georgian catalogs (three entries) and + /// Asserts required web input embeds the Inter, Georgian and Arabic catalogs (four entries) and /// rejects a manifest without Noto Sans Georgian Regular. #[test] fn required_web_embeds_both_catalogs_and_requires_georgian() { let f = Fixture::new(); f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]); - let entries = input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap(); - assert_eq!(entries.matches("CraftFont {").count(), 3); + let entries = input_fonts(Some(&f.0), true, true, false, &[], &[], None).unwrap(); + assert_eq!(entries.matches("CraftFont {").count(), 4); assert!(entries.contains("family: \"Inter\"")); assert!(entries.contains("family: \"Noto Sans Georgian\"")); + assert!(entries.contains("family: \"Noto Sans Arabic\"")); f.manifest("manifest.txt", &[("Other", "Regular")]); - assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap_err().contains("Noto Sans Georgian Regular")); + assert!(input_fonts(Some(&f.0), true, true, false, &[], &[], None).unwrap_err().contains("Noto Sans Georgian Regular")); } /// Asserts absent font input is empty when optional and an error when required, while present @@ -258,10 +343,10 @@ mod tests { #[test] fn optional_and_native_inputs_keep_their_existing_policy() { let f = Fixture::new(); - assert!(input_fonts(None, true, false, false, &[], &[]).unwrap().is_empty()); - assert!(input_fonts(None, true, true, false, &[], &[]).unwrap_err().contains("CRAFT_FONTS_DIR is missing")); - assert!(input_fonts(Some(&f.0), true, false, false, &[], &[]).unwrap().contains("Noto Sans Georgian")); - assert!(input_fonts(Some(&f.0), false, true, false, &[], &[]).unwrap().contains("Noto Sans Georgian")); + assert!(input_fonts(None, true, false, false, &[], &[], None).unwrap().is_empty()); + assert!(input_fonts(None, true, true, false, &[], &[], None).unwrap_err().contains("CRAFT_FONTS_DIR is missing")); + assert!(input_fonts(Some(&f.0), true, false, false, &[], &[], None).unwrap().contains("Noto Sans Georgian")); + assert!(input_fonts(Some(&f.0), false, true, false, &[], &[], None).unwrap().contains("Noto Sans Georgian")); } /// Asserts required web input rejects a manifest whose face file is missing, even when every @@ -271,12 +356,38 @@ mod tests { let f = Fixture::new(); f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]); std::fs::remove_file(f.0.join("fonts/face.ttf")).unwrap(); - assert!(input_fonts(Some(&f.0), true, true, false, &[], &[]).unwrap_err().contains("fonts/face.ttf")); + assert!(input_fonts(Some(&f.0), true, true, false, &[], &[], None).unwrap_err().contains("fonts/face.ttf")); } - /// #1902: a web build leaves the other scripts' faces out (an Arabic or Persian document shows - /// missing-glyph boxes) unless `FIGCRAFT_EMBED_SCRIPTS` names their script tags; native builds - /// keep every face, as before. + /// #1902: the default web catalog needs an Arabic fallback without local-font permission + /// or an extra distribution setting; otherwise Persian and Arabic text becomes boxes. + #[test] + fn default_web_catalog_keeps_arabic_without_opt_in() { + let f = Fixture::new(); + f.manifest("manifest.txt", &[("Noto Sans Georgian", "Regular"), ("Noto Sans Arabic", "Regular"), ("Noto Sans Hebrew", "Regular")]); + let entries = input_fonts(Some(&f.0), true, false, false, &[], &[], None).unwrap(); + assert!(entries.contains("family: \"Noto Sans Arabic\""), "default web text must have an Arabic/Persian fallback"); + assert!(!entries.contains("Noto Sans Hebrew"), "other scripts remain opt-in"); + } + + /// A required web release must not silently publish without its Arabic fallback. + #[test] + fn required_web_rejects_missing_arabic_regular() { + let f = Fixture::new(); + f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]); + for arabic in [None, Some("Bold")] { + let mut faces = vec![("Noto Sans Georgian", "Regular")]; + if let Some(style) = arabic { + faces.push(("Noto Sans Arabic", style)); + } + f.manifest("manifest.txt", &faces); + let result = input_fonts(Some(&f.0), true, true, false, &[], &[], None); + assert!(result.is_err_and(|e| e.contains("Noto Sans Arabic Regular")), "missing Arabic Regular must fail the release build"); + } + } + + /// Arabic is a default fallback; other scripts stay opt-in through `FIGCRAFT_EMBED_SCRIPTS`. + /// Native builds keep every face, as before. #[test] fn web_embeds_other_scripts_faces_only_when_asked() { let f = Fixture::new(); @@ -286,18 +397,18 @@ mod tests { ) .unwrap(); let families = |c: &Catalog| c.faces.iter().map(|(f, _)| f.clone()).collect::>(); - let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &[]).unwrap(); - assert_eq!(families(&web), ["Noto Sans Georgian"], "the web budget: Georgian only"); - let arabic = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &["Arab".to_string()], &[]).unwrap(); + let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &[], None).unwrap(); + assert_eq!(families(&web), ["Noto Sans Georgian", "Noto Sans Arabic"], "the default web script fallbacks"); + let arabic = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &["Arab".to_string()], &[], None).unwrap(); assert_eq!(families(&arabic), ["Noto Sans Georgian", "Noto Sans Arabic"]); // Several tags, any case, spaces, and a tag among a face's several scripts. - let more = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &scripts_from(Some(" hebr, LATN ")), &[]).unwrap(); - assert_eq!(families(&more), ["Noto Sans Georgian", "Noto Sans Hebrew", "Noto Sans Symbols"]); + let more = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &scripts_from(Some(" hebr, LATN ")), &[], None).unwrap(); + assert_eq!(families(&more), ["Noto Sans Georgian", "Noto Sans Arabic", "Noto Sans Hebrew", "Noto Sans Symbols"]); // Native builds keep every face whatever the variable says. - assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[], &[]).unwrap().faces.len(), 4); + assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[], &[], None).unwrap().faces.len(), 4); // The variable reaches the catalog through `input_fonts`. - assert!(input_fonts(Some(&f.0), true, false, false, &["Arab".into()], &[]).unwrap().contains("Noto Sans Arabic")); - assert!(!input_fonts(Some(&f.0), true, false, false, &[], &[]).unwrap().contains("Noto Sans Arabic")); + assert!(input_fonts(Some(&f.0), true, false, false, &["Arab".into()], &[], None).unwrap().contains("Noto Sans Arabic")); + assert!(input_fonts(Some(&f.0), true, false, false, &[], &[], None).unwrap().contains("Noto Sans Arabic")); assert!(scripts_from(None).is_empty()); } @@ -311,11 +422,15 @@ mod tests { let named = web_fonts(" Noto Sans Thai, ,Noto Sans Thia "); assert_eq!(named, ["Noto Sans Thai", "Noto Sans Thia"]); let families = |c: &Catalog| c.faces.iter().map(|(family, _)| family.clone()).collect::>(); - let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &named).unwrap(); + let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &named, None).unwrap(); assert_eq!(families(&web), ["Noto Sans Georgian", "Noto Sans Thai"], "the named family joins; the others stay out"); - assert_eq!(families(&craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &[]).unwrap()), ["Noto Sans Georgian"], "unset: as before"); - assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[], &[]).unwrap().faces.len(), 3, "native builds embed every family"); + assert_eq!( + families(&craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[], &[], None).unwrap()), + ["Noto Sans Georgian"], + "unset: as before" + ); + assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[], &[], None).unwrap().faces.len(), 3, "native builds embed every family"); assert_eq!(not_embedded(&named, &web.faces), ["Noto Sans Thia"], "a misspelt family is reported"); - assert!(input_fonts(Some(&f.0), true, false, false, &[], &named).unwrap().contains("family: \"Noto Sans Thai\"")); + assert!(input_fonts(Some(&f.0), true, false, false, &[], &named, None).unwrap().contains("family: \"Noto Sans Thai\"")); } } diff --git a/crates/text/src/embedded.rs b/crates/text/src/embedded.rs new file mode 100644 index 000000000..d9be4625f --- /dev/null +++ b/crates/text/src/embedded.rs @@ -0,0 +1,88 @@ +//! Lossless decoding of web fonts, shared by the document renderer and UI through static bytes. + +use std::sync::OnceLock; + +/// Matches the font-file limit: corrupted metadata must not request an unbounded allocation. +const MAX_UNPACKED_FONT_BYTES: usize = 256 * 1024 * 1024; + +/// One embedded zlib stream, decoded at most once; invalid streams stay unavailable. +pub(crate) struct PackedFont { + bytes: &'static [u8], + unpacked_len: usize, + decoded: OnceLock>>, +} + +impl PackedFont { + pub(crate) const fn new(bytes: &'static [u8], unpacked_len: usize) -> Self { + Self { bytes, unpacked_len, decoded: OnceLock::new() } + } + + pub(crate) fn data(&'static self) -> Option<&'static [u8]> { + self.decoded.get_or_init(|| unpack(self.bytes, self.unpacked_len)).as_deref() + } +} + +/// Decode exactly the declared size, refusing malformed, incomplete or trailing data. +pub(crate) fn unpack(bytes: &[u8], unpacked_len: usize) -> Option> { + if unpacked_len == 0 || unpacked_len > MAX_UNPACKED_FONT_BYTES { + return None; + } + // A fixed output buffer prevents even a valid compressed stream expanding past its budget. + let mut decoded = Vec::new(); + decoded.try_reserve_exact(unpacked_len).ok()?; + decoded.resize(unpacked_len, 0); + let mut decoder = flate2::Decompress::new(true); + let status = decoder.decompress(bytes, &mut decoded, flate2::FlushDecompress::Finish).ok()?; + (status == flate2::Status::StreamEnd && decoder.total_out() == unpacked_len as u64 && decoder.total_in() == bytes.len() as u64).then_some(decoded) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write as _; + + // A zlib stream of the synthetic bytes "font"; no font asset is needed by these tests. + const PACKED: &[u8] = &[120, 218, 75, 203, 207, 43, 1, 0, 4, 57, 1, 184]; + + #[test] + fn compressed_bytes_round_trip_exactly() { + let original = b"synthetic font bytes\0\xff\x80\0synthetic font bytes"; + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + encoder.write_all(original).unwrap(); + let packed = encoder.finish().unwrap(); + assert_eq!(unpack(&packed, original.len()).unwrap(), original); + } + + #[test] + fn corrupt_truncated_and_trailing_streams_are_refused() { + assert!(unpack(b"not a zlib stream", 4).is_none()); + for end in 0..PACKED.len() { + assert!(unpack(&PACKED[..end], 4).is_none(), "truncated at byte {end}"); + } + let mut corrupt = PACKED.to_vec(); + corrupt[11] ^= 1; + assert!(unpack(&corrupt, 4).is_none(), "checksum mismatch"); + let mut trailing = PACKED.to_vec(); + trailing.push(0); + assert!(unpack(&trailing, 4).is_none(), "trailing bytes"); + } + + #[test] + fn declared_size_is_exact_and_bounded() { + for len in [0, 3, 5, MAX_UNPACKED_FONT_BYTES + 1, usize::MAX] { + assert!(unpack(PACKED, len).is_none(), "invalid unpacked size {len}"); + } + assert_eq!(unpack(PACKED, 4).unwrap(), b"font"); + } + + #[test] + fn decoded_bytes_and_failures_are_cached() { + static FONT: PackedFont = PackedFont::new(PACKED, 4); + static BAD: PackedFont = PackedFont::new(PACKED, 3); + let first = FONT.data().unwrap(); + assert_eq!(first, b"font"); + assert!(std::ptr::eq(first, FONT.data().unwrap())); + assert!(BAD.data().is_none()); + assert!(BAD.decoded.get().is_some_and(Option::is_none)); + } +} diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 3c82cd261..b9bb70232 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -695,7 +695,7 @@ pub fn db() -> &'static RwLock { fn raw_db() -> &'static RwLock { DB.get_or_init(|| { let mut db = FontDb::default(); - for f in CRAFT_FONTS { + for f in CRAFT_FONTS.iter() { if let Some(face) = Face::from_bytes(FontBytes::Static(f.bytes), 0, Some(f.family), Some(f.style)) { db.add(face); } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index b6d87d669..37f603464 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -9,6 +9,8 @@ mod breaks; pub mod color; pub mod display; +#[cfg(target_arch = "wasm32")] +mod embedded; pub mod fontdb; mod layout; mod onpath; diff --git a/crates/text/tests/support/web_fallback.rs b/crates/text/tests/support/web_fallback.rs new file mode 100644 index 000000000..16a930328 --- /dev/null +++ b/crates/text/tests/support/web_fallback.rs @@ -0,0 +1,82 @@ +//! Exercise shaping with the actual default web catalog, without desktop font fallbacks. + +use super::{craft_fonts, pack_font}; + +#[path = "../../src/embedded.rs"] +mod embedded; +use figcraft_text::fontdb::{Face, FontBytes}; + +#[test] +fn default_web_fonts_render_persian_and_arabic_without_system_fonts() { + let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(std::path::PathBuf::from).filter(|p| p.join("fonts/manifest.txt").is_file()) else { + eprintln!("craft-fonts is absent; build-policy fixtures still run, real-font shaping skipped"); + return; + }; + // Check source availability independently of the web filter under test. Otherwise removing + // Arabic from that filter would skip this regression instead of reproducing the boxes. + if [("Inter", "Regular"), ("Inter", "SemiBold"), ("Noto Sans Georgian", "Regular"), ("Noto Sans Arabic", "Regular")] + .iter() + .any(|(family, style)| !figcraft_text::CRAFT_FONTS.iter().any(|font| font.family == *family && font.style == *style)) + { + eprintln!("complete release font catalog is absent; build-policy fixtures still run, real-font shaping skipped"); + return; + } + let packed_dir = super::tests::Fixture::new(); + let mut faces = Vec::new(); + for manifest in ["fonts/latin-manifest.txt", "fonts/manifest.txt"] { + if dir.join(manifest).is_file() { + faces.extend(craft_fonts(&dir, manifest, true, false, &[], &[], None).unwrap().faces); + } + } + + // This integration-test process owns its font database. Native embedding includes more + // families than the web, so retain only the web build's faces and disable system discovery. + figcraft_text::opt_out_of_system_fonts(); + let has_all_inter_styles = ["Regular", "Italic", "SemiBold", "Bold"].iter().all(|style| faces.iter().any(|(f, s)| f == "Inter" && s == style)); + let mut prior_raw_bytes = 0; + let mut packed_bytes = 0; + { + let mut db = figcraft_text::db().write().unwrap(); + *db = figcraft_text::FontDb::default(); + for (family, style) in faces { + let font = figcraft_text::CRAFT_FONTS.iter().find(|f| f.family == family && f.style == style).expect("manifest face is embedded"); + // Run the build-time compressor and the exact WASM decoder before shaping. + let source = packed_dir.0.join("face.ttf"); + std::fs::write(&source, font.bytes).unwrap(); + let (packed, len) = pack_font(&source, &packed_dir.0).unwrap(); + let packed = std::fs::read(packed).unwrap(); + packed_bytes += packed.len(); + if family != "Noto Sans Arabic" { + prior_raw_bytes += font.bytes.len(); + } + let decoded = embedded::unpack(&packed, len).unwrap(); + assert_eq!(decoded, font.bytes); + db.add(Face::from_bytes(FontBytes::Shared(std::sync::Arc::new(decoded)), 0, Some(font.family), Some(font.style)).unwrap()); + } + } + + if has_all_inter_styles { + assert!(packed_bytes < prior_raw_bytes, "including Arabic must not grow the embedded web font payload"); + } + eprintln!("web font payload: {packed_bytes} compressed bytes including Arabic; {prior_raw_bytes} raw bytes before Arabic"); + + for family in ["Iran Sans", "Inter"] { + for characters in ["۴۵,۰۰۰ تومان به کیف پول بومرنگ شما واریز شد.", "مرحبا بالعالم ١٢٣"] { + let mut text = figcraft_doc::TextData::new(characters); + text.style.font_family = family.into(); + let layout = figcraft_text::layout(&text, None, None); + assert!(!layout.glyphs.is_empty()); + assert!(layout.glyphs.iter().all(|g| g.gid != 0), "missing glyphs for {family}: {characters}"); + assert!(layout.glyphs.iter().any(|g| g.face.family == "Noto Sans Arabic")); + assert!(layout.lines.first().unwrap().rtl, "Arabic/Persian paragraphs run right to left"); + if characters.starts_with('۴') { + let x = |at| layout.glyphs.iter().find(|g| g.char_start == at).unwrap().x; + assert!(x(0) < x(5), "Persian digits keep their left-to-right order inside the RTL paragraph"); + } + } + let mut joined = figcraft_doc::TextData::new("بب"); + joined.style.font_family = family.into(); + let layout = figcraft_text::layout(&joined, None, None); + assert!(layout.glyphs.iter().all(|g| g.gid != g.face.glyph_for('ب')), "adjacent Arabic letters use joined forms"); + } +} diff --git a/docs/localization-parity.md b/docs/localization-parity.md index c3490a195..81028865d 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (a right-to-left UI language (Arabic) mirrors the window: the icon rail and layers panel on the right, the Design panel on the left, popovers beside it over the canvas, egui's scroll bars, submenus and checkboxes mirrored; `FIGCRAFT_EMBED_SCRIPTS` embeds other scripts' craft-fonts faces in a web build, so Arabic and Persian documents draw there (#1902); documents: a paragraph's base direction can be forced with Text ▸ Text direction, as Add right-to-left text says (#1830); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (a right-to-left UI language (Arabic) mirrors the window: the icon rail and layers panel on the right, the Design panel on the left, popovers beside it over the canvas, egui's scroll bars, submenus and checkboxes mirrored; web builds with craft-fonts embed Noto Sans Arabic Regular by default, and required web builds reject catalogs without it, so Persian and Arabic documents draw without extra build flags (#1902); other scripts remain opt-in with `FIGCRAFT_EMBED_SCRIPTS`; documents: a paragraph's base direction can be forced with Text ▸ Text direction, as Add right-to-left text says (#1830); Bosnian draft catalog, one/few/other plurals; German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; partial review, catalog remains a draft; Arabic draft catalog, count-neutral plurals and web font gate; Thai draft catalog and Thai UI fonts; a missing translation fails no check: `cargo xtask i18n-report` lists them; Vietnamese draft catalog; string counts re-measured: 2,352 entries; Russian and Turkish catalogs reviewed by native speakers, Russian one/few/many plurals; Czech and Indonesian drafts; the Japanese draft completed; counts re-measured; Windows UI language from the first preferred language; draft catalogs catch up: every draft translates every string again; Simplified Chinese draft catalog; macOS finds its downloadable CJK system fonts (#406); string counts re-measured: 2,272 entries, the drafts at 95–99%; Swedish command labels and menu wordings; Russian, Swedish, Turkish, Czech and Indonesian listed; a duplicated paragraph removed) · **Target:** Figma Design (desktop app 126.10.7) FigCraft's interface has a localization layer with an English catalog, a Russian catalog reviewed by a native speaker, and Spanish (with a Latin American overlay), French, German, Brazilian @@ -96,11 +96,14 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v embeds Noto Sans CJK SC (+16 MB) and offers Japanese, Korean and Simplified Chinese; without a Noto Sans CJK TC face built in it leaves Traditional Chinese out too; otherwise the language picker and System leave them out. No font file is in this repo. - embeds Noto Sans CJK SC (+16 MB) and offers Japanese, Korean and Simplified Chinese; otherwise the language picker and - System leave them out. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,Thai,Deva` (one tag per script wanted, as - the craft-fonts manifest lists them) embeds those scripts' faces as well, so an Arabic or Persian - document draws in Noto Sans Arabic (+0.8 MB) instead of missing-glyph boxes (#1902), and with `Arab` - the picker offers the Arabic UI catalog too, as on the desktop. No font file is in this repo. +- **Arabic and Persian on the web:** builds with craft-fonts embed Noto Sans Arabic Regular by + default, so documents have an Arabic-script fallback and the picker offers the Arabic UI without + extra build flags (#1902). Required web builds reject a catalog without that face. Web fonts are packed + losslessly at build time and restored once at runtime to preserve the WASM size budget; other + scripts remain optional through + `FIGCRAFT_EMBED_SCRIPTS=Hebr,Thai,Deva` (one tag per script wanted, as the manifest lists them). + Noto Sans Arabic is a fallback: matching Iran Sans exactly still needs that installed font via + local font access in a browser that supports it. No font file is added to this repository. ## Languages @@ -111,10 +114,8 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v | Traditional Chinese (Taiwan) | zh-Hant | 2,647 / 2,647 (100%: 1,975 UI strings, 641 command labels, 31 menu wordings; draft, counted 2026-11-03) | yes | CJK text and IME in documents; UI text in an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC or Heiti TC (web: only with a built-in TC face); zh-TW, zh-HK, zh-MO and zh-Hant read it, an explicit Hans stays Simplified | no | draft | 1–2 (after native review) | | Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) | | Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; UI font fallback to check | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` embeds Noto Sans Arabic (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | +| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web builds with craft-fonts embed Noto Sans Arabic by default for documents and the Arabic UI (#1902); the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) | | Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; the desktop UI takes an installed Devanagari face (Nirmala UI, Kohinoor Devanagari, Noto Sans Devanagari, Lohit) for names and values (#2014); no UI catalog | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) | | French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Indonesian | id | 2,292 / 2,352 (97.4%, draft) | yes | Latin | no | draft | 1–2 (after native review) | @@ -149,6 +150,7 @@ Hindi and Arabic. | Date | Change | Summary | |---|---|---| +| 2026-11-07 | patch | M10, #1902: Noto Sans Arabic Regular joins the default web font catalog, so Persian and Arabic documents no longer need `FIGCRAFT_EMBED_SCRIPTS=Arab`. Required web builds fail if the face is missing; web fonts are packed losslessly and restored once at runtime to preserve the WASM size budget. Other script fonts stay optional. Exact Iran Sans rendering requires that installed font through supported browsers' local font access. Existing duplicate Arabic rows and the repeated web-font paragraph are consolidated, preserving the mirrored window and pending panel-row mirroring. Grades and estimates unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source and marked as a draft awaiting native review. `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it; an explicit Hans still reads Simplified Chinese. The desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled. No plural forms. Localization grade and estimates unchanged | | 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build and its size are unchanged, and with `Arab` embedded the picker offers the Arabic UI as well (`cjk::can_show`, as on the desktop). Noto Sans Hebrew, Devanagari and Georgian join Arabic and Thai among the document fallbacks, so an embedded face draws its script in an Inter document. Tests: `web_embeds_other_scripts_faces_only_when_asked` in the build script, `every_embeddable_script_face_is_a_document_fallback`. | | 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as well as Hebrew and Arabic; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | diff --git a/docs/translating.md b/docs/translating.md index 6eb472281..18158ba07 100644 --- a/docs/translating.md +++ b/docs/translating.md @@ -87,16 +87,17 @@ Traditional Chinese is left out unless that build has a Noto Sans CJK TC face. A Chinese UI puts its Chinese face first so Han takes Simplified Chinese shapes, and a Traditional Chinese UI puts an installed Noto Sans CJK TC first, then the system's Taiwan faces (Microsoft JhengHei, PingFang TC, Heiti TC), so Han takes Traditional shapes. No font is added to this -repository. Georgian is drawn in -`FIGCRAFT_EMBED_CJK=1` (Noto Sans CJK SC, +16 MB); otherwise they are left out of the picker. The other -scripts' faces (Noto Sans Arabic, Hebrew, Thai, Devanagari) join a web build only with -`FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,Thai,Deva` (one tag per script wanted, as the manifest lists them), for -documents in those scripts; with `Arab` embedded the picker offers Arabic too (#1902). A -Chinese UI puts its Chinese face first so Han takes Simplified Chinese shapes. Georgian is drawn in -craft-fonts' Noto Sans Georgian, one of the built-in faces in `theme::install_fonts`, or else in an -installed font on the desktop. Web builds keep it only when the craft-fonts they're built with has -it (`crates/text/build.rs`); the commit releases pin doesn't yet (`docs/releasing.md`), so the web -picker leaves Georgian out. A new CJK or other non-Latin language also needs its script in +repository. + +Web builds with craft-fonts embed Noto Sans Arabic Regular by default for Persian and Arabic +documents, and the picker offers Arabic without extra build flags (#1902). Required web builds +reject a catalog without that face (`crates/text/build.rs`). Web faces are compressed losslessly +at build time and restored once at runtime to preserve the WASM size budget. Additional script +faces (Noto Sans Hebrew, Thai, Devanagari) join a web build with +`FIGCRAFT_EMBED_SCRIPTS=Hebr,Thai,Deva` (one tag per script wanted, as the manifest lists them). +Georgian is drawn in craft-fonts' Noto Sans Georgian, one of the built-in faces in +`theme::install_fonts`, or else in an installed font on the desktop. Required web builds also +require Noto Sans Georgian Regular. A new CJK or other non-Latin language needs its script in `cjk::language`, or a built-in craft-fonts face. ## Arabic draft @@ -112,10 +113,12 @@ This is deliberate: the current plural `Forms` have no zero/two fields. It is no of Arabic's six CLDR categories; wording remains valid for 0, 1, 2 and larger integer counts. Arabic text uses the existing bidi/shaping and Arabic system-font fallback on desktop. Web builds -require an embedded Noto Sans Arabic face to offer Arabic. The current web font budget filters -that face out, so Arabic is not offered on the web yet. No font is added to -this repository. The interface's panels are not mirrored; this catalog does not claim a complete -right-to-left interface. Native review and representative in-app checks remain required. +with craft-fonts include Noto Sans Arabic by default and offer Arabic. This fallback makes Persian +and Arabic text readable; matching Iran Sans exactly still requires that installed font. In a +browser that supports local font access, choose “Use fonts installed on this computer…” in the +Design panel's font menu and grant the browser's permission. No font is added to this repository. +The window mirrors (the panels swap sides), but rows inside the panels keep their left-to-right +order. Native review and representative in-app checks remain required. ## Traditional Chinese (Taiwan) draft From 5bb124a6221145c450ea7d26cef1642999e5d0e7 Mon Sep 17 00:00:00 2001 From: mahmoud Date: Sat, 7 Nov 2026 13:39:07 +0330 Subject: [PATCH 002/129] M10: report packed-font failures and verify generated catalogs --- ROADMAP.md | 4 +- crates/text/build.rs | 31 +++++-- crates/text/src/embedded.rs | 55 ++++++++++-- crates/text/src/fontdb.rs | 1 + .../text/tests/support/generated_catalog.rs | 90 +++++++++++++++++++ crates/text/tests/support/web_fallback.rs | 2 + docs/localization-parity.md | 2 +- 7 files changed, 168 insertions(+), 17 deletions(-) create mode 100644 crates/text/tests/support/generated_catalog.rs diff --git a/ROADMAP.md b/ROADMAP.md index 289d371e7..ce2931505 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -133,7 +133,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log -- **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. +- **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. - **2026-11-05** · M2, #1823: Suggest auto layout is its own command. `layout.suggest` used to run `layout.add` and made one row of everything. It now splits a frame's layers into rows or columns by the gaps between them, wraps each band of several layers in a hugging frame without fill and repeats inside it, so the design gets as many auto layout frames as it needs and keeps its placement where the gaps are even (the frame keeps its size). Uneven gaps, bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes are reported as `warnings`, and instances and layers inside them are refused. `layout.add` is unchanged. Tests in `layout_suggest_tests.rs`. Numbers unchanged. - **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row. - **2026-11-05** · M10, #2014: the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each; Bengali and Thai keep `crate::cjk`'s choice), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`. @@ -365,7 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| -| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. | +| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | diff --git a/crates/text/build.rs b/crates/text/build.rs index 38851f316..1a30ee4da 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -29,6 +29,21 @@ fn main() { let embed_scripts = scripts_from(std::env::var("FIGCRAFT_EMBED_SCRIPTS").ok().as_deref()); let web_fonts = web_fonts(&std::env::var("FIGCRAFT_WEB_FONTS").unwrap_or_default()); let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()); + let entries = match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &embed_scripts, &web_fonts, wasm.then_some(out_dir.as_path())) { + Ok(entries) => entries, + Err(e) => { + println!("cargo::error={e}"); + String::new() + } + }; + let out = out_dir.join("craft_fonts.rs"); + if let Err(e) = std::fs::write(&out, catalog_source(&entries, wasm)) { + println!("cargo::error=writing {}: {e}", out.display()); + } +} + +/// Wrap generated face entries in the native static slice or lazily decoded web catalog. +fn catalog_source(entries: &str, wasm: bool) -> String { // Compress the complete web catalog so adding the Arabic fallback stays within the WASM // size budget. Each face is restored once, byte-for-byte, before the existing font consumers. let mut src = if wasm { @@ -38,18 +53,12 @@ fn main() { } else { String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n") }; - match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &embed_scripts, &web_fonts, wasm.then_some(out_dir.as_path())) { - Ok(entries) => src.push_str(&entries), - Err(e) => println!("cargo::error={e}"), - } + src.push_str(entries); src.push_str("];\n"); if wasm { - src.push_str(" PACKED.iter().filter_map(|(family, style, font)| Some(CraftFont { family, style, bytes: font.data()? })).collect()\n});\n"); - } - let out = out_dir.join("craft_fonts.rs"); - if let Err(e) = std::fs::write(&out, src) { - println!("cargo::error=writing {}: {e}", out.display()); + src.push_str(" PACKED.iter().filter_map(|(family, style, font)| Some(CraftFont { family, style, bytes: font.data(family, style)? })).collect()\n});\n"); } + src } /// The script tags `FIGCRAFT_EMBED_SCRIPTS` names (comma- or space-separated), trimmed; none when @@ -228,6 +237,10 @@ fn pack_font(path: &std::path::Path, out_dir: &std::path::Path) -> Result<(PathB Ok((output, bytes.len())) } +#[cfg(test)] +#[path = "tests/support/generated_catalog.rs"] +mod generated_catalog; + #[cfg(test)] #[path = "tests/support/web_fallback.rs"] mod web_fallback; diff --git a/crates/text/src/embedded.rs b/crates/text/src/embedded.rs index d9be4625f..fd8e2d7b5 100644 --- a/crates/text/src/embedded.rs +++ b/crates/text/src/embedded.rs @@ -13,12 +13,22 @@ pub(crate) struct PackedFont { } impl PackedFont { + /// Describe an embedded stream without decoding or allocating until it is first used. pub(crate) const fn new(bytes: &'static [u8], unpacked_len: usize) -> Self { Self { bytes, unpacked_len, decoded: OnceLock::new() } } - pub(crate) fn data(&'static self) -> Option<&'static [u8]> { - self.decoded.get_or_init(|| unpack(self.bytes, self.unpacked_len)).as_deref() + /// Restore static font bytes once, or report the unavailable face once and cache the failure. + pub(crate) fn data(&'static self, family: &str, style: &str) -> Option<&'static [u8]> { + self.decoded + .get_or_init(|| { + let bytes = unpack(self.bytes, self.unpacked_len); + if bytes.is_none() { + log::warn!("embedded font {family} {style} could not be decoded"); + } + bytes + }) + .as_deref() } } @@ -44,6 +54,7 @@ mod tests { // A zlib stream of the synthetic bytes "font"; no font asset is needed by these tests. const PACKED: &[u8] = &[120, 218, 75, 203, 207, 43, 1, 0, 4, 57, 1, 184]; + /// Binary font data survives compression without losing any byte values. #[test] fn compressed_bytes_round_trip_exactly() { let original = b"synthetic font bytes\0\xff\x80\0synthetic font bytes"; @@ -53,6 +64,7 @@ mod tests { assert_eq!(unpack(&packed, original.len()).unwrap(), original); } + /// Invalid checksums, unfinished streams and appended data never become usable font bytes. #[test] fn corrupt_truncated_and_trailing_streams_are_refused() { assert!(unpack(b"not a zlib stream", 4).is_none()); @@ -67,6 +79,7 @@ mod tests { assert!(unpack(&trailing, 4).is_none(), "trailing bytes"); } + /// The declared size is both an exact output length and a bounded allocation request. #[test] fn declared_size_is_exact_and_bounded() { for len in [0, 3, 5, MAX_UNPACKED_FONT_BYTES + 1, usize::MAX] { @@ -75,14 +88,46 @@ mod tests { assert_eq!(unpack(PACKED, 4).unwrap(), b"font"); } + /// Repeated requests reuse the same decoded allocation, including a cached decode failure. #[test] fn decoded_bytes_and_failures_are_cached() { static FONT: PackedFont = PackedFont::new(PACKED, 4); static BAD: PackedFont = PackedFont::new(PACKED, 3); - let first = FONT.data().unwrap(); + let first = FONT.data("Synthetic", "Regular").unwrap(); assert_eq!(first, b"font"); - assert!(std::ptr::eq(first, FONT.data().unwrap())); - assert!(BAD.data().is_none()); + assert!(std::ptr::eq(first, FONT.data("Synthetic", "Regular").unwrap())); + assert!(BAD.data("Synthetic", "Invalid").is_none()); assert!(BAD.decoded.get().is_some_and(Option::is_none)); } + + /// An omitted face names its family and style in a single warning, even after repeated use. + #[test] + fn unavailable_font_is_reported_once() { + struct Warnings(std::sync::Mutex>); + impl log::Log for Warnings { + /// Capture only warnings emitted by the decoder. + fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { + metadata.level() == log::Level::Warn + } + + /// Retain messages so the test can count warnings for its own face. + fn log(&self, record: &log::Record<'_>) { + if self.enabled(record.metadata()) { + self.0.lock().unwrap().push(record.args().to_string()); + } + } + + /// Messages are already stored synchronously in memory. + fn flush(&self) {} + } + static WARNINGS: Warnings = Warnings(std::sync::Mutex::new(Vec::new())); + static BAD: PackedFont = PackedFont::new(b"broken stream", 4); + log::set_logger(&WARNINGS).unwrap(); + log::set_max_level(log::LevelFilter::Warn); + assert!(BAD.data("Unavailable Test Face", "SemiBold").is_none()); + assert!(BAD.data("Unavailable Test Face", "SemiBold").is_none()); + let messages = WARNINGS.0.lock().unwrap(); + let expected = "embedded font Unavailable Test Face SemiBold could not be decoded"; + assert_eq!(messages.iter().filter(|message| message.as_str() == expected).count(), 1); + } } diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index b9bb70232..33d4d39d4 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -692,6 +692,7 @@ pub fn db() -> &'static RwLock { raw_db() } +/// Initialize and return the shared database, loading valid embedded faces exactly once. fn raw_db() -> &'static RwLock { DB.get_or_init(|| { let mut db = FontDb::default(); diff --git a/crates/text/tests/support/generated_catalog.rs b/crates/text/tests/support/generated_catalog.rs new file mode 100644 index 000000000..77b108fe4 --- /dev/null +++ b/crates/text/tests/support/generated_catalog.rs @@ -0,0 +1,90 @@ +//! Compile and execute the generated web catalog independently of Cargo and optional font assets. + +use super::{catalog_source, craft_fonts, pack_font, tests::Fixture}; +use std::fmt::Write as _; + +/// Generated Rust must preserve each face's inputs, skip rejected faces, and initialize only once. +#[test] +fn generated_web_catalog_compiles_and_initializes() { + let fixture = Fixture::new(); + let mut manifest = String::new(); + let mut expected = String::from("static EXPECTED: &[(&str, &str, &[u8], usize, Option<&[u8]>)] = &[\n"); + for (index, (family, style, bytes, accepted)) in [ + ("Inter", "SemiBold", b"first synthetic font".as_slice(), true), + ("Noto Sans Arabic", "Regular", b"second synthetic font with different bytes".as_slice(), true), + ("Noto Sans Georgian", "Regular", b"rejected synthetic font".as_slice(), false), + ] + .into_iter() + .enumerate() + { + let relative = format!("fonts/face-{index}.ttf"); + std::fs::write(fixture.0.join(&relative), bytes).unwrap(); + let source = fixture.0.join(&relative).canonicalize().unwrap(); + let (packed, _) = pack_font(&source, &fixture.0).unwrap(); + writeln!(manifest, "{family} | {style} | {relative} | Latn").unwrap(); + let decoded = if accepted { format!("Some(include_bytes!({:?}).as_slice())", source) } else { "None".into() }; + writeln!(expected, "({family:?}, {style:?}, include_bytes!({packed:?}), {}, {decoded}),", bytes.len()).unwrap(); + } + expected.push_str("];\n"); + std::fs::write(fixture.0.join("fonts/manifest.txt"), manifest).unwrap(); + let entries = craft_fonts(&fixture.0, "fonts/manifest.txt", true, false, &[], &[], Some(&fixture.0)).unwrap().entries; + for populated in [true, false] { + let catalog = catalog_source(if populated { &entries } else { "" }, true); + compile_and_run(&fixture.0, &format!("const POPULATED: bool = {populated};\n{expected}{catalog}{HARNESS}")); + } +} + +/// Compile a std-only contract harness, then execute its assertions without discovering rlibs. +fn compile_and_run(dir: &std::path::Path, source: &str) { + let input = dir.join("generated_catalog.rs"); + let executable = dir.join(format!("generated_catalog{}", std::env::consts::EXE_SUFFIX)); + std::fs::write(&input, source).unwrap(); + let compiler = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); + let built = std::process::Command::new(compiler).arg("--edition=2024").arg(&input).arg("-o").arg(&executable).output().unwrap(); + assert!(built.status.success(), "generated catalog did not compile:\n{}", String::from_utf8_lossy(&built.stderr)); + let ran = std::process::Command::new(&executable).output().unwrap(); + assert!(ran.status.success(), "generated catalog failed:\n{}", String::from_utf8_lossy(&ran.stderr)); +} + +// This stub tests code-generation wiring; the real decoder has separate byte-for-byte tests. +// OnceLock deliberately preserves the real type's interior mutability, catching invalid static +// promotions (E0492) that a plain byte-slice stub would allow. +const HARNESS: &str = r#" +pub struct CraftFont { pub family: &'static str, pub style: &'static str, pub bytes: &'static [u8] } +static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +mod embedded { + pub struct PackedFont { + bytes: &'static [u8], len: usize, + decoded: std::sync::OnceLock>, + } + impl PackedFont { + /// Mirror the production constructor's const/static contract. + pub const fn new(bytes: &'static [u8], len: usize) -> Self { + Self { bytes, len, decoded: std::sync::OnceLock::new() } + } + /// Validate all generated inputs and return a distinct marker or a rejected face. + pub fn data(&'static self, family: &str, style: &str) -> Option<&'static [u8]> { + crate::CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + *self.decoded.get_or_init(|| { + let expected = crate::EXPECTED.iter().find(|row| row.0 == family && row.1 == style).unwrap(); + assert_eq!(self.bytes, expected.2); + assert_eq!(self.len, expected.3); + expected.4 + }) + } + } +} +/// Observe the generated public catalog twice; initialization must happen once, on first access. +fn main() { + use std::sync::atomic::Ordering::SeqCst; + assert_eq!(CALLS.load(SeqCst), 0); + let expected: Vec<_> = EXPECTED.iter().filter(|row| POPULATED && row.4.is_some()).collect(); + for _ in 0..2 { + assert_eq!(CRAFT_FONTS.len(), expected.len()); + for (font, row) in CRAFT_FONTS.iter().zip(&expected) { + assert_eq!((font.family, font.style, font.bytes), (row.0, row.1, row.4.unwrap())); + } + } + assert_eq!(CALLS.load(SeqCst), if POPULATED { EXPECTED.len() } else { 0 }); +} +"#; diff --git a/crates/text/tests/support/web_fallback.rs b/crates/text/tests/support/web_fallback.rs index 16a930328..f9fac6178 100644 --- a/crates/text/tests/support/web_fallback.rs +++ b/crates/text/tests/support/web_fallback.rs @@ -6,6 +6,8 @@ use super::{craft_fonts, pack_font}; mod embedded; use figcraft_text::fontdb::{Face, FontBytes}; +/// The default web faces render Persian and Arabic with joined letters and bidi ordering even +/// when the requested font is unavailable and system-font discovery is disabled. #[test] fn default_web_fonts_render_persian_and_arabic_without_system_fonts() { let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(std::path::PathBuf::from).filter(|p| p.join("fonts/manifest.txt").is_file()) else { diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 81028865d..98a815917 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -150,7 +150,7 @@ Hindi and Arabic. | Date | Change | Summary | |---|---|---| -| 2026-11-07 | patch | M10, #1902: Noto Sans Arabic Regular joins the default web font catalog, so Persian and Arabic documents no longer need `FIGCRAFT_EMBED_SCRIPTS=Arab`. Required web builds fail if the face is missing; web fonts are packed losslessly and restored once at runtime to preserve the WASM size budget. Other script fonts stay optional. Exact Iran Sans rendering requires that installed font through supported browsers' local font access. Existing duplicate Arabic rows and the repeated web-font paragraph are consolidated, preserving the mirrored window and pending panel-row mirroring. Grades and estimates unchanged. | +| 2026-11-07 | patch | M10, #1902: Noto Sans Arabic Regular joins the default web font catalog, so Persian and Arabic documents no longer need `FIGCRAFT_EMBED_SCRIPTS=Arab`. Required web builds fail if the face is missing; web fonts are packed losslessly and restored once at runtime to preserve the WASM size budget. Failed decoding reports the face once; generated catalog initialization is covered by a compiler regression. Other script fonts stay optional. Exact Iran Sans rendering requires that installed font through supported browsers' local font access. Existing duplicate Arabic rows and the repeated web-font paragraph are consolidated, preserving the mirrored window and pending panel-row mirroring. Grades and estimates unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source and marked as a draft awaiting native review. `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it; an explicit Hans still reads Simplified Chinese. The desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled. No plural forms. Localization grade and estimates unchanged | | 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build and its size are unchanged, and with `Arab` embedded the picker offers the Arabic UI as well (`cjk::can_show`, as on the desktop). Noto Sans Hebrew, Devanagari and Georgian join Arabic and Thai among the document fallbacks, so an embedded face draws its script in an Inter document. Tests: `web_embeds_other_scripts_faces_only_when_asked` in the build script, `every_embeddable_script_face_is_a_document_fallback`. | | 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as well as Hebrew and Arabic; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | From 36b2ee28fdf409f50a771e6a84248e72a1d2e6a2 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 7 Nov 2026 23:10:28 -0500 Subject: [PATCH 003/129] Fields: scrubbing a label moves half a step a point, as measured in Figma Measured in Figma: X from 100 gained 6 for a 12.2 px drag and 31 for 61.2 px; rotation 6 degrees and opacity 5% for 12.2 px. The base rate is now half a step a point (SCRUB_STEPS_PER_POINT); Shift x10, Alt x0.1 and the speed by height are kept on top and were not measured. No scrub direction changed. Tests that pinned the old rate follow the new one; docs/ui-parity.md updated. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/corner_individual_tests.rs | 6 +- crates/ui-egui/src/field_tests.rs | 76 +++++++++---------- crates/ui-egui/src/panels/selection_colors.rs | 10 +-- crates/ui-egui/src/selection_spacing_tests.rs | 2 +- crates/ui-egui/src/typography_scrub_tests.rs | 16 ++-- crates/ui-egui/src/widgets.rs | 9 ++- crates/ui-egui/src/windows_qa_tests.rs | 4 +- docs/ui-parity.md | 3 +- 8 files changed, 66 insertions(+), 60 deletions(-) diff --git a/crates/ui-egui/src/corner_individual_tests.rs b/crates/ui-egui/src/corner_individual_tests.rs index 281ab6f2a..53464a48a 100644 --- a/crates/ui-egui/src/corner_individual_tests.rs +++ b/crates/ui-egui/src/corner_individual_tests.rs @@ -75,7 +75,7 @@ fn ios_button_sets_corner_smoothing_to_60_percent() { #[test] fn corner_smoothing_icon_scrubs_with_modifiers_and_one_undo_step() { for (dx, modifiers, want) in - [(16.0, Modifiers::NONE, 0.66), (8.0, Modifiers::SHIFT, 1.0), (16.0, Modifiers::ALT, 0.516), (-80.0, Modifiers::NONE, 0.0)] + [(16.0, Modifiers::NONE, 0.58), (16.0, Modifiers::SHIFT, 1.0), (16.0, Modifiers::ALT, 0.508), (-160.0, Modifiers::NONE, 0.0)] { let (mut u, r) = scene(); u.app.run("node.set", json!({"ids": [r], "props": {"cornerSmoothing": 0.5}})); @@ -117,7 +117,7 @@ fn consecutive_smoothing_drags_preserve_fractional_percentages() { let history = u.app.session.undo_depth().0; let smoothing = |u: &Ui| u.app.session.doc().unwrap().node(r).unwrap().corners.smoothing; for (step, (dx, modifiers, want)) in - [(16.0, Modifiers::ALT, 0.516), (16.0, Modifiers::ALT, 0.532), (8.0, Modifiers::NONE, 0.612)].into_iter().enumerate() + [(16.0, Modifiers::ALT, 0.508), (16.0, Modifiers::ALT, 0.516), (8.0, Modifiers::NONE, 0.556)].into_iter().enumerate() { let from = u.ctx.read_response(Id::unique("smoothing").with("lead")).unwrap().rect.center(); u.frame_with(vec![Event::PointerMoved(from)], modifiers); @@ -133,7 +133,7 @@ fn consecutive_smoothing_drags_preserve_fractional_percentages() { assert!((smoothing(&u) - want).abs() < 1e-9, "gesture {step}: expected {want}, got {}", smoothing(&u)); assert_eq!(u.app.session.undo_depth().0, history + step + 1); } - for want in [0.532, 0.516, 0.5] { + for want in [0.516, 0.508, 0.5] { u.app.session.undo().unwrap(); assert!((smoothing(&u) - want).abs() < 1e-9, "undo restores the precise value"); } diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index e3bdad1dd..9a18254f6 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -111,17 +111,17 @@ fn typed_text_is_a_number_arithmetic_or_an_edit_relative_to_the_value() { } #[test] -fn a_scrub_moves_a_step_a_point_ten_with_shift_and_a_tenth_with_alt() { +fn a_scrub_moves_half_a_step_a_point_ten_times_that_with_shift_and_a_tenth_with_alt() { // (points dragged, the field's step, Shift, Alt) → how far the value moves let rows = [ - ((25.0, 1.0, false, false), 25.0), - ((-25.0, 1.0, false, false), -25.0), - ((10.0, 1.0, true, false), 100.0), - ((20.0, 1.0, false, true), 2.0), - ((20.0, 1.0, true, true), 20.0), - ((10.0, 0.1, false, false), 1.0), - ((10.0, 0.1, true, false), 10.0), - ((10.0, 10.0, false, false), 100.0), + ((25.0, 1.0, false, false), 12.5), + ((-25.0, 1.0, false, false), -12.5), + ((10.0, 1.0, true, false), 50.0), + ((20.0, 1.0, false, true), 1.0), + ((20.0, 1.0, true, true), 10.0), + ((10.0, 0.1, false, false), 0.5), + ((10.0, 0.1, true, false), 5.0), + ((10.0, 10.0, false, false), 50.0), ((0.0, 1.0, true, false), 0.0), ]; for ((dx, step, shift, alt), want) in rows { @@ -308,7 +308,7 @@ fn moving_up_or_down_while_scrubbing_changes_the_speed_and_says_so() { let (mut u, a, _) = setup(); let toast = |u: &Ui| u.app.ui.toast.clone().map(|t| t.0).unwrap_or_default(); // (rise in points, how far 40 points of scrub move X, the notice) - for (rise, want, notice) in [(150.0, 80.0, "2x"), (0.0, 40.0, ""), (-150.0, 20.0, "1/2"), (-300.0, 10.0, "1/4"), (40.0, 40.0, "")] { + for (rise, want, notice) in [(150.0, 40.0, "2x"), (0.0, 20.0, ""), (-150.0, 10.0, "1/2"), (-300.0, 5.0, "1/4"), (40.0, 20.0, "")] { let x0 = geom(&u, a).0; u.app.ui.toast = None; scrub_at_height(&mut u, "X", rise, 40.0); @@ -319,7 +319,7 @@ fn moving_up_or_down_while_scrubbing_changes_the_speed_and_says_so() { assert!(toast(&u).contains(notice), "rise {rise}: the notice says {}", toast(&u)); } } - // Speeds compose with the modifiers' rates: 2x with Shift is twenty steps a point. + // Speeds compose with the modifiers' rates: 2x with Shift is ten steps a point. let x0 = geom(&u, a).0; let from = label(&mut u, "X"); let shift = Modifiers { shift: true, ..Modifiers::NONE }; @@ -333,7 +333,7 @@ fn moving_up_or_down_while_scrubbing_changes_the_speed_and_says_so() { let to = pos2(up.x + 10.0, up.y); u.frame_with(vec![Event::PointerMoved(to), press(false, to)], shift); u.frame(vec![]); - assert_eq!(geom(&u, a).0 - x0, 200.0, "ten points at 2x with Shift"); + assert_eq!(geom(&u, a).0 - x0, 100.0, "ten points at 2x with Shift"); // The pointer reported gone from the window (egui's PointerGone) with the button still down // keeps the speed it had: no notice of 1x, and the scrub goes on at 2x once it is back. let x0 = geom(&u, a).0; @@ -356,7 +356,7 @@ fn moving_up_or_down_while_scrubbing_changes_the_speed_and_says_so() { let to = pos2(up.x + 30.0, up.y); u.frame_with(vec![Event::PointerMoved(to), press(false, to)], m); u.frame(vec![]); - assert_eq!(geom(&u, a).0 - x0, 40.0, "ten points before and ten after the pointer was gone, at 2x both"); + assert_eq!(geom(&u, a).0 - x0, 20.0, "ten points before and ten after the pointer was gone, at 2x both"); } #[test] @@ -366,11 +366,11 @@ fn scrubbing_the_label_moves_the_value_and_is_one_undo_step() { let alt = Modifiers { alt: true, ..Modifiers::NONE }; // (field, points, modifiers, x after): X starts at 10. let rows = [ - ("X", 25.0, Modifiers::NONE, 35.0), - ("X", 10.0, shift, 135.0), - ("X", 20.0, alt, 137.0), - ("X", -37.0, Modifiers::NONE, 100.0), - ("X", -8.0, shift, 20.0), + ("X", 24.0, Modifiers::NONE, 22.0), + ("X", 10.0, shift, 72.0), + ("X", 20.0, alt, 73.0), + ("X", -36.0, Modifiers::NONE, 55.0), + ("X", -8.0, shift, 15.0), ]; for (name, dx, m, want) in rows { let steps = undo_steps(&u); @@ -379,18 +379,18 @@ fn scrubbing_the_label_moves_the_value_and_is_one_undo_step() { assert_eq!(undo_steps(&u), steps + 1, "one undo step for the whole scrub"); } u.app.run("edit.undo", json!({})); - assert_eq!(geom(&u, a).0, 100.0, "undo takes back the last scrub alone"); + assert_eq!(geom(&u, a).0, 55.0, "undo takes back the last scrub alone"); // A few points aren't a drag yet (a click on the label), then it counts from the press. // Alt gives tenths (the field shows them); the fraction stays under a plain scrub. let width = |u: &Ui| u.app.session.doc().unwrap().node(a).unwrap().width; - scrub(&mut u, "Width", 7.0, alt); - assert_eq!(width(&u), 40.7); + scrub(&mut u, "Width", 8.0, alt); + assert_eq!(width(&u), 40.4); scrub(&mut u, "Width", 8.0, Modifiers::NONE); - assert_eq!(width(&u), 48.7); - // Fractional fields: opacity moves a percent a point, rotation a degree. - scrub(&mut u, "Opacity", -30.0, Modifiers::NONE); + assert_eq!(width(&u), 44.4); + // Fractional fields: opacity moves half a percent a point, rotation half a degree. + scrub(&mut u, "Opacity", -60.0, Modifiers::NONE); assert_eq!(u.app.session.doc().unwrap().node(a).unwrap().opacity, 0.7); - scrub(&mut u, "Rotation", 15.0, Modifiers::NONE); + scrub(&mut u, "Rotation", 30.0, Modifiers::NONE); let rot = figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().node(a).unwrap().transform); assert!((rot.abs() - 15.0).abs() < 1e-6, "rotation {rot}"); // A press on the label that doesn't move changes nothing. @@ -607,7 +607,7 @@ fn scrubbing_colour_picker_fields_is_live_and_one_undo_step() { let steps = undo_steps(&u); let from = lead(&u, Id::unique(("cp_f", "r"))); drag(&mut u, from, -20.0, Modifiers::NONE); - assert_eq!((rgba(&u)[0], undo_steps(&u)), (r0 - 20, steps + 1), "R"); + assert_eq!((rgba(&u)[0], undo_steps(&u)), (r0 - 10, steps + 1), "R"); // Committing adds a recent colour row and can lift the anchored picker. Settle its layout. for _ in 0..3 { u.frame(vec![]); @@ -721,7 +721,7 @@ fn scrubbing_a_prototype_delay_sets_it_once_when_let_go() { figcraft_doc::proto::Trigger::AfterDelay { ms } => ms, _ => panic!("still after a delay"), }; - assert_eq!((ms, undo_steps(&u)), (800, steps + 1)); + assert_eq!((ms, undo_steps(&u)), (650, steps + 1)); } /// Asserts scrubbing the scale panel's width scales the layer live in one undo step. @@ -734,7 +734,7 @@ fn scrubbing_the_scale_panel_width_scales_live_in_one_undo_step() { let from = lead(&u, Id::unique("scale_w")); drag(&mut u, from, 20.0, Modifiers::NONE); let (_, _, w, h) = geom(&u, a); - assert_eq!((w, h, undo_steps(&u)), (60.0, 45.0, steps + 1), "40×30 scaled to a width of 60"); + assert_eq!((w, h, undo_steps(&u)), (50.0, 37.5, steps + 1), "40×30 scaled to a width of 50"); } /// The texts painted in the last frame: what they say, whether they end in an ellipsis, and where @@ -1314,10 +1314,10 @@ fn the_page_background_opacity_field_sets_the_page_colour_alpha() { type_into(&mut u, "Opacity", "50", Key::Enter); assert!(near(page_bg(&u).a, 0.5), "{:?}", page_bg(&u)); assert_eq!(undo_steps(&u), steps + 1, "one undo step for the commit"); - // No label is drawn, so the field's leading strip scrubs it: a percent a point, live, and one + // No label is drawn, so the field's leading strip scrubs it: half a percent a point, live, and one // undo step for the whole drag. let edge = lead(&u, Id::unique("pagebg_a")); - drag(&mut u, edge, -25.0, Modifiers::NONE); + drag(&mut u, edge, -50.0, Modifiers::NONE); assert!(near(page_bg(&u).a, 0.25), "{:?}", page_bg(&u)); assert_eq!(undo_steps(&u), steps + 2, "one undo step for the whole scrub"); u.app.run("edit.undo", json!({})); @@ -1350,7 +1350,7 @@ fn the_page_background_opacity_field_sets_the_page_colour_alpha() { /// "You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option /// Windows: Alt" to scrub it (Adjust alignment, rotation, position, and dimensions). Alt is what -/// makes the drag a scrub there, not the fine rate: a point moves a step, as on the label. Without +/// makes the drag a scrub there, not the fine rate: a point moves half a step, as on the label. Without /// Alt a drag on the field is no click, so it neither edits nor moves anything. #[test] fn alt_held_over_a_field_scrubs_it() { @@ -1361,13 +1361,13 @@ fn alt_held_over_a_field_scrubs_it() { // a drag only once it has seen Alt; egui assigns a press by the frame before it). let alt = Modifiers { alt: true, ..Modifiers::NONE }; u.frame_with(vec![Event::PointerMoved(at)], alt); - drag(&mut u, at, 25.0, alt); - assert_eq!(geom(&u, a).0, 35.0, "a step a point: X from 10"); + drag(&mut u, at, 24.0, alt); + assert_eq!(geom(&u, a).0, 22.0, "half a step a point: X from 10"); assert_eq!(undo_steps(&u), steps + 1, "one undo step for the whole scrub"); - assert_eq!(field(&mut u, "X").1, "35", "the field shows it and isn't editing"); + assert_eq!(field(&mut u, "X").1, "22", "the field shows it and isn't editing"); let (at, _) = field(&mut u, "X"); drag(&mut u, at, 25.0, Modifiers::NONE); - assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub"); + assert_eq!(geom(&u, a).0, 22.0, "without Alt the field doesn't scrub"); assert_eq!(undo_steps(&u), steps + 1); // Alt let go before the button still ends the scrub with its undo step. let (at, _) = field(&mut u, "X"); @@ -1380,7 +1380,7 @@ fn alt_held_over_a_field_scrubs_it() { let to = pos2(at.x + 20.0, at.y); u.frame_with(vec![Event::PointerMoved(to), press(false, Modifiers::NONE, to)], Modifiers::NONE); u.frame(vec![]); - assert_eq!(geom(&u, a).0, 55.0, "twenty more"); + assert_eq!(geom(&u, a).0, 32.0, "ten more"); assert_eq!(undo_steps(&u), steps + 2, "committed when the button went up, without Alt"); // Without Alt the field doesn't take the drag at all (a touch swipe over it is the panel's to // scroll): the press is a click of the field's, not a drag. @@ -1392,7 +1392,7 @@ fn alt_held_over_a_field_scrubs_it() { assert!(!u.ctx.is_being_dragged(field_id), "a plain press on the field isn't a drag of the field's"); u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, Modifiers::NONE, pos2(at.x + 10.0, at.y))], Modifiers::NONE); u.frame(vec![]); - assert_eq!(geom(&u, a).0, 55.0, "nothing scrubbed"); + assert_eq!(geom(&u, a).0, 32.0, "nothing scrubbed"); // With Alt held over it, the field does take the drag. let (at, _) = field(&mut u, "X"); u.frame_with(vec![Event::PointerMoved(at)], alt); @@ -1401,5 +1401,5 @@ fn alt_held_over_a_field_scrubs_it() { assert!(u.ctx.is_being_dragged(field_id), "with Alt the drag is the field's"); u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, alt, pos2(at.x + 10.0, at.y))], alt); u.frame(vec![]); - assert_eq!(geom(&u, a).0, 65.0, "ten more"); + assert_eq!(geom(&u, a).0, 37.0, "five more"); } diff --git a/crates/ui-egui/src/panels/selection_colors.rs b/crates/ui-egui/src/panels/selection_colors.rs index dbb6f16e4..98ca91393 100644 --- a/crates/ui-egui/src/panels/selection_colors.rs +++ b/crates/ui-egui/src/panels/selection_colors.rs @@ -500,7 +500,7 @@ mod tests { let red = texts.into_iter().find(|(text, _)| text == "FF0000").unwrap().1; let start = Pos2::new(167.0, red.y); p.modifiers.alt = true; - for expected in [0.989, 0.979] { + for expected in [0.994, 0.989] { p.frame(vec![ Event::PointerMoved(start), Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: p.modifiers }, @@ -518,8 +518,8 @@ mod tests { let opacity = p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity; assert!((opacity - expected).abs() < 1e-6, "fine scrub kept fractional baseline: {opacity}"); } - assert!(p.frame(vec![]).iter().any(|(text, _)| text == "97.9%")); - for expected in [0.989, 0.999] { + assert!(p.frame(vec![]).iter().any(|(text, _)| text == "98.9%")); + for expected in [0.994, 0.999] { p.app.run("edit.undo", json!({})); let opacity = p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity; assert!((opacity - expected).abs() < 1e-6, "each fine scrub is one undo step: {opacity}"); @@ -555,13 +555,13 @@ mod tests { Event::PointerMoved(start), Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, ]); - for dx in [-10.0, -20.0, -30.0] { + for dx in [-20.0, -40.0, -60.0] { p.frame(vec![Event::PointerMoved(start + vec2(dx, 0.0))]); } assert!(p.app.session.ds().unwrap().interaction.is_some(), "the scrub commits only on release"); assert!(p.frame(vec![]).iter().any(|(text, _)| text == "70%"), "the live opacity stays visible while scrubbing"); p.frame(vec![Event::PointerButton { - pos: start - vec2(30.0, 0.0), + pos: start - vec2(60.0, 0.0), button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default(), diff --git a/crates/ui-egui/src/selection_spacing_tests.rs b/crates/ui-egui/src/selection_spacing_tests.rs index d23f34360..46a484fcc 100644 --- a/crates/ui-egui/src/selection_spacing_tests.rs +++ b/crates/ui-egui/src/selection_spacing_tests.rs @@ -62,7 +62,7 @@ fn spacing_fields_type_scrub_and_keep_one_undo_step() { u.frame(vec![]); let lead = u.ctx.read_response(field.with("lead")).unwrap().rect.center(); drag(&mut u, lead, vec2(16., 0.), true); - assert_eq!(xy(&u, ids[1]), (196., 100.)); + assert_eq!(xy(&u, ids[1]), (188., 100.)); assert_eq!(u.app.session.undo_depth().0, history + 1); u.app.run("edit.undo", json!({})); assert_eq!(xy(&u, ids[1]), (180., 100.)); diff --git a/crates/ui-egui/src/typography_scrub_tests.rs b/crates/ui-egui/src/typography_scrub_tests.rs index df61936db..13fe993b3 100644 --- a/crates/ui-egui/src/typography_scrub_tests.rs +++ b/crates/ui-egui/src/typography_scrub_tests.rs @@ -84,18 +84,18 @@ fn typography_icon_drag_changes_each_spacing_field_in_one_undo_step() { let mut f = Fields::new(); let undo = f.app.session.undo_depth().0; f.drag(key, 16.0, Modifiers::NONE); - assert_eq!(f.value(key), before + 16.0, "{key}: dragging the icon must change the value"); + assert_eq!(f.value(key), before + 8.0, "{key}: dragging the icon must change the value"); assert_eq!(f.app.session.undo_depth().0, undo + 1, "{key}: one gesture, one undo step"); f.app.session.undo().unwrap(); assert_eq!(f.value(key), before); f.app.session.redo().unwrap(); - assert_eq!(f.value(key), before + 16.0); + assert_eq!(f.value(key), before + 8.0); } } #[test] fn typography_icon_scrub_uses_shift_and_alt_rates_and_the_resize_cursor() { - for (modifiers, delta) in [(Modifiers::SHIFT, 160.0), (Modifiers::ALT, 1.6)] { + for (modifiers, delta) in [(Modifiers::SHIFT, 80.0), (Modifiers::ALT, 0.8)] { for (key, start) in [("ty_lh", 24.0), ("ty_ls", 0.0), ("ty_ps", 12.0)] { let mut f = Fields::new(); let p = f.lead(key); @@ -114,10 +114,10 @@ fn typography_icon_scrub_preserves_units_and_clamps_only_nonnegative_fields() { f.drag("ty_lh", 16.0, Modifiers::NONE); f.drag("ty_ls", -16.0, Modifiers::NONE); let t = f.app.session.doc().unwrap().node(f.text).unwrap().kind.text().unwrap(); - assert_eq!(t.style.line_height, LineHeight::Percent(166.0)); - assert_eq!(t.style.letter_spacing, LetterSpacing::Pixels(-14.0)); - f.drag("ty_lh", -200.0, Modifiers::NONE); - f.drag("ty_ps", -200.0, Modifiers::NONE); + assert_eq!(t.style.line_height, LineHeight::Percent(158.0)); + assert_eq!(t.style.letter_spacing, LetterSpacing::Pixels(-6.0)); + f.drag("ty_lh", -320.0, Modifiers::NONE); + f.drag("ty_ps", -320.0, Modifiers::NONE); assert_eq!(f.value("ty_lh"), 0.0); assert_eq!(f.value("ty_ps"), 0.0); assert!(f.app.ui.last_error.is_none(), "{:?}", f.app.ui.last_error); @@ -152,7 +152,7 @@ fn typography_icon_scrub_changes_only_the_selected_characters_without_ending_tex f.drag("ty_ls", 16.0, Modifiers::NONE); let t = f.app.session.doc().unwrap().node(f.text).unwrap().kind.text().unwrap(); assert_eq!(t.style_at(0).letter_spacing, LetterSpacing::Pixels(0.0)); - assert_eq!(t.style_at(1).letter_spacing, LetterSpacing::Pixels(16.0)); + assert_eq!(t.style_at(1).letter_spacing, LetterSpacing::Pixels(8.0)); assert_eq!(t.style_at(4).letter_spacing, LetterSpacing::Pixels(0.0)); assert!(f.app.session.ds().unwrap().text_edit.is_some()); assert_eq!(f.app.session.undo_depth().0, undo); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index eae46fd81..008c387db 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -114,10 +114,15 @@ fn key_steps(ctx: &egui::Context, suffix: &str, step: f64) -> (f64, f64) { } } -/// How far a scrub of `dx` points moves a value whose field steps by `step`: 1 step a point, ten -/// with Shift, a tenth with Alt (fine). +/// The steps a point of scrubbing moves a field by: half, as measured in Figma (12.2 px moved X +/// by 6, 61.2 px by 31). +pub const SCRUB_STEPS_PER_POINT: f64 = 0.5; + +/// How far a scrub of `dx` points moves a value whose field steps by `step`: half a step a point +/// ([`SCRUB_STEPS_PER_POINT`]), ten times that with Shift, a tenth with Alt (fine). pub fn scrub_amount(dx: f64, step: f64, shift: bool, alt: bool) -> f64 { dx * step + * SCRUB_STEPS_PER_POINT * match (shift, alt) { (true, false) => 10.0, (false, true) => 0.1, diff --git a/crates/ui-egui/src/windows_qa_tests.rs b/crates/ui-egui/src/windows_qa_tests.rs index f4b1fd7f4..40db85af1 100644 --- a/crates/ui-egui/src/windows_qa_tests.rs +++ b/crates/ui-egui/src/windows_qa_tests.rs @@ -70,10 +70,10 @@ fn a_scrubbed_field_keeps_its_value_when_the_pointer_lets_go() { for k in 1..=10 { u.frame(vec![Event::PointerMoved(from + vec2(4.0 * k as f32, 0.0))]); } - assert_eq!(width(&u, a).0, 80.0, "40 points to the right while dragging"); + assert_eq!(width(&u, a).0, 60.0, "40 points to the right while dragging: half a step a point"); u.button(from + vec2(40.0, 0.0), false); u.frame(vec![]); - assert_eq!(width(&u, a).0, 80.0, "kept after the release"); + assert_eq!(width(&u, a).0, 60.0, "kept after the release"); assert_eq!(u.app.session.doc().unwrap().node(a).unwrap().height, 30.0); } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index aa0ef25bd..d0fa0c254 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -73,7 +73,7 @@ interaction feel not yet compared. | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | | Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) | | Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; the pixel grid shows from 400% (`view_behaviour_tests`) | -| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: a step a point (1 px; 1% of opacity, 1° of rotation), ten with Shift, a tenth with Alt, each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; rates not compared with Figma's; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837) | +| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: half a step a point (0.5 px; 0.5% of opacity, 0.5° of rotation), as measured in Figma on 2026-11-08 (a 12.2 px drag moved X by 6, a 61.2 px drag by 31; rotation by 6° and opacity by 5% for 12.2 px; `plan/loop/measurements/scrub-and-panels.md`), ten times that with Shift, a tenth with Alt (neither measured), each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; the Shift and Alt rates and the speed by height are not compared with Figma's, and the rotation scrub's direction is not confirmed; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837) | | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session | @@ -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-07 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | | 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 c6c2696079c27a9e123b1d266eb0cc818a86c1d0 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 00:31:58 -0500 Subject: [PATCH 004/129] Docs: Shift and Alt scrub rates spelled out; one date; no local notes path (#2102 review) Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/widgets.rs | 2 +- docs/ui-parity.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 008c387db..aed1f05e1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -119,7 +119,7 @@ fn key_steps(ctx: &egui::Context, suffix: &str, step: f64) -> (f64, f64) { pub const SCRUB_STEPS_PER_POINT: f64 = 0.5; /// How far a scrub of `dx` points moves a value whose field steps by `step`: half a step a point -/// ([`SCRUB_STEPS_PER_POINT`]), ten times that with Shift, a tenth with Alt (fine). +/// ([`SCRUB_STEPS_PER_POINT`]), ten times that with Shift (5 steps a point), a tenth of that with Alt (0.05 steps a point, fine). pub fn scrub_amount(dx: f64, step: f64, shift: bool, alt: bool) -> f64 { dx * step * SCRUB_STEPS_PER_POINT diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d0fa0c254..c999b0a66 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -73,7 +73,7 @@ interaction feel not yet compared. | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | | Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) | | Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; the pixel grid shows from 400% (`view_behaviour_tests`) | -| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: half a step a point (0.5 px; 0.5% of opacity, 0.5° of rotation), as measured in Figma on 2026-11-08 (a 12.2 px drag moved X by 6, a 61.2 px drag by 31; rotation by 6° and opacity by 5% for 12.2 px; `plan/loop/measurements/scrub-and-panels.md`), ten times that with Shift, a tenth with Alt (neither measured), each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; the Shift and Alt rates and the speed by height are not compared with Figma's, and the rotation scrub's direction is not confirmed; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837) | +| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: half a step a point (0.5 px; 0.5% of opacity, 0.5° of rotation), as measured in Figma on 2026-11-08 (a 12.2 px drag moved X by 6, a 61.2 px drag by 31; rotation by 6° and opacity by 5% for 12.2 px), ten times that with Shift (5 steps a point) and a tenth of that with Alt (0.05 steps a point; neither measured), each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; the Shift and Alt rates and the speed by height are not compared with Figma's, and the rotation scrub's direction is not confirmed; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837) | | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session | @@ -187,7 +187,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| -| 2026-11-07 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | +| 2026-11-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | | 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 bceb0bb233d653d7d25fc16012ee1bc2d1011962 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 19:56:53 -0500 Subject: [PATCH 005/129] M5: present a tall frame sharp on HiDPI displays with a device-scale detail texture over the capped frame (#2127) Cause: - The presenter rasterises a whole frame once, capped at 16.8 MP (texture_scale), so a 1440 x 9701 frame is drawn at 1.0959 px per unit (1579 x 10632 px). - On a 2x display at Fit width or 100% the GPU stretches that 1.8x with linear filtering; scrolling only pans, so the same texture is reused. Fix: - render: render_area_at(doc, ids, b, scale, time), the GIF-clock form of render_area. - present/actions.rs: texture_scale split into pure texture_scale_for plus the ctx wrapper; pure detail_plan (the view plus a quarter margin each way, inside the frame, shrunk to the side and pixel caps; None when the whole texture is already at device scale); Presenter::detail_texture caches one detail for the current frame and renders it with render_area_at. - present/draw.rs: paints the detail right after the base texture, so overlays still paint over it; it is re-rendered when it stops covering the view, and not while a fling, drag or the wheel moves the view (the capped texture shows then). Verified: - tall_frame_detail_plan_renders_the_view_at_device_scale: compile error on main (neither function existed). - presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale: failed on main at the size[0] >= 2878 assert (only present texture 1579 x 10632). - present tests 99 passed; figcraft-ui-egui --lib 1107 passed; figcraft-render --lib 245 passed; clippy -D warnings, fmt and cargo xtask wasm clean. Not changed: - Transitions, smart animate, overlays, the bar thumbnail and the pane keep the capped whole-frame texture; MAX_TEXTURE_PIXELS is unchanged; no tiling. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/render/src/lib.rs | 5 ++ crates/ui-egui/src/present.rs | 4 ++ crates/ui-egui/src/present/actions.rs | 76 ++++++++++++++++++++++++++- crates/ui-egui/src/present/draw.rs | 14 ++++- crates/ui-egui/src/present/tests.rs | 38 ++++++++++++++ crates/ui-egui/src/present_tests.rs | 10 +++- docs/prototyping-parity.md | 5 +- docs/target-app-parity.md | 3 +- 8 files changed, 147 insertions(+), 8 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f138521ae..c4674c819 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -362,6 +362,11 @@ pub fn render_area(doc: &Document, ids: &[NodeId], b: Rect, scale: f64) -> Optio area_at(doc, ids, b, scale, 0.0) } +/// [`render_area`] `time` seconds into animated GIFs (the presenter plays them). +pub fn render_area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Option { + area_at(doc, ids, b, scale, time) +} + fn area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Option { let scale = if scale.is_finite() && scale > 0.0 { scale.min(64.0) } else { 1.0 }; let w = (b.width() * scale - 1e-6).ceil().max(1.0); diff --git a/crates/ui-egui/src/present.rs b/crates/ui-egui/src/present.rs index 8f23069f2..64ee81ef0 100644 --- a/crates/ui-egui/src/present.rs +++ b/crates/ui-egui/src/present.rs @@ -286,6 +286,9 @@ pub struct Presenter { anim_tex: Option, temp: Option, textures: HashMap, + /// The part of the presented frame in view, drawn at device scale over the (capped) whole-frame + /// texture; `bounds` is the page area it covers. + detail: Option<(NodeId, FrameTex)>, /// Small current-screen preview in the full-window bar, cached until its content changes. bar_thumb: Option<(NodeId, usize, egui::TextureHandle)>, arrived: f64, @@ -367,6 +370,7 @@ impl Presenter { anim_tex: None, temp: None, textures: HashMap::new(), + detail: None, bar_thumb: None, arrived: -1.0, delays_fired: HashSet::new(), diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index cfc3f26a8..52d75fa88 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -252,7 +252,8 @@ impl Presenter { } } - pub(super) fn texture(&mut self, ctx: &egui::Context, doc: &Document, id: NodeId, px_scale: f64, now: f64) -> Option { + /// Seconds into the frame's animated GIFs, and the frame of them showing (see [`Self::texture`]). + fn frame_clock(&self, ctx: &egui::Context, doc: &Document, id: NodeId, now: f64) -> (f64, Option<(u64, f64)>) { // Animated GIFs play from when the frame arrived: a new texture when one of them moves on, // and a wake-up for that moment (nothing else draws frames while it shows). egui wakes a // display frame before the time asked for, a little earlier still at times: ask that much @@ -262,6 +263,48 @@ impl Presenter { if let Some((_, next)) = clock { crate::repaint_in(ctx, next + f64::from(ctx.input(|i| i.predicted_dt))); } + (t, clock) + } + + /// The part of the frame `id` in view (`visible`, page units) at the full pixel scale `px`, for + /// a frame whose whole texture is capped below it (see [`detail_plan`]). While the view moves + /// (`moving`) it only returns a detail already rendered, the capped texture showing under it. + pub(super) fn detail_texture( + &mut self, + ctx: &egui::Context, + doc: &Document, + id: NodeId, + px: f64, + visible: figcraft_geom::Rect, + moving: bool, + now: f64, + ) -> Option { + let (t, clock) = self.frame_clock(ctx, doc, id, now); + let key = (self.rev, px.to_bits(), clock.map_or(0, |c| c.0)); + let covers = |b: &figcraft_geom::Rect| b.x0 <= visible.x0 && b.y0 <= visible.y0 && b.x1 >= visible.x1 && b.y1 >= visible.y1; + if let Some((did, d)) = &self.detail + && *did == id + && d.key == key + && (moving || covers(&d.bounds)) + { + return Some(d.clone()); + } + if moving { + return None; + } + let side = ctx.input(|i| i.max_texture_side) as f64 - 2.0; + let bounds = figcraft_render::export_bounds(doc, id)?; + let rect = detail_plan(bounds, visible, px, side)?; + let pix = figcraft_render::render_area_at(doc, &[id], rect, texture_scale_for(rect, px, side), t)?; + let img = crate::render_worker::screen_image(&pix, doc.color_profile); + let tex = ctx.load_texture(format!("present-detail-{}", id.0), img, egui::TextureOptions::LINEAR); + let ft = FrameTex { key, tex, bounds: rect }; + self.detail = Some((id, ft.clone())); + Some(ft) + } + + pub(super) fn texture(&mut self, ctx: &egui::Context, doc: &Document, id: NodeId, px_scale: f64, now: f64) -> Option { + let (t, clock) = self.frame_clock(ctx, doc, id, now); let key = (self.rev, px_scale.to_bits(), clock.map_or(0, |c| c.0)); if let Some(t) = self.textures.get(&id) && t.key == key @@ -285,12 +328,41 @@ const MAX_TEXTURE_PIXELS: f64 = 16_777_216.0; /// The pixel scale, at most `px`, at which `bounds` makes a texture the GPU takes (no side past /// its limit) of at most [`MAX_TEXTURE_PIXELS`]. pub(super) fn texture_scale(ctx: &egui::Context, bounds: figcraft_geom::Rect, px: f64) -> f64 { - let side = ctx.input(|i| i.max_texture_side) as f64 - 2.0; + texture_scale_for(bounds, px, ctx.input(|i| i.max_texture_side) as f64 - 2.0) +} + +/// [`texture_scale`] for a GPU taking textures up to `side` pixels a side. +pub(super) fn texture_scale_for(bounds: figcraft_geom::Rect, px: f64, side: f64) -> f64 { let (w, h) = (bounds.width().max(1.0), bounds.height().max(1.0)); let s = px.min(side / w.max(h)).min((MAX_TEXTURE_PIXELS / (w * h)).sqrt()); if s.is_finite() && s > 0.0 { s } else { 1e-3 } } +/// The page area to draw at the full pixel scale `px` over the whole frame's capped texture, when +/// that texture is below `px`: the part in `visible` with a margin (a quarter of its size each +/// way, shrunk until the area makes a texture the GPU takes), inside `bounds`. `None` when the +/// whole frame is already at `px`, or nothing of it is in view. When the view alone is past the +/// caps it is returned all the same, and drawn at the scale [`texture_scale_for`] gives it. +pub(super) fn detail_plan(bounds: figcraft_geom::Rect, visible: figcraft_geom::Rect, px: f64, side: f64) -> Option { + if texture_scale_for(bounds, px, side) >= px || !(px.is_finite() && px > 0.0) { + return None; + } + let view = visible.intersect(bounds); + if !(view.width() > 0.0 && view.height() > 0.0 && view.width().is_finite() && view.height().is_finite()) { + return None; + } + let fits = |r: &figcraft_geom::Rect| r.width() * px <= side && r.height() * px <= side && r.area() * px * px <= MAX_TEXTURE_PIXELS; + let mut margin = 0.25; + for _ in 0..8 { + let r = view.inflate(view.width() * margin, view.height() * margin).intersect(bounds); + if fits(&r) { + return Some(r); + } + margin /= 2.0; + } + Some(view) +} + /// The first interaction index on `id` whose trigger satisfies `want`. pub(super) fn find_trigger(doc: &Document, id: NodeId, want: impl Fn(&Trigger) -> bool) -> Option { doc.node(id)?.interactions.iter().position(|it| want(&it.trigger)) diff --git a/crates/ui-egui/src/present/draw.rs b/crates/ui-egui/src/present/draw.rs index b4d679144..c8bd8248f 100644 --- a/crates/ui-egui/src/present/draw.rs +++ b/crates/ui-egui/src/present/draw.rs @@ -74,7 +74,19 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte } } if !drawn && let Some(to) = &to_tex { - painter.with_clip_rect(l.clip).image(to.tex.id(), l.place.rect(to.bounds), uv, Color32::WHITE); + let on_clip = painter.with_clip_rect(l.clip); + on_clip.image(to.tex.id(), l.place.rect(to.bounds), uv, Color32::WHITE); + // A frame too big for one texture at device scale is drawn from a smaller one: the part in + // view is drawn again from a texture at device scale, over it (and the overlays over that). + let shown = l.clip.intersect(l.place.rect(to.bounds)); + if shown.is_positive() { + let (a, b) = (l.place.page(shown.min), l.place.page(shown.max)); + let visible = figcraft_geom::Rect::new(a.x, a.y, b.x, b.y); + let moving = p.fling.is_some() || p.drag_scroll.is_some() || p.wheel.is_some(); + if let Some(d) = p.detail_texture(ctx, &l.disp, p.current, px, visible, moving, now) { + on_clip.image(d.tex.id(), l.place.rect(d.bounds), uv, Color32::WHITE); + } + } } // Overlays (each with its background and opening transition); closing ones run it backwards. let mut ovs: Vec<(f64, OverlayState)> = diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index bba998788..9ed1fa665 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -436,3 +436,41 @@ fn smart_animate_frame_cost() { let per = t0.elapsed().as_secs_f64() * 1000.0 / f64::from(n); eprintln!("smart animate: {per:.2} ms per frame (80 layers, 400x800 px)"); } + +#[test] +fn tall_frame_detail_plan_renders_the_view_at_device_scale() { + use figcraft_geom::Rect as PageRect; + let bounds = PageRect::new(0.0, 0.0, 1440.0, 9701.0); + let visible = PageRect::new(0.0, 0.0, 1440.0, 860.0); + let side = 16382.0; + assert!(actions::texture_scale_for(bounds, 2.0, side) < 1.1, "the whole frame is capped below device scale"); + let r = actions::detail_plan(bounds, visible, 2.0, side).expect("a capped frame gets a detail"); + assert!(r.x0 <= visible.x0 && r.y0 <= visible.y0 && r.x1 >= visible.x1 && r.y1 >= visible.y1, "covers the view"); + assert!(r.x0 >= bounds.x0 && r.y0 >= bounds.y0 && r.x1 <= bounds.x1 && r.y1 <= bounds.y1, "inside the frame"); + assert!(r.width() * 2.0 <= side && r.height() * 2.0 <= side); + assert!(r.width() * r.height() * 4.0 <= 16_777_216.0); + let small = PageRect::new(0.0, 0.0, 1440.0, 900.0); + assert!(actions::detail_plan(small, PageRect::new(0.0, 0.0, 1440.0, 860.0), 2.0, side).is_none()); +} + +#[test] +fn presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale() { + let mut session = figcraft_engine::Session::new(); + let frame = id(&session.execute("node.create", &json!({"type": "frame", "width": 1440, "height": 9701})).unwrap()); + session.execute("node.create", &json!({"type": "rectangle", "parent": frame, "x": 100, "y": 100, "width": 300, "height": 200})).unwrap(); + let mut ui = Ui::new(session); + ui.hidpi = Some((2.0, 16_384)); + ui.run("proto.present", json!({"start": frame})); + ui.app.ui.present.as_mut().unwrap().view.scale = PresentScale::FitWidth; + ui.frames(2, Vec::new); + + let textures = ui.ctx.tex_manager(); + let textures = textures.read(); + let present: Vec<_> = textures.allocated().filter(|(_, m)| m.name.starts_with("present-")).map(|(_, m)| m.size).collect(); + assert!(!present.is_empty()); + assert!(present.iter().any(|s| s[0] >= 2878), "some texture shows the view at 2 px a unit: {present:?}"); + for s in &present { + // The scale caps the area; each side then rounds up to a whole pixel. + assert!(s[0] * s[1] <= 16_777_216 + s[0] + s[1] && s[0] <= 16_384 && s[1] <= 16_384, "{s:?}"); + } +} diff --git a/crates/ui-egui/src/present_tests.rs b/crates/ui-egui/src/present_tests.rs index 4a3819c09..631184bba 100644 --- a/crates/ui-egui/src/present_tests.rs +++ b/crates/ui-egui/src/present_tests.rs @@ -13,11 +13,13 @@ pub(crate) struct Ui { pub(crate) ctx: egui::Context, pub(crate) app: FigApp, pub(crate) time: f64, + /// A display's pixels per point and the biggest texture side its GPU takes (None: egui's defaults). + pub(crate) hidpi: Option<(f32, usize)>, } impl Ui { pub(crate) fn new(s: Session) -> Self { - let mut u = Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0 }; + let mut u = Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0, hidpi: None }; u.frames(3, Vec::new); u } @@ -29,8 +31,12 @@ impl Ui { /// [`Self::frame`], returning what egui output (the AccessKit tree when it's enabled). pub(crate) fn frame_output(&mut self, events: Vec) -> egui::FullOutput { self.time += 1.0 / 60.0; - let input = + let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), events, ..Default::default() }; + if let Some((ppp, side)) = self.hidpi { + input.max_texture_side = Some(side); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(ppp); + } let app = &mut self.app; let mut out = self.ctx.run_ui(input, |ui| app.ui(ui)); out.textures_delta.clear(); diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 7c216bcae..3cb52d2b9 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-06 · **Change:** patch (`proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-08 · **Change:** patch (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) **Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except media control, every transition and easing exist; key/gamepad triggers take controller buttons, @@ -91,7 +91,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Widgets react to clicks in a presented prototype | done | clicks only, like on the canvas | | Interactive components: instances play their variant's interactions, overridden per trigger | done | | | Drag-driven animations that follow the pointer, in their direction | done | | -| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537). Devices not compared with Figma's | +| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537); a frame too big for one texture at device scale (taller than about 2900 units at 1440 wide on a 2x display) shows the part in view from a second texture at device scale over the capped whole-frame one, drawn again when it stops covering the view and not while the view moves (#2127). Devices not compared with Figma's | | Hotspot hints, inspect panel in the presenter, comments in the presenter | done | | | Hide UI in the presenter (Options menu, Cmd/Ctrl+\) | done | the bar above the prototype and the navigation bar under it go away and the prototype takes their room; a toast names the key that brings them back; `proto.presentOptions {hideUi}`, kept for later presentations (#1820) | | Preview pane following edits live | done | | @@ -107,6 +107,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-08 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` | | 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. | | 2026-10-30 | minor | Opening a link in place: Open link has "Open in new tab", on by default; off, the web build's own tab goes to the link after the notice (or at once with it skipped); the desktop app has no tab of its own and opens the browser either way. Saved in files only when off (`openInNewTab`) and read from REST files. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 031521f51..0764fca6c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -652,6 +652,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-08 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | | 2026-11-04 | patch | M4, #1970: justified Chinese, Japanese and Korean text, written without spaces between words, aligns its right edge: the room on each line but a paragraph's last goes between its characters, each a word of its own as for line breaking ("Justify aligns the first word in each line of text to the left-most edge, and the last to the right-most edge"), wherever a line could break there, so none opens before a full stop or closing bracket, nor after an opening one. Latin text widens its spaces as before; mixed text widens both. A gap is reordered with the line's runs as a space of no width would be, so one beside a Hebrew word in Chinese text, or beside a Chinese word within that Hebrew, opens beside the word, not inside it. `figcraft_text::breaks::justify_between`, beside `break_between`, says where. Evidence: `tests::justified_ideographs_spread_the_room_between_characters` (fails on main). | | 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` puts it into the loop whose segments are the chain between the ends, at the gap and in the loop's own order, so a hole keeps its winding whichever end was clicked first; a loop listed out of walking order is left as it was. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | From 005cc73264c162e0cbcd63053ee5405ace8cb870 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 8 Nov 2026 20:00:05 -0500 Subject: [PATCH 006/129] M5: the presenter's detail texture takes the frame's bounds from its whole texture (#2127) detail_texture worked out the frame's export bounds again on every frame, even for a frame that fits one texture; the caller already has them in the whole-frame texture. The docs rows carry today's date. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/present/actions.rs | 11 ++++++----- crates/ui-egui/src/present/draw.rs | 2 +- docs/prototyping-parity.md | 4 ++-- docs/target-app-parity.md | 4 ++-- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index 52d75fa88..ec23bd8be 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -266,15 +266,17 @@ impl Presenter { (t, clock) } - /// The part of the frame `id` in view (`visible`, page units) at the full pixel scale `px`, for - /// a frame whose whole texture is capped below it (see [`detail_plan`]). While the view moves - /// (`moving`) it only returns a detail already rendered, the capped texture showing under it. + /// The part of the frame `id` (its whole texture covering `whole`, page units) in view + /// (`visible`) at the full pixel scale `px`, for a frame whose whole texture is capped below it + /// (see [`detail_plan`]). While the view moves (`moving`) it only returns a detail already + /// rendered, the capped texture showing under it. pub(super) fn detail_texture( &mut self, ctx: &egui::Context, doc: &Document, id: NodeId, px: f64, + whole: figcraft_geom::Rect, visible: figcraft_geom::Rect, moving: bool, now: f64, @@ -293,8 +295,7 @@ impl Presenter { return None; } let side = ctx.input(|i| i.max_texture_side) as f64 - 2.0; - let bounds = figcraft_render::export_bounds(doc, id)?; - let rect = detail_plan(bounds, visible, px, side)?; + let rect = detail_plan(whole, visible, px, side)?; let pix = figcraft_render::render_area_at(doc, &[id], rect, texture_scale_for(rect, px, side), t)?; let img = crate::render_worker::screen_image(&pix, doc.color_profile); let tex = ctx.load_texture(format!("present-detail-{}", id.0), img, egui::TextureOptions::LINEAR); diff --git a/crates/ui-egui/src/present/draw.rs b/crates/ui-egui/src/present/draw.rs index c8bd8248f..28bc11891 100644 --- a/crates/ui-egui/src/present/draw.rs +++ b/crates/ui-egui/src/present/draw.rs @@ -83,7 +83,7 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte let (a, b) = (l.place.page(shown.min), l.place.page(shown.max)); let visible = figcraft_geom::Rect::new(a.x, a.y, b.x, b.y); let moving = p.fling.is_some() || p.drag_scroll.is_some() || p.wheel.is_some(); - if let Some(d) = p.detail_texture(ctx, &l.disp, p.current, px, visible, moving, now) { + if let Some(d) = p.detail_texture(ctx, &l.disp, p.current, px, to.bounds, visible, moving, now) { on_clip.image(d.tex.id(), l.place.rect(d.bounds), uv, Color32::WHITE); } } diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 3cb52d2b9..113e1de57 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-08 · **Change:** patch (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) **Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except media control, every transition and easing exist; key/gamepad triggers take controller buttons, @@ -107,7 +107,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| -| 2026-11-08 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | +| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` | | 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. | | 2026-10-30 | minor | Opening a link in place: Open link has "Open in new tab", on by default; off, the web build's own tab goes to the link after the notice (or at once with it skipped); the desktop app has no tab of its own and opens the browser either way. Saved in files only when off (`openInNewTab`) and read from REST files. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0764fca6c..b801fb1fd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -652,7 +652,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| -| 2026-11-08 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | +| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | | 2026-11-04 | patch | M4, #1970: justified Chinese, Japanese and Korean text, written without spaces between words, aligns its right edge: the room on each line but a paragraph's last goes between its characters, each a word of its own as for line breaking ("Justify aligns the first word in each line of text to the left-most edge, and the last to the right-most edge"), wherever a line could break there, so none opens before a full stop or closing bracket, nor after an opening one. Latin text widens its spaces as before; mixed text widens both. A gap is reordered with the line's runs as a space of no width would be, so one beside a Hebrew word in Chinese text, or beside a Chinese word within that Hebrew, opens beside the word, not inside it. `figcraft_text::breaks::justify_between`, beside `break_between`, says where. Evidence: `tests::justified_ideographs_spread_the_room_between_characters` (fails on main). | | 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` puts it into the loop whose segments are the chain between the ends, at the gap and in the loop's own order, so a hole keeps its winding whichever end was clicked first; a loop listed out of walking order is left as it was. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). | From 982035aa7e6470491e8c0c452615466727fa2ea3 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Mon, 9 Nov 2026 11:53:22 +0100 Subject: [PATCH 007/129] M8: select the containing frame when clicking its background --- ROADMAP.md | 2 +- crates/engine/src/canvas/tools.rs | 3 ++ crates/engine/src/canvas/tools/drag.rs | 38 +++++++++++++----- .../engine/src/selection_behaviour_tests.rs | 39 +++++++++++++++++++ docs/ui-parity.md | 5 ++- 5 files changed, 74 insertions(+), 13 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 651f3ab2e..d4f1cb6b6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (clicking a device frame’s background after selecting a layer inside it selects the containing frame; dragging there still marquees its children (M8); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index a3284cd52..1cc3eb4af 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -422,6 +422,9 @@ pub(crate) enum Gesture { additive: bool, base: Vec, within: Option, + /// A click stepping out of a selected descendant picks its frame. Wait for a real drag + /// before replacing that selection with the marquee's contents. + pending_click: bool, }, Move { start: Point, diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index 64d48bc86..8038bf91c 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -76,8 +76,8 @@ impl Session { } // A frame's name label picks the frame itself. The background of a top-level frame with // layers in it is like the canvas (a press starts a marquee inside it) unless the frame is - // selected; an empty frame (or a widget, or a board object such as a sticky) is picked and - // dragged. + // selected; stepping out from a selected descendant is handled by the marquee below. + // An empty frame (or a widget, or a board object such as a sticky) is picked and dragged. let board_background = |leaf: NodeId| { !sel.contains(&leaf) && doc.node(leaf).is_some_and(|n| { @@ -85,11 +85,8 @@ impl Session { }) }; let label = label_at(&doc, page, &self.tool.labels, ev.p()); - let target = label.or_else(|| { - self.hit(&doc, page, ev.p(), ev.tol() * 2.0) - .filter(|leaf| ev.cmd || !board_background(*leaf)) - .map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)) - }); + let hit = label.or_else(|| self.hit(&doc, page, ev.p(), ev.tol() * 2.0)); + let target = label.or_else(|| hit.filter(|leaf| ev.cmd || !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd))); // A press inside the selection's box that reaches nothing above it (an unfilled shape's // inside, the frame or canvas behind it, or a layer stacked below the selected layer the // press is in) drags the selection. In a gap between selected layers, what's there is hit. @@ -171,10 +168,22 @@ impl Session { } None => { let within = self.marquee_within(ev.p())?; - if !ev.shift { + // Clicking the background of the frame containing the current selection steps + // out to that frame. Keep the marquee gesture (without a Move interaction), so + // dragging here still selects its contents and cannot leave a stale snapshot. + let parent = hit.filter(|f| !ev.shift && !ev.cmd && within == Some(*f) && sel.iter().any(|s| doc.is_ancestor(*f, *s))); + if let Some(f) = parent { + self.set_selection(vec![f]); + } else if !ev.shift { self.set_selection(vec![]); } - self.tool.gesture = Gesture::Marquee { start: ev.p(), additive: ev.shift, base: if ev.shift { sel } else { vec![] }, within }; + self.tool.gesture = Gesture::Marquee { + start: ev.p(), + additive: ev.shift, + base: if ev.shift { sel } else { vec![] }, + within, + pending_click: parent.is_some(), + }; } } Ok(()) @@ -195,9 +204,18 @@ impl Session { it.label = if ev.alt { "Duplicate" } else { "Move" }.into(); } } + if let Gesture::Marquee { start, pending_click, .. } = &mut g + && *pending_click + { + if within_slop(ev, *start) { + self.tool.gesture = g; + return Ok(()); + } + *pending_click = false; + } let res = match &g { Gesture::None => return self.hover(ev), - Gesture::Marquee { start, additive, base, within } => { + Gesture::Marquee { start, additive, base, within, .. } => { let r = Rect::from_points(*start, ev.p()); self.tool.overlay.marquee = Some([r.x0, r.y0, r.x1, r.y1]); // Cmd/Ctrl: the nested layers it touches. diff --git a/crates/engine/src/selection_behaviour_tests.rs b/crates/engine/src/selection_behaviour_tests.rs index c58527286..4947d3db3 100644 --- a/crates/engine/src/selection_behaviour_tests.rs +++ b/crates/engine/src/selection_behaviour_tests.rs @@ -108,6 +108,42 @@ fn sorted(mut v: Vec) -> Vec { v } +#[test] +fn clicking_a_device_background_after_its_nested_button_selects_the_device() { + let mut s = Session::new(); + let device = id(&ex(&mut s, "frame.create", json!({"x": 132, "y": -148, "width": 440, "height": 956}))); + let button = id(&ex(&mut s, "frame.create", json!({"parent": device, "x": 155, "y": 30, "width": 130, "height": 34}))); + rect(&mut s, 10.0, 5.0, Some(button)); + ex(&mut s, "layout.add", json!({"ids": [button], "direction": "horizontal"})); + ex(&mut s, "select.set", json!({"ids": [button]})); + let before = s.doc().unwrap().clone(); + let history = s.undo_depth(); + s.pointer(&ev(PointerKind::Down, 352.0, 330.0, NONE)).unwrap(); + assert_eq!(s.selection(), vec![device], "the parent is selected on press"); + // Small pointer jitter must not turn the click into a zero-sized marquee. + s.pointer(&ev(PointerKind::Move, 353.0, 330.0, NONE)).unwrap(); + s.pointer(&ev(PointerKind::Up, 353.0, 330.0, NONE)).unwrap(); + s.pointer(&ev(PointerKind::Hover, 353.0, 330.0, NONE)).unwrap(); + assert_eq!(s.selection(), vec![device], "the parent stays selected after release and hover"); + assert_eq!(*s.doc().unwrap(), before); + assert_eq!(s.undo_depth(), history, "selection adds no edit history"); +} + +#[test] +fn dragging_a_device_background_after_its_child_still_marquees_and_closes_cleanly() { + let mut s = Session::new(); + let k = scene(&mut s); + ex(&mut s, "select.set", json!({"ids": [k.d]})); + drag(&mut s, (390.0, 290.0), (190.0, 10.0), NONE); + assert_eq!(s.selection(), vec![k.n], "a background drag selects the nested frame"); + assert!(s.ds().unwrap().interaction.is_none(), "a marquee leaves no move snapshot behind"); + ex(&mut s, "node.set", json!({"id": k.n, "props": {"opacity": 0.5}})); + click(&mut s, 30.0, 130.0, NONE); + assert_eq!(s.doc().unwrap().node(k.n).unwrap().opacity, 0.5, "the next click keeps the edit"); + ex(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().node(k.n).unwrap().opacity, 1.0, "the edit retains its undo step"); +} + #[test] fn clicking_selects_by_the_documented_rules() { let mut s = Session::new(); @@ -130,6 +166,9 @@ fn clicking_selects_by_the_documented_rules() { ((520.0, 120.0), NONE, vec![], vec![k.r2], "a locked layer can't be selected on the canvas: the click goes to what is under it"), ((520.0, 220.0), NONE, vec![k.r], vec![], "a hidden layer can't be selected on the canvas (empty canvas deselects)"), ((390.0, 290.0), NONE, vec![k.r], vec![], "the background of a top-level frame with layers is like the canvas: a click deselects"), + ((390.0, 290.0), NONE, vec![k.c], vec![k.f], "clicking the containing frame's background steps out from its child"), + ((390.0, 290.0), NONE, vec![k.d], vec![k.f], "stepping out works from a deeper descendant too"), + ((390.0, 290.0), NONE, vec![], vec![], "without a selected descendant the background remains canvas-like"), ((390.0, 290.0), NONE, vec![k.f], vec![k.f], "a selected top-level frame stays selected when its background is clicked"), ((390.0, 290.0), CMD, vec![], vec![k.f], "silent: Cmd/Ctrl-click on a frame's background selects the frame (the deepest layer there)"), ((640.0, 40.0), NONE, vec![], vec![k.empty], "an empty top-level frame is selected by a click on it"), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 463be3b47..ca3528f59 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (a click on the containing frame’s background steps out from a selected descendant, while a drag there still marquees its children (M8, local interaction improvement; not measured against Figma); 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: @@ -56,7 +56,7 @@ interaction feel not yet compared. | Item | Status | Notes | |---|---|---| -| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to one axis (#498); a marquee selects what it touches; from a top-level frame's background, the layers inside it; locked and hidden layers are skipped (`selection_behaviour_tests`) | +| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to one axis (#498); a marquee selects what it touches; from a top-level frame's background, the layers inside it; clicking that background with a descendant selected steps out to the containing frame (a local interaction improvement, not measured against Figma), and pointer jitter keeps it selected; locked and hidden layers are skipped (`selection_behaviour_tests`) | | Deep select (Cmd/Ctrl-click, Cmd/Ctrl-marquee) | done | | | Select layer menu (every layer under the click) | done | | | Enter / Shift+Enter (children / parent), Tab / Shift+Tab (siblings) | done | Tab renames the next layer while renaming | @@ -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 | M8: a click on the background of a top-level frame containing a selected descendant now selects that frame, instead of clearing selection and showing Page. The first press stays a marquee gesture without an edit snapshot: pointer jitter keeps the frame selected, a drag still selects its children, and later edits retain their undo step. Synthetic regressions cover an auto layout button inside a device frame and a deeper descendant; the supplied real file was checked locally and is not committed. This is a local interaction improvement, not a new Figma parity claim. Verified: the real file and a native screenshot; 16 selection tests and 1111 UI tests passed. The engine suite passed 1899 tests, with one pre-existing table row-growth failure also reproduced without this fix (3 ignored). Counts 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 62f02f305126cda8cb1657f3b0e6fea2ddc89939 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Mon, 9 Nov 2026 11:55:35 +0100 Subject: [PATCH 008/129] M8: keep the roadmap unchanged for the selection fix --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index d4f1cb6b6..651f3ab2e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (clicking a device frame’s background after selecting a layer inside it selects the containing frame; dragging there still marquees its children (M8); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through From 71229fa8da83ede0d2d88de446ea480e1bb45dae Mon Sep 17 00:00:00 2001 From: Carbocode Date: Mon, 9 Nov 2026 12:19:04 +0100 Subject: [PATCH 009/129] M2: align canvas padding bands with inside strokes --- ROADMAP.md | 3 +- crates/ui-egui/src/canvas/handles.rs | 22 +++--- .../src/canvas/handles/padding_tests.rs | 69 +++++++++++++++++++ docs/auto-layout-parity.md | 4 +- 4 files changed, 88 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/canvas/handles/padding_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 651f3ab2e..50c363e8b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (canvas padding bands follow included inside strokes; the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M2: Canvas padding bands follow the inner edge of included inside strokes, including per-side weights; gap bands use the same content insets. Geometry regression tests cover stroke growth, exclusion and center/outside alignment. Dimensions and padding values are unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | diff --git a/crates/ui-egui/src/canvas/handles.rs b/crates/ui-egui/src/canvas/handles.rs index 491189eda..3ea0e8e33 100644 --- a/crates/ui-egui/src/canvas/handles.rs +++ b/crates/ui-egui/src/canvas/handles.rs @@ -350,13 +350,17 @@ fn al_zones(app: &FigApp) -> Option { app.to_screen(p.x, p.y) }; let band = |x0: f64, y0: f64, x1: f64, y1: f64| Rect::from_two_pos(to(x0, y0), to(x1, y1)); - let [pt, pr, pb, pl] = al.padding; + let [pt, pr, pb, pl] = al.padding.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 }); + let (it, ir, ib, il) = figcraft_layout::insets(n, al); let (fw, fh) = (n.width, n.height); + // Padding starts at the inside edge of an included stroke, as the layout's content does. + // The bands exclude the stroke itself so their labels and drags still edit only padding. + let (left, top, right, bottom) = (il - pl, it - pt, fw - ir + pr, fh - ib + pb); let bands = vec![ - (0, band(0.0, 0.0, fw, pt.max(4.0)), pt), - (1, band(fw - pr.max(4.0), 0.0, fw, fh), pr), - (2, band(0.0, fh - pb.max(4.0), fw, fh), pb), - (3, band(0.0, 0.0, pl.max(4.0), fh), pl), + (0, band(left, top, right, top + pt.max(4.0)), pt), + (1, band(right - pr.max(4.0), top, right, bottom), pr), + (2, band(left, bottom - pb.max(4.0), right, bottom), pb), + (3, band(left, top, left + pl.max(4.0), bottom), pl), ]; // An auto gap shows (and is dragged from) the distance the layout gives it; the drag makes it a // fixed gap again, as typing one does. @@ -369,8 +373,8 @@ fn al_zones(app: &FigApp) -> Option { let mut tracks = Vec::new(); if let Some(g) = figcraft_layout::grid_geometry(doc, id) { // Grid: bands between columns (column gap) and between rows (row gap), and the tracks. - let (top, bottom) = (g.rows.first().map(|r| r.0).unwrap_or(pt), g.rows.last().map(|r| r.1).unwrap_or(fh - pb)); - let (left, right) = (g.columns.first().map(|c| c.0).unwrap_or(pl), g.columns.last().map(|c| c.1).unwrap_or(fw - pr)); + let (top, bottom) = (g.rows.first().map(|r| r.0).unwrap_or(it), g.rows.last().map(|r| r.1).unwrap_or(fh - ib)); + let (left, right) = (g.columns.first().map(|c| c.0).unwrap_or(il), g.columns.last().map(|c| c.1).unwrap_or(fw - ir)); for pair in g.columns.windows(2) { if let [a, b] = pair { gaps.push(main(band(a.1, top, b.0, bottom), false, al.gap)); @@ -396,7 +400,7 @@ fn al_zones(app: &FigApp) -> Option { let flip = |r: figcraft_geom::Rect| if vertical { figcraft_geom::Rect::new(r.y0, r.x0, r.y1, r.x1) } else { r }; let fband = |x0: f64, y0: f64, x1: f64, y1: f64| if vertical { band(y0, x0, y1, x1) } else { band(x0, y0, x1, y1) }; // Main-axis length and padding, cross-axis length and padding. - let (mw, mp0, mp1, cw, cp0, cp1) = if vertical { (fh, pt, pb, fw, pl, pr) } else { (fw, pl, pr, fh, pt, pb) }; + let (mw, mp0, mp1, cw, cp0, cp1) = if vertical { (fh, it, ib, fw, il, ir) } else { (fw, il, ir, fh, it, ib) }; let boxes: Vec = figcraft_layout::flow_children(doc, id) .into_iter() .filter_map(|c| doc.node(c)) @@ -799,4 +803,6 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { #[cfg(test)] mod character_fill_tests; #[cfg(test)] +mod padding_tests; +#[cfg(test)] mod region_tests; diff --git a/crates/ui-egui/src/canvas/handles/padding_tests.rs b/crates/ui-egui/src/canvas/handles/padding_tests.rs new file mode 100644 index 000000000..c361c2da5 --- /dev/null +++ b/crates/ui-egui/src/canvas/handles/padding_tests.rs @@ -0,0 +1,69 @@ +//! Padding bands follow the content box, including the frame's inside stroke. + +use egui::Rect; +use figcraft_doc::NodeId; +use figcraft_engine::{Session, params::id_of}; +use serde_json::json; + +use super::al_zones; +use crate::layers_drag_tests::Ui; + +fn scene() -> (Ui, NodeId) { + let mut s = Session::new(); + let f = id_of( + &s.execute( + "frame.create", + &json!({"x": 100, "y": 100, "width": 300, "height": 200, + "props": {"layout": "horizontal", "gap": 10, "padding": [10, 20, 30, 40], "stroke": "#000000", "strokeWeight": 4, "strokeAlign": "inside"} + }), + ) + .unwrap()["id"], + ) + .unwrap(); + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + (Ui::new(s), f) +} + +#[test] +fn padding_bands_follow_uniform_and_individual_inside_strokes() { + let (mut u, f) = scene(); + for (props, stroke) in [ + (json!({"strokeWeight": 4}), [4.0; 4]), + (json!({"strokeWeight": 24}), [24.0; 4]), + (json!({"strokeSides": [8, 12, 16, 24]}), [8.0, 12.0, 16.0, 24.0]), + (json!({"strokesIncluded": false}), [0.0; 4]), + (json!({"strokesIncluded": true, "strokeAlign": "center"}), [0.0; 4]), + (json!({"strokeAlign": "outside"}), [0.0; 4]), + ] { + u.app.run("node.set", json!({"ids": [f], "props": props})); + let [t, r, b, l] = stroke; + let expected = [ + (l, t, 300.0 - r, t + 10.0), + (300.0 - r - 20.0, t, 300.0 - r, 200.0 - b), + (l, 200.0 - b - 30.0, 300.0 - r, 200.0 - b), + (l, t, l + 40.0, 200.0 - b), + ]; + let zones = al_zones(&u.app).unwrap(); + for ((side, band, value), (x0, y0, x1, y1)) in zones.bands.iter().zip(expected) { + let expected = Rect::from_two_pos(u.app.to_screen(100.0 + x0, 100.0 + y0), u.app.to_screen(100.0 + x1, 100.0 + y1)); + assert_eq!(*band, expected, "side {side}, stroke {stroke:?}"); + assert_eq!(*value, [10.0, 20.0, 30.0, 40.0][*side]); + } + } +} + +#[test] +fn gap_bands_span_the_content_box_inside_stroke_and_padding() { + let (mut u, f) = scene(); + for _ in 0..2 { + u.app.run("shape.rectangle", json!({"parent": f, "width": 40, "height": 20})); + } + u.app.run("select.set", json!({"ids": [f]})); + for (mode, expected) in [("horizontal", (184.0, 114.0, 194.0, 266.0)), ("vertical", (144.0, 134.0, 376.0, 144.0))] { + u.app.run("node.set", json!({"ids": [f], "props": {"layout": mode}})); + let zones = al_zones(&u.app).unwrap(); + assert_eq!(zones.gaps.len(), 1); + let (x0, y0, x1, y1) = expected; + assert_eq!(zones.gaps[0].rect, Rect::from_two_pos(u.app.to_screen(x0, y0), u.app.to_screen(x1, y1))); + } +} diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index f60cd4350..1f55d3b5f 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-03 · **Change:** patch (a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (canvas padding bands follow included inside strokes; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -52,6 +52,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Padding per side (uniform, vertical/horizontal, individual) | pass | `padding_and_stroke_rules` | | A frame is never smaller than its padding (plus an included inside stroke), even when Fixed, hugging or given a smaller max | **fixed** | was free to shrink below its padding | | Strokes included: only the frame's own **inside** stroke takes up space; center and outside strokes never do | **fixed** | every stroke alignment counted before; per-side inside weights count per side (silent on individual weights) | +| Canvas padding and gap bands follow the included inside stroke | **fixed** | Padding bands begin at the stroke's inner edge; flow gap bands span the available content box. Uniform and individual weights, excluded strokes and center/outside alignment are covered by `canvas::handles::padding_tests`. | | New auto layout includes inside strokes by default | **fixed** | the default was excluded | | Strokes included / excluded setting in the Design panel | **added** | `strokesIncluded` existed as a prop only | | Gap: fixed distance; negative gaps overlap | pass | `gap_rules` | @@ -101,6 +102,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M2: Canvas padding bands follow the inner edge of included inside strokes, including per-side weights; gap bands use the same content insets. Geometry regression tests cover stroke growth, exclusion and center/outside alignment. Dimensions and padding values are unchanged. | | 2026-11-05 | patch | M2, #1823: Suggest auto layout is no longer Add auto layout under another name: `layout.suggest` splits a frame's layers into rows (Vertical) or else columns (Horizontal) by the gaps between their boxes, wraps each band of several layers in a new frame without fill or clipping that hugs it, and repeats inside it (16 levels, 1,000 layers per frame at most). The frame keeps its size; gap and padding come from the bands, so layers keep their boxes where the gaps are even and the bands start at the same offset; instances and layers inside them are refused; uneven gaps (smallest used), bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes come back as `warnings`. A band frame hugs only when its own split succeeds: a band whose layers overlap along both axes gets no auto layout and stays Fixed, so it cannot reflow those children. `direction` sets the top level only; one undo step; `layout.add` is unchanged. Tests in `layout_suggest_tests.rs` | | 2026-11-02 | patch | M2: 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. The modifier was ignored before. Test: `padding_individual_tests` | | 2026-11-03 | patch | M2, #1825: baseline alignment of a layer without text (an icon next to a text) puts its bottom on the line's baseline, as the help center's figure shows ("the bottoms of the icon and the word home are aligned on the red line"); it kept to the top of the line. A layer reaching below the text's baseline moves the text down, and a line with no text lines the layers' bottoms up (the documentation is silent; CSS baseline alignment does the same). Tests: `alignment_rules` (three cases), engine `baseline_alignment_puts_an_icons_bottom_on_the_text_baseline`. Numbers unchanged. | From d329e126749fe3b07c8271b664146436a12e511a Mon Sep 17 00:00:00 2001 From: Carbocode Date: Mon, 9 Nov 2026 12:31:40 +0100 Subject: [PATCH 010/129] M2: resize padding through central grips with linked-side previews --- ROADMAP.md | 3 +- crates/ui-egui/src/canvas/handles.rs | 52 ++++++---- .../src/canvas/handles/padding_tests.rs | 96 ++++++++++++++++++- docs/auto-layout-parity.md | 15 ++- docs/ui-parity.md | 5 +- 5 files changed, 148 insertions(+), 23 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 50c363e8b..3e1250607 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (canvas padding bands follow included inside strokes; the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (padding drags start only on central grips; canvas padding bands follow included inside strokes; the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | | 2026-11-09 | patch | M2: Canvas padding bands follow the inner edge of included inside strokes, including per-side weights; gap bands use the same content insets. Geometry regression tests cover stroke growth, exclusion and center/outside alignment. Dimensions and padding values are unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | diff --git a/crates/ui-egui/src/canvas/handles.rs b/crates/ui-egui/src/canvas/handles.rs index 3ea0e8e33..dea5deb48 100644 --- a/crates/ui-egui/src/canvas/handles.rs +++ b/crates/ui-egui/src/canvas/handles.rs @@ -331,6 +331,18 @@ struct Zones { tracks: Vec<[Pos2; 2]>, } +/// A small screen-space target at the padding band's centre. Keep it independent of the band's +/// size and zoom: the rest of the band belongs to ordinary canvas selection and movement. +fn padding_handle(side: usize, band: Rect) -> Rect { + Rect::from_center_size(band.center(), if side.is_multiple_of(2) { vec2(20.0, 12.0) } else { vec2(12.0, 20.0) }) +} + +/// Alt links opposing sides, Alt+Shift all four. Shift alone retains the existing axis gesture. +/// Painting and editing share this rule so the highlighted sides are exactly those that change. +fn padding_affects(side: usize, candidate: usize, modifiers: egui::Modifiers) -> bool { + candidate == side || (modifiers.alt && modifiers.shift) || ((modifiers.alt || modifiers.shift) && candidate == (side + 2) % 4) +} + fn al_zones(app: &FigApp) -> Option { let ds = app.session.ds().ok()?; if ds.selection.len() != 1 || ds.text_edit.is_some() || ds.vector_edit.is_some() { @@ -511,7 +523,7 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) { draw_crop(app, painter, id, &img, r); return; } - let hover = painter.ctx().input(|i| i.pointer.hover_pos()); + let (hover, modifiers) = painter.ctx().input(|i| (i.pointer.hover_pos(), i.modifiers)); let tool_move = app.session.tool.tool == figcraft_engine::ToolId::Move && !app.session.tool.busy(); let dragging: Option = painter.ctx().data(|d| d.get_temp(drag_id())); if !tool_move && dragging.is_none() { @@ -520,17 +532,23 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) { let Some(z) = al_zones(app) else { return }; let active_side = match &dragging { Some(Drag::Padding { side, .. }) => Some(*side), - _ => None, + _ => hover.and_then(|pos| z.bands.iter().find(|(side, r, _)| padding_handle(*side, *r).contains(pos)).map(|(side, _, _)| *side)), }; for seg in &z.tracks { painter.add(Shape::dashed_line(seg, Stroke::new(1.0, PINK.gamma_multiply(0.6)), 3.0, 3.0)); } for (side, r, v) in &z.bands { - let hot = hover.is_some_and(|h| r.contains(h)) || active_side == Some(*side); + let handle = padding_handle(*side, *r); + let linked = active_side.is_some_and(|active| padding_affects(active, *side, modifiers)); + let hot = hover.is_some_and(|h| r.contains(h) || handle.contains(h)) || linked; if hot { painter.rect_filled(*r, CornerRadius::ZERO, PINK.gamma_multiply(0.25)); - pink_label(painter, crate::canvas::fmt(*v), r.center()); + let offset = if side.is_multiple_of(2) { vec2(28.0, 0.0) } else { vec2(0.0, -20.0) }; + pink_label(painter, crate::canvas::fmt(*v), r.center() + offset); } + let grip = Rect::from_center_size(handle.center(), if side.is_multiple_of(2) { vec2(16.0, 4.0) } else { vec2(4.0, 16.0) }); + painter.rect_filled(grip, CornerRadius::same(2), if linked { PINK } else { PINK.gamma_multiply(0.6) }); + painter.rect_stroke(grip, CornerRadius::same(2), Stroke::new(if linked { 1.5 } else { 1.0 }, Color32::WHITE), StrokeKind::Outside); } let drag_key = match &dragging { Some(Drag::Gap { key, .. }) => Some(*key), @@ -551,12 +569,12 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) { /// Pointer handling; returns true when a handle owns the pointer this frame. pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { - let (pressed, down, released, shift) = ctx.input(|i| { + let (pressed, down, released, modifiers) = ctx.input(|i| { ( i.pointer.button_pressed(egui::PointerButton::Primary), i.pointer.primary_down(), i.pointer.button_released(egui::PointerButton::Primary), - i.modifiers.shift, + i.modifiers, ) }); let dragging: Option = ctx.data(|d| d.get_temp(drag_id())); @@ -567,7 +585,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { return true; } if down { - apply(app, &drag, pos, shift); + apply(app, &drag, pos, modifiers); ctx.set_cursor_icon(egui::CursorIcon::Grabbing); } if released || !down { @@ -672,14 +690,14 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { } let Some(Zones { id, bands, gaps, .. }) = al_zones(app) else { return false }; for (side, r, v) in bands { - if r.contains(pos) { + if padding_handle(side, r).contains(pos) { ctx.set_cursor_icon(if side % 2 == 0 { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }); if pressed { let _ = app.session.begin_interaction("Padding"); ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Padding { id, side, start: pos, value: v })); - return true; } - return false; + // Hover owns the cursor too; otherwise the canvas tool replaces the resize arrows. + return true; } } for g in gaps { @@ -696,7 +714,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { false } -fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { +fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, modifiers: egui::Modifiers) { let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0).max(1e-6); match drag { Drag::Gradient { id, fills, index, which } => { @@ -745,10 +763,12 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { _ => pos.x - start.x, }) / zoom; let v = (value + d).round().max(0.0); - let key = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"].get(*side).copied().unwrap_or("paddingTop"); - // Shift drags both sides of the axis together. - let props = - if shift { if side % 2 == 0 { json!({"paddingVertical": v}) } else { json!({"paddingHorizontal": v}) } } else { json!({ key: v }) }; + let props: serde_json::Map = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"] + .iter() + .enumerate() + .filter(|(candidate, _)| padding_affects(*side, *candidate, modifiers)) + .map(|(_, key)| ((*key).to_owned(), json!(v))) + .collect(); let _ = app.session.execute("node.set", &json!({"ids": [id], "props": props})); } Drag::Crop { id, fills, index, which, start, rect } => { @@ -764,7 +784,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { let (cx, cy) = corners.get(*which).copied().unwrap_or((x1, y1)); let (ow, oh) = (cx - ax, cy - ay); let (mut nw, mut nh) = (u.0 - ax, u.1 - ay); - if !shift { + if !modifiers.shift { // Node aspect matters: the unit box is not square in pixels. let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return }; let k = ((nw * n.width).abs() / (ow * n.width).abs().max(1e-9)).max((nh * n.height).abs() / (oh * n.height).abs().max(1e-9)); diff --git a/crates/ui-egui/src/canvas/handles/padding_tests.rs b/crates/ui-egui/src/canvas/handles/padding_tests.rs index c361c2da5..a67fadcf7 100644 --- a/crates/ui-egui/src/canvas/handles/padding_tests.rs +++ b/crates/ui-egui/src/canvas/handles/padding_tests.rs @@ -1,11 +1,11 @@ //! Padding bands follow the content box, including the frame's inside stroke. -use egui::Rect; +use egui::{Event, Rect, vec2}; use figcraft_doc::NodeId; use figcraft_engine::{Session, params::id_of}; use serde_json::json; -use super::al_zones; +use super::{Drag, al_zones, drag_id}; use crate::layers_drag_tests::Ui; fn scene() -> (Ui, NodeId) { @@ -67,3 +67,95 @@ fn gap_bands_span_the_content_box_inside_stroke_and_padding() { assert_eq!(zones.gaps[0].rect, Rect::from_two_pos(u.app.to_screen(x0, y0), u.app.to_screen(x1, y1))); } } + +#[test] +fn padding_drag_starts_only_on_the_central_handle_and_undoes_in_one_step() { + let (mut u, f) = scene(); + u.app.run("node.set", json!({"ids": [f], "props": {"strokeWeight": 24}})); + u.frame(vec![]); + let top = al_zones(&u.app).unwrap().bands[0].1; + // The band away from its handle remains available to ordinary canvas tools. + let away = top.center() + vec2(50.0, 0.0); + u.button(away, true); + assert!(!matches!(u.ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Padding { .. }))); + u.button(away, false); + u.app.run("select.set", json!({"ids": [f]})); + u.frame(vec![]); + + let center = al_zones(&u.app).unwrap().bands[0].1.center(); + let zoom = u.app.session.ds().unwrap().view.zoom as f32; + u.button(center, true); + assert!(matches!(u.ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Padding { side: 0, .. }))); + let to = center + vec2(0.0, 6.0 * zoom); + u.frame(vec![Event::PointerMoved(to)]); + u.button(to, false); + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [16.0, 20.0, 30.0, 40.0]); + u.app.run("edit.undo", json!({})); + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [10.0, 20.0, 30.0, 40.0]); +} + +#[test] +fn every_padding_grip_has_a_resize_cursor_and_links_the_requested_sides() { + for modifiers in + [egui::Modifiers::NONE, egui::Modifiers::ALT, egui::Modifiers::SHIFT, egui::Modifiers { alt: true, shift: true, ..Default::default() }] + { + for side in 0..4 { + let (mut u, f) = scene(); + let center = al_zones(&u.app).unwrap().bands[side].1.center(); + let output = u.frame_with(vec![Event::PointerMoved(center)], modifiers); + let cursor = if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }; + assert_eq!(output.platform_output.cursor_icon, cursor, "padding side {side}"); + u.button(center, true); + assert!(matches!(u.ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Padding { side: active, .. }) if active == side)); + let zoom = u.app.session.ds().unwrap().view.zoom as f32; + let delta = [vec2(0.0, 6.0), vec2(-6.0, 0.0), vec2(0.0, -6.0), vec2(6.0, 0.0)][side] * zoom; + let to = center + delta; + u.frame_with(vec![Event::PointerMoved(to)], modifiers); + u.button(to, false); + let mut expected = [10.0, 20.0, 30.0, 40.0]; + let value = expected[side] + 6.0; + if modifiers.alt && modifiers.shift { + expected = [value; 4]; + } else { + expected[side] = value; + if modifiers.alt || modifiers.shift { + expected[(side + 2) % 4] = value; + } + } + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, expected); + u.app.run("edit.undo", json!({})); + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [10.0, 20.0, 30.0, 40.0]); + } + } +} + +#[test] +fn modifier_keys_highlight_linked_padding_bands_before_and_during_a_drag() { + let (mut u, _) = scene(); + let zones = al_zones(&u.app).unwrap(); + let center = zones.bands[0].1.center(); + u.frame(vec![Event::PointerMoved(center)]); + // Pressing modifiers without moving the pointer previews the other affected sides. + for (modifiers, active) in [ + (egui::Modifiers::NONE, [true, false, false, false]), + (egui::Modifiers::ALT, [true, false, true, false]), + (egui::Modifiers { alt: true, shift: true, ..Default::default() }, [true; 4]), + (egui::Modifiers::NONE, [true, false, false, false]), + ] { + let output = u.frame_with(vec![], modifiers); + let shapes = crate::live_tests::flat(&output.shapes); + for ((side, rect, _), active) in zones.bands.iter().zip(active) { + let lit = shapes.iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.rect == *rect && r.fill == super::PINK.gamma_multiply(0.25))); + assert_eq!(lit, active, "side {side}, modifiers {modifiers:?}"); + } + } + u.button(center, true); + let modifiers = egui::Modifiers { alt: true, shift: true, ..Default::default() }; + let output = u.frame_with(vec![], modifiers); + let zones = al_zones(&u.app).unwrap(); + let shapes = crate::live_tests::flat(&output.shapes); + for (_, rect, _) in &zones.bands { + assert!(shapes.iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.rect == *rect && r.fill == super::PINK.gamma_multiply(0.25)))); + } + u.button(center, false); +} diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 1f55d3b5f..d3ae1fa83 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (canvas padding bands follow included inside strokes; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (padding drags start only on central grips; canvas padding bands follow included inside strokes; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -27,6 +27,16 @@ outside the new frame’s layout flow and adding an unnecessary level to the lay the selected container makes later changes to a child’s size reflow its siblings directly. Selecting several groups still wraps that selection in a shared auto layout frame. +## Canvas padding grips + +Padding bands begin at the inner edge of an included inside stroke. Each band's central grip +starts a padding drag; the rest of the band still highlights on hover and remains available to +ordinary canvas tools. The grip shows vertical resize arrows on the top and bottom, horizontal +arrows on the sides. Alt synchronises the opposite side to the dragged value, and Alt+Shift +synchronises all four. Shift alone retains the existing opposite-side gesture. Affected bands +and grips highlight immediately when modifiers change, both before and during a drag. One undo +restores every affected side. + ## Rules from the documentation Status: **pass** (a case in the suite holds), **fixed** (the suite found a divergence, now fixed), @@ -52,7 +62,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Padding per side (uniform, vertical/horizontal, individual) | pass | `padding_and_stroke_rules` | | A frame is never smaller than its padding (plus an included inside stroke), even when Fixed, hugging or given a smaller max | **fixed** | was free to shrink below its padding | | Strokes included: only the frame's own **inside** stroke takes up space; center and outside strokes never do | **fixed** | every stroke alignment counted before; per-side inside weights count per side (silent on individual weights) | -| Canvas padding and gap bands follow the included inside stroke | **fixed** | Padding bands begin at the stroke's inner edge; flow gap bands span the available content box. Uniform and individual weights, excluded strokes and center/outside alignment are covered by `canvas::handles::padding_tests`. | +| Canvas padding and gap bands follow the included inside stroke | **fixed** | Padding bands begin at the stroke's inner edge; flow gap bands span the available content box. Only the central grip starts a padding drag; hovering the band still highlights it. Geometry and pointer interactions are covered by `canvas::handles::padding_tests`. | | New auto layout includes inside strokes by default | **fixed** | the default was excluded | | Strokes included / excluded setting in the Design panel | **added** | `strokesIncluded` existed as a prop only | | Gap: fixed distance; negative gaps overlap | pass | `gap_rules` | @@ -102,6 +112,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | | 2026-11-09 | patch | M2: Canvas padding bands follow the inner edge of included inside strokes, including per-side weights; gap bands use the same content insets. Geometry regression tests cover stroke growth, exclusion and center/outside alignment. Dimensions and padding values are unchanged. | | 2026-11-05 | patch | M2, #1823: Suggest auto layout is no longer Add auto layout under another name: `layout.suggest` splits a frame's layers into rows (Vertical) or else columns (Horizontal) by the gaps between their boxes, wraps each band of several layers in a new frame without fill or clipping that hugs it, and repeats inside it (16 levels, 1,000 layers per frame at most). The frame keeps its size; gap and padding come from the bands, so layers keep their boxes where the gaps are even and the bands start at the same offset; instances and layers inside them are refused; uneven gaps (smallest used), bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes come back as `warnings`. A band frame hugs only when its own split succeeds: a band whose layers overlap along both axes gets no auto layout and stays Fixed, so it cannot reflow those children. `direction` sets the top level only; one undo step; `layout.add` is unchanged. Tests in `layout_suggest_tests.rs` | | 2026-11-02 | patch | M2: 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. The modifier was ignored before. Test: `padding_individual_tests` | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 463be3b47..82e01ba23 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (padding drags start only on central grips; 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: @@ -120,7 +120,7 @@ interaction feel not yet compared. | Masks: what a mask hides doesn't take clicks; a mask group's box is the mask's | done | | | Layout grids (Ctrl+G) | done | columns, rows and grid; stretch, left, centre, right; Auto count; several per frame; styles; not shown or snapped on a rotated frame; a nested frame's grids snap but only top-level frames draw them | | Gamut warnings for Display P3 files | done | colour picker note; View ▸ Soft-proof sRGB stripes what sRGB can't show (the canvas itself is sRGB) | -| Gradient and padding/gap handles on the canvas | done | the gradient's handles and stops show while its picker is open, and dragging one keeps the picker open (#1852) | +| Gradient and padding/gap handles on the canvas | done | each padding band has a central grip, which alone starts padding drags; the value label sits beside it and the whole band still highlights on hover (`canvas::handles::padding_tests`); the gradient's handles and stops show while its picker is open, and dragging one keeps the picker open (#1852) | | Hover outline, selection colours, handle sizes | done | measured from UI3 screenshots; the outline follows the layer's geometry, rounded corners (each radius and the smoothing) included, whatever the stroke alignment (#1506) | | Cursors per tool and modifier | done | the engine names a cursor for every tool, modifier and hover target (`tool.overlay.cursor`, tabled in `cursor_tests`) and the UI shows the system's or draws its own at the pointer (`cursors.rs`, `cursors_tests`; original glyphs from lines and the code-drawn icons). Arrow for Move and Scale; two-headed arrows on the handles that follow the handle and the box's rotation; outside a corner a curved rotate arrow turned to that corner, turning with the pointer while rotating; crosshair for the frame, section, slice, shape, pencil and Text tools; the I-beam over a text with the Text tool and over the text being edited; the pen as a cross with what a click does beside it (nothing: a new point; a ring: closes, connects to or goes on from a point; a plus: adds a point on a segment, also Alt in vector edit mode; a curve: bends, the Bend tool or Cmd/Ctrl); open and closed hand for the Hand tool, Space and the middle button; zoom in and out (Alt) while Z is held; eyedropper; comment pin; the copy cursor with Alt over a selected layer and while Alt-dragging; not-allowed while a drag resizes, rotates or moves a layer inside an instance (it is undone on release) and over a layers row that takes no drop. Ruler guides and gradient, crop and padding handles keep their own cursors (the tool's used to replace them). `ui.inspect` reports `cursor`. Left: no cursor for removing a point with the pen (the pen doesn't remove points); the drawn cursors follow the pointer a frame behind the system's; not compared with Figma's side by side | | Multiplayer cursors, cursor chat, spotlight | partial | in live sessions: named cursors, chat bubbles that fade, `/` to chat, spotlight from your avatar's menu with a banner; no audio or reactions | @@ -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 | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | | 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 d7432c3989854f497d5584e0a8723dd407e69a00 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Mon, 9 Nov 2026 12:34:06 +0100 Subject: [PATCH 011/129] M2: leave the roadmap unchanged for padding fixes --- ROADMAP.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 3e1250607..651f3ab2e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** patch (padding drags start only on central grips; canvas padding bands follow included inside strokes; the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,8 +365,6 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | -| 2026-11-09 | patch | M2: Canvas padding bands follow the inner edge of included inside strokes, including per-side weights; gap bands use the same content insets. Geometry regression tests cover stroke growth, exclusion and center/outside alignment. Dimensions and padding values are unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | | 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged | From b27ab45feefdc1ccd98d983fa0018d2d6712b674 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 14:57:41 -0500 Subject: [PATCH 012/129] M5: tests for the presenter detail: reuse, re-render on an edit, and detail_plan's edge cases (#2133 review) Pins the detail texture being kept while nothing changes and made again after an edit, and detail_plan's empty, outside, invalid, partly outside, margin-shrinking, over-cap and small-side cases. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 triaged and briefed; Sonnet 5.5 verified and wrote at medium --- crates/ui-egui/src/present/tests.rs | 62 +++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index 9ed1fa665..dde23026f 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -474,3 +474,65 @@ fn presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale() { assert!(s[0] * s[1] <= 16_777_216 + s[0] + s[1] && s[0] <= 16_384 && s[1] <= 16_384, "{s:?}"); } } + +/// A tall frame on a 2x display, presented, and the page area its detail texture shows. +fn tall_hidpi(side: usize) -> Ui { + let mut session = figcraft_engine::Session::new(); + let frame = id(&session.execute("node.create", &json!({"type": "frame", "width": 1440, "height": 9701})).unwrap()); + session.execute("node.create", &json!({"type": "rectangle", "parent": frame, "x": 100, "y": 100, "width": 300, "height": 200})).unwrap(); + let mut ui = Ui::new(session); + ui.hidpi = Some((2.0, side)); + ui.run("proto.present", json!({"start": frame})); + ui.app.ui.present.as_mut().unwrap().view.scale = PresentScale::FitWidth; + ui.frames(2, Vec::new); + ui +} + +fn detail_bounds(ui: &Ui) -> Option { + ui.app.ui.present.as_ref().and_then(|p| p.detail.as_ref().map(|(_, d)| d.bounds)) +} + +#[test] +fn the_detail_is_kept_while_nothing_changes_and_made_again_when_the_frame_does() { + let mut ui = tall_hidpi(16_384); + let tex_id = |ui: &Ui| ui.app.ui.present.as_ref().and_then(|p| p.detail.as_ref().map(|(_, d)| d.tex.id())); + let first = tex_id(&ui).expect("a detail is drawn"); + let bounds = detail_bounds(&ui).unwrap(); + assert!( + bounds.x0 == 0.0 && bounds.y0 == 0.0 && bounds.x1 == 1440.0 && bounds.y1 > 860.0 && bounds.y1 < 9701.0, + "the view and a margin: {bounds:?}" + ); + ui.frames(5, Vec::new); + assert_eq!(tex_id(&ui), Some(first), "the same view makes no new render"); + let rect = ui.app.session.doc().unwrap().node(ui.app.session.doc().unwrap().first_page().unwrap()).unwrap().children[0]; + let child = ui.app.session.doc().unwrap().node(rect).unwrap().children[0]; + ui.run("node.set", json!({"id": child, "props": {"x": 120}})); + ui.frames(3, Vec::new); + assert_ne!(tex_id(&ui), Some(first), "an edit renders the detail again"); +} + +#[test] +fn detail_plan_edge_cases() { + use figcraft_geom::Rect as R; + let bounds = R::new(0.0, 0.0, 1440.0, 9701.0); + let side = 16382.0; + // Nothing in view, an empty or invalid view, a bad scale: no detail. + for v in [R::new(0.0, 10_000.0, 1440.0, 11_000.0), R::new(0.0, 100.0, 0.0, 100.0)] { + assert!(actions::detail_plan(bounds, v, 2.0, side).is_none(), "{v:?}"); + } + for px in [0.0, -1.0, f64::NAN] { + assert!(actions::detail_plan(bounds, R::new(0.0, 0.0, 1440.0, 860.0), px, side).is_none(), "{px}"); + } + // Partly outside: the part inside. + let r = actions::detail_plan(bounds, R::new(0.0, -500.0, 1440.0, 360.0), 2.0, side).unwrap(); + assert!(r.y0 == 0.0 && r.y1 >= 360.0, "{r:?}"); + // A view whose quarter margin passes the pixel cap gets a smaller margin that fits. + let r = actions::detail_plan(bounds, R::new(0.0, 3000.0, 1440.0, 5000.0), 2.0, side).unwrap(); + assert!(r.height() > 2000.0 && r.height() < 3000.0 && r.width() * r.height() * 4.0 <= 16_777_216.0, "{r:?}"); + // A view past the caps by itself is returned as it is. + let tall = R::new(0.0, 1000.0, 1440.0, 5000.0); + assert_eq!(actions::detail_plan(bounds, tall, 2.0, side), Some(tall)); + // A small texture limit: the view alone is over it, so it is the view. + let view = R::new(0.0, 0.0, 1440.0, 860.0); + assert_eq!(actions::detail_plan(bounds, view, 2.0, 2048.0), Some(view)); +} From e7dfc815d16555d6c4bdbe775466a81927a1092b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 06:49:59 -0500 Subject: [PATCH 013/129] M7: Present mode: a click in comment mode adds a comment on the frame (#2209) In the presenter's comment mode a click on the presented frame starts a draft at the clicked point (mapped back through the presenter's placement) and opens the editor's composer beside a pin; posting adds the comment on the frame's page and the mode stays on. Escape closes the draft, then the mode. While the mode is on the player ignores the pointer, so no click interaction or hotspot fires. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/canvas/comments.rs | 84 +++++++++++++++++++-------- crates/ui-egui/src/comments_tests.rs | 82 ++++++++++++++++++++++++++ crates/ui-egui/src/present/chrome.rs | 14 ++++- crates/ui-egui/src/present/player.rs | 7 ++- docs/prototyping-parity.md | 5 +- 5 files changed, 163 insertions(+), 29 deletions(-) diff --git a/crates/ui-egui/src/canvas/comments.rs b/crates/ui-egui/src/canvas/comments.rs index a9e9c1267..b7410f9c6 100644 --- a/crates/ui-egui/src/canvas/comments.rs +++ b/crates/ui-egui/src/canvas/comments.rs @@ -830,37 +830,46 @@ fn escape(app: &mut FigApp, ctx: &egui::Context) -> bool { true } +/// The draft's composer next to its pin at `at` (screen), kept inside `bounds`; posting adds the +/// comment (on `page` when given, else the current one) and shows its thread. The editor and the +/// presenter both draw it here. +fn draft_composer(app: &mut FigApp, ctx: &egui::Context, at: Pos2, bounds: Rect, page: Option) { + let Some((x, y, mut text)) = app.ui.comments.draft.clone() else { return }; + let t = Tokens::get(ctx); + let people = app.session.doc().map(|d| d.comment_people()).unwrap_or_default(); + let me = me(app); + let mut pick = std::mem::take(&mut app.ui.comments.mention); + let mut post = false; + egui::Area::new(Id::unique("comment_draft")).order(egui::Order::Foreground).fixed_pos(popover_pos(at, bounds)).show(ctx, |ui| { + popover_frame(&t).show(ui, |ui| { + ui.set_width(POPOVER_W - 24.0); + post = composer(ui, Id::unique("comment_draft_text"), &mut text, tr("Add a comment"), &people, &me, &mut pick); + }); + }); + app.ui.comments.mention = pick; + if post { + let mut params = json!({"x": x, "y": y, "text": text.trim(), "anchor": true}); + if let (Some(page), Some(o)) = (page, params.as_object_mut()) { + o.insert("page".into(), json!(page)); + } + let r = app.run("comment.add", params); + app.ui.comments.draft = None; + if let Some(id) = r.and_then(|v| v.get("id").and_then(Value::as_u64)) { + app.ui.comments.show(id); + } + } else if let Some(d) = &mut app.ui.comments.draft { + d.2 = text; + } +} + /// The thread popover and the draft composer, floating next to their pins on the canvas. pub fn popovers(app: &mut FigApp, ctx: &egui::Context) { if escape(app, ctx) { return; } let canvas = app.canvas.rect; - if let Some((x, y, mut text)) = app.ui.comments.draft.clone() { - let t = Tokens::get(ctx); - let people = app.session.doc().map(|d| d.comment_people()).unwrap_or_default(); - let me = me(app); - let mut pick = std::mem::take(&mut app.ui.comments.mention); - let mut post = false; - egui::Area::new(Id::unique("comment_draft")).order(egui::Order::Foreground).fixed_pos(popover_pos(app.to_screen(x, y), canvas)).show( - ctx, - |ui| { - popover_frame(&t).show(ui, |ui| { - ui.set_width(POPOVER_W - 24.0); - post = composer(ui, Id::unique("comment_draft_text"), &mut text, tr("Add a comment"), &people, &me, &mut pick); - }); - }, - ); - app.ui.comments.mention = pick; - if post { - let r = app.run("comment.add", json!({"x": x, "y": y, "text": text.trim(), "anchor": true})); - app.ui.comments.draft = None; - if let Some(id) = r.and_then(|v| v.get("id").and_then(Value::as_u64)) { - app.ui.comments.show(id); - } - } else if let Some(d) = &mut app.ui.comments.draft { - d.2 = text; - } + if let Some((x, y, _)) = app.ui.comments.draft { + draft_composer(app, ctx, app.to_screen(x, y), canvas, None); return; } let Some(open) = app.ui.comments.open else { return }; @@ -1228,6 +1237,31 @@ pub fn presenter(app: &mut FigApp, ctx: &egui::Context, frame: NodeId, place: cr if let Some(id) = clicked { toggle(app, id); } + // A click on the presented frame (not on a pin or a popover) starts a comment there: the + // presented point back to the frame as designed. + let frame_rect = place.rect(fb).intersect(clip); + let click = ctx.input(|i| if i.pointer.primary_clicked() { i.pointer.interact_pos() } else { None }); + if clicked.is_none() + && let Some(q) = click.filter(|q| frame_rect.contains(*q)) + && ctx.layer_id_at(q).is_none_or(|l| l.order == egui::Order::Background) + { + let pt = place.page(q); + start_draft(app, fb.x0 + (pt.x - place.page_min.0), fb.y0 + (pt.y - place.page_min.1)); + } + if let Some((x, y, _)) = app.ui.comments.draft { + let at = to_screen((x, y)); + let r = pin_rect(at); + egui::Area::new(Id::unique("present_comment_draft_pin")).order(egui::Order::Foreground).fixed_pos(r.min).interactable(false).show( + ctx, + |ui| { + let (rr, _) = ui.allocate_exact_size(r.size(), Sense::hover()); + ui.painter().rect_filled(rr, BUBBLE, ACCENT); + ui.painter().circle_filled(rr.center(), 3.0, crate::theme::ACCENT_ON); + }, + ); + draft_composer(app, ctx, at, ctx.content_rect(), doc.page_of(frame)); + return; + } match app.ui.comments.open.and_then(|o| pins.iter().find(|p| p.id == o)) { Some(p) => thread(app, ctx, p.id, p.at, ctx.content_rect()), // A thread on another frame (or none) closes. diff --git a/crates/ui-egui/src/comments_tests.rs b/crates/ui-egui/src/comments_tests.rs index 0ccd32f10..f97f4f0a4 100644 --- a/crates/ui-egui/src/comments_tests.rs +++ b/crates/ui-egui/src/comments_tests.rs @@ -272,6 +272,88 @@ fn the_presenter_shows_the_frames_comments() { let _ = other; } +/// A presenter on a 400 x 300 frame (at page 50, 40) with a second frame, the comment mode on. +/// Returns the harness, the frame, the other frame and the presented frame's top-left on screen. +fn present_comment_mode() -> (Ui, figcraft_doc::NodeId, figcraft_doc::NodeId, Pos2) { + let mut s = Session::new(); + let f = id(&s.execute("node.create", &json!({"type": "frame", "x": 50, "y": 40, "width": 400, "height": 300})).unwrap()); + let other = id(&s.execute("node.create", &json!({"type": "frame", "x": 700, "y": 0, "width": 400, "height": 300})).unwrap()); + let mut u = Ui::new(s); + u.run("proto.present", json!({"start": f})); + key(&mut u, Key::C, Modifiers::NONE); + assert_eq!(u.app.inspect()["presenter"]["comments"], true); + let screen = egui::Rect::from_min_size(pos2(0.0, 80.0), vec2(1440.0, 820.0)); + (u, f, other, screen.center() - vec2(200.0, 150.0)) +} + +fn comment_count(u: &Ui) -> usize { + u.app.session.doc().unwrap().comments.len() +} + +#[test] +fn a_click_in_the_presenters_comment_mode_adds_a_comment_on_the_frame() { + let (mut u, f, _, frame_min) = present_comment_mode(); + click(&mut u, frame_min + vec2(120.0, 90.0)); + assert!(comments(&u)["draft"].is_array(), "the click opens a draft"); + u.frame(vec![Event::Text("hello".into())]); + key(&mut u, Key::Enter, Modifiers::NONE); + assert_eq!(comment_count(&u), 1); + let doc = u.app.session.doc().unwrap(); + let c = &doc.comments[0]; + assert_eq!(c.first.text, "hello"); + assert_eq!(c.anchor, Some(f)); + assert!((c.x - 120.0).abs() <= 1.0 && (c.y - 90.0).abs() <= 1.0, "frame-relative spot {},{}", c.x, c.y); + assert_eq!(u.app.inspect()["presenter"]["comments"], true, "the mode stays on"); + assert!(u.app.ui.present.is_some()); +} + +#[test] +fn a_click_off_the_frame_in_the_presenters_comment_mode_adds_no_draft() { + let (mut u, _, _, frame_min) = present_comment_mode(); + click(&mut u, frame_min + vec2(-60.0, 90.0)); + assert!(comments(&u)["draft"].is_null()); + assert_eq!(comment_count(&u), 0); + assert_eq!(u.app.inspect()["presenter"]["comments"], true); +} + +#[test] +fn escape_closes_the_presenters_draft_then_the_mode() { + let (mut u, _, _, frame_min) = present_comment_mode(); + click(&mut u, frame_min + vec2(120.0, 90.0)); + u.frame(vec![Event::Text("draft".into())]); + key(&mut u, Key::Escape, Modifiers::NONE); + assert!(comments(&u)["draft"].is_null(), "Escape closes the draft"); + assert_eq!(comment_count(&u), 0, "and adds no comment"); + assert_eq!(u.app.inspect()["presenter"]["comments"], true); + assert!(u.app.ui.present.is_some()); + key(&mut u, Key::Escape, Modifiers::NONE); + assert_eq!(u.app.inspect()["presenter"]["comments"], false, "Escape with no draft turns the mode off"); + assert!(u.app.ui.present.is_some(), "and keeps the presentation open"); + key(&mut u, Key::Escape, Modifiers::NONE); + assert!(u.app.ui.present.is_none(), "with the mode off Escape still ends the presentation"); +} + +#[test] +fn a_click_in_the_presenters_comment_mode_does_not_navigate() { + let (mut u, f, other, frame_min) = present_comment_mode(); + u.run("proto.interaction.add", json!({"id": f, "trigger": {"type": "onClick"}, "action": {"type": "navigate", "dest": other}})); + u.frames(2, Vec::new); + click(&mut u, frame_min + vec2(120.0, 90.0)); + u.frames(30, Vec::new); + assert_eq!(u.app.inspect()["presenter"]["current"], json!(f), "the click placed a comment, it didn't follow the link"); + assert!(comments(&u)["draft"].is_array()); +} + +#[test] +fn typing_c_into_the_presenters_draft_keeps_the_mode_on() { + let (mut u, _, _, frame_min) = present_comment_mode(); + click(&mut u, frame_min + vec2(120.0, 90.0)); + u.frame(vec![Event::Text("c".into())]); + key(&mut u, Key::C, Modifiers::NONE); + assert_eq!(u.app.inspect()["presenter"]["comments"], true); + assert!(comments(&u)["draft"].is_array()); +} + #[derive(Clone, Default)] struct Clip(Arc>>); diff --git a/crates/ui-egui/src/present/chrome.rs b/crates/ui-egui/src/present/chrome.rs index 4fc57ff0f..d29fd40e2 100644 --- a/crates/ui-egui/src/present/chrome.rs +++ b/crates/ui-egui/src/present/chrome.rs @@ -94,12 +94,24 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) { } _ => {} } + // Escape with no draft or thread open turns the comment mode off and keeps the presentation. + let cu = &app.ui.comments; + if live + && pres.view.comments + && pres.link_notice.is_none() + && cu.open.is_none() + && cu.draft.is_none() + && !cu.mention.active() + && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) + { + pres.view.comments = false; + } if live && pres.view.comments && let Some((frame, place, clip)) = pres.shown { crate::comments::presenter(app, &ctx, frame, place, clip); - } else if app.ui.comments.open.is_some() { + } else if app.ui.comments.open.is_some() || app.ui.comments.draft.is_some() { app.ui.comments.close(); } finish(app, &mut pres); diff --git a/crates/ui-egui/src/present/player.rs b/crates/ui-egui/src/present/player.rs index 8bcbea09d..ff821620a 100644 --- a/crates/ui-egui/src/present/player.rs +++ b/crates/ui-egui/src/present/player.rs @@ -60,7 +60,12 @@ pub(super) fn player(p: &mut Presenter, ui: &mut Ui, rect: Rect, now: f64, chrom // The pane only takes the keyboard while the pointer is over it. While a link notice shows // the prototype takes neither keys nor the pointer (Escape there cancels the notice). let keys = chrome.keys && p.link_notice.is_none() && (!chrome.pane || over); - input(p, &ctx, &l, InputMode { over_area: over && p.link_notice.is_none(), keys_on: keys, pane: chrome.pane, now }); + input( + p, + &ctx, + &l, + InputMode { over_area: over && p.link_notice.is_none() && !(p.view.comments && !chrome.pane), keys_on: keys, pane: chrome.pane, now }, + ); } else { p.pads.clear(); } diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 7c216bcae..50ebc706c 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-06 · **Change:** patch (`proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-10 · **Change:** patch (in the presenter's comment mode (C) a click on the presented frame starts a comment there and the mode stays on for the next one, Escape closes the draft and then the mode, measured in Figma's web app 2026-11-10 (#2209); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) **Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except media control, every transition and easing exist; key/gamepad triggers take controller buttons, @@ -92,7 +92,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Interactive components: instances play their variant's interactions, overridden per trigger | done | | | Drag-driven animations that follow the pointer, in their direction | done | | | Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537). Devices not compared with Figma's | -| Hotspot hints, inspect panel in the presenter, comments in the presenter | done | | +| Hotspot hints, inspect panel in the presenter, comments in the presenter | done | in comment mode (C) a click on the presented frame starts a comment there (a click off the frame does nothing, and the prototype's own click interactions don't fire) and the mode stays on for the next comment; Escape closes the draft, then the mode (the presentation stays open), as measured in Figma's web app 2026-11-10 (#2209). No comments sidebar in the presenter | | Hide UI in the presenter (Options menu, Cmd/Ctrl+\) | done | the bar above the prototype and the navigation bar under it go away and the prototype takes their room; a toast names the key that brings them back; `proto.presentOptions {hideUi}`, kept for later presentations (#1820) | | Preview pane following edits live | done | | | Edit interactions on several layers at once | done | | @@ -107,6 +107,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-10 | patch | M7, #2209: the presenter's comment mode showed the frame's pins but nothing started a comment. Measured in Figma's web app: with the mode on (C or the bar's comment button) a click on the presented frame drops a pin at the click and opens an "Add a comment" composer beside it; Enter posts, the pin stays at the same frame-relative spot and the mode stays on; a click on the background does nothing; Escape closes a composer, and with none open turns the mode off; the comment shows on the frame in the editor. Now the same: the click starts the draft at the point mapped back through the presenter's placement, the editor's composer is shared, the post carries the frame's page, the player ignores the pointer while the mode is on (no click interactions or hotspots fire), and Escape closes the draft, then the mode. Tests: `comments_tests::a_click_in_the_presenters_comment_mode_adds_a_comment_on_the_frame` and four more. | | 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` | | 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. | | 2026-10-30 | minor | Opening a link in place: Open link has "Open in new tab", on by default; off, the web build's own tab goes to the link after the notice (or at once with it skipped); the desktop app has no tab of its own and opens the browser either way. Saved in files only when off (`openInNewTab`) and read from REST files. | From fba314a340b0908a7d60c2ec145f327a581927a6 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 06:53:23 -0500 Subject: [PATCH 014/129] Present mode: comment mode drops only the prototype's presses; hover and the wheel still work (#2209) The pointer stayed off the prototype entirely in comment mode, which also stopped wheel scrolling and hover triggers. Only a press is now kept from it (a click there places a comment). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote (review fix) --- crates/ui-egui/src/present/input.rs | 6 +++++- crates/ui-egui/src/present/player.rs | 8 +++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/present/input.rs b/crates/ui-egui/src/present/input.rs index bfebd4b11..b8e94a22c 100644 --- a/crates/ui-egui/src/present/input.rs +++ b/crates/ui-egui/src/present/input.rs @@ -162,13 +162,16 @@ fn fire_pads(p: &mut Presenter, doc: &Document, root: NodeId, pads: &[String], n /// player takes the keyboard; `pane`: it plays in the preview pane (which always fits). pub(super) struct InputMode { pub over_area: bool, + /// Presses reach the prototype: false in the presenter's comment mode, where a click places a + /// comment (hover and the wheel still work). + pub clicks: bool, pub keys_on: bool, pub pane: bool, pub now: f64, } pub(super) fn input(p: &mut Presenter, ctx: &egui::Context, l: &Layout, mode: InputMode) { - let InputMode { over_area, keys_on, pane, now } = mode; + let InputMode { over_area, clicks, keys_on, pane, now } = mode; let (pos, pressed, released, down, wheel, velocity, dt, keys) = ctx.input(|i| { let keys: Vec<(egui::Key, egui::Modifiers)> = i .events @@ -190,6 +193,7 @@ pub(super) fn input(p: &mut Presenter, ctx: &egui::Context, l: &Layout, mode: In ) }); let keys = if keys_on { keys } else { Vec::new() }; + let pressed = pressed && clicks; // Controller buttons pressed while a link notice shows are dropped, as keys are. let pads = std::mem::take(&mut p.pads); let pads = if p.link_notice.is_none() { pads } else { Vec::new() }; diff --git a/crates/ui-egui/src/present/player.rs b/crates/ui-egui/src/present/player.rs index ff821620a..5e79cdbe2 100644 --- a/crates/ui-egui/src/present/player.rs +++ b/crates/ui-egui/src/present/player.rs @@ -64,7 +64,13 @@ pub(super) fn player(p: &mut Presenter, ui: &mut Ui, rect: Rect, now: f64, chrom p, &ctx, &l, - InputMode { over_area: over && p.link_notice.is_none() && !(p.view.comments && !chrome.pane), keys_on: keys, pane: chrome.pane, now }, + InputMode { + over_area: over && p.link_notice.is_none(), + clicks: !(p.view.comments && !chrome.pane), + keys_on: keys, + pane: chrome.pane, + now, + }, ); } else { p.pads.clear(); From 5d118c744715f423ab352d0e4034c022222719b9 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Tue, 10 Nov 2026 12:56:08 +0100 Subject: [PATCH 015/129] M2: keep padding grips reachable on tiny frames --- crates/ui-egui/src/canvas/handles.rs | 58 +++++++++----- .../src/canvas/handles/padding_tests.rs | 79 +++++++++++++++++++ docs/auto-layout-parity.md | 7 +- docs/ui-parity.md | 3 +- 4 files changed, 126 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/canvas/handles.rs b/crates/ui-egui/src/canvas/handles.rs index dea5deb48..16c97977f 100644 --- a/crates/ui-egui/src/canvas/handles.rs +++ b/crates/ui-egui/src/canvas/handles.rs @@ -331,10 +331,34 @@ struct Zones { tracks: Vec<[Pos2; 2]>, } -/// A small screen-space target at the padding band's centre. Keep it independent of the band's -/// size and zoom: the rest of the band belongs to ordinary canvas selection and movement. -fn padding_handle(side: usize, band: Rect) -> Rect { - Rect::from_center_size(band.center(), if side.is_multiple_of(2) { vec2(20.0, 12.0) } else { vec2(12.0, 20.0) }) +/// Screen-space grip targets. Opposite grips stay at least 20 pixels apart, moving outward from +/// their midpoint only when needed: tiny frames and zoomed-out content must not merge them into +/// one indistinguishable target. Bands keep their actual padding geometry. +fn padding_handles(bands: &[(usize, Rect, f64)]) -> Vec<(usize, Rect, f64)> { + bands + .iter() + .map(|&(side, band, value)| { + let mut center = band.center(); + if let Some((_, opposite, _)) = bands.iter().find(|(s, _, _)| *s == (side + 2) % 4) { + let (axis, other) = if side.is_multiple_of(2) { (&mut center.y, opposite.center().y) } else { (&mut center.x, opposite.center().x) }; + if (*axis - other).abs() < 20.0 { + *axis = (*axis + other) / 2.0 + if matches!(side, 0 | 3) { -10.0 } else { 10.0 }; + } + } + let rect = Rect::from_center_size(center, if side.is_multiple_of(2) { vec2(20.0, 12.0) } else { vec2(12.0, 20.0) }); + (side, rect, value) + }) + .collect() +} + +/// Resolve overlapping targets by distance to the visible grip, shared by hover and press. +/// Iteration order alone can let an earlier target steal clicks on a later grip's painted bar. +fn padding_at(handles: &[(usize, Rect, f64)], pos: Pos2) -> Option<(usize, Rect, f64)> { + handles + .iter() + .filter(|(_, rect, _)| rect.contains(pos)) + .min_by(|(_, a, _), (_, b, _)| a.center().distance_sq(pos).total_cmp(&b.center().distance_sq(pos))) + .copied() } /// Alt links opposing sides, Alt+Shift all four. Shift alone retains the existing axis gesture. @@ -530,21 +554,21 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) { return; } let Some(z) = al_zones(app) else { return }; + let handles = padding_handles(&z.bands); let active_side = match &dragging { Some(Drag::Padding { side, .. }) => Some(*side), - _ => hover.and_then(|pos| z.bands.iter().find(|(side, r, _)| padding_handle(*side, *r).contains(pos)).map(|(side, _, _)| *side)), + _ => hover.and_then(|pos| padding_at(&handles, pos).map(|(side, _, _)| side)), }; for seg in &z.tracks { painter.add(Shape::dashed_line(seg, Stroke::new(1.0, PINK.gamma_multiply(0.6)), 3.0, 3.0)); } - for (side, r, v) in &z.bands { - let handle = padding_handle(*side, *r); + for ((side, r, v), (_, handle, _)) in z.bands.iter().zip(&handles) { let linked = active_side.is_some_and(|active| padding_affects(active, *side, modifiers)); - let hot = hover.is_some_and(|h| r.contains(h) || handle.contains(h)) || linked; + let hot = hover.is_some_and(|h| r.contains(h)) || linked; if hot { painter.rect_filled(*r, CornerRadius::ZERO, PINK.gamma_multiply(0.25)); let offset = if side.is_multiple_of(2) { vec2(28.0, 0.0) } else { vec2(0.0, -20.0) }; - pink_label(painter, crate::canvas::fmt(*v), r.center() + offset); + pink_label(painter, crate::canvas::fmt(*v), handle.center() + offset); } let grip = Rect::from_center_size(handle.center(), if side.is_multiple_of(2) { vec2(16.0, 4.0) } else { vec2(4.0, 16.0) }); painter.rect_filled(grip, CornerRadius::same(2), if linked { PINK } else { PINK.gamma_multiply(0.6) }); @@ -689,16 +713,14 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { return false; } let Some(Zones { id, bands, gaps, .. }) = al_zones(app) else { return false }; - for (side, r, v) in bands { - if padding_handle(side, r).contains(pos) { - ctx.set_cursor_icon(if side % 2 == 0 { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }); - if pressed { - let _ = app.session.begin_interaction("Padding"); - ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Padding { id, side, start: pos, value: v })); - } - // Hover owns the cursor too; otherwise the canvas tool replaces the resize arrows. - return true; + if let Some((side, _, value)) = padding_at(&padding_handles(&bands), pos) { + ctx.set_cursor_icon(if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }); + if pressed { + let _ = app.session.begin_interaction("Padding"); + ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Padding { id, side, start: pos, value })); } + // Hover owns the cursor too; otherwise the canvas tool replaces the resize arrows. + return true; } for g in gaps { if g.rect.contains(pos) { diff --git a/crates/ui-egui/src/canvas/handles/padding_tests.rs b/crates/ui-egui/src/canvas/handles/padding_tests.rs index a67fadcf7..9f9d6e026 100644 --- a/crates/ui-egui/src/canvas/handles/padding_tests.rs +++ b/crates/ui-egui/src/canvas/handles/padding_tests.rs @@ -24,6 +24,85 @@ fn scene() -> (Ui, NodeId) { (Ui::new(s), f) } +/// The four visible grips in paint order, without relying on the hit-test geometry. +fn painted_grips(output: &egui::FullOutput) -> Vec { + crate::live_tests::flat(&output.shapes) + .iter() + .filter_map(|shape| match shape { + egui::Shape::Rect(r) + if r.fill == super::PINK.gamma_multiply(0.6) + && ((r.rect.width() == 16.0 && r.rect.height() == 4.0) || (r.rect.width() == 4.0 && r.rect.height() == 16.0)) => + { + Some(r.rect) + } + _ => None, + }) + .collect() +} + +/// Even collapsed content boxes and reduced zoom leave each painted grip independently usable. +#[test] +fn tiny_frames_keep_every_painted_padding_grip_reachable() { + for (width, height, zoom, stroke) in [ + (300.0, 4.0, 1.0, 0.0), + (300.0, 6.0, 1.0, 0.0), + (300.0, 10.0, 1.0, 0.0), + (300.0, 20.0, 0.25, 0.0), + (300.0, 20.0, 1.0, 8.0), + (4.0, 200.0, 1.0, 0.0), + (4.0, 4.0, 0.25, 0.0), + ] { + for side in 0_usize..4 { + let (mut u, f) = scene(); + u.app.run("node.set", json!({"ids": [f], "props": {"width": width, "height": height, "padding": 0, "strokeWeight": stroke}})); + u.app.session.ds_mut().unwrap().view.zoom = zoom; + let grips = painted_grips(&u.frame_output(vec![Event::PointerGone])); + assert_eq!(grips.len(), 4); + let center = grips[side].center(); + let output = u.frame_output(vec![Event::PointerMoved(center)]); + assert_eq!( + output.platform_output.cursor_icon, + if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal } + ); + u.button(center, true); + assert!( + matches!(u.ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Padding { side: active, .. }) if active == side), + "{width}x{height}, zoom {zoom}, stroke {stroke}, side {side}" + ); + let to = center + [vec2(0.0, 2.0), vec2(-2.0, 0.0), vec2(0.0, -2.0), vec2(2.0, 0.0)][side] * zoom as f32; + u.frame(vec![Event::PointerMoved(to)]); + u.button(to, false); + let mut expected = [0.0; 4]; + expected[side] = 2.0; + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, expected); + u.app.run("edit.undo", json!({})); + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [0.0; 4]); + } + } +} + +/// A painted side grip wins over a neighbouring grip's enlarged, overlapping hit target. +#[test] +fn overlapping_padding_targets_use_the_nearest_grip_for_hover_and_press() { + let (mut u, f) = scene(); + u.app.run("node.set", json!({"ids": [f], "props": {"width": 4, "height": 4, "padding": 0, "strokeWeight": 0}})); + let grips = painted_grips(&u.frame_output(vec![Event::PointerGone])); + assert_eq!(grips.len(), 4); + // On the upper part of the right bar, also inside the top grip's larger hit target. + let point = egui::pos2(grips[1].center().x - 1.0, grips[0].center().y + 5.0); + assert!(grips[1].contains(point)); + let handles = super::padding_handles(&al_zones(&u.app).unwrap().bands); + assert_eq!(handles.iter().filter(|(_, r, _)| r.contains(point)).count(), 2); + let output = u.frame_output(vec![Event::PointerMoved(point)]); + assert_eq!(output.platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal); + let shapes = crate::live_tests::flat(&output.shapes); + assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == grips[1] && r.fill == super::PINK))); + assert!(!shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == grips[0] && r.fill == super::PINK))); + u.button(point, true); + assert!(matches!(u.ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Padding { side: 1, .. }))); + u.button(point, false); +} + #[test] fn padding_bands_follow_uniform_and_individual_inside_strokes() { let (mut u, f) = scene(); diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index d3ae1fa83..122a34716 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (padding drags start only on central grips; canvas padding bands follow included inside strokes; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-10 · **Change:** patch (padding grips stay reachable on tiny frames and at reduced zoom; padding drags start only on central grips; canvas padding bands follow included inside strokes; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -35,7 +35,9 @@ ordinary canvas tools. The grip shows vertical resize arrows on the top and bott arrows on the sides. Alt synchronises the opposite side to the dragged value, and Alt+Shift synchronises all four. Shift alone retains the existing opposite-side gesture. Affected bands and grips highlight immediately when modifiers change, both before and during a drag. One undo -restores every affected side. +restores every affected side. On very small frames or at reduced zoom, opposite grips move +outward to stay at least 20 screen pixels apart; the padding bands keep their geometry. +Overlapping hit targets select the nearest visible grip for both hover and drag. ## Rules from the documentation @@ -112,6 +114,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. | | 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | | 2026-11-09 | patch | M2: Canvas padding bands follow the inner edge of included inside strokes, including per-side weights; gap bands use the same content insets. Geometry regression tests cover stroke growth, exclusion and center/outside alignment. Dimensions and padding values are unchanged. | | 2026-11-05 | patch | M2, #1823: Suggest auto layout is no longer Add auto layout under another name: `layout.suggest` splits a frame's layers into rows (Vertical) or else columns (Horizontal) by the gaps between their boxes, wraps each band of several layers in a new frame without fill or clipping that hugs it, and repeats inside it (16 levels, 1,000 layers per frame at most). The frame keeps its size; gap and padding come from the bands, so layers keep their boxes where the gaps are even and the bands start at the same offset; instances and layers inside them are refused; uneven gaps (smallest used), bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes come back as `warnings`. A band frame hugs only when its own split succeeds: a band whose layers overlap along both axes gets no auto layout and stays Fixed, so it cannot reflow those children. `direction` sets the top level only; one undo step; `layout.add` is unchanged. Tests in `layout_suggest_tests.rs` | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 82e01ba23..2274c4e05 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-09 · **Change:** minor (padding drags start only on central grips; the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (padding grips stay reachable on tiny frames and at reduced zoom; padding drags start only on central grips; 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: @@ -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-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. | | 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | | 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 | From 205fb12075b6d712d83ada03a3c264f56c46c930 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 08:06:04 -0500 Subject: [PATCH 016/129] Present mode: a click on the draft's own pin keeps the typed draft (#2209) The pin isn't interactable, so the click fell through and started a new draft. Review item on #2211. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote (review fix, no brief) --- crates/ui-egui/src/canvas/comments.rs | 5 ++++- crates/ui-egui/src/comments_tests.rs | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/comments.rs b/crates/ui-egui/src/canvas/comments.rs index b7410f9c6..1026ea47c 100644 --- a/crates/ui-egui/src/canvas/comments.rs +++ b/crates/ui-egui/src/canvas/comments.rs @@ -1241,8 +1241,11 @@ pub fn presenter(app: &mut FigApp, ctx: &egui::Context, frame: NodeId, place: cr // presented point back to the frame as designed. let frame_rect = place.rect(fb).intersect(clip); let click = ctx.input(|i| if i.pointer.primary_clicked() { i.pointer.interact_pos() } else { None }); + // The draft's own pin isn't interactable, so a click on it would start a new draft and lose + // the typed text: it is left alone. + let draft_pin = app.ui.comments.draft.as_ref().map(|(x, y, _)| pin_rect(to_screen((*x, *y)))); if clicked.is_none() - && let Some(q) = click.filter(|q| frame_rect.contains(*q)) + && let Some(q) = click.filter(|q| frame_rect.contains(*q) && !draft_pin.is_some_and(|r| r.contains(*q))) && ctx.layer_id_at(q).is_none_or(|l| l.order == egui::Order::Background) { let pt = place.page(q); diff --git a/crates/ui-egui/src/comments_tests.rs b/crates/ui-egui/src/comments_tests.rs index f97f4f0a4..f8d73f0d7 100644 --- a/crates/ui-egui/src/comments_tests.rs +++ b/crates/ui-egui/src/comments_tests.rs @@ -307,6 +307,18 @@ fn a_click_in_the_presenters_comment_mode_adds_a_comment_on_the_frame() { assert!(u.app.ui.present.is_some()); } +#[test] +fn a_click_on_the_presenters_draft_pin_keeps_the_typed_draft() { + let (mut u, _, _, frame_min) = present_comment_mode(); + let at = frame_min + vec2(120.0, 90.0); + click(&mut u, at); + u.frame(vec![Event::Text("typed".into())]); + // The pin's body sits above and right of the point it marks. + click(&mut u, at + vec2(6.0, -6.0)); + let draft = u.app.ui.comments.draft.clone(); + assert_eq!(draft.as_ref().map(|d| d.2.as_str()), Some("typed"), "the draft stays open with its text: {draft:?}"); +} + #[test] fn a_click_off_the_frame_in_the_presenters_comment_mode_adds_no_draft() { let (mut u, _, _, frame_min) = present_comment_mode(); From 4df32625e060229b283b046db4ccb38e03f1bffb Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 10 Nov 2026 10:18:41 -0500 Subject: [PATCH 017/129] Present mode comments: anchor within the presented frame, keep a draft that fails to post, drop a press held into comment mode (#2209) comment.add takes an optional `within` frame (with anchor true): the search starts at that frame, so a frame stacked over the presented one can't take the comment. The presenter's draft passes it. A draft whose comment.add fails is kept with its text, and a press begun before the comment mode started is dropped so its release is no click. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/comment.rs | 47 ++++++++++++++++++---- crates/ui-egui/src/canvas/comments.rs | 21 ++++++---- crates/ui-egui/src/comments_tests.rs | 56 +++++++++++++++++++++++++++ crates/ui-egui/src/present/input.rs | 15 +++++++ 4 files changed, 125 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 388d56d88..35ea38901 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -312,9 +312,12 @@ fn own(cmd: &str, m: &Message, who: &str, what: &str) -> crate::Result<()> { } /// A node to pin to: a node id on `page`, `true` for the innermost frame under the point, else none. -fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>) -> Option { +fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>, within: Option) -> Option { match v { - Some(Value::Bool(true)) => frame_at(doc, page, x, y), + Some(Value::Bool(true)) => match within.filter(|w| *w != page && doc.page_of(*w) == Some(page) && contains(doc, *w, x, y)) { + Some(w) => frame_in(doc, w, x, y, Some(w)), + None => frame_at(doc, page, x, y), + }, Some(v) => id_of(v).filter(|a| *a != page && doc.page_of(*a) == Some(page)), None => None, } @@ -670,7 +673,7 @@ pub fn specs() -> Vec { spec!( "comment.add", "Add comment", - "{x, y, text, page?, author?, anchor? (node id to pin to; true = innermost frame under the point)}", + "{x, y, text, page?, author?, anchor? (node id to pin to; true = innermost frame under the point), within? (with anchor true: search only inside this frame on the page, which is the anchor when no child holds the point)}", true, |s, p| { let x = req_num("comment.add", p, "x")?; @@ -682,7 +685,7 @@ pub fn specs() -> Vec { if !doc.pages.contains(&page) { return Err(bad("comment.add", format!("{page} is not a page"))); } - let anchor = anchor_at(doc, page, x, y, get(p, "anchor")); + let anchor = anchor_at(doc, page, x, y, get(p, "anchor"), id(p, "within")); let (lx, ly) = local(doc, anchor, x, y); let mut c = Comment { id: s.doc_mut()?.new_comment_id(), @@ -772,7 +775,7 @@ pub fn specs() -> Vec { let (x, y) = (req_num("comment.move", p, "x")?, req_num("comment.move", p, "y")?); let doc = s.doc()?; let page = doc.comment(id).map(|c| c.page).ok_or_else(|| bad("comment.move", "no comment"))?; - let anchor = anchor_at(doc, page, x, y, Some(get(p, "anchor").unwrap_or(&Value::Bool(true)))); + let anchor = anchor_at(doc, page, x, y, Some(get(p, "anchor").unwrap_or(&Value::Bool(true))), None); let (lx, ly) = local(doc, anchor, x, y); if let Some(c) = s.doc_mut()?.comment_mut(id) { (c.x, c.y, c.anchor) = (lx, ly, anchor); @@ -974,9 +977,20 @@ pub fn specs() -> Vec { /// Innermost frame (or component/instance/section) under a page point, for anchoring. fn frame_at(doc: &Document, page: NodeId, x: f64, y: f64) -> Option { + frame_in(doc, page, x, y, None) +} + +/// Whether the page point lies inside node `n`'s box. +fn contains(doc: &Document, n: NodeId, x: f64, y: f64) -> bool { + let Some(node) = doc.node(n) else { return false }; + let l = doc.world_transform(n).inverse() * geom::Point::new(x, y); + l.x >= 0.0 && l.y >= 0.0 && l.x <= node.width && l.y <= node.height +} + +/// The innermost frame-like or section under the point, searching from `root` (with `found` as the fallback). +fn frame_in(doc: &Document, root: NodeId, x: f64, y: f64, mut found: Option) -> Option { let pt = geom::Point::new(x, y); - let mut found = None; - let mut stack = vec![page]; + let mut stack = vec![root]; while let Some(parent) = stack.pop() { let Some(n) = doc.node(parent) else { continue }; for c in n.children.iter().rev() { @@ -1012,6 +1026,25 @@ mod tests { assert_eq!(super::parse_link("figcraft://comment/5/"), Some(5)); } + #[test] + fn comment_add_within_anchors_to_the_presented_frame() { + let mut s = Session::new(); + let mk = |s: &mut Session, params: serde_json::Value| crate::params::id_of(&s.execute("node.create", ¶ms).unwrap()["id"]).unwrap(); + let a = mk(&mut s, json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 200})); + let b = mk(&mut s, json!({"type": "frame", "x": 100, "y": 0, "width": 200, "height": 200})); + let anchor = |s: &mut Session, params: serde_json::Value| { + let c = s.execute("comment.add", ¶ms).unwrap(); + let id = c["id"].as_u64().unwrap(); + s.doc().unwrap().comment(id).unwrap().anchor + }; + assert_eq!(anchor(&mut s, json!({"x": 150, "y": 50, "text": "t", "anchor": true})), Some(b)); + assert_eq!(anchor(&mut s, json!({"x": 150, "y": 50, "text": "t", "anchor": true, "within": a})), Some(a)); + let c = mk(&mut s, json!({"type": "frame", "x": 120, "y": 20, "width": 50, "height": 50, "parent": a})); + assert_eq!(anchor(&mut s, json!({"x": 130, "y": 30, "text": "t", "anchor": true, "within": a})), Some(c)); + // A point outside `within` ignores it. + assert_eq!(anchor(&mut s, json!({"x": 250, "y": 50, "text": "t", "anchor": true, "within": a})), Some(b)); + } + #[test] fn comment_thread_lifecycle_and_anchoring() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/canvas/comments.rs b/crates/ui-egui/src/canvas/comments.rs index 1026ea47c..b12dd7907 100644 --- a/crates/ui-egui/src/canvas/comments.rs +++ b/crates/ui-egui/src/canvas/comments.rs @@ -833,7 +833,10 @@ fn escape(app: &mut FigApp, ctx: &egui::Context) -> bool { /// The draft's composer next to its pin at `at` (screen), kept inside `bounds`; posting adds the /// comment (on `page` when given, else the current one) and shows its thread. The editor and the /// presenter both draw it here. -fn draft_composer(app: &mut FigApp, ctx: &egui::Context, at: Pos2, bounds: Rect, page: Option) { +/// +/// `target` is the page and the presented frame when called from the presenter: the comment then +/// anchors within that frame. A comment that fails to post leaves the draft and its text. +fn draft_composer(app: &mut FigApp, ctx: &egui::Context, at: Pos2, bounds: Rect, target: Option<(NodeId, NodeId)>) { let Some((x, y, mut text)) = app.ui.comments.draft.clone() else { return }; let t = Tokens::get(ctx); let people = app.session.doc().map(|d| d.comment_people()).unwrap_or_default(); @@ -849,13 +852,17 @@ fn draft_composer(app: &mut FigApp, ctx: &egui::Context, at: Pos2, bounds: Rect, app.ui.comments.mention = pick; if post { let mut params = json!({"x": x, "y": y, "text": text.trim(), "anchor": true}); - if let (Some(page), Some(o)) = (page, params.as_object_mut()) { + if let (Some((page, frame)), Some(o)) = (target, params.as_object_mut()) { o.insert("page".into(), json!(page)); + o.insert("within".into(), json!(frame)); } - let r = app.run("comment.add", params); - app.ui.comments.draft = None; - if let Some(id) = r.and_then(|v| v.get("id").and_then(Value::as_u64)) { - app.ui.comments.show(id); + if let Some(r) = app.run("comment.add", params) { + app.ui.comments.draft = None; + if let Some(id) = r.get("id").and_then(Value::as_u64) { + app.ui.comments.show(id); + } + } else if let Some(d) = &mut app.ui.comments.draft { + d.2 = text; } } else if let Some(d) = &mut app.ui.comments.draft { d.2 = text; @@ -1262,7 +1269,7 @@ pub fn presenter(app: &mut FigApp, ctx: &egui::Context, frame: NodeId, place: cr ui.painter().circle_filled(rr.center(), 3.0, crate::theme::ACCENT_ON); }, ); - draft_composer(app, ctx, at, ctx.content_rect(), doc.page_of(frame)); + draft_composer(app, ctx, at, ctx.content_rect(), doc.page_of(frame).map(|page| (page, frame))); return; } match app.ui.comments.open.and_then(|o| pins.iter().find(|p| p.id == o)) { diff --git a/crates/ui-egui/src/comments_tests.rs b/crates/ui-egui/src/comments_tests.rs index f8d73f0d7..6cde5a6db 100644 --- a/crates/ui-egui/src/comments_tests.rs +++ b/crates/ui-egui/src/comments_tests.rs @@ -366,6 +366,62 @@ fn typing_c_into_the_presenters_draft_keeps_the_mode_on() { assert!(comments(&u)["draft"].is_array()); } +#[test] +fn a_comment_posted_in_the_overlap_anchors_to_the_presented_frame() { + let mut s = Session::new(); + let a = id(&s.execute("node.create", &json!({"type": "frame", "x": 50, "y": 40, "width": 400, "height": 300})).unwrap()); + // Stacked after `a` and overlapping its right part. + s.execute("node.create", &json!({"type": "frame", "x": 250, "y": 40, "width": 400, "height": 300})).unwrap(); + let mut u = Ui::new(s); + u.run("proto.present", json!({"start": a})); + key(&mut u, Key::C, Modifiers::NONE); + let screen = egui::Rect::from_min_size(pos2(0.0, 80.0), vec2(1440.0, 820.0)); + let frame_min = screen.center() - vec2(200.0, 150.0); + click(&mut u, frame_min + vec2(250.0, 90.0)); + u.frame(vec![Event::Text("overlap".into())]); + key(&mut u, Key::Enter, Modifiers::NONE); + assert_eq!(comment_count(&u), 1); + let c = u.app.session.doc().unwrap().comments[0].clone(); + assert_eq!(c.anchor, Some(a), "the comment is on the presented frame, not the one stacked over it"); + assert_eq!(comments(&u)["open"], c.id, "its pin shows in the presenter"); +} + +#[test] +fn a_draft_that_fails_to_post_keeps_its_text() { + let (mut h, _) = crate::live_tests::Harness::new(); + // A view-only link: the session refuses every edit, a comment too. + crate::live_server_tests::joined(&mut h, figcraft_engine::live::Access::View); + h.frames(2); + start_draft(&mut h.app, 150.0, 150.0); + h.frame(vec![]); + h.frame(vec![Event::Text("hello".into())]); + let k = |pressed| Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + h.frame(vec![k(true), k(false)]); + h.frames(2); + assert!(h.app.session.doc().unwrap().comments.is_empty(), "the session refused the comment"); + let draft = h.app.ui.comments.draft.clone(); + assert_eq!(draft.as_ref().map(|d| d.2.as_str()), Some("hello"), "the draft and its text stay: {draft:?}"); +} + +#[test] +fn a_press_held_into_the_presenters_comment_mode_does_not_navigate_on_release() { + let mut s = Session::new(); + let f = id(&s.execute("node.create", &json!({"type": "frame", "x": 50, "y": 40, "width": 400, "height": 300})).unwrap()); + let other = id(&s.execute("node.create", &json!({"type": "frame", "x": 700, "y": 0, "width": 400, "height": 300})).unwrap()); + let mut u = Ui::new(s); + u.run("proto.interaction.add", json!({"id": f, "trigger": {"type": "onClick"}, "action": {"type": "navigate", "dest": other}})); + u.run("proto.present", json!({"start": f})); + u.frames(2, Vec::new); + let screen = egui::Rect::from_min_size(pos2(0.0, 80.0), vec2(1440.0, 820.0)); + let at = screen.center() - vec2(200.0, 150.0) + vec2(120.0, 90.0); + u.button(at, true); + key(&mut u, Key::C, Modifiers::NONE); + assert_eq!(u.app.inspect()["presenter"]["comments"], true); + u.button(at, false); + u.frames(30, Vec::new); + assert_eq!(u.app.inspect()["presenter"]["current"], json!(f), "the press began before comment mode, so its release is no click"); +} + #[derive(Clone, Default)] struct Clip(Arc>>); diff --git a/crates/ui-egui/src/present/input.rs b/crates/ui-egui/src/present/input.rs index b8e94a22c..793283d7c 100644 --- a/crates/ui-egui/src/present/input.rs +++ b/crates/ui-egui/src/present/input.rs @@ -34,6 +34,19 @@ fn release_drag_scroll(p: &mut Presenter, l: &Layout, down: bool, velocity: Vec2 } } +/// Without clicks (the comment mode), forget a press in progress and what it began: a drag-scroll and a +/// transition following the pointer. +fn drop_press(p: &mut Presenter, clicks: bool) { + if clicks { + return; + } + p.press = None; + p.drag_scroll = None; + if let Some(a) = p.anim.as_mut() { + a.follow = None; + } +} + /// Scrolls the first of `targets` the wheel can still move, and smooths the wheel's speed over /// ~50 ms whatever the frame rate. fn wheel_scroll(p: &mut Presenter, l: &Layout, base: &Document, targets: Vec, wheel: Vec2, dt: f64) { @@ -194,6 +207,8 @@ pub(super) fn input(p: &mut Presenter, ctx: &egui::Context, l: &Layout, mode: In }); let keys = if keys_on { keys } else { Vec::new() }; let pressed = pressed && clicks; + // A press already in progress when the comment mode starts is dropped, so its release is no click. + drop_press(p, clicks); // Controller buttons pressed while a link notice shows are dropped, as keys are. let pads = std::mem::take(&mut p.pads); let pads = if p.link_notice.is_none() { pads } else { Vec::new() }; From c0dbaecec3f10d8851b59864c8210a9b80a52189 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 06:01:15 -0500 Subject: [PATCH 018/129] Merge fix: main's field tests with this PR's scrub rate main's the_rotation_field_shows_and_sets_the_rotation_on_the_page (added in #2200) scrubbed the Rotation field 15 points and expected +15 degrees, the old one-step-a-point rate. This PR measured the rotation icon in Figma at about half a degree a point (a 12.2 px drag gave 6 degrees), and the PR's own scrubbing_the_label_moves_the_value test already drags Rotation 30 points for 15 degrees. The test now drags 30 points; the +15 expectation and what it checks (page angle through a rotated parent, one undo step) are unchanged. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/field_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 8e54f7b3e..483acd444 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -470,7 +470,7 @@ fn the_rotation_field_shows_and_sets_the_rotation_on_the_page() { assert_eq!(field(&mut u, "Rotation").1, "18°"); // Scrubbing is one undo step. let steps = undo_steps(&u); - scrub(&mut u, "Rotation", 15.0, Modifiers::NONE); + scrub(&mut u, "Rotation", 30.0, Modifiers::NONE); assert!((page(&u, r) - 33.0).abs() < 1e-6, "{}", page(&u, r)); assert_eq!(undo_steps(&u), steps + 1); // Mixed: layers in differently turned parents agree when their page angles do. From 0859f94c7d80e9d76b925361730034947526b6c8 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 20:27:55 -0500 Subject: [PATCH 019/129] Presenter: the hidpi detail replaces the whole-frame texture instead of drawing over it (#2127) Both textures start from a transparent pixmap, so a translucent layer was counted twice where the detail covered it. The whole-frame texture is now drawn only around the detail rect (up to four clipped strips), then the detail. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/present/draw.rs | 37 ++++++++++++++++--- crates/ui-egui/src/present/tests.rs | 56 +++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/present/draw.rs b/crates/ui-egui/src/present/draw.rs index 28bc11891..0afe7cd86 100644 --- a/crates/ui-egui/src/present/draw.rs +++ b/crates/ui-egui/src/present/draw.rs @@ -75,17 +75,24 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte } if !drawn && let Some(to) = &to_tex { let on_clip = painter.with_clip_rect(l.clip); - on_clip.image(to.tex.id(), l.place.rect(to.bounds), uv, Color32::WHITE); // A frame too big for one texture at device scale is drawn from a smaller one: the part in - // view is drawn again from a texture at device scale, over it (and the overlays over that). + // view is drawn from a texture at device scale instead. The detail REPLACES that part of the + // whole-frame texture (the base is drawn only around it): both start from a transparent + // pixmap, so drawn over it a translucent layer would count twice. let shown = l.clip.intersect(l.place.rect(to.bounds)); + let mut detail = None; if shown.is_positive() { let (a, b) = (l.place.page(shown.min), l.place.page(shown.max)); let visible = figcraft_geom::Rect::new(a.x, a.y, b.x, b.y); let moving = p.fling.is_some() || p.drag_scroll.is_some() || p.wheel.is_some(); - if let Some(d) = p.detail_texture(ctx, &l.disp, p.current, px, to.bounds, visible, moving, now) { - on_clip.image(d.tex.id(), l.place.rect(d.bounds), uv, Color32::WHITE); - } + detail = p.detail_texture(ctx, &l.disp, p.current, px, to.bounds, visible, moving, now); + } + let hole = detail.as_ref().map(|d| l.clip.intersect(l.place.rect(d.bounds))); + for part in base_parts(l.clip, hole) { + painter.with_clip_rect(part).image(to.tex.id(), l.place.rect(to.bounds), uv, Color32::WHITE); + } + if let Some(d) = detail { + on_clip.image(d.tex.id(), l.place.rect(d.bounds), uv, Color32::WHITE); } } // Overlays (each with its background and opening transition); closing ones run it backwards. @@ -133,3 +140,23 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte ctx.request_repaint(); } } + +/// The parts of `clip` outside `hole` (up to four disjoint rectangles; `clip` itself with no hole). +pub(super) fn base_parts(clip: Rect, hole: Option) -> Vec { + let Some(h) = hole.filter(|h| h.is_positive()) else { + return vec![clip]; + }; + let h = h.intersect(clip); + if !h.is_positive() { + return vec![clip]; + } + [ + Rect::from_min_max(clip.min, egui::pos2(clip.max.x, h.min.y)), + Rect::from_min_max(egui::pos2(clip.min.x, h.max.y), clip.max), + Rect::from_min_max(egui::pos2(clip.min.x, h.min.y), egui::pos2(h.min.x, h.max.y)), + Rect::from_min_max(egui::pos2(h.max.x, h.min.y), egui::pos2(clip.max.x, h.max.y)), + ] + .into_iter() + .filter(|r| r.is_positive()) + .collect() +} diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index dde23026f..58c669754 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -536,3 +536,59 @@ fn detail_plan_edge_cases() { let view = R::new(0.0, 0.0, 1440.0, 860.0); assert_eq!(actions::detail_plan(bounds, view, 2.0, 2048.0), Some(view)); } + +#[test] +fn the_detail_replaces_the_whole_frame_texture_instead_of_drawing_over_it() { + // A frame with no fill holding a 50% rectangle: both textures start from a transparent pixmap, + // so drawn over each other the rectangle would count twice (75%, not 50%). + let mut session = figcraft_engine::Session::new(); + let frame = id(&session.execute("node.create", &json!({"type": "frame", "width": 1440, "height": 9701, "props": {"fills": []}})).unwrap()); + let r = + id(&session.execute("node.create", &json!({"type": "rectangle", "parent": frame, "x": 0, "y": 0, "width": 1440, "height": 9701})).unwrap()); + session.execute("node.set", &json!({"id": r, "props": {"fill": "#ff0000", "opacity": 0.5}})).unwrap(); + let mut ui = Ui::new(session); + ui.hidpi = Some((2.0, 16_384)); + ui.run("proto.present", json!({"start": frame})); + ui.app.ui.present.as_mut().unwrap().view.scale = PresentScale::FitWidth; + ui.frames(2, Vec::new); + + // The pixel's alpha is the rectangle's 0.5 in the whole-frame render and in the detail render. + let doc = ui.app.session.doc().unwrap(); + let alpha = |pix: &figcraft_render::Pixmap| pix.data()[3]; + let whole = figcraft_render::render_node_at(doc, frame, 0.5, 0.0).unwrap(); + let detail = figcraft_render::render_area_at(doc, &[frame], figcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), 2.0, 0.0).unwrap(); + assert!((i32::from(alpha(&whole)) - 128).abs() <= 1 && (i32::from(alpha(&detail)) - 128).abs() <= 1); + + // On screen, no whole-frame texture is drawn under the detail: one texture covers its centre. + let out = ui.frame_output(Vec::new()); + let prims = ui.ctx.tessellate(out.shapes, 2.0); + let names: std::collections::HashMap = + ui.ctx.tex_manager().read().allocated().map(|(id, m)| (*id, m.name.clone())).collect(); + let mut present: Vec<(String, egui::Rect, egui::Rect)> = Vec::new(); + for prim in &prims { + if let egui::epaint::Primitive::Mesh(m) = &prim.primitive + && let Some(n) = names.get(&m.texture_id).filter(|n| n.starts_with("present-")) + { + let bbox = m.vertices.iter().fold(egui::Rect::NOTHING, |r, v| r.union(egui::Rect::from_min_max(v.pos, v.pos))); + present.push((n.clone(), bbox, prim.clip_rect)); + } + } + let (_, dbox, dclip) = present.iter().find(|(n, ..)| n.starts_with("present-detail-")).expect("the detail is drawn"); + let centre = dbox.intersect(*dclip).center(); + let covering: Vec<_> = present.iter().filter(|(_, b, c)| b.contains(centre) && c.contains(centre)).map(|(n, ..)| n.as_str()).collect(); + assert_eq!(covering.len(), 1, "only the detail covers the view's centre:: {covering:?}"); +} + +#[test] +fn base_parts_leave_the_hole_out() { + use egui::{Rect, pos2}; + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)); + assert_eq!(draw::base_parts(clip, None), vec![clip]); + let hole = Rect::from_min_max(pos2(10.0, 20.0), pos2(60.0, 70.0)); + let parts = draw::base_parts(clip, Some(hole)); + assert_eq!(parts.len(), 4); + let area: f32 = parts.iter().map(|r| r.width() * r.height()).sum(); + assert_eq!(area, 100.0 * 100.0 - 50.0 * 50.0); + assert!(parts.iter().all(|r| !r.intersects(hole.shrink(0.01)))); + assert!(draw::base_parts(clip, Some(clip)).is_empty()); +} From 6d4df2b9099f97c1eef2c1b722629a5a690d8838 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 21:15:22 -0500 Subject: [PATCH 020/129] Presenter: a view a rounding error past the frame keeps its detail texture (#2127) The page rect of the view, converted back from the screen, can stand a hair outside the frame. The cached detail is always inside the frame, so it never covered that view, and a still view rendered a new detail every frame. detail_texture now clips the view to the frame first. Test: present::tests::a_view_a_rounding_error_past_the_frame_keeps_its_detail (failed before: a new texture on the second call). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/present/actions.rs | 4 ++++ crates/ui-egui/src/present/tests.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index ec23bd8be..d3386da0a 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -281,6 +281,10 @@ impl Presenter { moving: bool, now: f64, ) -> Option { + // Converted back from the screen, the view can stand a rounding error outside the frame, + // which a detail (always inside the frame) never covers: a still view would then render a + // new detail every frame. + let visible = visible.intersect(whole); let (t, clock) = self.frame_clock(ctx, doc, id, now); let key = (self.rev, px.to_bits(), clock.map_or(0, |c| c.0)); let covers = |b: &figcraft_geom::Rect| b.x0 <= visible.x0 && b.y0 <= visible.y0 && b.x1 >= visible.x1 && b.y1 >= visible.y1; diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index 58c669754..2cb710923 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -511,6 +511,22 @@ fn the_detail_is_kept_while_nothing_changes_and_made_again_when_the_frame_does() assert_ne!(tex_id(&ui), Some(first), "an edit renders the detail again"); } +#[test] +fn a_view_a_rounding_error_past_the_frame_keeps_its_detail() { + let mut ui = tall_hidpi(16_384); + let ctx = ui.ctx.clone(); + let doc = ui.app.session.doc().unwrap().clone(); + let now = ui.time; + let p = ui.app.ui.present.as_mut().unwrap(); + let id = p.current; + let whole = figcraft_geom::Rect::new(0.0, 0.0, 1440.0, 9701.0); + // The screen-to-page round trip can put the view a hair outside the frame. + let view = figcraft_geom::Rect::new(-1e-9, 0.0, 1440.0 + 1e-9, 860.0); + let first = p.detail_texture(&ctx, &doc, id, 2.0, whole, view, false, now).expect("a detail").tex.id(); + let again = p.detail_texture(&ctx, &doc, id, 2.0, whole, view, false, now).expect("a detail").tex.id(); + assert_eq!(again, first, "the same view reuses its detail instead of rendering a new one"); +} + #[test] fn detail_plan_edge_cases() { use figcraft_geom::Rect as R; From a7fd34288d612dadfe8d460367eb61345d77752e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 00:04:29 -0500 Subject: [PATCH 021/129] Presenter: a still view keeps its detail at fractional scales, tested end to end (#2127) The rounding overshoot fixed in 6d4df2b9, through the presenter's own frames rather than a direct call: a tall frame presented fit-to-width at eleven fractional widths, and a still view keeps its detail texture for four more frames. Before 6d4df2b9 it failed at width 1555.5 (a new texture on every frame). Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 drove and wrote --- crates/ui-egui/src/present/tests.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index 2cb710923..61edc5bf8 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -527,6 +527,29 @@ fn a_view_a_rounding_error_past_the_frame_keeps_its_detail() { assert_eq!(again, first, "the same view reuses its detail instead of rendering a new one"); } +#[test] +fn a_still_view_keeps_its_detail_at_fractional_scales() { + // Frame widths that give fractional fit-width scales: the view's page rect then comes back + // from the screen with rounding, a hair past the frame's edge. + let mut with_detail = 0; + for w in [1001.3, 1111.1, 1234.5, 1337.7, 1440.9, 1555.5, 1666.6, 1777.7, 1888.8, 1999.9, 2345.6] { + let mut session = figcraft_engine::Session::new(); + let frame = id(&session.execute("node.create", &json!({"type": "frame", "width": w, "height": 9701})).unwrap()); + session.execute("node.create", &json!({"type": "rectangle", "parent": frame, "x": 100, "y": 100, "width": 300, "height": 200})).unwrap(); + let mut ui = Ui::new(session); + ui.hidpi = Some((2.0, 16_384)); + ui.run("proto.present", json!({"start": frame})); + ui.app.ui.present.as_mut().unwrap().view.scale = PresentScale::FitWidth; + ui.frames(2, Vec::new); + let tex_id = |ui: &Ui| ui.app.ui.present.as_ref().and_then(|p| p.detail.as_ref().map(|(_, d)| d.tex.id())); + let Some(first) = tex_id(&ui) else { continue }; + with_detail += 1; + ui.frames(4, Vec::new); + assert_eq!(tex_id(&ui), Some(first), "width {w}: a still view keeps its detail"); + } + assert!(with_detail >= 3, "most of these widths need a detail texture: {with_detail}"); +} + #[test] fn detail_plan_edge_cases() { use figcraft_geom::Rect as R; From acf7c9531891776a07cc28694aec0035d2655972 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 03:07:08 -0500 Subject: [PATCH 022/129] M8: the rename and font name fields keep long text inside them (#2318) The theme gives an editor at least a field's height, taller than the one-line rename rows and frame labels, so the typed name hung below the row; the font menu's search box put its hint and text along the top. Rename editors are now centred on their row, and the search box is centred in its box through a shared widgets::search_edit. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- .../ui-egui/src/panels/typography/picker.rs | 3 +- crates/ui-egui/src/select_all_tests.rs | 56 +++++++++++++++++++ crates/ui-egui/src/widgets.rs | 19 ++++++- 3 files changed, 75 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/typography/picker.rs b/crates/ui-egui/src/panels/typography/picker.rs index 1dc884569..8c0773ac4 100644 --- a/crates/ui-egui/src/panels/typography/picker.rs +++ b/crates/ui-egui/src/panels/typography/picker.rs @@ -96,8 +96,7 @@ pub(crate) fn font_picker( i.count_and_consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown) as i64 - i.count_and_consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp) as i64 }); - let search = - ui.add(egui::TextEdit::singleline(&mut q).hint_text(tr("Search fonts")).desired_width(ui.available_width()).font(regular(11.5))); + let search = widgets::search_edit(ui, &mut q, tr("Search fonts"), regular(11.5)); crate::widgets::select_all_on_focus(ui, &search, &q); if just_opened { search.request_focus(); diff --git a/crates/ui-egui/src/select_all_tests.rs b/crates/ui-egui/src/select_all_tests.rs index d86de12df..2679c94f3 100644 --- a/crates/ui-egui/src/select_all_tests.rs +++ b/crates/ui-egui/src/select_all_tests.rs @@ -140,3 +140,59 @@ fn a_field_left_mid_edit_selects_all_on_the_next_click() { assert!(ctx.memory(|m| m.has_focus(id.with("te")))); assert_eq!(selection(&ctx, id.with("te")), Some((0, 6))); } + +/// The vertical middle of the first painted text that contains `needle`, from one frame's shapes. +fn text_mid_y(shapes: &[egui::epaint::ClippedShape], needle: &str) -> Option { + fn find(s: &egui::Shape, needle: &str) -> Option { + match s { + egui::Shape::Text(t) if t.galley.text().contains(needle) => Some(t.pos.y + t.galley.rect.center().y), + egui::Shape::Vec(v) => v.iter().find_map(|s| find(s, needle)), + _ => None, + } + } + shapes.iter().find_map(|c| find(&c.shape, needle)) +} + +/// Runs one more quiet frame of `f` and returns its shapes. +fn shapes_of(ctx: &egui::Context, f: &mut impl FnMut(&mut Ui)) -> Vec { + let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let mut child = ui.new_child(UiBuilder::new().max_rect(FIELD)); + f(&mut child); + }); + out.textures_delta.clear(); + out.shapes +} + +/// A rename in a row one line tall (the Layers panel's rows, a frame's name label): the typed text +/// sits in the middle of the row, not hanging below it (#2318). The theme's least height for an +/// editor is more than that row, which pushed the text down by the difference. +#[test] +fn a_rename_field_in_a_short_row_centres_its_text() { + let ctx = egui::Context::default(); + let id = Id::unique("short_rename"); + let row = Rect::from_min_size(pos2(20.0, 20.0), vec2(120.0, 16.0)); + let mut f = |ui: &mut Ui| { + widgets::rename_field(ui, id, "Frame 1", row, egui::FontId::proportional(11.0), false); + }; + click(&ctx, pos2(60.0, 28.0), None, &mut f); + assert!(ctx.memory(|m| m.has_focus(id.with("te")))); + let mid = text_mid_y(&shapes_of(&ctx, &mut f), "Frame 1").expect("the text is painted"); + assert!((mid - row.center().y).abs() <= 1.0, "text centre {mid} vs row centre {}", row.center().y); +} + +/// The font menu's search box shows its hint (and what is typed) in the middle of the box, not +/// along its top edge (#2318). +#[test] +fn the_font_search_box_centres_its_hint() { + let ctx = egui::Context::default(); + let mut q = String::new(); + let mut mid_box = 0.0; + let mut f = |ui: &mut Ui| { + let r = widgets::search_edit(ui, &mut q, "Search fonts", egui::FontId::proportional(11.5)); + mid_box = r.rect.center().y; + }; + let shapes = shapes_of(&ctx, &mut f); + let mid = text_mid_y(&shapes, "Search fonts").expect("the hint is painted"); + assert!((mid - mid_box).abs() <= 1.0, "hint centre {mid} vs box centre {mid_box}"); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 8bd0b47c8..84a98bc21 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1381,7 +1381,10 @@ pub fn text_field_inline(ui: &mut Ui, id: Id, value: &str, rect: Rect, font: egu Some(mut text) => { ui.painter().rect_filled(rect.expand(2.0), CornerRadius::same(4), t.panel); ui.painter().rect_stroke(rect.expand(2.0), CornerRadius::same(4), Stroke::new(1.0, crate::theme::ACCENT), StrokeKind::Inside); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect)); + // The editor is at least the theme's field height; centred on a shorter row it + // keeps its text on the row's middle line instead of hanging below it (#2318). + let edit = Rect::from_center_size(rect.center(), vec2(rect.width(), rect.height().max(FIELD_H))); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(edit)); let r = crate::bidi::single_line(&mut child, te_id, &mut text, font, rect.width()); a11y::own_focus(&r); keep_focus(&r, started); @@ -1472,3 +1475,17 @@ pub fn sublabels(ui: &mut Ui, a: &str, b: Option<&str>) { pub fn col_width(w: f32) -> f32 { ((w - PAD - PAD_RIGHT - GUTTER * 2.0 - 24.0) / 2.0).max(40.0) } + +/// The search box of a menu (the font list's): one line, as wide as the menu, its hint and text +/// centred in the box. [`egui::TextEdit`] puts the text at the top of a box taller than a line +/// unless told otherwise (#2318). +pub(crate) fn search_edit(ui: &mut Ui, text: &mut String, hint: &str, font: egui::FontId) -> Response { + ui.add( + egui::TextEdit::singleline(text) + .hint_text(hint) + .desired_width(ui.available_width()) + .font(font) + .align(Align2::LEFT_CENTER) + .min_size(vec2(0.0, FIELD_H)), + ) +} From 1070e81708f2e24fff78d769aded5c921d3e0705 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Fri, 13 Nov 2026 11:45:13 +0100 Subject: [PATCH 023/129] M2: preserve canvas hover and context menus over padding grips --- crates/ui-egui/src/canvas/handles.rs | 50 +++++++++++-------- .../src/canvas/handles/padding_tests.rs | 36 +++++++++++++ crates/ui-egui/src/canvas/input.rs | 20 ++++++-- docs/auto-layout-parity.md | 7 ++- docs/ui-parity.md | 6 +-- 5 files changed, 88 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/canvas/handles.rs b/crates/ui-egui/src/canvas/handles.rs index 16c97977f..e5f3a38a0 100644 --- a/crates/ui-egui/src/canvas/handles.rs +++ b/crates/ui-egui/src/canvas/handles.rs @@ -591,8 +591,15 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) { let _ = Align2::CENTER_CENTER; } -/// Pointer handling; returns true when a handle owns the pointer this frame. -pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { +/// A handle may own only the cursor while ordinary canvas hover and secondary clicks continue. +pub enum Input { + Ignored, + Hover(egui::CursorIcon), + Captured, +} + +/// Consume active handle gestures, but report padding hover separately from captured input. +pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> Input { let (pressed, down, released, modifiers) = ctx.input(|i| { ( i.pointer.button_pressed(egui::PointerButton::Primary), @@ -606,7 +613,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { // Escape or Undo closed the gesture under the held button: the drag is over. if !gesture_open(app) { ctx.data_mut(|d| d.remove::(drag_id())); - return true; + return Input::Captured; } if down { apply(app, &drag, pos, modifiers); @@ -616,7 +623,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { let _ = app.session.commit_interaction(); ctx.data_mut(|d| d.remove::(drag_id())); } - return true; + return Input::Captured; } // Hover cursors / press to start. if let Some((id, fills, index, g)) = gradient_target(app) { @@ -633,16 +640,16 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { let _ = app.session.begin_interaction("Edit gradient"); ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gradient { id, fills, index, which })); } - return true; + return Input::Captured; } } // Stops: select and slide them; a click elsewhere on the line adds one there. - let (Some(a), Some(b)) = (pts[0], pts[1]) else { return false }; + let (Some(a), Some(b)) = (pts[0], pts[1]) else { return Input::Ignored }; let stop_hit = g.stops.iter().position(|st| (a + (b - a) * st.position - pos).length() <= 8.0); let t = line_param(a, b, pos); let on_line = t.is_some_and(|(_, d)| d <= 5.0); if stop_hit.is_none() && !on_line { - return false; + return Input::Ignored; } ctx.set_cursor_icon(if stop_hit.is_some() { egui::CursorIcon::Grab } else { egui::CursorIcon::Copy }); if pressed { @@ -663,7 +670,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { ctx.data_mut(|d| d.insert_temp(crate::colorpicker::stop_id(), stop)); ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gradient { id, fills, index, which: 3 + stop })); } - return true; + return Input::Captured; } if let Some((id, index, e)) = blur_target(app, ctx) { let hit = blur_points(app, id, &e).and_then(|pts| pts.iter().position(|p| (*p - pos).length() <= 8.0)); @@ -673,15 +680,15 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { let _ = app.session.begin_interaction("Edit progressive blur"); ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Blur { id, index, which })); } - return true; + return Input::Captured; } } if let Some((id, fills, index, _, rect)) = crop_target(app) { // Crop mode: the layer's own resize handles crop it (the pointer events carry Cmd/Ctrl). if app.ui.crop.is_some() && on_resize_handle(app, pos) { - return false; + return Input::Ignored; } - let Some(c) = crop_corners(app, id, rect) else { return false }; + let Some(c) = crop_corners(app, id, rect) else { return Input::Ignored }; let start = screen_to_unit(app, id, pos).unwrap_or((0.0, 0.0)); let corner = c.iter().position(|p| (*p - pos).length() <= 8.0); let inside = start.0 >= rect.0.min(rect.2) && start.0 <= rect.0.max(rect.2) && start.1 >= rect.1.min(rect.3) && start.1 <= rect.1.max(rect.3); @@ -693,7 +700,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { if pressed { app.ui.crop = None; } - return false; + return Input::Ignored; } }; ctx.set_cursor_icon(if which == 4 { @@ -707,20 +714,21 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { let _ = app.session.begin_interaction("Crop image"); ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Crop { id, fills, index, which, start, rect })); } - return true; + return Input::Captured; } if app.session.tool.tool != figcraft_engine::ToolId::Move || app.session.tool.busy() { - return false; + return Input::Ignored; } - let Some(Zones { id, bands, gaps, .. }) = al_zones(app) else { return false }; + let Some(Zones { id, bands, gaps, .. }) = al_zones(app) else { return Input::Ignored }; if let Some((side, _, value)) = padding_at(&padding_handles(&bands), pos) { - ctx.set_cursor_icon(if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }); + let cursor = if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }; + ctx.set_cursor_icon(cursor); if pressed { let _ = app.session.begin_interaction("Padding"); ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Padding { id, side, start: pos, value })); + return Input::Captured; } - // Hover owns the cursor too; otherwise the canvas tool replaces the resize arrows. - return true; + return Input::Hover(cursor); } for g in gaps { if g.rect.contains(pos) { @@ -728,12 +736,12 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool { if pressed { let _ = app.session.begin_interaction("Gap"); ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gap { id, start: pos, value: g.value, vertical: g.vertical, key: g.key })); - return true; + return Input::Captured; } - return false; + return Input::Ignored; } } - false + Input::Ignored } fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, modifiers: egui::Modifiers) { diff --git a/crates/ui-egui/src/canvas/handles/padding_tests.rs b/crates/ui-egui/src/canvas/handles/padding_tests.rs index 9f9d6e026..a29734089 100644 --- a/crates/ui-egui/src/canvas/handles/padding_tests.rs +++ b/crates/ui-egui/src/canvas/handles/padding_tests.rs @@ -238,3 +238,39 @@ fn modifier_keys_highlight_linked_padding_bands_before_and_during_a_drag() { } u.button(center, false); } + +/// Hover over a grip must still update the layer under the pointer without editing the document. +#[test] +fn padding_grip_hover_preserves_canvas_hover_and_resize_cursor() { + let (mut u, f) = scene(); + let other = id_of(&u.app.session.execute("shape.rectangle", &json!({"x": 500, "y": 100, "width": 40, "height": 40})).unwrap()["id"]).unwrap(); + u.app.run("select.set", json!({"ids": [f]})); + let over_other = u.app.to_screen(520.0, 120.0); + u.frame(vec![Event::PointerMoved(over_other)]); + assert_eq!(u.app.session.ds().unwrap().hover, Some(other)); + let history = u.app.session.undo_depth(); + let grip = al_zones(&u.app).unwrap().bands[0].1.center(); + let output = u.frame_output(vec![Event::PointerMoved(grip)]); + assert_eq!(u.app.session.ds().unwrap().hover, Some(f), "the previous layer must not stay hovered"); + assert_eq!(output.platform_output.cursor_icon, egui::CursorIcon::ResizeVertical); + assert_eq!(u.app.session.undo_depth(), history); + assert!(u.ctx.data(|d| d.get_temp::(drag_id())).is_none()); +} + +/// Right-click on any padding grip opens the ordinary canvas menu without starting a drag. +#[test] +fn padding_grips_preserve_secondary_click_context_menus() { + for side in 0..4 { + let (mut u, f) = scene(); + let center = al_zones(&u.app).unwrap().bands[side].1.center(); + let history = u.app.session.undo_depth(); + u.frame(vec![Event::PointerMoved(center)]); + for pressed in [true, false] { + u.frame(vec![Event::PointerButton { pos: center, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }]); + } + let (_, targets) = u.app.ui.context_menu.as_ref().expect("right-click on the grip opens the menu"); + assert!(targets.contains(&f)); + assert!(u.ctx.data(|d| d.get_temp::(drag_id())).is_none()); + assert_eq!(u.app.session.undo_depth(), history); + } +} diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index b4cff10aa..7c4bc09ee 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -283,9 +283,15 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo if !app.canvas.dragging && resp.hovered() && crate::guides::input(app, &ctx, pos) { return false; } - if !app.canvas.dragging && resp.hovered() && crate::handles::input(app, &ctx, pos) { - return false; - } + let handle_cursor = if !app.canvas.dragging && resp.hovered() { + match crate::handles::input(app, &ctx, pos) { + crate::handles::Input::Captured => return false, + crate::handles::Input::Hover(cursor) => Some(cursor), + crate::handles::Input::Ignored => None, + } + } else { + None + }; if resp.secondary_clicked() { open_context_menu(app, pos, mods.command); return true; @@ -382,7 +388,13 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo send(app, PointerKind::Up, release_pos.unwrap_or(pos), &mods); } } - true + // Padding hover changes the cursor without skipping the normal hover and context-menu paths. + if let Some(cursor) = handle_cursor { + ctx.set_cursor_icon(cursor); + false + } else { + true + } } /// Pointer event `kind` at screen point `pos`, to the tools. diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 099cfacb8..70048cc60 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** patch (padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -37,7 +37,9 @@ synchronises all four. Shift alone retains the existing opposite-side gesture. A and grips highlight immediately when modifiers change, both before and during a drag. One undo restores every affected side. On very small frames or at reduced zoom, opposite grips move outward to stay at least 20 screen pixels apart; the padding bands keep their geometry. -Overlapping hit targets select the nearest visible grip for both hover and drag. +Overlapping hit targets select the nearest visible grip for both hover and drag. Hover keeps +the resize cursor while updating the hovered layer, and a secondary click opens the normal +canvas context menu. Only the primary press and active drag capture pointer input. ## Rules from the documentation @@ -114,6 +116,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | M2, #2152: Padding grips preserve canvas hover and secondary-click context menus while retaining their resize cursor. Only primary presses and active handle drags capture input. Regressions reproduce both stale layer hover and blocked right-click menus. | | 2026-11-11 | patch | M2.1: grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) (this replaces the 2026-10-11 rule from the documentation). Layout behaviour suite: three cases flipped, three added | | 2026-11-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. | | 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bde1ecf74..e928b4c12 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 (padding grips stay reachable on tiny frames and at reduced zoom; 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-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) 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: @@ -130,7 +130,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Masks: what a mask hides doesn't take clicks; a mask group's box is the mask's | done | | | Layout grids (Ctrl+G) | done | columns, rows and grid; stretch, left, centre, right; Auto count; several per frame; styles; not shown or snapped on a rotated frame; a nested frame's grids snap but only top-level frames draw them | | Gamut warnings for Display P3 files | done | colour picker note; View ▸ Soft-proof sRGB stripes what sRGB can't show (the canvas itself is sRGB) | -| Gradient and padding/gap handles on the canvas | done | each padding band has a central grip, which alone starts padding drags; the value label sits beside it and the whole band still highlights on hover (`canvas::handles::padding_tests`); the gradient's handles and stops show while its picker is open, and dragging one keeps the picker open (#1852) | +| Gradient and padding/gap handles on the canvas | done | the gradient's handles and stops show while its picker is open, and dragging one keeps the picker open (#1852) | | Hover outline, selection colours, handle sizes | done | measured from UI3 screenshots; the outline follows the layer's geometry, rounded corners (each radius and the smoothing) included, whatever the stroke alignment (#1506) | | Cursors per tool and modifier | done | the engine names a cursor for every tool, modifier and hover target (`tool.overlay.cursor`, tabled in `cursor_tests`) and the UI shows the system's or draws its own at the pointer (`cursors.rs`, `cursors_tests`; original glyphs from lines and the code-drawn icons). Arrow for Move and Scale; two-headed arrows on the handles that follow the handle and the box's rotation; outside a corner a curved rotate arrow turned to that corner, turning with the pointer while rotating; crosshair for the frame, section, slice, shape, pencil and Text tools, drawn dark with a white edge so it shows on any canvas colour whatever the system's pointer style (#2198); the I-beam over a text with the Text tool and over the text being edited; the pen as a cross with what a click does beside it (nothing: a new point; a ring: closes, connects to or goes on from a point; a plus: adds a point on a segment, also Alt in vector edit mode; a curve: bends, the Bend tool or Cmd/Ctrl); open and closed hand for the Hand tool, Space and the middle button; zoom in and out (Alt) while Z is held; eyedropper; comment pin; the copy cursor with Alt over a selected layer and while Alt-dragging; not-allowed while a drag resizes, rotates or moves a layer inside an instance (it is undone on release) and over a layers row that takes no drop. Ruler guides and gradient, crop and padding handles keep their own cursors (the tool's used to replace them). `ui.inspect` reports `cursor`. Left: no cursor for removing a point with the pen (the pen doesn't remove points); the drawn cursors follow the pointer a frame behind the system's; not compared with Figma's side by side | | Multiplayer cursors, cursor chat, spotlight | partial | in live sessions: named cursors, chat bubbles that fade, `/` to chat, spotlight from your avatar's menu with a banner; no audio or reactions | @@ -238,8 +238,6 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | 2026-11-07 | patch | Main menu: a submenu opens on the first frame its row is hovered instead of after 0.15 s (Figma's main menu measured with synthetic pointer events and 1 ms polling: median 11 ms to open, 13 ms to switch rows, no hover delay); the safe-triangle aim is unchanged, though the same measurement saw no aim logic in Figma, left for the maintainer to decide | | 2026-11-10 | patch | M5, #1560: locked layers follow Figma's rules (Lock and unlock layers; measured in Figma's web app): a locked layer selected in the Layers panel ignores the arrow keys and the nudge commands while its properties still edit, and a child of a locked layer keeps its padlock inert (the Layers panel padlock, Lock/Unlock and `object.toggleLock` without a value no longer lock the child on its own) | | 2026-11-10 | patch | #2217: the main menu's submenus (Object, say) ran past the window's bottom, behind the taskbar, with the lowest commands out of reach, because submenus were not constrained to the window (to keep them beside their row). Every menu panel now scrolls when taller than the window less 8 pt margins, and a submenu is held within the window's height (moved up, never above the top) while keeping its place beside its row, so menu-aim is unchanged. Tests: `menu_overflow_tests.rs`. Numbers unchanged. | -| 2026-11-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. | -| 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | | 2026-11-09 | minor | M1, #1494: fill, stroke and effect rows in the Design panel couldn't be selected, so the keyboard couldn't copy one (only the row's menu could). A click on a row's grip or background now highlights it (`property_rows`; the row is a click target under its controls and its grip takes a click, neither focusable, so Tab still goes control to control), Cmd/Ctrl+C copies that paint or effect, and Cmd/Ctrl+V pastes it onto the selected layers, on top or in place of their highlighted row of that kind, while it is still the last copy (Copy and paste properties between layers). Escape or a press on the canvas lets the highlight go before the selection. Tests: `property_rows_tests` (22) | | 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 | From a87e8fb25b659c6bd6a5e256fdcc783b99cd55b0 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Fri, 13 Nov 2026 11:51:30 +0100 Subject: [PATCH 024/129] M2: use theme tokens for padding grip fill and outline --- crates/ui-egui/src/canvas/handles.rs | 10 +++++-- .../src/canvas/handles/padding_tests.rs | 29 +++++++++++++++++++ crates/ui-egui/src/theme.rs | 8 +++++ docs/auto-layout-parity.md | 3 +- 4 files changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/handles.rs b/crates/ui-egui/src/canvas/handles.rs index e5f3a38a0..87bde6962 100644 --- a/crates/ui-egui/src/canvas/handles.rs +++ b/crates/ui-egui/src/canvas/handles.rs @@ -554,6 +554,7 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) { return; } let Some(z) = al_zones(app) else { return }; + let tokens = crate::theme::Tokens::get(painter.ctx()); let handles = padding_handles(&z.bands); let active_side = match &dragging { Some(Drag::Padding { side, .. }) => Some(*side), @@ -571,8 +572,13 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) { pink_label(painter, crate::canvas::fmt(*v), handle.center() + offset); } let grip = Rect::from_center_size(handle.center(), if side.is_multiple_of(2) { vec2(16.0, 4.0) } else { vec2(4.0, 16.0) }); - painter.rect_filled(grip, CornerRadius::same(2), if linked { PINK } else { PINK.gamma_multiply(0.6) }); - painter.rect_stroke(grip, CornerRadius::same(2), Stroke::new(if linked { 1.5 } else { 1.0 }, Color32::WHITE), StrokeKind::Outside); + painter.rect_filled(grip, CornerRadius::same(2), if linked { tokens.padding_grip } else { tokens.padding_grip.gamma_multiply(0.6) }); + painter.rect_stroke( + grip, + CornerRadius::same(2), + Stroke::new(if linked { 1.5 } else { 1.0 }, tokens.padding_grip_border), + StrokeKind::Outside, + ); } let drag_key = match &dragging { Some(Drag::Gap { key, .. }) => Some(*key), diff --git a/crates/ui-egui/src/canvas/handles/padding_tests.rs b/crates/ui-egui/src/canvas/handles/padding_tests.rs index a29734089..84756db67 100644 --- a/crates/ui-egui/src/canvas/handles/padding_tests.rs +++ b/crates/ui-egui/src/canvas/handles/padding_tests.rs @@ -274,3 +274,32 @@ fn padding_grips_preserve_secondary_click_context_menus() { assert_eq!(u.app.session.undo_depth(), history); } } + +/// Custom light/dark palettes must control both grip states and their outlines. +#[test] +fn padding_grips_use_the_theme_fill_and_outline() { + for mut tokens in [crate::theme::Tokens::light(), crate::theme::Tokens::dark()] { + let (mut u, _) = scene(); + let grips = painted_grips(&u.frame_output(vec![Event::PointerGone])); + assert_eq!(grips.len(), 4); + tokens.padding_grip = if tokens.dark { egui::Color32::from_rgb(20, 40, 60) } else { egui::Color32::from_rgb(120, 40, 60) }; + tokens.padding_grip_border = egui::Color32::from_rgb(210, 180, 150); + for active in [false, true] { + let events = if active { vec![Event::PointerMoved(grips[0].center())] } else { vec![Event::PointerGone] }; + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, u.screen)), events, ..Default::default() }; + let mut output = u.ctx.clone().run_ui(raw, |ui| { + crate::theme::apply(ui.ctx(), tokens); + super::draw(&mut u.app, ui.painter()); + }); + output.textures_delta.clear(); + let shapes = crate::live_tests::flat(&output.shapes); + for (side, grip) in grips.iter().enumerate() { + let linked = active && side == 0; + let fill = if linked { tokens.padding_grip } else { tokens.padding_grip.gamma_multiply(0.6) }; + assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == *grip && r.fill == fill))); + let width = if linked { 1.5 } else { 1.0 }; + assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == *grip && r.stroke.color == tokens.padding_grip_border && r.stroke.width == width))); + } + } + } +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e8a039ba5..784ada713 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -42,6 +42,10 @@ pub struct Tokens { pub success: Color32, pub warning: Color32, pub guide: Color32, + /// Auto layout padding grips on the canvas. + pub padding_grip: Color32, + /// Contrasting edge around padding grips, including their dimmed state. + pub padding_grip_border: Color32, pub tab_bar: Color32, pub tab_active: Color32, pub shadow: Color32, @@ -133,6 +137,8 @@ impl Tokens { success: DEV_READY, warning: Color32::from_rgb(0xFF, 0xCD, 0x29), guide: Color32::from_rgb(0xF2, 0x48, 0x22), + padding_grip: Color32::from_rgb(0xF2, 0x48, 0x8C), + padding_grip_border: Color32::WHITE, tab_bar: Color32::from_rgb(0xE8, 0xE8, 0xE8), tab_active: Color32::from_rgb(0xFF, 0xFF, 0xFF), shadow: Color32::from_black_alpha(40), @@ -176,6 +182,8 @@ impl Tokens { success: DEV_READY, warning: Color32::from_rgb(0xFF, 0xCD, 0x29), guide: Color32::from_rgb(0xF2, 0x48, 0x22), + padding_grip: Color32::from_rgb(0xF2, 0x48, 0x8C), + padding_grip_border: Color32::WHITE, tab_bar: Color32::from_rgb(0x1E, 0x1E, 0x1E), tab_active: Color32::from_rgb(0x2C, 0x2C, 0x2C), shadow: Color32::from_black_alpha(90), diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 70048cc60..691936b65 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** patch (padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** patch (padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -116,6 +116,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | M2, #2152: Padding grip fills and outlines come from dedicated theme tokens, preserving linked-state emphasis and border widths. A rendering regression checks custom light and dark palettes. | | 2026-11-13 | patch | M2, #2152: Padding grips preserve canvas hover and secondary-click context menus while retaining their resize cursor. Only primary presses and active handle drags capture input. Regressions reproduce both stale layer hover and blocked right-click menus. | | 2026-11-11 | patch | M2.1: grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) (this replaces the 2026-10-11 rule from the documentation). Layout behaviour suite: three cases flipped, three added | | 2026-11-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. | From 8336043787091e58f395fc780beb98545b9d0de0 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:16:59 +0100 Subject: [PATCH 025/129] M4: a rounded vector point reaches along the whole of a segment whose other end is sharp (#2334) --- crates/doc/src/lib.rs | 2 + crates/doc/src/vector.rs | 60 +++++++-- crates/doc/src/vector_radius_tests.rs | 114 ++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/vector_point_radius_tests.rs | 40 ++++++ crates/ui-egui/src/vector_point_xy_tests.rs | 4 +- docs/ui-parity.md | 5 +- 7 files changed, 213 insertions(+), 14 deletions(-) create mode 100644 crates/doc/src/vector_radius_tests.rs create mode 100644 crates/ui-egui/src/vector_point_radius_tests.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6a0c2aedf..aaf5659a8 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1350,6 +1350,8 @@ mod proto_overlay_anchor_tests; #[cfg(test)] mod tests; #[cfg(test)] +mod vector_radius_tests; +#[cfg(test)] mod vector_regions_tests; #[cfg(test)] mod width_sides_tests; diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index fd6d48072..768c2f6ee 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -145,6 +145,25 @@ struct Corner { cut2: f64, } +/// Where point `v` turns between its two segments, for rounding it: `r` its radius, `s1`/`s2` the +/// segments (`a1`/`a2` whether `v` is their `a` end), `c1`/`c2` them as curves running away from +/// `v`, `u1`/`u2` the directions they leave in, `angle` between those, and `l1`/`l2` their lengths. +struct Turn { + v: usize, + r: f64, + s1: usize, + a1: bool, + s2: usize, + a2: bool, + c1: CubicBez, + c2: CubicBez, + u1: Vec2, + u2: Vec2, + angle: f64, + l1: f64, + l2: f64, +} + /// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to /// those ends, and the point it ends at. struct CornerCurve { @@ -391,10 +410,11 @@ impl VectorNetwork { } /// The network with its rounded points drawn in: each sharp point with a corner radius becomes - /// an arc between its two segments (the radius shrinks so the arc fits in half of each - /// segment, like a polygon's corners). A curved segment is cut where the arc meets it and keeps - /// the rest of its curve, the arc leaving along its direction there. `None` when no point is - /// rounded. + /// an arc between its two segments. The radius shrinks so the arc fits: a segment whose other + /// end is rounded too is shared, half for each end, as a polygon's sides are, and one whose + /// other end stays sharp can be used whole (as in Figma, #2334). A curved segment is cut where + /// the arc meets it and keeps the rest of its curve, the arc leaving along its direction there. + /// `None` when no point is rounded. pub fn rounded(&self) -> Option { self.rounded_smoothed(0.0) } @@ -424,7 +444,9 @@ impl VectorNetwork { *x = true; } } - let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect(); + let turns: Vec> = (0..self.vertices.len()).map(|v| self.turn(v, incident.get(v)?)).collect(); + let rounds: Vec = turns.iter().map(Option::is_some).collect(); + let corners: Vec = turns.iter().flatten().filter_map(|t| self.corner(t, smoothing, &on_loop, &rounds)).collect(); let mut out = self.clone(); for v in &mut out.vertices { v.radius = 0.0; @@ -558,10 +580,9 @@ impl VectorNetwork { joining.next().is_none().then_some(first) } - /// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments - /// run on smoothly or fold back. With `smoothing`, a point between two straight segments that - /// are both `on_loop` gets a smoothed corner. - fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option { + /// How point `v` (its `incident` segments) turns, if it is rounded: it has a radius and two + /// segments that neither run on smoothly nor fold back there. + fn turn(&self, v: usize, incident: &[(usize, bool)]) -> Option { let r = self.vertices.get(v)?.radius; let [(s1, a1), (s2, a2)] = *incident else { return None }; if !(r > 0.0 && r.is_finite()) || s1 == s2 { @@ -577,6 +598,23 @@ impl VectorNetwork { if !(l1 > 1e-9 && l2 > 1e-9) { return None; } + Some(Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 }) + } + + /// How far along segment `s` (`l` long) from its `a` end (`at_a`) or its `b` end the corner + /// there may reach: all of it when the other end stays sharp, half when that end is rounded + /// too (`rounds`, by point) and takes the other half. + fn room(&self, s: usize, at_a: bool, l: f64, rounds: &[bool]) -> f64 { + let far = self.segments.get(s).map(|x| if at_a { x.b } else { x.a }); + if far.and_then(|f| rounds.get(f)).copied().unwrap_or(false) { l / 2.0 } else { l } + } + + /// The corner of a rounded point (`p`, see [`Self::turn`]); it reaches along each segment as + /// far as [`Self::room`] allows (`rounds`: which points are rounded). With `smoothing`, a point + /// between two straight segments that are both `on_loop` gets a smoothed corner. + fn corner(&self, p: &Turn, smoothing: f64, on_loop: &[bool], rounds: &[bool]) -> Option { + let &Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 } = p; + let reach = self.room(s1, a1, l1, rounds).min(self.room(s2, a2, l2, rounds)); let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false); if smoothing > 0.0 @@ -584,7 +622,7 @@ impl VectorNetwork { && is_line(&c2) && closed(s1) && closed(s2) - && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing) + && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, reach, r, smoothing) && let (Some(first), Some(last)) = (curves.first(), curves.last()) { let (a, b) = (first.p0, last.p3); @@ -595,7 +633,7 @@ impl VectorNetwork { let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2); return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) }); } - let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0); + let t = (r / (angle / 2.0).tan()).min(reach); let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2)); // A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between // them and ρ the radius of the circle through both ends (the corner radius between lines). diff --git a/crates/doc/src/vector_radius_tests.rs b/crates/doc/src/vector_radius_tests.rs new file mode 100644 index 000000000..6301e2d13 --- /dev/null +++ b/crates/doc/src/vector_radius_tests.rs @@ -0,0 +1,114 @@ +//! How far a rounded point's arc may reach along its segments (#2334): the whole segment when the +//! segment's other end stays sharp, half of it when that end is rounded too. Figma draws a single +//! rounded point of a 100 × 100 square with radius 100 as an arc from one neighbour to the other. + +use figcraft_geom::kurbo::{CubicBez, ParamCurve, PathSeg}; +use figcraft_geom::{BezPath, Point}; + +use crate::vector::VectorNetwork; + +/// A 100 × 100 square's points: top left, top right, bottom right, bottom left. +const SQUARE: [Point; 4] = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + +/// A network through `pts` (closed or open) whose points have radii `radii`. +fn network(pts: &[Point], closed: bool, radii: &[f64]) -> VectorNetwork { + let mut n = VectorNetwork::from_points(pts, closed); + for (v, r) in n.vertices.iter_mut().zip(radii) { + v.radius = *r; + } + n +} + +/// The cubic curves of `path` (the rounded points' arcs; every other segment is straight). +fn curves(path: &BezPath) -> Vec { + path.segments() + .filter_map(|s| match s { + PathSeg::Cubic(c) => Some(c), + _ => None, + }) + .collect() +} + +/// Whether `a` and `b` are the same point to within rounding. +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-9 +} + +/// Checks that `path` draws, for each `(corner, prev, next, t)` of `want`, a circular arc +/// between the points `t` from `corner` toward `prev` and toward `next` (a right angle, so the +/// circle's radius is `t`), and no other curve. +fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) { + let got = curves(path); + assert_eq!(got.len(), want.len(), "{why}: {got:?}"); + for &(corner, prev, next, t) in want { + let toward = |p: Point| corner + (p - corner) / (p - corner).hypot() * t; + let (a, b) = (toward(prev), toward(next)); + let center = a + (b - corner); + let mid = center + (corner - center) / (corner - center).hypot() * t; + let arc = got.iter().find(|c| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a))); + let Some(arc) = arc else { panic!("{why}: no arc from {a:?} to {b:?} in {got:?}") }; + assert!(near(arc.eval(0.5), mid), "{why}: the arc at {corner:?} passes {:?}, not {mid:?}", arc.eval(0.5)); + } +} + +#[test] +fn a_rounded_points_arc_reaches_as_far_as_its_segments_other_ends_allow() { + let [tl, tr, br, bl] = SQUARE; + // (radii of [top left, top right, bottom right, bottom left], each arc as (point, its + // neighbours, how far it reaches along both), derivation) + #[allow(clippy::type_complexity)] + let rows: Vec<([f64; 4], Vec<(Point, Point, Point, f64)>, &str)> = vec![ + ([0.0, 0.0, 100.0, 0.0], vec![(br, tr, bl, 100.0)], "the issue's square: the arc runs from one sharp neighbour to the other"), + ([0.0, 0.0, 500.0, 0.0], vec![(br, tr, bl, 100.0)], "a larger radius stops at the sharp neighbours"), + ([0.0, 0.0, 75.0, 0.0], vec![(br, tr, bl, 75.0)], "a radius past half the segments is drawn whole"), + ([0.0, 0.0, 40.0, 0.0], vec![(br, tr, bl, 40.0)], "a radius that fits half the segments is unchanged"), + ( + [0.0, 10.0, 100.0, 0.0], + vec![(tr, tl, br, 10.0), (br, tr, bl, 50.0)], + "the segment to the rounded top right is shared, half each, and the shorter room wins", + ), + ( + [100.0, 0.0, 100.0, 0.0], + vec![(tl, bl, tr, 100.0), (br, tr, bl, 100.0)], + "opposite points share no segment: each reaches its sharp neighbours (a lens)", + ), + ( + [100.0; 4], + vec![(tl, bl, tr, 50.0), (tr, tl, br, 50.0), (br, tr, bl, 50.0), (bl, br, tl, 50.0)], + "every point rounded: a circle, as before", + ), + ]; + for (radii, want, why) in rows { + let net = network(&SQUARE, true, &radii); + assert_arcs(&net.fill_path(), &want, why); + assert_arcs(&net.stroke_path(), &want, why); + // The stored radii stay as they were set. + assert_eq!(net.vertices.iter().map(|p| p.radius).collect::>(), radii.to_vec(), "{why}"); + } +} + +#[test] +fn an_open_paths_ends_leave_its_rounded_point_the_whole_segments() { + let pts = [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0)]; + // (radii, derivation): the ends don't turn, so a radius on them rounds nothing and takes no + // room from the middle point. + let rows: Vec<([f64; 3], &str)> = + vec![([0.0, 100.0, 0.0], "sharp ends"), ([100.0, 100.0, 100.0], "ends with a radius of their own stay sharp and leave the room to it")]; + for (radii, why) in rows { + let net = network(&pts, false, &radii); + assert_arcs(&net.stroke_path(), &[(pts[1], pts[0], pts[2], 100.0)], why); + } +} + +#[test] +fn a_smoothed_corner_takes_the_room_of_a_sharp_neighbour_before_losing_smoothing() { + // Radius 40 with smoothing 0.6 eases in from 1.6 × 40 = 64 along each side. Half of a 100 + // side (50) would cut smoothing down; the whole side next to sharp points leaves all of it. + let net = network(&SQUARE, true, &[0.0, 0.0, 40.0, 0.0]); + let path = net.rounded_smoothed(0.6).unwrap().fill_path(); + let ends: Vec = curves(&path).iter().flat_map(|c| [c.p0, c.p3]).collect(); + for p in [Point::new(100.0, 36.0), Point::new(36.0, 100.0)] { + assert!(ends.iter().any(|e| (*e - p).hypot() < 1e-6), "the smoothed corner starts at {p:?}: {ends:?}"); + } + assert!(ends.iter().all(|e| e.x >= 36.0 - 1e-6 && e.y >= 36.0 - 1e-6), "and reaches no further: {ends:?}"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1f9811a8..936059d4c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -296,6 +296,8 @@ mod vector_keys_tests; #[cfg(test)] mod vector_panel_tests; #[cfg(test)] +mod vector_point_radius_tests; +#[cfg(test)] mod vector_point_xy_tests; #[cfg(test)] mod vector_tail_ui_tests; diff --git a/crates/ui-egui/src/vector_point_radius_tests.rs b/crates/ui-egui/src/vector_point_radius_tests.rs new file mode 100644 index 000000000..5a10a2421 --- /dev/null +++ b/crates/ui-egui/src/vector_point_radius_tests.rs @@ -0,0 +1,40 @@ +//! The vector edit panel's Corner radius for a point (#2334): a typed radius larger than half the +//! point's segments is kept and shown as typed, and the point is drawn rounded across the whole of +//! the segments whose other ends stay sharp, as Figma draws it. + +use egui::Key; +use figcraft_geom::Point; +use figcraft_geom::kurbo::{ParamCurve, PathSeg}; +use serde_json::json; + +use crate::field_tests::{field, type_into}; +use crate::vector_point_xy_tests::setup; + +#[test] +fn a_typed_radius_is_kept_shown_and_drawn_across_the_sharp_neighbours_segments() { + // The 100 × 60 rectangle in vector edit mode; point 2 is its bottom right corner. + let (mut u, id) = setup(); + u.app.session.execute("vector.edit.select", &json!({"vertices": [2]})).unwrap(); + type_into(&mut u, "Corner radius", "100", Key::Enter); + assert_eq!(field(&mut u, "Corner radius").1, "100", "the field shows the radius as typed"); + let doc = u.app.session.doc().unwrap(); + let net = figcraft_engine::vectoredit::network(doc, id).unwrap(); + assert_eq!(net.vertices.iter().map(|v| v.radius).collect::>(), vec![0.0, 0.0, 100.0, 0.0], "only point 2 stores it, unclamped"); + assert_eq!(net.vertices[2].point(), Point::new(100.0, 60.0)); + // Both neighbours are sharp, so the arc reaches the whole 60 of the shorter side: from the top + // right corner to 60 along the bottom, on a circle of radius 60 centred at (40, 0). + let arcs: Vec<_> = net + .fill_path() + .segments() + .filter_map(|s| match s { + PathSeg::Cubic(c) => Some(c), + _ => None, + }) + .collect(); + assert_eq!(arcs.len(), 1, "{arcs:?}"); + let ends = [arcs[0].p0, arcs[0].p3]; + let close = |a: Point, b: Point| (a - b).hypot() < 1e-9; + assert!(ends.iter().any(|e| close(*e, Point::new(100.0, 0.0))) && ends.iter().any(|e| close(*e, Point::new(40.0, 60.0))), "{ends:?}"); + let h = 60.0 / 2f64.sqrt(); + assert!(close(arcs[0].eval(0.5), Point::new(40.0 + h, h)), "{:?}", arcs[0].eval(0.5)); +} diff --git a/crates/ui-egui/src/vector_point_xy_tests.rs b/crates/ui-egui/src/vector_point_xy_tests.rs index e93f62873..7f6c911e3 100644 --- a/crates/ui-egui/src/vector_point_xy_tests.rs +++ b/crates/ui-egui/src/vector_point_xy_tests.rs @@ -9,7 +9,9 @@ use serde_json::json; use crate::field_tests::{field, scrub, type_into, undo_steps}; use crate::layers_drag_tests::Ui; -fn setup() -> (Ui, NodeId) { +/// A 100 × 60 rectangle at the origin, selected and in vector edit mode (points clockwise from +/// the top left), and its id. +pub(crate) fn setup() -> (Ui, NodeId) { let mut s = Session::new(); let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap(); let id = NodeId(r["id"].as_u64().unwrap()); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e928b4c12..176138513 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 (M4: a rounded vector point next to sharp ones reaches along the whole of its segments, as in Figma (#2334); 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: @@ -97,7 +97,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Rectangle, ellipse (arc handles and Design panel arc fields), polygon, star, line, arrow; Shift/Alt | done | Alt draws lines from the centre too (`shapes_behaviour_tests`) | | Corner radius handles (inside each corner of a rectangle or frame, a polygon's or star's top point; Alt: one corner), star ratio handle; Count and Ratio fields | done | handles hide under 48 px on screen; no count handle on the canvas (the Count field instead); corner smoothing rounds rectangles and frames only | | Pen: vector networks, branch, close, bend; pencil | done | pen pressure on Windows and from browser styluses only; outside edit mode the Pen closes on its first point, connects to its other points and continues a selected open path from an end point (`vector_multi_behaviour_tests`); Escape ends the path and keeps its layer in edit mode with the pen, so the next path joins the same vector and another Escape leaves edit mode (#760, `pen_end_tests`); Enter or a double-click ends the path (at the double-click's point, added once) and edits the vector with the Move tool, a double-click with the idle pen edits the layer under it, and in edit mode the pen's Enter or double-click takes the Move tool (#1430, `pen_vector_edit_tests`); switching from Design to Prototype or Inspect ends the path and returns to Move (#308) | -| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn; Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | +| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn, an arc reaching along the whole of a segment whose other end is sharp and half of one whose other end is rounded too, so one rounded corner of a 100 × 100 square with radius 100 runs from one neighbour to the other, while the radius field keeps what was typed (#2334, `vector_radius_tests`, `vector_point_radius_tests`); Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | | Shape builder (Shift+M) on fills, strokes and open paths; variable width (Shift+W), one side with Alt | done | | | Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003) | | Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image 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, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check | @@ -215,6 +215,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | M4, #2334: a vector point's corner radius was cut to half of its shorter segment, so radius 100 on one corner of a 100 × 100 square drew a radius-50 arc. Figma (the issue's screenshot) draws it from one neighbour to the other. Now each arc may reach along the whole of a segment whose other end stays sharp, and along half of one whose other end is rounded too (as before; Figma's plugin docs clamp each end of such an edge to half its length); the shorter room of the two segments wins, and a smoothed corner uses the same room before losing smoothing. The stored radius and the Point section's field were already as typed. Not measured: how Figma splits a segment between two rounded ends with different radii. Tests: `vector_radius_tests` (doc), `vector_point_radius_tests` (UI) | | 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 e62b14084527d75b9fe4ce74a1a38710dbb30dc6 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:34:37 +0100 Subject: [PATCH 026/129] M4: the radius tests pick each arc by its middle too (opposite corners share both ends, #2334) --- crates/doc/src/vector_radius_tests.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/vector_radius_tests.rs b/crates/doc/src/vector_radius_tests.rs index 6301e2d13..d892669db 100644 --- a/crates/doc/src/vector_radius_tests.rs +++ b/crates/doc/src/vector_radius_tests.rs @@ -45,9 +45,10 @@ fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) { let (a, b) = (toward(prev), toward(next)); let center = a + (b - corner); let mid = center + (corner - center) / (corner - center).hypot() * t; - let arc = got.iter().find(|c| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a))); - let Some(arc) = arc else { panic!("{why}: no arc from {a:?} to {b:?} in {got:?}") }; - assert!(near(arc.eval(0.5), mid), "{why}: the arc at {corner:?} passes {:?}, not {mid:?}", arc.eval(0.5)); + // Two arcs can share both ends (opposite corners of a square), so the middle picks one. + let ends = |c: &&CubicBez| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a)); + let passing: Vec = got.iter().filter(ends).map(|c| c.eval(0.5)).collect(); + assert!(passing.iter().any(|&m| near(m, mid)), "{why}: no arc at {corner:?} from {a:?} to {b:?} through {mid:?}; arcs between them pass {passing:?}"); } } From dc7bc62c5e4de375af0c6221b5974a6d42378f8f Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:35:34 +0100 Subject: [PATCH 027/129] M4: rustfmt the radius test's arc check (#2334) --- crates/doc/src/vector_radius_tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/vector_radius_tests.rs b/crates/doc/src/vector_radius_tests.rs index d892669db..b48414a76 100644 --- a/crates/doc/src/vector_radius_tests.rs +++ b/crates/doc/src/vector_radius_tests.rs @@ -48,7 +48,10 @@ fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) { // Two arcs can share both ends (opposite corners of a square), so the middle picks one. let ends = |c: &&CubicBez| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a)); let passing: Vec = got.iter().filter(ends).map(|c| c.eval(0.5)).collect(); - assert!(passing.iter().any(|&m| near(m, mid)), "{why}: no arc at {corner:?} from {a:?} to {b:?} through {mid:?}; arcs between them pass {passing:?}"); + assert!( + passing.iter().any(|&m| near(m, mid)), + "{why}: no arc at {corner:?} from {a:?} to {b:?} through {mid:?}; arcs between them pass {passing:?}" + ); } } From a870a08cdb4dd6f3d1b19243fe294879d4378691 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 12:16:52 -0500 Subject: [PATCH 028/129] docs: merge back the parity rows that recent merges duplicated or garbled Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- docs/boards-parity.md | 7 ++----- docs/components-parity.md | 2 +- docs/dev-mode-parity.md | 4 ++-- docs/file-format-parity.md | 7 +++---- docs/localization-parity.md | 6 ++---- docs/ui-parity.md | 20 ++++++-------------- 6 files changed, 16 insertions(+), 30 deletions(-) diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 19b7ac13d..567b9b61e 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -32,15 +32,11 @@ all end with the same geometry. | Prototyping and Developer Mode refuse on boards | done | `proto.*`, `dev.*`, `view.prototype`, `view.devMode` say why | | Sticky notes | done | a square frame (200 wide, growing taller through auto layout), 8 soft colours, a soft shadow, the note's text 16 by default (FigJam's "Small", read twice from its size field, 2026-11-12) and fixed as it fills: the note grows taller and never shrinks its text (2026-11-09, #2157); a size menu in the contextual bar (Small 16, Medium 24, Large 40, Extra large 64, Huge 96; a number when the size matches none) sets every selected sticky, the note grows taller when Huge no longer fits and shrinks back to square at Large, and the sticky tool remembers the last size for new stickies, all measured in FigJam's web app, 2026-11-12; stickies saved with another size keep it, the author's name at the bottom; a click places one and starts typing; Enter or a double-click edits; Shift+Cmd/Ctrl+Enter adds the next one beside it | | Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; size presets done (the bar's menu, `board.setStyle {fontSize}`, `board.sticky {fontSize}`); no stacks | -| Shapes with text | done | rectangle, rounded rectangle, ellipse, diamond, triangle, speech bubble, chevron; text centred and wrapping inside the outline; shape type and text size from the contextual bar | +| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, more shapes (cylinder, cross, star…), shape libraries | missing | | | Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) | -| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, the advanced shape libraries (engineering and other icon shapes) | missing | | -| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was | | Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector leaving by the handle's side (`at: [x, y]`, a point of the page); let go on another sticky or shape, inside a section too, and a connector joins the two instead, the object outlined while over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile (`board_connect_tests`, #1919) | -| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) | -| Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before | | Curved connectors, elbows around objects, dragging an end to re-attach | done | `board.setStyle {style: curved}` (and the contextual bar): one curve leaving and arriving along the sides; an elbow whose short way would cross what it joins goes around their boxes, 24 units clear; a selected connector shows its two ends as handles, and dragging one onto an object attaches it there (the object is outlined while dragging), onto empty canvas leaves it free (`board.reattach {id, end, target, side?}`, one undo step) | | A connector end on any part of an object | done | holding Cmd/Ctrl while moving an end places it where the pointer is on the object, as a share of its box, so it follows moves and resizes; the line leaves by the side facing the other end. Without the key an end snaps to a side | | Connector paths reshaped by hand | done | a selected elbow or curved connector shows path handles: one on each run long enough to take one, one in the middle of a curve. Dragging a run moves it, and a first or last run gains an extra run to stay on its end; a curve's middle goes where it is dragged (`board.reshape`, one undo step). The shape travels with what the connector joins and is saved with the file; changing the style or moving an end to something else goes back to routing itself. No way back by itself otherwise: the public help describes none | @@ -72,6 +68,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Shapes with text, Connectors, Create the next shape already connected. | | 2026-11-12 | minor | M12: a sticky's text-size menu. Measured in FigJam's web app, 2026-11-12: the menu lists Small 16, Medium 24, Large 40, Extra large 64 and Huge 96 (typing 40 shows Large), a fresh sticky is Small = 16 (read twice from the size field; the 18 of 2026-11-09 did not reproduce), the note stays square to Extra large and grows taller at Huge with the same width and shrinks back at Large, choosing a size with two stickies selected sets both, and the sticky tool remembers the last size. `STICKY_TEXT_SIZE` is 16, `STICKY_SIZES` holds the table, `board.setStyle {fontSize}` sizes stickies and sets the tool's size, `board.sticky` takes `fontSize`, and the contextual bar shows a size menu when only stickies carry text (shapes keep S/M/L/XL, unmeasured). Stacks are still missing. Tests: `a_new_sticky_is_small_16`, `the_sticky_sizes_are_figjams`, `set_style_font_size_sizes_every_selected_sticky`, `the_sticky_tool_remembers_the_last_size`, `a_huge_sticky_grows_taller_and_shrinks_back`, `a_selected_sticky_has_a_size_menu_instead_of_the_size_cells` | | 2026-11-09 | minor | M12, #2172: a board table's height change goes into its rows. Measured in FigJam's web app, 2026-11-09 (a table has no lock-proportions control and never scales proportionally): a bottom-edge drag grows only the last row, a corner drag shares the change equally over every row and column, text keeps its size, and a table stops shrinking at about 52 per cell with a row never shorter than its wrapped text. FigCraft already split a width change equally (every cell fills); the bug was height: a bottom or corner resize turned the table from hugging to fixed height, so the rows stayed at 40 with blank space below them (or were clipped when shrunk) and typing no longer grew the table. `board_table::settle_resize`, called first in the normalize pass, finds a table left at a fixed height, puts the change into the rows' minimum height (the last row, or every row when both axes changed), raises a width that is too narrow to `columns x 40`, and returns the table to hugging, so every route (drag, `node.set`, `transform.resize`, MCP, live-session peers) gives the same result, in one undo step. FigCraft's floor is 40 (FigJam's is about 52) and there are no per-column widths yet: a side drag of the right edge still splits equally where FigJam grows only the last column. Numbers unchanged. Tests: `board_tables_tests` (the bottom, corner and side drags, the floor, typing after a resize and undo, live sessions, junk). | | 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` | diff --git a/docs/components-parity.md b/docs/components-parity.md index 3d23800b0..22ba2c4ed 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -13,7 +13,6 @@ accounts). | Feature | Status | Notes | |---|---|---| | 2026-11-11 | minor | M3, #2022: an instance lists only the properties its variant's layers use (its variant properties, slots, and the boolean, text and instance swap properties a layer of its current variant reads), as measured in Figma's web app: an instance of variant A lists `State` and `A label`, never `B label` or a property no layer reads. The set and its variants still list every definition, so unused ones can be deleted there. A long property name in the panel is cut to one line with an ellipsis, the full name on hover, instead of wrapping over the rows around it. Tests: `prop_order_tests::an_instance_lists_only_the_properties_its_variant_uses`, `component_props_reorder_tests::a_long_property_name_stays_on_one_line`, `prop_value_tests::a_set_keeps_each_named_text_definition_and_layers_read_their_own`. Grade unchanged. | -| Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main | | Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main; with two or more layers selected the Design panel header's component button opens a menu with Create component, Create multiple components (each layer its own component in place, one undo step) and Create component set (each layer a component, wrapped in place in a set 20 px around: variants `Property 1=` left to right, `prop=value` names kept, layers that all share a name give a set of that name with `Property 1=Default` variants; measured in Figma), one layer keeps the plain click (#2088) | | Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances | | What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | @@ -81,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Create component, instances, detach, reset, go to main, restore main, push changes. | | 2026-11-07 | minor | M3, #2084: a group's context menu in the Local variables window has Duplicate group (after Rename group, before Delete group). It adds a group named after the original plus " 2" (the next free number when taken: " 3"), whose variables are copies of the originals with the same leaf names, values in every mode, description, scopes, hidden-from-publishing and code syntax, each sent as `variable.duplicate` plus a rename in one `command.batch` labelled Duplicate group, so one undo step. Measured in the incumbent with one mode; an alias to a variable of the same group keeps pointing at the original. Ungroup is not built. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-12 | minor | M7, #2215: pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215). The same section the frames' Variable modes use (`variable.setMode` without layers sets the page's mode), one undo step per pick. Binding the page background to a variable is not in the reference and is not offered | diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index d77dce75f..0443708c0 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -14,8 +14,7 @@ repository, third-party integrations. Remaining: 1–2 h. | 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why | | Properties with their styles and variables; redlines on hover | done | positions from the frame around the layer (groups aren't frames), rotation, radius (CSS corner order), opacity, blend; colours in hex, RGB, CSS, HSL or HSB (`inspect.properties {colorFormat}`, the Inspect tab's Color format) | -| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235) | -| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) | +| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) | | Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours | | Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) | @@ -31,6 +30,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Code: CSS, iOS (SwiftUI), Android (Compose), Flutter. | | 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged | | 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | 2026-10-30 | minor | Gap 16: `figcraft-cli connect publish [--mappings figcraft.connect.json] [--dry-run]` publishes a code repository's mappings to a design file (as the incumbent's Code Connect CLI publishes a repository's mappings): it links each entry's component or set by name, warns about and skips links that don't fit, saves the file in place through the engine's save (or not, with `--dry-run`) and fails when nothing links. Dev Mode breadth (~98%) and ready (~78%) unchanged at this rounding; hours unchanged | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index feeac9e05..bdef310aa 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -39,8 +39,7 @@ and prototype interactions are still unchecked there. | BMP | — | yes | | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | ## Export @@ -53,9 +52,8 @@ export limit, not a native document nesting limit. | Format | Figma | FigCraft | Notes | Hours | |---|---|---|---|---| -| PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels | — | -| JPG | yes | yes | white where transparent; quality 1 to 100 (`quality` on `file.export`, export settings and MCP `export`; default 90; the Export panel has no control for it yet); a color profile per setting as for PNG (`colorProfile`), the file tagged with an ICC profile (APP2) for sRGB and for Display P3 | — | | PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels; a color profile per setting (Same as file, the default, sRGB or Display P3: `colorProfile`), the pixels converted and the file tagged (`sRGB` chunk, or ICC and `cICP`) | — | +| JPG | yes | yes | white where transparent; quality 1 to 100 (`quality` on `file.export`, export settings and MCP `export`; default 90; the Export panel has no control for it yet); a color profile per setting as for PNG (`colorProfile`), the file tagged with an ICC profile (APP2) for sRGB and for Display P3 | — | | SVG | yes (outline text option, ids) | yes | alpha/luminance masks kept; noise, texture, progressive and background blur, glass embedded as images; outline text (off: `` with one `` per line, one style per layer), unique id attributes from layer names, explicit depth-limit refusal, nested frames clipped by their parent's clip (#327), simplified strokes (stroke attributes for centred strokes and for inside and outside strokes on boxes and ellipses) | — | | PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal; RGB is always sRGB (no color profile setting and no output intent) | CMYK output intent 2–4 | | WebP | — | yes (ours) | a color profile per setting as for PNG; sRGB files untagged, Display P3 files with the generated ICC profile | — | @@ -198,6 +196,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. | | 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software | | 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, #2297: the `.fig` exporter writes an image paint's adjustments as `paintFilter` (seven fields: exposure, contrast, vibrance from saturation, temperature, tint, highlights, shadows; the tint's sign is flipped, as the importer reads it), and no longer warns about them; the importer already read them. Not checked in other software | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 3b48ac54c..f8b782e16 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -110,11 +110,8 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v | Simplified Chinese (Mandarin) | zh-Hans | 2,216 / 2,352 (94.2%, draft) | yes | CJK text and IME in documents; UI text in an installed Chinese face, ahead of Japanese ones (web: the `FIGCRAFT_EMBED_CJK` build) | no | draft | 1–2 (after native review) | | Traditional Chinese (Taiwan) | zh-Hant | 2,647 / 2,647 (100%: 1,975 UI strings, 641 command labels, 31 menu wordings; draft, counted 2026-11-03) | yes | CJK text and IME in documents; UI text in an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC or Heiti TC (web: only with a built-in TC face); zh-TW, zh-HK, zh-MO and zh-Hant read it, an explicit Hans stays Simplified | no | draft | 1–2 (after native review) | | Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) | -| Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; UI font fallback to check | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` embeds Noto Sans Arabic (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | | Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; the desktop UI takes an installed Devanagari face (Nirmala UI, Kohinoor Devanagari, Noto Sans Devanagari, Lohit) for names and values (#2014); no UI catalog | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) | +| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` embeds Noto Sans Arabic (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) | | French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Indonesian | id | 2,292 / 2,352 (97.4%, draft) | yes | Latin | no | draft | 1–2 (after native review) | @@ -149,6 +146,7 @@ Hindi and Arabic. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Hindi, Arabic. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source and marked as a draft awaiting native review. `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it; an explicit Hans still reads Simplified Chinese. The desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled. No plural forms. Localization grade and estimates unchanged | | 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build and its size are unchanged, and with `Arab` embedded the picker offers the Arabic UI as well (`cjk::can_show`, as on the desktop). Noto Sans Hebrew, Devanagari and Georgian join Arabic and Thai among the document fallbacks, so an embedded face draws its script in an Inter document. Tests: `web_embeds_other_scripts_faces_only_when_asked` in the build script, `every_embeddable_script_face_is_a_document_fallback`. | | 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as well as Hebrew and Arabic; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bb2c91040..64304c775 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -16,9 +16,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Item | Status | Notes | |---|---|---| | Light and dark themes | done | colours from `theme::Tokens`; component, variant and instance rows in the Layers panel take the theme's component tint, at AA on the panel and on their selected row (hidden ones in the faded text colour, at least 3:1 on the panel, a hovered row and their selected row), and the rows inside a selected component a tone of its row (`layers_component_rows_tests`, #1903); a file or a page made while the dark theme shows gets a `#1E1E1E` page (`#F5F5F5` in the light theme), its own from then on: changing the theme repaints no page and opened files keep theirs; the file the app opens with takes the theme once it is known; the CLI, MCP and exports have no theme and keep `#F5F5F5`; text drawn with the Text tool is white on a dark page and black on a light one (so is text a command makes in the app without naming a fill; headless sessions keep black) (`theme_pages_tests`, `dark_page_text_tests`) | -| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | frameless window on Windows/Linux with drawn buttons; tabs reorder by dragging along the strip, and closing one whose file has unsaved changes asks Don't Save / Cancel / Save (Alt+close drops the changes at once, #2032); on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) | -| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | rail and tab strip icons 20 pt (#553); frameless window on Windows/Linux with drawn buttons; on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) | -| Light and dark themes | done | colours from `theme::Tokens`; a file or a page made while the dark theme shows gets a `#1E1E1E` page (`#F5F5F5` in the light theme), its own from then on: changing the theme repaints no page and opened files keep theirs; the file the app opens with takes the theme once it is known; the CLI, MCP and exports have no theme and keep `#F5F5F5`; text drawn with the Text tool is white on a dark page and black on a light one (so is text a command makes in the app without naming a fill; headless sessions keep black) (`theme_pages_tests`, `dark_page_text_tests`) | +| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | rail and tab strip icons 20 pt (#553); frameless window on Windows/Linux with drawn buttons; tabs reorder by dragging along the strip, and closing one whose file has unsaved changes asks Don't Save / Cancel / Save (Alt+close drops the changes at once, #2032); on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) | | Minimize UI (Shift+Cmd/Ctrl+\\, the Minimize button by the file name) and Show/Hide UI (Cmd/Ctrl+\\) | done | Minimize collapses the navigation bar and both sidebars and keeps the toolbar and the panel widths; "If you select an object while the panels are minimized, the left sidebar remains minimized while the right sidebar expands [...] Once all objects are deselected, the right panel minimizes again" (Explore the navigation bar and left sidebar); a small Expand button at the top left of the canvas puts them back (FigCraft's own, the article names no control for it). Hide UI takes the toolbar too (`panel_width_tests`, `shortcuts_tests`; #1835) | | Resizable panels | done | each panel's edge drags its width (left 240–450, right 240–500, 240 by default, as measured in Figma's web app on 2026-11-08; a double-click on the edge or View ▸ Panels ▸ Reset panel widths puts the default back); the widths are each window's own, the main window's are kept in the preferences when a drag ends and come back at the next start (a width saved under other limits is clamped to the current ones on load, and one that isn't a number, NaN or infinite, falls back to 240), a new window opens with those of the window it comes from; Minimize UI hides the panels and brings them back as they were; the view keeps its centre and zoom while a panel is resized; in a window too small for them the panels give way so the canvas keeps 160 px (the left one first), down to the smallest window (800×500) (`panel_width_tests`). The double-click reset to 240 matches Figma's; no snap points | | Design panel's sections on one grid | done | every section lays its rows out on the same grid: the panel is 240 pt, its content 16 pt in from the left and 8 pt from the right, two 88 pt columns at that width with 8 pt gutters and a 24 pt column for the buttons at a row's end (the columns are flex, so they share the panel when it is dragged wider); rows 24 pt in a 32 pt track, 10 pt captions over them; section titles 11 pt semibold and a row's values 11 pt, their buttons 24 pt and 4 pt apart. The panel's edge is drawn inside it: a frame stroke counts as margin and took 1 pt off each side, putting every right margin 1–2 pt out (checked in the app on Windows over the control channel) | @@ -65,8 +63,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Escape with layers selected | done | clears the selection at once, whatever the nesting; it never selects the parent. Measured in the Figma web app (2026-11-08) with a rectangle in a group in a frame, selected from the canvas (a double-click into the group), from the Layers panel, and after Tab moved the selection to its sibling: one Escape selects nothing, a second leaves nothing selected. Escape still leaves text and vector editing, ends gestures and the pen first, and ends the focus view once nothing or the focused frame is selected (`selection_behaviour_tests`, `devfocus_tests`) | | Enter / Shift+Enter (children / parent), Tab / Shift+Tab (siblings) | done | Tab renames the next layer while renaming | | Resize handles: Shift keeps proportions, Alt from centre, constraints-aware | done | Alt shrinks too; past an edge flips (several layers mirror); groups and mixed rotations scale each layer along its own axes, keeping rotation and flip (no skew: children turned off a right angle are approximate); Cmd/Ctrl ignores a frame's constraints (`transform_behaviour_tests`); Shift keeps the ratio (a corner by the axis dragged most, an edge scaling the other axis about the opposite edge's middle), Alt keeps the centre, Shift+Alt does both, each read afresh on every move (`handle_drags_resize_by_the_documented_rules`; measured in Figma's web app, 2026-11-08; Ctrl/Cmd while dragging not measurable) | -| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; the Rotation field shows and sets the rotation on the page (its own angle plus its parents'), in frames and groups alike, measured in Figma's web app 2026-11-10 (#2196): a rectangle drawn inside a turned frame reads 0, typing 7 makes it 7 on the page; the panel sends `node.set absoluteRotation`, while `rotation` stays the angle to the parent for scripts, inspect, codegen and the formats. Pinned, not measured: several layers read one value when their page angles agree (typing sets them all, one undo step); a flipped layer reads in the same form as before (a horizontal flip reads 180 plus the angle) and typing keeps the flip; a flipped parent is handled by the world math. Tests: `absolute_rotation_sets_the_rotation_on_the_page_keeping_the_centre`, `the_absolute_rotation_key_turns_about_a_moved_origin_too`, `the_rotation_field_shows_and_sets_the_rotation_on_the_page` | -| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; Shift lands the rotation on multiples of 15° (measured in Figma: a layer at 7° or -4.27° ends at 15°), not 15° steps from where the drag began; layers with different rotations step the turn from 0 | +| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; Shift lands the rotation on multiples of 15° (measured in Figma: a layer at 7° or -4.27° ends at 15°), not 15° steps from where the drag began; layers with different rotations step the turn from 0; the Rotation field shows and sets the rotation on the page (its own angle plus its parents'), in frames and groups alike, measured in Figma's web app 2026-11-10 (#2196): a rectangle drawn inside a turned frame reads 0, typing 7 makes it 7 on the page; the panel sends `node.set absoluteRotation`, while `rotation` stays the angle to the parent for scripts, inspect, codegen and the formats. Pinned, not measured: several layers read one value when their page angles agree (typing sets them all, one undo step); a flipped layer reads in the same form as before (a horizontal flip reads 180 plus the angle) and typing keeps the flip; a flipped parent is handled by the world math. Tests: `absolute_rotation_sets_the_rotation_on_the_page_keeping_the_centre`, `the_absolute_rotation_key_turns_about_a_moved_origin_too`, `the_rotation_field_shows_and_sets_the_rotation_on_the_page` | | Flip, rotate 90° | done | | | Rotation origin (Alt+R) | done | a handle at the selection's centre to drag (snaps to the box's corners, edge middles and centre), double-click puts it back, Escape or Alt+R hides it; the corner handles, the rotation field, Rotate 90°/180° and `transform.rotate` turn about it; it follows the layers and lasts as long as the selection, not saved (the documentation doesn't say; pinned) | | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | @@ -83,10 +80,8 @@ interaction feel only partly compared: the interactions measured so far, case by | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session | | Smart selection spacing | partial | with layers in a row, a column or an aligned grid selected, the Layout section shows horizontal and vertical spacing ("Mixed" until set; typed, scrubbed, fractional and negative) and pink handles in the gaps on the canvas drag them, one undo step, Escape cancels (`arrange.spacing`; sizes, parents and offsets within each track kept; at most 2,000 layers; flow children, locked layers and layers inside instances left out). A ring at each layer's centre drags it to another place in a regular row, column or complete top-left-aligned grid: the others close up and make room around it with the gaps kept, and with Cmd/Ctrl held the two layers swap places instead, previewed live while dragging (`selection_reorder_tests`; no ring on a layer under 16 px on screen). Not covered: reordering irregular grids, and several marked layers moved together. Checked by its author on macOS and in the app on Windows (#402) | -| Selection colors | partial | the Design panel shows the section from two paint groups (paints sharing a style, a variable and a value count as one group), or from one when a selected layer has children (a frame, group, component or instance), and lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). A row's Styles menu also offers enabled libraries' published color styles and Create style (`selection.createColorStyle`); no library variables and no new variable from a row (#403) | -| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes; Tab while the box shows, or the chord again, switches to pick select: a pink outline on the first selected layer (the page's top layer with nothing selected), Tab and Shift+Tab move it between sibling layers in Layers order, Enter into a frame's top child, Shift+Enter out to the parent, Space selects it, Escape or a press on the canvas ends it; `ui.key` takes the same keys (#1836) | | Selection colors | partial | the Design panel shows the section from two paint groups (paints sharing a style, a variable and a value count as one group), or from one when a selected layer has children (a frame, group, component or instance; a layer without children shows it only with two paint groups, such as a red fill and a blue stroke; one paint group, however many layers share it, hides it), counting the selected layers' own fills and strokes and their descendants' (measured in Figma's web app, 2026-11-09, #2188, on frames, groups and rectangles only; the rule for components and instances is not measured), and lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). A row's Styles menu also lists each enabled library's published color styles under the library's name (a library that can't be read offers none), and a linked row's menu switches it to another style; a library style is copied in, linked and read-only, in the same undo step (`selection.applyColorStyle` with `library`). Create style on an ordinary row asks for a name (the next free "Color n" first) and makes a style of the row's whole paint, gradients, opacity, blend mode and variables bound to gradient stops included, linked to every fill and stroke the row stands for in one undo step; a name in use keeps the window open (`selection.createColorStyle`). Text ranges with fills of their own take the style's value, without a link. No library variables from there, and no new variable from a row (#403) | -| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes | +| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes; Tab while the box shows, or the chord again, switches to pick select: a pink outline on the first selected layer (the page's top layer with nothing selected), Tab and Shift+Tab move it between sibling layers in Layers order, Enter into a frame's top child, Shift+Enter out to the parent, Space selects it, Escape or a press on the canvas ends it; `ui.key` takes the same keys (#1836) | ## Tools @@ -99,11 +94,8 @@ interaction feel only partly compared: the interactions measured so far, case by | Pen: vector networks, branch, close, bend; pencil | done | pen pressure on Windows and from browser styluses only; outside edit mode the Pen closes on its first point, connects to its other points and continues a selected open path from an end point (`vector_multi_behaviour_tests`); Escape ends the path and keeps its layer in edit mode with the pen, so the next path joins the same vector and another Escape leaves edit mode (#760, `pen_end_tests`); Enter or a double-click ends the path (at the double-click's point, added once) and edits the vector with the Move tool, a double-click with the idle pen edits the layer under it, and in edit mode the pen's Enter or double-click takes the Move tool (#1430, `pen_vector_edit_tests`); switching from Design to Prototype or Inspect ends the path and returns to Move (#308) | | Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn; Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | | Shape builder (Shift+M) on fills, strokes and open paths; variable width (Shift+W), one side with Alt | done | | -| Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003) | -| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image 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, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check | -| Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. Not yet included: per-paragraph settings, text-style support and the `.fig` import/export mapping (#1827). Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` | | Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003); a boolean group takes a corner radius from the Design panel and from `node.set cornerRadius`: every sharp corner of its result rounds, convex and concave, layers inside keep their own radius and do not stack with it, a radius larger than the edges allow shrinks to fit while the field keeps the value typed, Flatten bakes the arcs and a mixed selection reads Mixed; measured in Figma's web app on 2026-11-10 (#2222; `crates/pathops/src/round_tests.rs`, `crates/render/src/boolean_radius_tests.rs`, `crates/engine/src/boolean_radius_tests.rs`, the boolean group test in `crates/ui-egui/src/field_tests.rs`). Pinned and not yet compared with Figma: corner smoothing on a boolean group draws the polygon profile between straight edges, a corner beside a curve stays within the curve piece next to it, and there is no radius handle on the canvas | -| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; no spell check | +| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image 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, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check | | Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. At three levels (the text layer, a paragraph and a text style, per Explore text properties): the paragraph level is the caret's or the selection's paragraphs while editing (`text.wrapStyle`; the control follows them), or `start`/`end` on `node.set wrapStyle` (a paragraph's own style beats the layer's; setting the layer sets every paragraph again; Enter carries it to the new paragraph; inspect reports `lineWrapStyles` when paragraphs differ and CSS `text-wrap` only when they agree); the text-style level is a style's `wrapStyle` (shown read-only in the style editor, applied with the style, moved by `style.update`, unlinking when edited). The `.fig` import/export mapping stays open (#1827): a `.fig` export leaves the wrap styles out and a `.fig` import reads every text as Auto, so the wrap styles are lost through a `.fig` round trip. Test: `text_behaviour_tests::wrap_style_per_paragraph_overrides_the_layers`, `styles_behaviour_tests::text_styles_carry_the_wrap_style`, `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` | | Text: direction override (Text ▸ Text direction) | done | per paragraph (`ParaList::direction`: auto, ltr, rtl): Text ▸ Text direction ▸ Auto / Left to right / Right to left and `text.direction {direction, ids?}` set the edited paragraphs while editing, else every paragraph of the selected texts; `node.set textDirection` the layer's (or the chars `start`/`end` name); the Type settings control appears once a right-to-left script is in the text or a direction is forced; inspect reports `textDirection` when the paragraphs agree and `lineDirections` otherwise; Developer Mode's CSS writes `direction: ltr` or `rtl` when every paragraph is forced the same way (with `text-align: left` beside `rtl`, as Left is absolute on the canvas); `.fig` import and export carry each line's `sourceDirectionality`, read up to the paragraph count. Layout gives the paragraph its base level, so a forced right-to-left paragraph of Latin letters starts at the right, mirrors its list gutter and indent and orders its runs right to left, and a forced left-to-right paragraph of Hebrew the other way ("By default, Figma automatically handles text direction based on language detection. However, controls are available to override text direction per paragraph", "Go to Text > Text direction. Select Left to right or Right to left", Add right-to-left text). Not included: a direction in text styles (the article names none). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests` | | Text: superscript and subscript | done | `sups` / `subs` use the font's own glyphs where it has the feature and every letter or digit of the run gets one; otherwise the standard glyphs are drawn shrunk and raised or lowered by the font's OS/2 superscript and subscript metrics (0.65 em at 0.35 em up or 0.14 em down without them), and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says ("Figma draws a synthesized version by using the font's standard version of the character, shrinking it, and positioning it accordingly"; mixed glyphs "all update to the synthesized form for consistency"), #1828; tests `text::tests::superscript_native_or_synthesised_and_never_mixed`, `text_behaviour_tests::superscript_and_subscript_are_synthesised_without_glyphs_for_them` | @@ -118,7 +110,7 @@ interaction feel only partly compared: the interactions measured so far, case by | 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); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_testsPreferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_testszoom 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`) | +| 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); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); Preferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); 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 | @@ -147,7 +139,6 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | | Count | Notes | |---|---|---| | Documented shortcuts (rows) | 137 | each with macOS and Windows/Linux keys | -| Bound as documented | 136 (110 before this suite) | 113 keymap bindings, 15 held keys, gestures and presentation keys, 6 vector edit tool keys | | Bound as documented | 136 (110 before this suite) | 113 keymap bindings, 16 held keys, gestures and presentation keys, 6 vector edit tool keys | | Bound on other keys (documented conflict) | 1 | Run last plugin: the documentation also gives Ctrl+Alt+P to pixel preview on Windows; the plugin takes Ctrl+Alt+Shift+P there | | Missing | 0 | moving the rotation origin (Alt+R, `transform.rotationOrigin`) and placing an object with Enter after choosing its tool (`tool.place`) were the last two | @@ -214,6 +205,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): UI3 layout, Light and dark themes, Rotate just outside a corner, Selection colors, Keyboard box selection, Boolean groups, Text: point, auto height, fixed, Text: wrap style, Bound as documented, Pan/zoom. | | 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-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 | Drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis with no 45° snap, Alt copies, Shift keeps a resize's ratio (an edge scales about the opposite edge's middle), Alt keeps the centre, Shift+Alt does both, and a modifier changed mid-drag is read fresh on each move; FigCraft matches in all six, Ctrl/Cmd while dragging could not be measured; no code change | this page | From 0d7328733e24d6012d9b39c1f2128390f97214c8 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 12:54:54 -0500 Subject: [PATCH 029/129] M8: the font menu's search uses the shared search box (#2318) The font menu allocates a FIELD_H rect at the menu's width and calls widgets::search_box there, so it gets the same magnifier and field look as the other search boxes (field_editor selects all on focus and centres its text). widgets::search_edit is gone; the hint-centring test points at search_box, a new test checks the hint sits after the magnifier, and the font-menu regrow test's width threshold allows for the box's margin and magnifier. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/font_menu_regrow_tests.rs | 4 +-- .../ui-egui/src/panels/typography/picker.rs | 5 ++-- crates/ui-egui/src/select_all_tests.rs | 28 +++++++++++++++++-- crates/ui-egui/src/widgets.rs | 14 ---------- 4 files changed, 31 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/font_menu_regrow_tests.rs b/crates/ui-egui/src/font_menu_regrow_tests.rs index b4a9d8804..5e095f394 100644 --- a/crates/ui-egui/src/font_menu_regrow_tests.rs +++ b/crates/ui-egui/src/font_menu_regrow_tests.rs @@ -75,13 +75,13 @@ fn centre(n: &Node) -> Pos2 { Pos2::new(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) } -/// The top of the search field: the text input as wide as `menu` (the panel's own fields are narrower). +/// The top of the search field: the text input nearly as wide as `menu`, less the search box's margin and magnifier (the panel's own fields are narrower). fn search_top(nodes: &[Node], menu: Rect) -> f32 { let field = nodes .iter() .filter(|n| n.role() == Role::TextInput) .filter_map(|n| n.bounds()) - .find(|b| menu.contains(Pos2::new(b.x0 as f32 + 1.0, b.y0 as f32 + 1.0)) && b.x1 - b.x0 > f64::from(menu.width()) - 40.0) + .find(|b| menu.contains(Pos2::new(b.x0 as f32 + 1.0, b.y0 as f32 + 1.0)) && b.x1 - b.x0 > f64::from(menu.width()) - 60.0) .expect("the menu has a search field"); field.y0 as f32 } diff --git a/crates/ui-egui/src/panels/typography/picker.rs b/crates/ui-egui/src/panels/typography/picker.rs index 8c0773ac4..11c040805 100644 --- a/crates/ui-egui/src/panels/typography/picker.rs +++ b/crates/ui-egui/src/panels/typography/picker.rs @@ -75,6 +75,7 @@ pub(crate) fn font_picker( let just_opened = anchor.clicked(); let hi_id = Id::unique("font_highlight"); let q_id = Id::unique("font_query"); + let search_id = Id::unique("font_search"); craft_ui::combo::Menu::new(ui, anchor) .height(MENU_HEIGHT) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) @@ -96,8 +97,8 @@ pub(crate) fn font_picker( i.count_and_consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown) as i64 - i.count_and_consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp) as i64 }); - let search = widgets::search_edit(ui, &mut q, tr("Search fonts"), regular(11.5)); - crate::widgets::select_all_on_focus(ui, &search, &q); + let (field, _) = ui.allocate_exact_size(vec2(ui.available_width(), widgets::FIELD_H), egui::Sense::hover()); + let search = widgets::search_box(ui, field, search_id, &mut q, tr("Search fonts")); if just_opened { search.request_focus(); } diff --git a/crates/ui-egui/src/select_all_tests.rs b/crates/ui-egui/src/select_all_tests.rs index 2679c94f3..ecb77001a 100644 --- a/crates/ui-egui/src/select_all_tests.rs +++ b/crates/ui-egui/src/select_all_tests.rs @@ -187,12 +187,36 @@ fn a_rename_field_in_a_short_row_centres_its_text() { fn the_font_search_box_centres_its_hint() { let ctx = egui::Context::default(); let mut q = String::new(); + let id = Id::unique("font_search"); let mut mid_box = 0.0; let mut f = |ui: &mut Ui| { - let r = widgets::search_edit(ui, &mut q, "Search fonts", egui::FontId::proportional(11.5)); - mid_box = r.rect.center().y; + let (field, _) = ui.allocate_exact_size(vec2(120.0, widgets::FIELD_H), egui::Sense::hover()); + widgets::search_box(ui, field, id, &mut q, "Search fonts"); + mid_box = field.center().y; }; let shapes = shapes_of(&ctx, &mut f); let mid = text_mid_y(&shapes, "Search fonts").expect("the hint is painted"); assert!((mid - mid_box).abs() <= 1.0, "hint centre {mid} vs box centre {mid_box}"); } + +/// The font menu's search field is the shared search box: its text starts after the magnifier, +/// not at the field's left edge as a bare editor's would (#2318). +#[test] +fn the_font_search_box_leaves_room_for_the_magnifier() { + fn left(s: &egui::Shape) -> Option { + match s { + egui::Shape::Text(t) if t.galley.text().contains("Search fonts") => Some(t.pos.x), + egui::Shape::Vec(v) => v.iter().find_map(left), + _ => None, + } + } + let ctx = egui::Context::default(); + let mut q = String::new(); + let id = Id::unique("font_search_icon"); + let mut f = |ui: &mut Ui| { + let (field, _) = ui.allocate_exact_size(vec2(120.0, widgets::FIELD_H), egui::Sense::hover()); + widgets::search_box(ui, field, id, &mut q, "Search fonts"); + }; + let x = shapes_of(&ctx, &mut f).iter().find_map(|c| left(&c.shape)).expect("the hint is painted"); + assert!(x >= FIELD.min.x + 20.0, "hint starts at {x}, field at {}", FIELD.min.x); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 84a98bc21..ee2e7d794 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1475,17 +1475,3 @@ pub fn sublabels(ui: &mut Ui, a: &str, b: Option<&str>) { pub fn col_width(w: f32) -> f32 { ((w - PAD - PAD_RIGHT - GUTTER * 2.0 - 24.0) / 2.0).max(40.0) } - -/// The search box of a menu (the font list's): one line, as wide as the menu, its hint and text -/// centred in the box. [`egui::TextEdit`] puts the text at the top of a box taller than a line -/// unless told otherwise (#2318). -pub(crate) fn search_edit(ui: &mut Ui, text: &mut String, hint: &str, font: egui::FontId) -> Response { - ui.add( - egui::TextEdit::singleline(text) - .hint_text(hint) - .desired_width(ui.available_width()) - .font(font) - .align(Align2::LEFT_CENTER) - .min_size(vec2(0.0, FIELD_H)), - ) -} From b38b4e3793106e6d69bae944be08435dd1e824ad Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 15:34:43 -0500 Subject: [PATCH 030/129] docs: the Arabic row names both builds that embed Noto Sans Arabic on the web crates/text/build.rs keeps the face for a web build when FIGCRAFT_EMBED_SCRIPTS names Arab or when FIGCRAFT_WEB_FONTS names the family (CodeRabbit on #2350). Co-Authored-By: Claude Opus 5.5 --- docs/localization-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index f8b782e16..e74c0df7f 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -111,7 +111,7 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v | Traditional Chinese (Taiwan) | zh-Hant | 2,647 / 2,647 (100%: 1,975 UI strings, 641 command labels, 31 menu wordings; draft, counted 2026-11-03) | yes | CJK text and IME in documents; UI text in an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC or Heiti TC (web: only with a built-in TC face); zh-TW, zh-HK, zh-MO and zh-Hant read it, an explicit Hans stays Simplified | no | draft | 1–2 (after native review) | | Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) | | Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; the desktop UI takes an installed Devanagari face (Nirmala UI, Kohinoor Devanagari, Noto Sans Devanagari, Lohit) for names and values (#2014); no UI catalog | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` embeds Noto Sans Arabic (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) | +| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab`, or with `FIGCRAFT_WEB_FONTS` naming Noto Sans Arabic, embeds it (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) | | French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Indonesian | id | 2,292 / 2,352 (97.4%, draft) | yes | Latin | no | draft | 1–2 (after native review) | From f451e60ceb954e801e4b286f00b9960e56ec59cf Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 23:42:18 -0500 Subject: [PATCH 031/129] M5: a chain of After delay variant changes plays to the end (#2352) Change to swapped the instance's variant in place, so the next variant's After delay kept the instance's node id and was already recorded as fired: the chain stopped after one step. The swap now clears the fired keys inside the instance and records when it happened; next_delay counts a timer from the later of the screen's arrival and that swap. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/present.rs | 6 ++ crates/ui-egui/src/present/actions.rs | 3 + .../src/present/afterdelay_chain_tests.rs | 98 +++++++++++++++++++ crates/ui-egui/src/present/navigate.rs | 5 +- docs/prototyping-parity.md | 3 +- 5 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/present/afterdelay_chain_tests.rs diff --git a/crates/ui-egui/src/present.rs b/crates/ui-egui/src/present.rs index 8f23069f2..8f8570342 100644 --- a/crates/ui-egui/src/present.rs +++ b/crates/ui-egui/src/present.rs @@ -290,6 +290,8 @@ pub struct Presenter { bar_thumb: Option<(NodeId, usize, egui::TextureHandle)>, arrived: f64, delays_fired: HashSet<(NodeId, usize)>, + /// When each instance last changed variant (Change to): its After delay timers count from then. + swapped: HashMap, /// Mouse triggers waiting out their delay. waiting: Vec, hovered: Vec, @@ -370,6 +372,7 @@ impl Presenter { bar_thumb: None, arrived: -1.0, delays_fired: HashSet::new(), + swapped: HashMap::new(), waiting: Vec::new(), hovered: Vec::new(), press: None, @@ -460,6 +463,9 @@ mod tail_tests; #[cfg(test)] mod delay_tests; +#[cfg(test)] +mod afterdelay_chain_tests; + #[cfg(test)] mod overlay_anchor_tests; diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index cfc3f26a8..017003025 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -218,6 +218,9 @@ impl Presenter { } figcraft_engine::components::sync_instance(d, inst); self.settle(&before); + // The new variant's After delay interactions are fresh: they count from now. + self.delays_fired.retain(|(id, _)| !doc.is_ancestor(inst, *id)); + self.swapped.insert(inst, now); true } Action::SetVariable { variable, value, expr } => { diff --git a/crates/ui-egui/src/present/afterdelay_chain_tests.rs b/crates/ui-egui/src/present/afterdelay_chain_tests.rs new file mode 100644 index 000000000..e8a5551f1 --- /dev/null +++ b/crates/ui-egui/src/present/afterdelay_chain_tests.rs @@ -0,0 +1,98 @@ +//! A chain of variant After delay steps (Change to) plays to the end, each step's delay counted +//! from when its variant appeared (#2352). Driven through egui headless on the harness's clock. + +use figcraft_doc::{NodeId, NodeKind}; +use figcraft_engine::Session; +use serde_json::{Value, json}; + +use crate::present_tests::{Ui as Harness, id}; + +fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}")) +} + +/// Variants A to D of one set, an instance on A in a screen, each step an After delay of `ms` +/// changing to the next variant. (harness presenting the screen, the instance, the variants) +fn chain(ms: u32) -> (Harness, NodeId, Vec) { + let mut s = Session::new(); + let variants: Vec = ["A", "B", "C", "D"] + .iter() + .enumerate() + .map(|(k, state)| { + let f = id(&ex( + &mut s, + "frame.create", + json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}), + )); + id(&ex(&mut s, "component.create", json!({"ids": [f]}))) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + for pair in variants.windows(2) { + let it = json!({"id": pair[0], "trigger": {"type": "afterDelay", "ms": ms}, "action": {"type": "changeTo", "dest": pair[1]}, "transition": {"type": "instant"}, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", it); + } + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + (u, inst, variants) +} + +/// The variant (index) the instance shows in the presenter. +fn shown(u: &Harness, inst: NodeId, variants: &[NodeId]) -> Option { + let p = crate::tabs::shown_or_paused(&u.app)?; + let d = p.doc.as_ref()?; + match d.node(inst)?.kind { + NodeKind::Instance { component, .. } => variants.iter().position(|v| *v == component), + _ => None, + } +} + +#[test] +fn a_chain_of_variant_after_delays_plays_to_the_end() { + let (mut u, inst, variants) = chain(0); + u.frames(30, Vec::new); + assert_eq!(shown(&u, inst, &variants), Some(3), "A -> B -> C -> D"); +} + +#[test] +fn each_step_waits_its_own_delay_from_when_its_variant_appeared() { + let (mut u, inst, variants) = chain(500); + // Step until the instance shows B, then note the time. + let mut guard = 0; + while shown(&u, inst, &variants) != Some(1) { + u.frame(Vec::new()); + guard += 1; + assert!(guard < 120, "A never changed to B"); + } + let appeared = u.time; + while u.time < appeared + 0.4 { + u.frame(Vec::new()); + } + assert_eq!(shown(&u, inst, &variants), Some(1), "400 ms after B appeared: still B"); + while u.time < appeared + 0.6 { + u.frame(Vec::new()); + } + assert_eq!(shown(&u, inst, &variants), Some(2), "600 ms after B appeared: C"); +} + +#[test] +fn a_single_after_delay_still_fires_once() { + let mut s = Session::new(); + let a = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 400, "name": "A"}))); + let b = id(&ex(&mut s, "frame.create", json!({"x": 400, "y": 0, "width": 300, "height": 400, "name": "B"}))); + let it = json!({"id": a, "trigger": {"type": "afterDelay", "ms": 100}, "action": {"type": "navigate", "dest": b}, "transition": {"type": "instant"}, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", it); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": a})); + u.frames(3, Vec::new); + let name = |u: &Harness| u.app.inspect()["presenter"]["name"].as_str().unwrap_or_default().to_string(); + assert_eq!(name(&u), "A", "not before the delay"); + u.frames(30, Vec::new); + assert_eq!(name(&u), "B", "once the delay is over"); + u.frames(60, Vec::new); + assert_eq!(name(&u), "B", "and not again"); +} diff --git a/crates/ui-egui/src/present/navigate.rs b/crates/ui-egui/src/present/navigate.rs index b5ae19cec..676a32f03 100644 --- a/crates/ui-egui/src/present/navigate.rs +++ b/crates/ui-egui/src/present/navigate.rs @@ -170,6 +170,7 @@ impl Presenter { } self.arrived = now; self.delays_fired.clear(); + self.swapped.clear(); self.waiting.clear(); self.hovered.clear(); self.rev += 1; @@ -245,7 +246,9 @@ pub(crate) fn next_delay(p: &Presenter, doc: &Document, root: NodeId, now: f64) if let Trigger::AfterDelay { ms } = it.trigger && !p.delays_fired.contains(&(id, k)) { - let due = since + f64::from(ms) / 1000.0 - now; + // Inside an instance that changed variant, the timer starts when it did. + let from = p.swapped.iter().filter(|(inst, _)| doc.is_ancestor(**inst, id)).fold(since, |a, (_, t)| a.max(*t)); + let due = from + f64::from(ms) / 1000.0 - now; if next.is_none_or(|(_, d)| due < d) { next = Some(((id, k), due)); } diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 6ca217eec..d9f5d51b0 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -39,7 +39,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Key/gamepad on a controller: the trigger takes a controller button in place of a key, pressed anywhere on the screen | **added** | `Gamepad A` … `Gamepad Home` (the standard layout's 17 buttons, face buttons by position) as the trigger's key, picked from the Controller menu beside the key field; the player polls controllers only while the prototype has such a trigger and the window has the focus, and plays each press once (held buttons don't repeat); Windows reads Xbox-compatible controllers, the browser its Gamepad API's standard-mapped ones; `controller_buttons_fire_key_gamepad_triggers`, `controller_buttons_play_key_gamepad_triggers` | | A controller button is not the keyboard key of the same name; the d-pad is not the arrow keys; a keyboard modifier held makes a button press another input | silent | pinned as stated | | REST files: controller triggers (`device` other than `KEYBOARD`) | **added** | they were skipped; their code reads as the standard layout's button index (silent: the schema doesn't say what the codes count); two buttons at once or an unknown code is skipped with a warning; `controller_triggers_import_as_their_button` | -| After delay: timed from when the screen shows | pass | `triggers_fire_on_their_gesture` | +| After delay: timed from when the screen shows; a chain of variant changes on After delay plays to the end, each step's delay counted from when its variant appears (#2352) | pass | `triggers_fire_on_their_gesture`, `a_chain_of_variant_after_delays_plays_to_the_end` | | After delay on an overlay: timed from when the overlay opens, again each time it opens | **fixed** | timed from when the screen under it arrived (a toast opened late closed at once) and fired only the first time; `an_overlays_after_delay_counts_from_when_it_opens` | | Nested layers with the same trigger: the top-most layer's interaction wins; a layer without that trigger lets it through to the one under it | pass | `nested_hotspots_and_click_through`, `hotspots_priority_and_click_through` | | A layer without interactions over a hotspot | silent | it doesn't block it: clicks reach the hotspot under it | @@ -108,6 +108,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-14 | patch | M5, #2352: a chain of variant changes on After delay plays to the end (A to B to C to D); before, the step a variant had fired stayed marked as fired when the instance changed variant, so the chain stopped after one step, and now each step's delay counts from when its variant appears (`crates/ui-egui/src/present/afterdelay_chain_tests.rs`). Numbers unchanged | | 2026-11-09 | patch | M7, #2158: a connection dragged from a variant (or a layer in it) onto a sibling variant of its set did nothing, because the drop looked only for top-level frames and a variant's top-level frame is its set. It now creates Change to the sibling (On click, Instant, as measured in Figma's web app) and outlines the sibling while dragging; the set's background and the variant itself still add nothing, and a frame outside the set still gets Navigate to | | 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` | | 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. | From c59dc0fdcbab6b1659495c13ed351847d3bccf30 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 00:41:10 -0500 Subject: [PATCH 032/129] M3: the Local variables window resizes from its edges and corners (#2354) The window was fixed at 880 x 480. It now resizes from every edge and corner, down to 480 x 240 and up to the screen less a margin, and its header, sidebar and table follow its current size. Egui's memory keeps the size and place while the app runs. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/dialogs/variables_panel.rs | 16 +++- crates/ui-egui/src/lib.rs | 2 + .../src/variables_window_resize_tests.rs | 89 +++++++++++++++++++ docs/components-parity.md | 3 +- 4 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/variables_window_resize_tests.rs diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index 067d54ea9..f4eff6639 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -239,6 +239,14 @@ impl<'a> View<'a> { } } +/// The smallest the window can be dragged to. +const MIN_SIZE: egui::Vec2 = vec2(480.0, 240.0); + +/// The largest the window can be dragged to: the screen less a margin. +fn max_size(screen: Rect) -> egui::Vec2 { + (screen.size() - vec2(16.0, 16.0)).max(MIN_SIZE) +} + /// Show the editor while it's open (call once per frame). pub fn show(app: &mut FigApp, ctx: &Context) { let Some(mut st) = app.ui.variables.take() else { return }; @@ -267,12 +275,16 @@ pub fn show(app: &mut FigApp, ctx: &Context) { .id(Id::unique("variables_window")) .title_bar(false) .collapsible(false) - .resizable(false) - .fixed_size(size) + .resizable(true) + .default_size(size) + .min_size(MIN_SIZE) + .max_size(max_size(screen)) .pivot(Align2::CENTER_CENTER) .default_pos(screen.center()) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(0))) .show(ctx, |ui| { + // The window's current size (its default until the user drags an edge or corner). + let size = ui.available_size().max(MIN_SIZE); ui.set_min_size(size); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); header(app, ui, &mut open); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4a0b38768..bfb2ab216 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -294,6 +294,8 @@ mod variables_rename_tests; #[cfg(test)] mod variables_select_tests; #[cfg(test)] +mod variables_window_resize_tests; +#[cfg(test)] mod variants_discovery_tests; #[cfg(test)] mod vector_keys_tests; diff --git a/crates/ui-egui/src/variables_window_resize_tests.rs b/crates/ui-egui/src/variables_window_resize_tests.rs new file mode 100644 index 000000000..67ed7faa9 --- /dev/null +++ b/crates/ui-egui/src/variables_window_resize_tests.rs @@ -0,0 +1,89 @@ +//! The Local variables window resizes from its edges and corners, height as well as width, stops at +//! a minimum size, and keeps its size when it is closed and opened again (#2354). + +use egui::{Event, Id, Pos2, Rect, vec2}; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; +use crate::live_tests::{flat, texts}; + +const COUNT: usize = 60; + +/// The window open on a collection of many number variables. +fn window() -> Ui { + let mut s = Session::new(); + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + for k in 0..COUNT { + s.execute("variable.create", &json!({"collection": "Theme", "name": format!("v{k:02}"), "type": "number", "value": 1})).unwrap(); + } + let mut u = Ui::new(s); + u.app.ui.variables = Some(Default::default()); + for _ in 0..10 { + u.frame(vec![]); + } + u +} + +fn rect(u: &Ui) -> Rect { + u.ctx.memory(|m| m.area_rect(Id::unique("variables_window"))).expect("the variables window has an area") +} + +/// How many variable rows are drawn inside the window (the table clips the rest). +fn rows(u: &mut Ui) -> usize { + let window = rect(u); + let shapes = flat(&u.frame_output(vec![]).shapes); + texts(&shapes).iter().filter(|(t, p, _)| t.len() == 3 && t.starts_with('v') && window.contains(*p)).count() +} + +/// Drag the bottom-right corner by `by` and let go. +fn drag_corner(u: &mut Ui, by: egui::Vec2) { + let from = rect(u).right_bottom(); + u.drag_to(from, from + by); + let to: Pos2 = from + by; + u.frame(vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }]); + for _ in 0..5 { + u.frame(vec![]); + } +} + +#[test] +fn the_variables_window_grows_when_dragged_taller() { + let mut u = window(); + let before = rect(&u); + let rows_before = rows(&mut u); + drag_corner(&mut u, vec2(0.0, 200.0)); + let after = rect(&u); + assert!((after.height() - before.height() - 200.0).abs() < 2.0, "height {} -> {}", before.height(), after.height()); + let rows_after = rows(&mut u); + assert!(rows_after > rows_before, "the table shows more rows: {rows_before} -> {rows_after}"); +} + +#[test] +fn the_variables_window_keeps_a_minimum_size() { + let mut u = window(); + drag_corner(&mut u, vec2(-2000.0, -2000.0)); + let r = rect(&u); + assert!((r.width() - 480.0).abs() < 3.0, "width {}", r.width()); + assert!((r.height() - 240.0).abs() < 3.0, "height {}", r.height()); +} + +#[test] +fn a_resized_variables_window_keeps_its_size_when_reopened() { + let mut u = window(); + drag_corner(&mut u, vec2(0.0, 150.0)); + let resized = rect(&u); + let close = resized.right_top() + vec2(-22.0, 22.0); + u.button(close, true); + u.button(close, false); + for _ in 0..5 { + u.frame(vec![]); + } + assert!(u.app.ui.variables.is_none(), "the Close button closed the window"); + u.app.ui.variables = Some(Default::default()); + for _ in 0..10 { + u.frame(vec![]); + } + let again = rect(&u); + assert!((again.width() - resized.width()).abs() < 1.0 && (again.height() - resized.height()).abs() < 1.0, "{resized:?} -> {again:?}"); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 3d23800b0..3420f1bcf 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -66,7 +66,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Editing a style updates its layers; detach and delete keep values; editing a styled property unlinks that style | done | an edited fill/stroke/effect/grid list or text chars unlink; applying a style replaces variables bound to what it sets; text styles on text layers only | | Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) | | Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style (a face name from a string variable, or a numeric weight from a number variable, which picks the nearest face and a variable font's `wght` axis), size, line height and letter spacing, the rest through the command; a bound line height is applied in pixels, as the reference tool does (measured 2026-11-10) | -| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step) | +| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); the window resizes from its edges and corners (minimum 480 x 240) and keeps its size and place while the app runs, #2354 | | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | | Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values | @@ -81,6 +81,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 480 x 240), and keeps its size and place while the app runs. | | 2026-11-07 | minor | M3, #2084: a group's context menu in the Local variables window has Duplicate group (after Rename group, before Delete group). It adds a group named after the original plus " 2" (the next free number when taken: " 3"), whose variables are copies of the originals with the same leaf names, values in every mode, description, scopes, hidden-from-publishing and code syntax, each sent as `variable.duplicate` plus a rename in one `command.batch` labelled Duplicate group, so one undo step. Measured in the incumbent with one mode; an alias to a variable of the same group keeps pointing at the original. Ungroup is not built. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-12 | minor | M7, #2215: pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215). The same section the frames' Variable modes use (`variable.setMode` without layers sets the page's mode), one undo step per pick. Binding the page background to a variable is not in the reference and is not offered | From d3f275fa709ffd6e454e41fd66a16c1b2675bb1b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 01:48:54 -0500 Subject: [PATCH 033/129] M5: a temporary variant change that reverts keeps the After delay deadline (#2352) The swap times now travel with the while-hovering / while-pressing snapshot, so reverting a hover's variant change restores them and the variant shown again fires on its own deadline. Test a_hover_variant_that_reverts_keeps_the_after_delay_deadline (red before: left Some(0), right Some(2) at 1.3 s); present 102 passed, clippy clean (CodeRabbit on #2362). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/present.rs | 3 ++ .../src/present/afterdelay_chain_tests.rs | 53 +++++++++++++++++++ crates/ui-egui/src/present/navigate.rs | 2 + 3 files changed, 58 insertions(+) diff --git a/crates/ui-egui/src/present.rs b/crates/ui-egui/src/present.rs index 8f8570342..6ac376fb1 100644 --- a/crates/ui-egui/src/present.rs +++ b/crates/ui-egui/src/present.rs @@ -248,6 +248,9 @@ struct Snapshot { overlays: Vec, history: Vec, scroll: HashMap, + /// When each instance last changed variant: a temporary change that reverts restores it, so + /// the variant shown again keeps its After delay deadline. + swapped: HashMap, } /// A "while hovering / while pressing" state that reverts when the pointer leaves / lifts. diff --git a/crates/ui-egui/src/present/afterdelay_chain_tests.rs b/crates/ui-egui/src/present/afterdelay_chain_tests.rs index e8a5551f1..945f0f57a 100644 --- a/crates/ui-egui/src/present/afterdelay_chain_tests.rs +++ b/crates/ui-egui/src/present/afterdelay_chain_tests.rs @@ -79,6 +79,59 @@ fn each_step_waits_its_own_delay_from_when_its_variant_appeared() { assert_eq!(shown(&u, inst, &variants), Some(2), "600 ms after B appeared: C"); } +/// A hover that changes the variant and reverts leaves the variant shown again on its own After +/// delay deadline (counted from the screen's arrival), not from the hover. +#[test] +fn a_hover_variant_that_reverts_keeps_the_after_delay_deadline() { + let mut s = Session::new(); + let variants: Vec = ["A", "Hover", "Next"] + .iter() + .enumerate() + .map(|(k, state)| { + let f = id(&ex( + &mut s, + "frame.create", + json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}), + )); + id(&ex(&mut s, "component.create", json!({"ids": [f]}))) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let instant = json!({"type": "instant"}); + let delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 1000}, "action": {"type": "changeTo", "dest": variants[2]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", delay); + let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", hover); + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + u.frame(Vec::new()); + let start = u.time; + let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default(); + let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}")); + let r: Vec = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect(); + let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0)); + while u.time < start + 0.8 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + u.frame(vec![egui::Event::PointerMoved(on)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant"); + while u.time < start + 0.9 { + u.frame(vec![egui::Event::PointerMoved(on)]); + } + u.frame(vec![egui::Event::PointerMoved(away)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again"); + while u.time < start + 1.3 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + assert_eq!(shown(&u, inst, &variants), Some(2), "A's 1,000 ms delay from the arrival fired, not 1,000 ms after the hover"); +} + #[test] fn a_single_after_delay_still_fires_once() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/present/navigate.rs b/crates/ui-egui/src/present/navigate.rs index 676a32f03..b76ac8844 100644 --- a/crates/ui-egui/src/present/navigate.rs +++ b/crates/ui-egui/src/present/navigate.rs @@ -150,6 +150,7 @@ impl Presenter { overlays: self.overlays.clone(), history: self.history.clone(), scroll: self.scroll.clone(), + swapped: self.swapped.clone(), }) } @@ -228,6 +229,7 @@ impl Presenter { self.overlays = t.snap.overlays; self.history = t.snap.history; self.scroll = t.snap.scroll; + self.swapped = t.snap.swapped; self.stop_scrolling(); self.hovered.clear(); self.rev += 1; From 4b9e900f89f99f8086c967776b3d9c2a364d00d4 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 02:49:35 -0500 Subject: [PATCH 034/129] M3: the Local variables window's minimum width fits the table's header row (#2354) At 480 points the table was 279 wide, leaving 11 points next to the 220-point search field for a library collection's Extend collection button. The minimum is now 600 x 240 (table 399 wide); the default size's clamp uses the same minimum. variables 43 passed, clippy clean (CodeRabbit on #2363). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/variables_panel.rs | 7 ++++--- crates/ui-egui/src/variables_window_resize_tests.rs | 2 +- docs/components-parity.md | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index f4eff6639..4e3b1e541 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -239,8 +239,9 @@ impl<'a> View<'a> { } } -/// The smallest the window can be dragged to. -const MIN_SIZE: egui::Vec2 = vec2(480.0, 240.0); +/// The smallest the window can be dragged to: wide enough that the table's header row holds the +/// search field and a library collection's "Extend collection" button side by side. +const MIN_SIZE: egui::Vec2 = vec2(600.0, 240.0); /// The largest the window can be dragged to: the screen less a margin. fn max_size(screen: Rect) -> egui::Vec2 { @@ -269,7 +270,7 @@ pub fn show(app: &mut FigApp, ctx: &Context) { st.collection = coll.map(|c| c.id.clone()); let t = Tokens::get(ctx); let screen = ctx.content_rect(); - let size = vec2(880.0_f32.min(screen.width() - 80.0).max(480.0), 480.0_f32.min(screen.height() - 120.0).max(240.0)); + let size = vec2(880.0_f32.min(screen.width() - 80.0).max(MIN_SIZE.x), 480.0_f32.min(screen.height() - 120.0).max(MIN_SIZE.y)); let mut open = true; egui::Window::new(tr("Local variables")) .id(Id::unique("variables_window")) diff --git a/crates/ui-egui/src/variables_window_resize_tests.rs b/crates/ui-egui/src/variables_window_resize_tests.rs index 67ed7faa9..b08d2ace1 100644 --- a/crates/ui-egui/src/variables_window_resize_tests.rs +++ b/crates/ui-egui/src/variables_window_resize_tests.rs @@ -64,7 +64,7 @@ fn the_variables_window_keeps_a_minimum_size() { let mut u = window(); drag_corner(&mut u, vec2(-2000.0, -2000.0)); let r = rect(&u); - assert!((r.width() - 480.0).abs() < 3.0, "width {}", r.width()); + assert!((r.width() - 600.0).abs() < 3.0, "width {}", r.width()); assert!((r.height() - 240.0).abs() < 3.0, "height {}", r.height()); } diff --git a/docs/components-parity.md b/docs/components-parity.md index 3420f1bcf..e910c511a 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -66,7 +66,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Editing a style updates its layers; detach and delete keep values; editing a styled property unlinks that style | done | an edited fill/stroke/effect/grid list or text chars unlink; applying a style replaces variables bound to what it sets; text styles on text layers only | | Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) | | Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style (a face name from a string variable, or a numeric weight from a number variable, which picks the nearest face and a variable font's `wght` axis), size, line height and letter spacing, the rest through the command; a bound line height is applied in pixels, as the reference tool does (measured 2026-11-10) | -| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); the window resizes from its edges and corners (minimum 480 x 240) and keeps its size and place while the app runs, #2354 | +| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 | | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | | Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values | @@ -81,7 +81,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| -| 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 480 x 240), and keeps its size and place while the app runs. | +| 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. | | 2026-11-07 | minor | M3, #2084: a group's context menu in the Local variables window has Duplicate group (after Rename group, before Delete group). It adds a group named after the original plus " 2" (the next free number when taken: " 3"), whose variables are copies of the originals with the same leaf names, values in every mode, description, scopes, hidden-from-publishing and code syntax, each sent as `variable.duplicate` plus a rename in one `command.batch` labelled Duplicate group, so one undo step. Measured in the incumbent with one mode; an alias to a variable of the same group keeps pointing at the original. Ungroup is not built. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-12 | minor | M7, #2215: pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215). The same section the frames' Variable modes use (`variable.setMode` without layers sets the page's mode), one undo step per pick. Binding the page background to a variable is not in the reference and is not offered | From 24c2988bd5f4cc5492c46bd9796acd9e68cdb9cb Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 02:59:37 -0500 Subject: [PATCH 035/129] M5: a reverted hover keeps the delays that ran; an edit drops the swap times (#2352) The while-hovering / while-pressing snapshot also keeps the fired After delays, and the revert puts back the ones the temporary variant change cleared (keeping any that fired during it), so a delay that already ran on the variant doesn't run again. When an edit in the editor replaces the presented document, the run-time swap times are cleared with the rest of that state. Tests: a_hover_variant_that_reverts_does_not_rerun_a_fired_delay (red before: count left 2, right 1) and an_edit_while_presenting_drops_the_swap_times (red before: left Some(0), right Some(1)); present 104 passed, clippy clean (CodeRabbit on #2362). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/present.rs | 3 + .../src/present/afterdelay_chain_tests.rs | 83 +++++++++++++++++++ crates/ui-egui/src/present/navigate.rs | 5 ++ 3 files changed, 91 insertions(+) diff --git a/crates/ui-egui/src/present.rs b/crates/ui-egui/src/present.rs index 6ac376fb1..f7af47c5f 100644 --- a/crates/ui-egui/src/present.rs +++ b/crates/ui-egui/src/present.rs @@ -251,6 +251,9 @@ struct Snapshot { /// When each instance last changed variant: a temporary change that reverts restores it, so /// the variant shown again keeps its After delay deadline. swapped: HashMap, + /// The After delays that had fired: a temporary variant change clears the swapped instance's, + /// and the revert puts them back so a delay that already ran doesn't run again. + delays_fired: HashSet<(NodeId, usize)>, } /// A "while hovering / while pressing" state that reverts when the pointer leaves / lifts. diff --git a/crates/ui-egui/src/present/afterdelay_chain_tests.rs b/crates/ui-egui/src/present/afterdelay_chain_tests.rs index 945f0f57a..e407e7322 100644 --- a/crates/ui-egui/src/present/afterdelay_chain_tests.rs +++ b/crates/ui-egui/src/present/afterdelay_chain_tests.rs @@ -132,6 +132,89 @@ fn a_hover_variant_that_reverts_keeps_the_after_delay_deadline() { assert_eq!(shown(&u, inst, &variants), Some(2), "A's 1,000 ms delay from the arrival fired, not 1,000 ms after the hover"); } +/// A delay that already ran on a variant stays run after a hover changes the variant and reverts: +/// the keys the temporary change cleared come back with the revert. +#[test] +fn a_hover_variant_that_reverts_does_not_rerun_a_fired_delay() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]})); + ex(&mut s, "variable.create", json!({"collection": "Run", "name": "count", "type": "number", "value": 0})); + let count = s.doc().unwrap().variables.get("count").map(|v| v.id.clone()).unwrap(); + let variants: Vec = ["A", "Hover"] + .iter() + .enumerate() + .map(|(k, state)| { + let f = id(&ex( + &mut s, + "frame.create", + json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}), + )); + id(&ex(&mut s, "component.create", json!({"ids": [f]}))) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let instant = json!({"type": "instant"}); + // A's delay leaves A on screen: it counts its runs (count = count + 1). + let inc = json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": count}}, {"value": {"type": "number", "value": 1}}]}}); + let delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 100}, "action": {"type": "setVariable", "variable": count, "value": null, "expr": inc}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", delay); + let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", hover); + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + u.frame(Vec::new()); + let start = u.time; + let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default(); + let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}")); + let r: Vec = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect(); + let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0)); + while u.time < start + 0.3 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + let fired: Vec<(NodeId, usize)> = crate::tabs::shown_or_paused(&u.app).map(|p| p.delays_fired.iter().copied().collect()).unwrap_or_default(); + assert!(!fired.is_empty(), "A's delay ran before the hover"); + u.frame(vec![egui::Event::PointerMoved(on)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant"); + u.frame(vec![egui::Event::PointerMoved(away)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again"); + u.frames(5, Vec::new); + let p = crate::tabs::shown_or_paused(&u.app).expect("presenting"); + assert!(fired.iter().all(|k| p.delays_fired.contains(k)), "the delay that ran before the hover is still marked as run: {:?}", p.delays_fired); + let runs = p.design.as_ref().and_then(|d| d.variables.resolve(&count, &Default::default())); + assert_eq!(runs, Some(figcraft_doc::VariableValue::Number(1.0)), "A's delay ran once, not again after the hover"); +} + +/// An edit in the editor while presenting brings back the editor's variants, so the swap times of +/// the variants changed at run time no longer delay them. +#[test] +fn an_edit_while_presenting_drops_the_swap_times() { + let (mut u, inst, variants) = chain(500); + let start = u.time; + let mut guard = 0; + while shown(&u, inst, &variants) != Some(1) { + u.frame(Vec::new()); + guard += 1; + assert!(guard < 120, "A never changed to B"); + } + // An edit: the presenter shows the editor's document again, the instance on A. + u.run("page.rename", json!({"name": "Renamed"})); + u.frame(Vec::new()); + let edited = u.time; + // A's 500 ms delay counts from the screen's arrival, long past: it fires at once, not 500 ms + // after the run-time change to B. + while u.time < edited + 0.2 { + u.frame(Vec::new()); + } + assert!(edited < start + 0.9, "the edit came before B's own delay was due"); + assert_eq!(shown(&u, inst, &variants), Some(1), "A changed to B again right after the edit"); +} + #[test] fn a_single_after_delay_still_fires_once() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/present/navigate.rs b/crates/ui-egui/src/present/navigate.rs index b76ac8844..de4439c24 100644 --- a/crates/ui-egui/src/present/navigate.rs +++ b/crates/ui-egui/src/present/navigate.rs @@ -42,6 +42,8 @@ impl Presenter { self.closing.retain(|(_, o)| doc.contains(o.id)); // These hold states of the document before the edit. self.temp = None; + // The edit's variants replace the runtime ones: their swap times no longer apply. + self.swapped.clear(); self.anim = None; self.scroll_anim = None; self.stop_scrolling(); @@ -151,6 +153,7 @@ impl Presenter { history: self.history.clone(), scroll: self.scroll.clone(), swapped: self.swapped.clone(), + delays_fired: self.delays_fired.clone(), }) } @@ -230,6 +233,8 @@ impl Presenter { self.history = t.snap.history; self.scroll = t.snap.scroll; self.swapped = t.snap.swapped; + // Put back the delays the temporary variant change cleared; keep the ones that fired since. + self.delays_fired.extend(t.snap.delays_fired); self.stop_scrolling(); self.hovered.clear(); self.rev += 1; From 5a482af812cbab55c01cbc440cbf627903aaa3e1 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 03:38:02 -0500 Subject: [PATCH 036/129] M3: the Local variables window fits a narrow screen and resizes from a fixed corner (#2354) The minimum (600 x 240) is capped at the screen less its margin, so on a screen narrower than that the window stays inside it. The window is pinned at its top-left corner and opens centred, so dragging one edge leaves the opposite one in place (the centre pivot moved both). Tests on_a_narrow_screen_the_variables_window_fits_inside_it (red before: the window ran from x -26 to 576 on a 550-wide screen) and the top-edge check in the_variables_window_grows_when_dragged_taller (red before: 210 -> 190); variables 44 passed, clippy clean (CodeRabbit on #2363). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/variables_panel.rs | 23 +++++++++++-------- .../src/variables_window_resize_tests.rs | 17 ++++++++++++++ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index 4e3b1e541..d018e7f2f 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -243,9 +243,11 @@ impl<'a> View<'a> { /// search field and a library collection's "Extend collection" button side by side. const MIN_SIZE: egui::Vec2 = vec2(600.0, 240.0); -/// The largest the window can be dragged to: the screen less a margin. -fn max_size(screen: Rect) -> egui::Vec2 { - (screen.size() - vec2(16.0, 16.0)).max(MIN_SIZE) +/// The smallest and largest the window can be: at most the screen less a margin, and at least +/// [`MIN_SIZE`] unless the screen is smaller than that (then the screen less the margin). +fn limits(screen: Rect) -> (egui::Vec2, egui::Vec2) { + let max = (screen.size() - vec2(16.0, 16.0)).max(vec2(1.0, 1.0)); + (MIN_SIZE.min(max), max) } /// Show the editor while it's open (call once per frame). @@ -270,7 +272,8 @@ pub fn show(app: &mut FigApp, ctx: &Context) { st.collection = coll.map(|c| c.id.clone()); let t = Tokens::get(ctx); let screen = ctx.content_rect(); - let size = vec2(880.0_f32.min(screen.width() - 80.0).max(MIN_SIZE.x), 480.0_f32.min(screen.height() - 120.0).max(MIN_SIZE.y)); + let (min, max) = limits(screen); + let size = vec2(880.0_f32.min(screen.width() - 80.0), 480.0_f32.min(screen.height() - 120.0)).clamp(min, max); let mut open = true; egui::Window::new(tr("Local variables")) .id(Id::unique("variables_window")) @@ -278,14 +281,16 @@ pub fn show(app: &mut FigApp, ctx: &Context) { .collapsible(false) .resizable(true) .default_size(size) - .min_size(MIN_SIZE) - .max_size(max_size(screen)) - .pivot(Align2::CENTER_CENTER) - .default_pos(screen.center()) + .min_size(min) + .max_size(max) + // Pinned at its top-left corner, so dragging one edge leaves the opposite one in place; + // it opens centred. + .pivot(Align2::LEFT_TOP) + .default_pos((screen.center() - size / 2.0).max(screen.min)) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(0))) .show(ctx, |ui| { // The window's current size (its default until the user drags an edge or corner). - let size = ui.available_size().max(MIN_SIZE); + let size = ui.available_size().max(min); ui.set_min_size(size); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); header(app, ui, &mut open); diff --git a/crates/ui-egui/src/variables_window_resize_tests.rs b/crates/ui-egui/src/variables_window_resize_tests.rs index b08d2ace1..e2dedae75 100644 --- a/crates/ui-egui/src/variables_window_resize_tests.rs +++ b/crates/ui-egui/src/variables_window_resize_tests.rs @@ -55,10 +55,27 @@ fn the_variables_window_grows_when_dragged_taller() { drag_corner(&mut u, vec2(0.0, 200.0)); let after = rect(&u); assert!((after.height() - before.height() - 200.0).abs() < 2.0, "height {} -> {}", before.height(), after.height()); + assert!((after.min.y - before.min.y).abs() < 2.0, "the top edge stays where it was: {} -> {}", before.min.y, after.min.y); let rows_after = rows(&mut u); assert!(rows_after > rows_before, "the table shows more rows: {rows_before} -> {rows_after}"); } +#[test] +fn on_a_narrow_screen_the_variables_window_fits_inside_it() { + // Narrower than the minimum (600): the window takes the screen less its margin instead. + let mut s = Session::new(); + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + let mut u = Ui::new(s); + u.screen = vec2(550.0, 700.0); + u.app.ui.variables = Some(Default::default()); + for _ in 0..10 { + u.frame(vec![]); + } + let r = rect(&u); + let screen = Rect::from_min_size(Pos2::ZERO, u.screen); + assert!(screen.contains_rect(r), "the window {r:?} is inside the screen {screen:?}"); +} + #[test] fn the_variables_window_keeps_a_minimum_size() { let mut u = window(); From 3a8313aba72992e0527eb8815d8e7dea69d897b9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 03:40:07 -0500 Subject: [PATCH 037/129] M5: a delay fired on a hover variant doesn't block the restored variant's delay (#2352) A fired-delay key is (node, index), and inside an instance the index belongs to the variant shown. On revert, keys that fired during the temporary change inside an instance it changed the variant of are dropped (they name the hover variant's interactions); the snapshot's keys come back and the other new ones stay. Test a_delay_fired_on_a_hover_variant_does_not_block_the_restored_variants_delay (red before: A's runs left 0, right 1); present 105 passed, clippy clean (CodeRabbit on #2362). Co-Authored-By: Claude Opus 5.5 --- .../src/present/afterdelay_chain_tests.rs | 64 +++++++++++++++++++ crates/ui-egui/src/present/navigate.rs | 11 +++- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/present/afterdelay_chain_tests.rs b/crates/ui-egui/src/present/afterdelay_chain_tests.rs index e407e7322..e07976f28 100644 --- a/crates/ui-egui/src/present/afterdelay_chain_tests.rs +++ b/crates/ui-egui/src/present/afterdelay_chain_tests.rs @@ -190,6 +190,70 @@ fn a_hover_variant_that_reverts_does_not_rerun_a_fired_delay() { assert_eq!(runs, Some(figcraft_doc::VariableValue::Number(1.0)), "A's delay ran once, not again after the hover"); } +/// A delay that fires on the hover variant names that variant's interaction: after the revert it +/// doesn't count as A's delay at the same index, which still runs on its own deadline. +#[test] +fn a_delay_fired_on_a_hover_variant_does_not_block_the_restored_variants_delay() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]})); + ex(&mut s, "variable.create", json!({"collection": "Run", "name": "a_runs", "type": "number", "value": 0})); + ex(&mut s, "variable.create", json!({"collection": "Run", "name": "hover_runs", "type": "number", "value": 0})); + let var = |s: &Session, name: &str| s.doc().unwrap().variables.get(name).map(|v| v.id.clone()).unwrap(); + let (a_runs, hover_runs) = (var(&s, "a_runs"), var(&s, "hover_runs")); + let inc = |v: &str| json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": v}}, {"value": {"type": "number", "value": 1}}]}}); + let variants: Vec = ["A", "Hover"] + .iter() + .enumerate() + .map(|(k, state)| { + let f = id(&ex( + &mut s, + "frame.create", + json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}), + )); + id(&ex(&mut s, "component.create", json!({"ids": [f]}))) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let instant = json!({"type": "instant"}); + // A: index 0 a 1,000 ms delay counting its runs, index 1 the hover. Hover: index 0 a delay due at once. + let a_delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 1000}, "action": {"type": "setVariable", "variable": a_runs, "value": null, "expr": inc(&a_runs)}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", a_delay); + let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", hover); + let h_delay = json!({"id": variants[1], "trigger": {"type": "afterDelay", "ms": 0}, "action": {"type": "setVariable", "variable": hover_runs, "value": null, "expr": inc(&hover_runs)}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", h_delay); + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + u.frame(Vec::new()); + let start = u.time; + let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default(); + let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}")); + let r: Vec = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect(); + let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0)); + let value = |u: &Harness, v: &str| { + crate::tabs::shown_or_paused(&u.app).and_then(|p| p.design.as_ref().and_then(|d| d.variables.resolve(v, &Default::default()))) + }; + while u.time < start + 0.2 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + while u.time < start + 0.4 { + u.frame(vec![egui::Event::PointerMoved(on)]); + } + assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant"); + assert_eq!(value(&u, &hover_runs), Some(figcraft_doc::VariableValue::Number(1.0)), "the hover variant's delay ran"); + u.frame(vec![egui::Event::PointerMoved(away)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again"); + while u.time < start + 1.3 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + assert_eq!(value(&u, &a_runs), Some(figcraft_doc::VariableValue::Number(1.0)), "A's own delay at index 0 ran on its deadline"); +} + /// An edit in the editor while presenting brings back the editor's variants, so the swap times of /// the variants changed at run time no longer delay them. #[test] diff --git a/crates/ui-egui/src/present/navigate.rs b/crates/ui-egui/src/present/navigate.rs index de4439c24..dbfd32506 100644 --- a/crates/ui-egui/src/present/navigate.rs +++ b/crates/ui-egui/src/present/navigate.rs @@ -225,6 +225,14 @@ impl Presenter { pub(super) fn revert(&mut self, now: f64) { let Some(t) = self.temp.take() else { return }; + // The delays fired during the temporary change: inside an instance it changed the variant + // of, a key names the temporary variant's interaction, not the restored one's, so drop it; + // keep the others, and put back the ones the change cleared. + let changed: Vec = self.swapped.iter().filter(|(i, at)| t.snap.swapped.get(*i) != Some(*at)).map(|(i, _)| *i).collect(); + let restored = &t.snap.doc; + let during: Vec<(NodeId, usize)> = self.delays_fired.difference(&t.snap.delays_fired).copied().collect(); + let mut fired = t.snap.delays_fired.clone(); + fired.extend(during.into_iter().filter(|(id, _)| !changed.iter().any(|i| i == id || restored.is_ancestor(*i, *id)))); self.begin(t.transition.reversed(), t.dur, t.easing, now); self.current = t.snap.current; self.design = Some(t.snap.doc); @@ -233,8 +241,7 @@ impl Presenter { self.history = t.snap.history; self.scroll = t.snap.scroll; self.swapped = t.snap.swapped; - // Put back the delays the temporary variant change cleared; keep the ones that fired since. - self.delays_fired.extend(t.snap.delays_fired); + self.delays_fired = fired; self.stop_scrolling(); self.hovered.clear(); self.rev += 1; From 29fe911dd937cb963b4d144606f06bda280318f3 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 04:37:56 -0500 Subject: [PATCH 038/129] M3: on a short screen the Local variables window's body takes what is left (#2354) The body below the header had a 160-point floor, so with the minimum capped by a screen lower than 220 points the content ran past the window. It now takes the height left below the header (the table scrolls). Test on_a_short_screen_the_variables_window_fits_inside_it (red before: the window ran to y 206 on a 180-high screen); variables 45 passed, clippy clean (CodeRabbit on #2363). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/variables_panel.rs | 3 ++- .../src/variables_window_resize_tests.rs | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index d018e7f2f..233181fb7 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -294,7 +294,8 @@ pub fn show(app: &mut FigApp, ctx: &Context) { ui.set_min_size(size); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); header(app, ui, &mut open); - let h = (size.y - 44.0).max(160.0); + // The body below the 44-point header: what is left of the window (the table scrolls). + let h = (size.y - 44.0).max(0.0); let top_down = egui::Layout::top_down(egui::Align::Min); ui.horizontal_top(|ui| { ui.allocate_ui_with_layout(vec2(SIDEBAR_W, h), top_down, |ui| sidebar(app, ui, &views, &doc.variables, &mut st)); diff --git a/crates/ui-egui/src/variables_window_resize_tests.rs b/crates/ui-egui/src/variables_window_resize_tests.rs index e2dedae75..8ec2c4113 100644 --- a/crates/ui-egui/src/variables_window_resize_tests.rs +++ b/crates/ui-egui/src/variables_window_resize_tests.rs @@ -76,6 +76,25 @@ fn on_a_narrow_screen_the_variables_window_fits_inside_it() { assert!(screen.contains_rect(r), "the window {r:?} is inside the screen {screen:?}"); } +#[test] +fn on_a_short_screen_the_variables_window_fits_inside_it() { + // Lower than the minimum (240): the body takes what is left below the header and scrolls. + let mut s = Session::new(); + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + for k in 0..COUNT { + s.execute("variable.create", &json!({"collection": "Theme", "name": format!("v{k:02}"), "type": "number", "value": 1})).unwrap(); + } + let mut u = Ui::new(s); + u.screen = vec2(800.0, 180.0); + u.app.ui.variables = Some(Default::default()); + for _ in 0..10 { + u.frame(vec![]); + } + let r = rect(&u); + let screen = Rect::from_min_size(Pos2::ZERO, u.screen); + assert!(screen.contains_rect(r), "the window {r:?} is inside the screen {screen:?}"); +} + #[test] fn the_variables_window_keeps_a_minimum_size() { let mut u = window(); From 55239a44f1a74ac01b42baa79dc91d70ce14be89 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 04:40:10 -0500 Subject: [PATCH 039/129] M5: a reverted hover leaves no fired key for a layer that is gone (#2352) On revert, fired-delay keys are kept only for layers the restored document has: a layer only the hover variant had is gone again, and its id may be issued anew by the next hover. Test a_hover_variants_own_layer_leaves_no_fired_key_after_the_revert (red before: a key for the missing NodeId(8) stayed); present 106 passed, clippy clean (CodeRabbit on #2362). Co-Authored-By: Claude Opus 5.5 --- .../src/present/afterdelay_chain_tests.rs | 52 +++++++++++++++++++ crates/ui-egui/src/present/navigate.rs | 2 + 2 files changed, 54 insertions(+) diff --git a/crates/ui-egui/src/present/afterdelay_chain_tests.rs b/crates/ui-egui/src/present/afterdelay_chain_tests.rs index e07976f28..af67d1f1a 100644 --- a/crates/ui-egui/src/present/afterdelay_chain_tests.rs +++ b/crates/ui-egui/src/present/afterdelay_chain_tests.rs @@ -254,6 +254,58 @@ fn a_delay_fired_on_a_hover_variant_does_not_block_the_restored_variants_delay() assert_eq!(value(&u, &a_runs), Some(figcraft_doc::VariableValue::Number(1.0)), "A's own delay at index 0 ran on its deadline"); } +/// A layer that only the hover variant has, with its own After delay that ran during the hover, +/// leaves no fired key behind after the revert (its id may be issued again by the next hover). +#[test] +fn a_hover_variants_own_layer_leaves_no_fired_key_after_the_revert() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]})); + ex(&mut s, "variable.create", json!({"collection": "Run", "name": "runs", "type": "number", "value": 0})); + let runs = s.doc().unwrap().variables.get("runs").map(|v| v.id.clone()).unwrap(); + let inc = json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": runs}}, {"value": {"type": "number", "value": 1}}]}}); + let frames: Vec = ["A", "Hover"] + .iter() + .enumerate() + .map(|(k, state)| { + id(&ex(&mut s, "frame.create", json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}))) + }) + .collect(); + // Only the hover state has this layer, with a delay due at once. + let dot = id(&ex(&mut s, "shape.rectangle", json!({"x": 160, "y": 610, "width": 10, "height": 10, "parent": frames[1]}))); + let instant = json!({"type": "instant"}); + let dot_delay = json!({"id": dot, "trigger": {"type": "afterDelay", "ms": 0}, "action": {"type": "setVariable", "variable": runs, "value": null, "expr": inc}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", dot_delay); + let variants: Vec = frames.iter().map(|f| id(&ex(&mut s, "component.create", json!({"ids": [f]})))).collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", hover); + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + u.frame(Vec::new()); + let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default(); + let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}")); + let r: Vec = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect(); + let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0)); + for _ in 0..6 { + u.frame(vec![egui::Event::PointerMoved(on)]); + } + assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant"); + let p = crate::tabs::shown_or_paused(&u.app).expect("presenting"); + let ran = p.design.as_ref().and_then(|d| d.variables.resolve(&runs, &Default::default())); + assert_eq!(ran, Some(figcraft_doc::VariableValue::Number(1.0)), "the hover variant's own layer ran its delay"); + u.frame(vec![egui::Event::PointerMoved(away)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again"); + let p = crate::tabs::shown_or_paused(&u.app).expect("presenting"); + let d = p.design.as_ref().expect("a document"); + let stale: Vec<_> = p.delays_fired.iter().filter(|(id, _)| !d.contains(*id)).collect(); + assert!(stale.is_empty(), "no fired key names a layer the restored document lacks: {stale:?}"); +} + /// An edit in the editor while presenting brings back the editor's variants, so the swap times of /// the variants changed at run time no longer delay them. #[test] diff --git a/crates/ui-egui/src/present/navigate.rs b/crates/ui-egui/src/present/navigate.rs index dbfd32506..a83e3940f 100644 --- a/crates/ui-egui/src/present/navigate.rs +++ b/crates/ui-egui/src/present/navigate.rs @@ -233,6 +233,8 @@ impl Presenter { let during: Vec<(NodeId, usize)> = self.delays_fired.difference(&t.snap.delays_fired).copied().collect(); let mut fired = t.snap.delays_fired.clone(); fired.extend(during.into_iter().filter(|(id, _)| !changed.iter().any(|i| i == id || restored.is_ancestor(*i, *id)))); + // A layer the temporary change added is gone again (and its id may be issued anew). + fired.retain(|(id, _)| restored.contains(*id)); self.begin(t.transition.reversed(), t.dur, t.easing, now); self.current = t.snap.current; self.design = Some(t.snap.doc); From 8133b31c7484d64b196c8b0ba053ff631a84616b Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 14:02:39 +0530 Subject: [PATCH 040/129] Text: embedded Noto Sans JP backs up Japanese runs (#2375) --- crates/text/src/fontdb.rs | 3 ++- crates/text/src/fontdb_tests.rs | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 65df051e7..f5774307e 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -555,7 +555,7 @@ fn names(f: &skrifa::FontRef) -> (Option, Option) { /// document: the browser has no other fonts. The symbol fonts come last: Apple Symbols (macOS), /// Segoe UI Symbol (Windows) and the Noto symbol and math fonts (Linux), for signs such as ⌖ and ⤒ /// that no text face has. -const FALLBACK_FAMILIES: [&str; 32] = [ +const FALLBACK_FAMILIES: [&str; 33] = [ "Inter", "Helvetica Neue", "Arial", @@ -563,6 +563,7 @@ const FALLBACK_FAMILIES: [&str; 32] = [ "DejaVu Sans", "Noto Sans", "BIZ UDPGothic", + "Noto Sans JP", "Hiragino Sans", "PingFang SC", "Hiragino Sans GB", diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index bf459fe06..2585ced73 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -604,6 +604,7 @@ fn every_embeddable_script_face_is_a_document_fallback() { "Noto Sans Hebrew", "Noto Sans Devanagari", "Noto Sans Georgian", + "Noto Sans JP", "Noto Sans Symbols", "Noto Sans Symbols 2", ] { From 2462a86253e4c8838b6c44f2f3469e2962a4ef58 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 17:41:14 +0530 Subject: [PATCH 041/129] Batch: a refused step names its step and keeps its kind (#2181) --- crates/engine/src/batch_step_ref_tests.rs | 57 +++++++++++++++++++++++ crates/engine/src/error.rs | 2 + 2 files changed, 59 insertions(+) diff --git a/crates/engine/src/batch_step_ref_tests.rs b/crates/engine/src/batch_step_ref_tests.rs index 17d9fc725..e50824edb 100644 --- a/crates/engine/src/batch_step_ref_tests.rs +++ b/crates/engine/src/batch_step_ref_tests.rs @@ -652,3 +652,60 @@ fn a_continue_batch_reports_runtime_errors_and_runs_later_steps() { assert_eq!(results[6]["ok"], true); assert_eq!(s.doc().unwrap().node(s.page().unwrap()).unwrap().name, "Done"); } + +#[test] +fn a_refused_step_names_its_step_and_keeps_its_kind() { + let mut s = Session::new(); + let comp = id(&s.execute("node.create", &json!({"type": "component", "name": "Button", "width": 100, "height": 40})).unwrap()); + let inst = id(&s.execute("instance.create", &json!({"component": comp})).unwrap()); + let before = s.doc().unwrap().clone(); + let undo = s.undo_depth(); + let result = s.execute( + "command.batch", + &json!({"commands": [ + {"command": "node.create", "params": {"type": "rectangle", "parent": inst, "width": 10, "height": 10}} + ]}), + ); + match result { + Err(EngineError::Disabled(cmd, msg)) => { + assert_eq!(cmd, "node.create"); + assert!(msg.starts_with("step 0: "), "{msg}"); + assert!(msg.contains("can't be added"), "{msg}"); + } + other => panic!("expected Disabled, got {other:?}"), + } + assert_eq!(s.doc().unwrap(), &before, "the batch rolled back"); + assert_eq!(s.undo_depth(), undo, "no undo step for the refused batch"); + // Outside a batch the same refusal keeps its kind and says no step. + match s.execute("node.create", &json!({"type": "rectangle", "parent": inst, "width": 10, "height": 10})) { + Err(EngineError::Disabled(_, msg)) => assert!(!msg.contains("step "), "{msg}"), + other => panic!("expected Disabled, got {other:?}"), + } +} + +#[test] +fn an_internal_step_says_which_step_without_changing_kind() { + use crate::derived; + let mut s = Session::new(); + let r = id(&s.execute("node.create", &json!({"type": "rectangle", "width": 10, "height": 10})).unwrap()); + let before = s.doc().unwrap().clone(); + derived::PANIC.with(|p| p.set(true)); + let result = s.execute( + "command.batch", + &json!({"commands": [ + {"command": "node.set", "params": {"ids": [r], "props": {"name": "Renamed"}}} + ]}), + ); + derived::PANIC.with(|p| p.set(false)); + match result { + Err(EngineError::Internal { cmd, msg }) => { + assert_eq!(cmd, "node.set"); + assert!(msg.starts_with("step 0: "), "{msg}"); + } + other => panic!("expected Internal, got {other:?}"), + } + assert_eq!(s.doc().unwrap(), &before, "the panicking step is rolled back"); + // Kinds without a message are left as they are. + assert!(matches!(EngineError::NoNode(figcraft_doc::NodeId(7)).at_step(2), EngineError::NoNode(_))); + assert!(matches!(EngineError::Waiting.at_step(2), EngineError::Waiting)); +} diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index e3f4e79e9..52ca4fb1f 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -43,6 +43,8 @@ impl EngineError { match self { EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: format!("step {step}: {msg}") }, EngineError::Other(msg) => EngineError::Other(format!("step {step}: {msg}")), + EngineError::Disabled(cmd, msg) => EngineError::Disabled(cmd, format!("step {step}: {msg}")), + EngineError::Internal { cmd, msg } => EngineError::Internal { cmd, msg: format!("step {step}: {msg}") }, e => e, } } From d4e2641fa03acae5c8023c2b71e79dd4cf4dc159 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:09:48 +0530 Subject: [PATCH 042/129] Automation roots: same_file doesn't open a path outside the roots, native NT link targets and names Windows trims are refused, and the docs say network paths are refused --- crates/engine/src/automation/file_access.rs | 56 ++++++++++++- .../src/automation/file_access/tests.rs | 83 +++++++++++++++++++ docs/mcp.md | 10 ++- 3 files changed, 145 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index 249d3483c..934c62ad9 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -127,6 +127,10 @@ const MAX_LINKS: u8 = 40; /// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute /// is refused as well, rather than left to what comes next. fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option { + // Win32 lookups trim a trailing period or space from a name, but not always from one in the middle of a path: refused as given. + if has_trimmed_name(path) { + return Some(Unresolved::Linked); + } // Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a // bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes // `..` by name, so `link\..\x` is `x` and never goes through the link. @@ -180,6 +184,10 @@ fn nothing_there(e: &std::io::Error) -> bool { /// the way is opened in turn while the path is resolved, and the device behind a name such as /// `LPT1` can be a printer on another computer. fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option { + // A native NT name (`\Device\Mup\server\share`) has no prefix for `std` or `craft_docpath`, yet the system follows it to wherever it names. + if is_native_name(Path::new(p)) { + return Some(Refused::Device); + } match craft_docpath::resolve(p, None) { // With a root passed as the document path (what a link would be relative to), a path on // that root's share is allowed. @@ -199,7 +207,11 @@ fn is_volume(p: &str) -> bool { let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else { return false; }; - volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}') + let bytes = volume.as_bytes(); + bytes.len() == 44 + && volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) + && volume.ends_with('}') + && bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() }) } /// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`] @@ -224,6 +236,11 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) - Entry::Link(target) => target, }; let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true }; + // Judged as written too: joined onto the link's folder, a rooted target such as `\Device\Mup\x` would keep that folder's drive, + // and Win32 trims a trailing period or space that the kernel follows as it is. + if refused_spelling(&target.to_string_lossy(), roots).is_some() || is_rooted_without_drive(&target) || has_trimmed_name(&target) { + return true; + } // A relative target is relative to the link's folder; an absolute one replaces it. let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path())); return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look); @@ -231,6 +248,26 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) - false } +/// Whether `path` is a native NT name (`\Device\…`, `\DosDevices\…`, `\GLOBAL??\…`, `\??\…`, `\Sessions\…`, `\GLOBALROOT\…`), which a link +/// may hold: no prefix for `std`, yet the system follows it to wherever it names. +fn is_native_name(path: &Path) -> bool { + let bytes = path.as_os_str().as_encoded_bytes(); + [&br"\Device\"[..], &br"\DosDevices\"[..], &br"\GLOBAL??\"[..], &br"\??\"[..], &br"\Sessions\"[..], &br"\GLOBALROOT\"[..]].iter().any(|p| { + bytes.get(..p.len() - 1).is_some_and(|b| b.eq_ignore_ascii_case(&p[..p.len() - 1])) && matches!(bytes.get(p.len() - 1), None | Some(b'\\')) + }) +} + +/// Whether a link's target starts with one separator and no drive (`\RPC Control\x`, `\BaseNamedObjects\x`, `\work`): `std` sees no +/// prefix in it, yet the system reads it in its own object namespace or on the link's drive, and may follow it to wherever it names. +fn is_rooted_without_drive(path: &Path) -> bool { + matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\')) +} + +/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up. +fn has_trimmed_name(path: &Path) -> bool { + path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' ')))) +} + /// `p` with its `.` and `..` taken by name, as Windows takes them. fn lexical(p: &Path) -> PathBuf { let mut out = PathBuf::new(); @@ -273,9 +310,24 @@ pub(crate) fn within_app_folder(path: &Path, folder: &Path) -> bool { matches!((std::fs::canonicalize(path), std::fs::canonicalize(folder)), (Ok(p), Ok(f)) if p.starts_with(&f)) } +/// Whether `a` and `b` are the same file. Comparing opens both, so while roots confine this thread a +/// path that resolving would not be allowed to open (on another computer, or a device: see +/// [`refused_unresolved`]) is never opened. Whether it is the same file can't then be told, and the +/// callers guard against overwriting a file through another name for it, so it counts as the same: +/// the guard keeps asking (a path like that can't be written anyway). A local path outside the +/// roots is compared. pub fn same_file(a: impl AsRef, b: impl AsRef) -> bool { let (a, b) = (a.as_ref(), b.as_ref()); - a == b || same_file::is_same_file(a, b).unwrap_or(false) + if a == b { + return true; + } + if let Some(scope) = current() { + let roots = [scope.read.as_slice(), scope.write.as_slice()].concat(); + if cfg!(windows) && [a, b].into_iter().any(|p| refused_unresolved(p, &roots).is_some()) { + return true; + } + } + same_file::is_same_file(a, b).unwrap_or(false) } /// `p` without Windows' `\\?\` prefix, for messages. diff --git a/crates/engine/src/automation/file_access/tests.rs b/crates/engine/src/automation/file_access/tests.rs index d642befb1..57dd48c6f 100644 --- a/crates/engine/src/automation/file_access/tests.rs +++ b/crates/engine/src/automation/file_access/tests.rs @@ -229,6 +229,8 @@ fn spellings_of_other_computers_and_devices_are_refused() { r"C:\work\LPT³\x.png", r"C:\work\conout$", r"C:\work\aux:stream", + // A volume name that is not a GUID could be an alias of anything. + r"\\?\Volume{remote}\x.png", // After a name `craft_docpath` refuses for another reason. r"C:\work\a:b\prn.png", ]; @@ -402,6 +404,34 @@ fn a_parent_after_a_link_is_taken_by_name() { assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root"); } +/// Comparing two files opens both, so a path the roots don't allow is not compared: it is not the +/// same file as one inside, even when it is another name for it (a hard link outside the roots). +#[test] +fn same_file_does_not_open_a_path_outside_the_roots() { + let f = Fixture::new("same-file"); + let inside = f.p("root/in.txt"); + let outside = f.p("outside/linked.txt"); + if std::fs::hard_link(&inside, &outside).is_err() { + eprintln!("skipped: hard links can't be made here"); + return; + } + assert!(super::same_file(&inside, &outside), "unconfined, another name for a file is the same file"); + let roots = Arc::new(f.rw()); + confined(Some(&roots), || { + assert!(super::same_file(&inside, &outside), "a local path outside the roots is compared, and a hard link to a file inside is that file"); + if cfg!(windows) { + assert!( + super::same_file(&inside, r"\\192.0.2.1\share\x"), + "a path on another computer is never opened, and counts as the same so that the guard keeps asking" + ); + } + assert!(super::same_file(&inside, &inside), "a path is the same file as itself"); + let other = f.p("root/sub/other.txt"); + std::fs::write(&other, b"other").unwrap(); + assert!(!super::same_file(&inside, &other), "two files inside are compared, and differ"); + }); +} + /// A path on another computer and a device path are refused before anything is opened: resolving /// them made Windows contact the server, which may send it the signed-in user's credentials /// (#1094). Each is refused with a message that only the check before resolving gives: had the @@ -468,6 +498,59 @@ fn links_to_other_computers_are_refused_before_they_are_followed() { assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok()); } +/// A native NT name is told with or without the separator after its first name: a link to `\Device` alone, with the +/// rest of the path after it, reaches `\Device\Mup\...`. +#[test] +fn native_names_are_told_with_or_without_the_closing_separator() { + for p in + [r"\Device", r"\Device\Mup\203.0.113.5\s", r"\device\mup", r"\DosDevices", r"\GLOBAL??", r"\??", r"\??\UNC\x\y", r"\Sessions", r"\GLOBALROOT"] + { + assert!(super::is_native_name(Path::new(p)), "{p}"); + } + for p in [r"\Devices", r"\Devicex\y", r"Device", r"\work\Device", r"\\server\share", r"\"] { + assert!(!super::is_native_name(Path::new(p)), "{p}"); + } +} + +/// A link target that starts with one separator and no drive names a root the system reads in its own object namespace or on the +/// link's drive, whichever directory it names. +#[test] +fn rooted_link_targets_without_a_drive_are_refused() { + for p in [r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\work", r"\"] { + assert!(super::is_rooted_without_drive(Path::new(p)), "{p}"); + } + for p in [r"Device", r"work\x", r"C:\x", r"\\server\share", r"\\?\C:\x", ""] { + assert!(!super::is_rooted_without_drive(Path::new(p)), "{p}"); + } +} + +/// A link whose text is a native NT name (`\Device\Mup\server\share`) or ends in a period, and a path with a name that ends in a +/// space, are refused as written: joined onto the link's folder the first would keep that folder's drive, and Windows trims the +/// others where it looks a name up but not where the kernel follows a link. +#[test] +#[cfg(windows)] +fn native_names_and_names_windows_trims_are_refused_as_written() { + let f = Fixture::new("native-trimmed"); + let r = f.rw(); + if !symlink_dir(Path::new(r"\Device\Mup\192.0.2.1\share"), &f.0.join("root/native")) + || !symlink_dir(Path::new("remote."), &f.0.join("root/trimmed")) + { + eprintln!("skipped: this system doesn't let tests make symbolic links"); + return; + } + let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be"); + // However the system stores the native name, the link is refused. + let native = f.p("root/native/x.png"); + assert!(r.check(Path::new(&native), Access::Read).is_err(), "{native}"); + let p = f.p("root/trimmed/x.png"); + let e = r.check(Path::new(&p), Access::Read).expect_err(&p); + assert!(e.starts_with(&standard(&p)), "{p}: {e}"); + let p = f.p("root/remote /x.png"); + let e = r.check(Path::new(&p), Access::Write).expect_err(&p); + assert!(e.starts_with(&standard(&p)), "{p}: {e}"); + assert_eq!(super::refused_spelling(r"\??\UNC\192.0.2.1\share\x", &[]), Some(craft_docpath::Refused::Device)); +} + #[test] fn a_scope_confines_the_thread_and_ends_with_it() { let f = Fixture::new("scope"); diff --git a/docs/mcp.md b/docs/mcp.md index 9b44a0c55..700d1d48a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -94,8 +94,14 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`: (writing through it would create its target, wherever that is). A path outside the roots gets the same refusal whatever exists there, so a refusal doesn't tell what is outside. Folders are compared by whole names: `/work2/x` is not inside `/work`. On Windows the case comes from the disk (`C:\WORK\x` is - inside `C:\work`), `\\?\` and UNC (`\\server\share\…`) paths are resolved like drive-letter ones, - and new names that are devices (`CON`, `NUL`, `COM1`…) or streams (`a.png:x`) are refused. + inside `C:\work`), `\\?\C:\…` paths are resolved like drive-letter ones, and + new names that are devices (`CON`, `NUL`, `COM1`…) or streams (`a.png:x`) are refused. + A path on another computer (`\\server\share\…`, `\\?\UNC\…`, WebDAV's `\\host@SSL\share\…`) or a device + path (`\\.\pipe\…`, `\\?\GLOBALROOT\…`) is refused by its spelling before anything looks it up, since looking + it up would contact that host, unless a root is on the same share; a link whose target is one of those is + refused too. A local volume's `\\?\Volume{…}\` path is let through. A link whose text is a native NT name + (`\Device\…`, `\??\…`, `\GLOBAL??\…`) is refused as a device path, and so is a name that ends in a period or a space, in a + path or as a link's target, since Windows trims it where it looks a name up. - **The network:** a confined call reaches no FigCraft or plugin server, so it can't send a document anywhere through one. Hosting, joining, publishing and sharing a file (`collab.host`, `collab.join`, `collab.publish`, `collab.share` …), team libraries on a server (`library.check` From 9e99135ffcc90facd026a3e2697e71ebadc9ed40 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:36:43 +0100 Subject: [PATCH 043/129] M0: reject invalid complete versions before writing Cargo.toml Validate the numeric core, prerelease identifiers and build metadata before the version command changes the manifest. Add boundary and malformed-input coverage. --- xtask/src/main.rs | 71 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7ff4bba4f..42ec5f610 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -266,6 +266,27 @@ fn parity() -> bool { true } +/// Cargo versions require a numeric core and nonempty, ASCII prerelease/build identifiers. +fn valid_version(v: &str) -> bool { + let (without_build, build) = v.split_once('+').map_or((v, None), |(version, build)| (version, Some(build))); + let (core, pre) = without_build.split_once('-').map_or((without_build, None), |(core, pre)| (core, Some(pre))); + let mut numbers = core.split('.'); + if !(0..3).all(|_| { + numbers.next().is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit()) && (n.len() == 1 || !n.starts_with('0')) && n.parse::().is_ok()) + }) || numbers.next().is_some() + { + return false; + } + let identifiers = |s: &str, allow_numeric_leading_zeroes: bool| { + s.split('.').all(|id| { + !id.is_empty() + && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + && (allow_numeric_leading_zeroes || id.len() == 1 || !id.starts_with('0') || !id.bytes().all(|b| b.is_ascii_digit())) + }) + }; + pre.is_none_or(|p| identifiers(p, false)) && build.is_none_or(|b| identifiers(b, true)) +} + fn version(sub: Option<&str>, value: Option<&str>) -> bool { let path = root().join("Cargo.toml"); let Ok(text) = std::fs::read_to_string(&path) else { return false }; @@ -277,9 +298,7 @@ fn version(sub: Option<&str>, value: Option<&str>) -> bool { .to_string(); match (sub, value) { (Some("set"), Some(v)) => { - let valid = - v.split(['-', '+']).next().is_some_and(|core| core.split('.').count() == 3 && core.split('.').all(|p| p.parse::().is_ok())); - if !valid { + if !valid_version(v) { eprintln!("version must look like 1.2.3 or 1.2.3-rc.1"); return false; } @@ -296,3 +315,49 @@ fn version(sub: Option<&str>, value: Option<&str>) -> bool { } } } + +#[cfg(test)] +mod version_tests { + use super::valid_version; + + #[test] + fn accepts_cargo_versions_including_prerelease_and_build_metadata() { + for v in [ + "0.0.0", + "1.2.3", + "18446744073709551615.0.0", + "1.2.3-0", + "1.2.3-01a", + "1.2.3-alpha-beta.1", + "1.2.3-18446744073709551616", + "1.2.3+001", + "1.2.3-rc.1+build.7", + ] { + assert!(valid_version(v), "{v}"); + } + } + + #[test] + fn rejects_versions_that_would_leave_the_manifest_invalid() { + for v in [ + "", + "1.2", + "1.2.3.4", + "01.2.3", + "1.02.3", + "1.2.03", + "18446744073709551616.0.0", + "1.2.3-", + "1.2.3-01", + "1.2.3-rc.01", + "1.2.3-a..b", + "1.2.3-a_b", + "1.2.3+", + "1.2.3+meta+again", + "1.2.3-alpha\"", + "1.2.3-alpha\n", + ] { + assert!(!valid_version(v), "{v:?}"); + } + } +} From e780264e55cb18b765f7a86cfdeb970b687c028c Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Sun, 15 Nov 2026 15:07:16 +0100 Subject: [PATCH 044/129] i18n(sv): translate 21 new strings Brings the Swedish catalog up to date with upstream main (3bbd1d3c). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/sv.toml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index a64458182..313089e9b 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -22,6 +22,7 @@ name = "Svenska" "A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "En samling i den här filen med dessa lägen och variabler: ange overrides för deras värden per läge och lägg till egna variabler" "A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "Det finns redan en .figcraft-fil med det här namnet. Välj dess fullständiga namn för att bekräfta att den ersätts." "A later vote" = "En senare omröstning" +"A layer in an auto layout frame is placed by its frame" = "Ett lager i en auto layout-frame placeras av framen" "A layer on its own aligns to its frame: select more layers, or one in a frame" = "Ett ensamt lager justeras mot sin frame: markera fler lager, eller ett lager i en frame" "A responsive product page: hero, features, figures, a quote and a footer" = "En responsiv produktsida: toppsektion, funktioner, figurer, ett citat och en sidfot" "A spring plays until it settles: its mass, stiffness and damping set how long" = "En fjäder spelas tills den stannar: dess massa, styvhet och dämpning avgör hur länge" @@ -123,6 +124,7 @@ name = "Svenska" "Android Vector Drawable" = "Android Vector Drawable" "Angular" = "Vinkelmått" "Animation" = "Animering" +"Annotation" = "Anteckning" "Annotations" = "Annoteringar" "Annotations shown on the canvas" = "Annoteringar som visas på arbetsytan" "Another server, or one that needs its key. The usual server is set in Preferences." = "En annan server, eller en som kräver sin nyckel. Standardservern anges i Inställningar." @@ -522,6 +524,7 @@ name = "Svenska" "Duo" = "Duo" "Duplicate" = "Duplicera" "Duplicate by dragging" = "Duplicera genom att dra" +"Duplicate group" = "Duplicera grupp" "Duplicate mode" = "Duplicera läge" "Duplicate page" = "Duplicera sida" "Edit" = "Redigera" @@ -534,6 +537,9 @@ name = "Svenska" "Edit padding on all sides" = "Redigera padding på alla sidor" "Edit style" = "Redigera stil" "Edit variable" = "Redigera variabel" +"Edit variables" = "Redigera variabler" +"Scope" = "Omfång" +"No scope is shared by all the selected variables" = "Inget omfång delas av alla markerade variabler" "Edit with the builder" = "Redigera med byggaren" "Edited {when}" = "Ändrat {when}" "Effect settings" = "Effektinställningar" @@ -883,6 +889,7 @@ name = "Svenska" "Pasted design layers; the clipboard didn't carry the images of: {layers}" = "Designlager inklistrade; urklippet innehöll inte bilderna för: {layers}" "Remove these results from the file" = "Ta bort de här resultaten från filen" "Scroll wheel zoom" = "Zooma med scrollhjulet" +"Invert zoom direction" = "Invertera zoomriktning" "Shared by your team on {server}" = "Delat av ditt team på {server}" "Slot name" = "Platsens namn" "Mar" = "Mar" @@ -1399,6 +1406,7 @@ name = "Svenska" "Server for online sharing" = "Server för delning online" "Server key" = "Servernyckel" "Set as default" = "Ange som standard" +"Set as opening page" = "Ange som startsida" "Set corner smoothing to 60%" = "Ställ in hörnutjämning på 60 %" "Set variable" = "Ange variabel" "Set variable mode" = "Ange variabelläge" @@ -1574,6 +1582,11 @@ name = "Svenska" "Text content" = "Textinnehåll" "Text on a path" = "Text längs en bana" "Text size" = "Textstorlek" +"Small" = "Liten" +"Medium" = "Medel" +"Large" = "Stor" +"Extra large" = "Extra stor" +"Huge" = "Enorm" "Text style" = "Textstil" "Text styles" = "Textstilar" "Texts" = "Texter" @@ -1618,6 +1631,7 @@ name = "Svenska" "This version can't be read." = "Den här versionen kan inte läsas." "This version doesn't have it: all of it is new." = "Den här versionen saknar det: allt är nytt." "Tidy up" = "Snygga till" +"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Markera en rad, en kolumn eller ett helt rutnät med tre eller fler lager, utanför ett auto layout-flöde" "Tile" = "Sida vid sida" "Tile type" = "Upprepningstyp" "Timer" = "Timer" @@ -1879,6 +1893,7 @@ name = "Svenska" "set-variable actions without a value were skipped" = "åtgärder för att ange variabel utan värde hoppades över" "set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" = "åtgärder för att ange variabelläge på samlingar eller lägen som inte finns i variabel-JSON:en hoppades över" "shape generated outline is missing or damaged; using its rectangle" = "konturen som genererats av en form saknas eller är skadad; dess rektangel används" +"shape with text layers import as frames with their text" = "lager med form och text importeras som frames med sin text" "slot content assignment target is missing or is not slot content" = "målet för tilldelningen av fackinnehåll saknas eller är inte fackinnehåll" "slot content assignment uses the empty GUID sentinel and was skipped" = "tilldelningen av fackinnehåll använder det tomma GUID:t som markörvärde och hoppades över" "slot layers without a matching slot property were imported as frames" = "facklager utan en motsvarande fackegenskap importerades som frames" @@ -1886,6 +1901,7 @@ name = "Svenska" "some vector segments refer to style settings missing from the file; they use the layer's stroke" = "vissa vektorsegment hänvisar till stilinställningar som saknas i filen; de använder lagrets kontur" "stale or invalid grid track sizing entries were ignored" = "inaktuella eller ogiltiga storleksposter för rutnätsspår ignorerades" "stars and polygons without point counts or geometry use the default point count" = "stjärnor och polygoner utan antal punkter eller geometri använder standardantalet punkter" +"sticky layers import as frames with their text" = "fästlappslager importeras som frames med sin text" "style settings of some vector segments aren't supported; those segments use the layer's stroke" = "stilinställningar för vissa vektorsegment stöds inte; de segmenten använder lagrets kontur" "text path underline or strikethrough decoration is not rendered" = "understrykning eller genomstrykning av text på bana ritas inte" "text style overrides refer to missing table entries" = "overrides av textstilar hänvisar till tabellposter som saknas" @@ -2351,6 +2367,7 @@ name = "Svenska" "plugins.runLast" = "Kör senaste plugin" "pref.autoSave" = "Spara filer automatiskt" "pref.highlightHover" = "Framhäv lager vid hovring" +"pref.invertZoom" = "Invertera zoomriktning" "pref.keepTool" = "Behåll verktyget markerat efter användning" "pref.language" = "Gränssnittsspråk" "pref.nudge" = "Steglängd" @@ -2508,6 +2525,7 @@ name = "Svenska" "text.weightDown" = "Minska teckenvikten" "text.weightUp" = "Öka teckenvikten" "text.wrapStyle" = "Radbrytningsstil" +"tool.annotation" = "Anteckning" "tool.arrow" = "Pil" "tool.comment" = "Kommentar" "tool.connector" = "Koppling" @@ -2696,6 +2714,9 @@ name = "Svenska" "text.alignJustify" = "Marginaljustera text" "text.alignLeft" = "Vänsterjustera text" "text.alignRight" = "Högerjustera text" +"text.directionAuto" = "Auto" +"text.directionLtr" = "Vänster till höger" +"text.directionRtl" = "Höger till vänster" "view.assets" = "Resurser" "view.design" = "Design" "view.layers" = "Lager" From ea8c630821f53f28099064ecc77e8a98cb4ff64e Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:34:15 +0100 Subject: [PATCH 045/129] cli: reject malformed attach address components Validate a nonempty host and a u16 port before attempting attachment. Preserve valid address spelling and bare-port behavior. --- apps/figcraft-cli/src/args.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index 4696b8664..b8372ece4 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -316,7 +316,10 @@ fn whole_number(s: &str) -> Result { /// `mcp --attach`: `host:port` as given, or a bare port on 127.0.0.1. fn attach(s: &str) -> Result { - if s.contains(':') { + if let Some((host, port)) = s.rsplit_once(':') { + if host.is_empty() || port.parse::().is_err() { + return Err(ValueError::Attach); + } return Ok(s.to_owned()); } let port: u16 = s.parse().map_err(|_| ValueError::Attach)?; @@ -461,6 +464,12 @@ mod tests { assert_eq!(a.attach.as_deref(), Some("127.0.0.1:7979")); let Command::Mcp(a) = ok(&["mcp", "--attach=localhost:7979"]) else { panic!("mcp") }; assert_eq!(a.attach.as_deref(), Some("localhost:7979")); + for address in ["127.0.0.1:7979", "[::1]:7979", "[fe80::1%3]:7979", "localhost:0"] { + let Command::Mcp(a) = ok(&["mcp", "--attach", address]) else { panic!("mcp") }; + assert_eq!(a.attach.as_deref(), Some(address)); + } + let Command::Mcp(a) = ok(&["mcp", "--attach", "0"]) else { panic!("mcp") }; + assert_eq!(a.attach.as_deref(), Some("127.0.0.1:0")); let Command::Mcp(a) = ok(&["mcp", "--attach", "7979", "--timeout", "300"]) else { panic!("mcp") }; assert_eq!(a.timeout, Some(300)); let Command::Mcp(a) = ok(&["mcp", "--automation-read-root", "in", "--automation-write-root", "out"]) else { panic!("mcp") }; @@ -514,6 +523,11 @@ mod tests { (&["perf", "--layers", "10,x"], ValueValidation), (&["perf", "--layers", "10", "--layers", "20"], ArgumentConflict), (&["mcp", "--attach", "notaport"], ValueValidation), + (&["mcp", "--attach", ":7979"], ValueValidation), + (&["mcp", "--attach", "localhost:"], ValueValidation), + (&["mcp", "--attach", "localhost:notaport"], ValueValidation), + (&["mcp", "--attach", "localhost:65536"], ValueValidation), + (&["mcp", "--attach", "[::1]"], ValueValidation), (&["mcp", "--attach", "7979", "--timeout", "0"], ValueValidation), (&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation), (&["mcp", "--timeout", "300"], MissingRequiredArgument), @@ -543,6 +557,7 @@ mod tests { &["export", "x.figcraft", "-o", "out", "--help"], &["export", "-o", "--help"], &["mcp", "--attach", "notaport", "--help"], + &["mcp", "--attach", "localhost:notaport", "--help"], &["mcp", "--bogus", "-h"], &["--no-system-fonts", "plugin", "publish", "--bogus", "--help"], ] { From 8244acce2d37c0e6dc1b25ffa45c7de251020cd3 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:58:13 +0100 Subject: [PATCH 046/129] cli: escape device names in generated export filenames Use the shared device-name escaping rule for generated CLI export basenames, before existing length caps. --- apps/figcraft-cli/src/files.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/figcraft-cli/src/files.rs b/apps/figcraft-cli/src/files.rs index 165057086..8c606236f 100644 --- a/apps/figcraft-cli/src/files.rs +++ b/apps/figcraft-cli/src/files.rs @@ -242,6 +242,7 @@ pub fn info(path: &str, as_json: bool) -> CliResult { fn sanitize(name: &str) -> String { let s = figcraft_engine::cmd::file::safe_file_name(name); let s = s.trim_matches(|c: char| c == '.' || c.is_whitespace()); + let s = figcraft_engine::file_access::escape_device_names(s); if s.is_empty() { "layer".into() } else { s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect() } } @@ -543,6 +544,10 @@ mod tests { assert_eq!(sanitize("Home / Hero"), "Home _ Hero"); assert_eq!(sanitize("../.."), "_"); assert_eq!(sanitize(""), "layer"); + assert_eq!(sanitize("CON"), "_CON"); + assert_eq!(sanitize(" .nul.txt. "), "_nul.txt"); + assert_eq!(sanitize("COM1"), "_COM1"); + assert_eq!(sanitize("HomeCON"), "HomeCON"); // The same characters the app's export keeps (#1154): only what file systems refuse goes. assert_eq!(sanitize("Homepage - desktop (live + verbeteringen)"), "Homepage - desktop (live + verbeteringen)"); assert_eq!(sanitize("Q&A, 50% #1 [v2] {x} ~é"), "Q&A, 50% #1 [v2] {x} ~é"); From af87503d04a1411caa145bed0b393aff7f83dccc Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:59:34 +0100 Subject: [PATCH 047/129] Implement escape_device_names function Prefix generated path components using the existing device classifier, after filtering and suffix construction. --- crates/engine/src/automation/file_access.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index 249d3483c..8d04488e6 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -345,6 +345,12 @@ fn device_name(n: &str) -> bool { && stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³'))) } +/// Prefix Windows device-name components of a generated export path with `_`. +/// Apply after character filtering and suffix construction, so a safe suffix stays unchanged. +pub fn escape_device_names(path: &str) -> String { + path.split('/').map(|name| if device_name(name) { format!("_{name}") } else { name.to_string() }).collect::>().join("/") +} + thread_local! { static ROOTS: RefCell>> = const { RefCell::new(None) }; } From 19a4a309e4a8d4db9d23d404f6e1f7a9393d0a87 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:01:13 +0100 Subject: [PATCH 048/129] test: cover generated device-name path components Exercise device names, extensions, nested components and safe near-matches using the existing device-name classification. --- .../src/automation/file_access/tests.rs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/engine/src/automation/file_access/tests.rs b/crates/engine/src/automation/file_access/tests.rs index d642befb1..0e80de0f6 100644 --- a/crates/engine/src/automation/file_access/tests.rs +++ b/crates/engine/src/automation/file_access/tests.rs @@ -9,6 +9,27 @@ use serde_json::json; use super::{Access, Roots, allow, confined, current}; use crate::Session; +#[test] +fn generated_export_paths_escape_device_components_and_preserve_other_names() { + for (path, expected) in [ + ("CON", "_CON"), + ("CoN.txt", "_CoN.txt"), + ("nul.txt", "_nul.txt"), + ("PRN/icon", "_PRN/icon"), + ("folder/COM1", "folder/_COM1"), + ("LPT9.png", "_LPT9.png"), + ("COM¹", "_COM¹"), + ("LPT²/icon", "_LPT²/icon"), + ("CONIN$", "_CONIN$"), + ("HomeCON", "HomeCON"), + ("COM10", "COM10"), + ("CON@2x", "CON@2x"), + ("folder/.NUL", "folder/.NUL"), + ] { + assert_eq!(super::escape_device_names(path), expected, "{path}"); + } +} + /// A fresh folder for one test: `/figcraft-roots--`, holding `root/`, `root2/` /// (a sibling whose name starts like the root's) and `outside/`. struct Fixture(PathBuf); From 71cd63a21b5db85277db55bb01f0ec5577beba65 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:02:12 +0100 Subject: [PATCH 049/129] engine: escape device components after export suffixes Apply the shared device-name rule to completed folder/name/suffix components before collision numbering, with regression coverage. --- crates/engine/src/cmd/file/export.rs | 30 +++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file/export.rs b/crates/engine/src/cmd/file/export.rs index bbc52e1b5..ac8353c30 100644 --- a/crates/engine/src/cmd/file/export.rs +++ b/crates/engine/src/cmd/file/export.rs @@ -295,7 +295,7 @@ pub fn jobs_for(items: impl IntoIterator)>, d if out.len() >= MAX_EXPORT_FILES { return out; } - let stem = format!("{base}{}", safe_file_name(&e.file_suffix())); + let stem = crate::file_access::escape_device_names(&format!("{base}{}", safe_file_name(&e.file_suffix()))); let ext = e.format.ext(); let file = (1..).map(|k| if k == 1 { format!("{stem}.{ext}") } else { format!("{stem} {k}.{ext}") }).find(|f| used.insert(f.to_lowercase())); @@ -439,3 +439,31 @@ pub(super) fn export_frames_pdf(s: &mut Session, p: &Value) -> Result { None => Ok(json!({"format": "pdf", "pages": pages, "data": base64::engine::general_purpose::STANDARD.encode(&bytes)})), } } + +#[cfg(test)] +mod filename_tests { + use super::*; + + #[test] + fn export_jobs_escape_device_names_after_suffixes_and_before_numbering() { + let mut doc = Document::new("Export names"); + let page = doc.first_page().unwrap(); + let cases = [ + ("C", "ON", "_CON.png"), + ("_con", "", "_con 2.png"), + ("CON/icon", "", "_CON/icon.png"), + ("Home", "CON", "HomeCON.png"), + ("COM", "1", "_COM1.png"), + ("COM1", "@2x", "COM1@2x.png"), + ]; + let items: Vec<_> = cases + .iter() + .map(|(name, suffix, _)| { + let id = doc.create(page, NodeKind::Frame, name, 0.0, 0.0, 10.0, 10.0).unwrap(); + (id, vec![ExportSetting { suffix: (*suffix).into(), ..Default::default() }]) + }) + .collect(); + let files: Vec<_> = jobs_for(items, &doc).into_iter().map(|job| job.file).collect(); + assert_eq!(files, cases.map(|(_, _, expected)| expected)); + } +} From 4382b9b5919b762d622b1541ee2b16abf87f006c Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:27:19 +0100 Subject: [PATCH 050/129] docs: explain generated device-name prefixes Document the reserved Windows name prefix alongside the existing generated export filename rules. --- docs/cli.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/cli.md b/docs/cli.md index a83fbe5c3..07b19e58b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -118,7 +118,8 @@ page 1 "Screens": 380 nodes, 4 top-level after the frame (`Home.png`, `Settings.png`…); with no frames, one file per top-level layer. The name is kept as it is, except for the characters file systems refuse (`/ \ : * ? " < > |` and control characters), which become `_`, and leading or trailing spaces and dots, which are - dropped. A name is cut at 100 characters. The app's export replaces the same characters (there a + dropped. Reserved Windows device names such as `CON` get a leading `_`. + A name is cut at 100 characters. The app's export replaces the same characters (there a `/` makes a folder). Two layers with the same name get `Name 2`, `Name 3`… - `` has an image extension: one file with the given `--node`, or the whole page composited. - `--node` takes a layer id (`12` or `0:12`) or a layer name. From 14bdeff5916e0d56c51ae9638bb7d88094737744 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:30:31 +0100 Subject: [PATCH 051/129] fix: check device names after filename length limits Cap generated CLI names before device-name escaping, then cap again so the prefix fits both limits. Cover character and byte truncation boundaries. --- apps/figcraft-cli/src/files.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/apps/figcraft-cli/src/files.rs b/apps/figcraft-cli/src/files.rs index 8c606236f..20cca566d 100644 --- a/apps/figcraft-cli/src/files.rs +++ b/apps/figcraft-cli/src/files.rs @@ -242,8 +242,10 @@ pub fn info(path: &str, as_json: bool) -> CliResult { fn sanitize(name: &str) -> String { let s = figcraft_engine::cmd::file::safe_file_name(name); let s = s.trim_matches(|c: char| c == '.' || c.is_whitespace()); - let s = figcraft_engine::file_access::escape_device_names(s); - if s.is_empty() { "layer".into() } else { s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect() } + let cap = |s: &str| s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect::(); + // Truncation can expose a device name; its escape must still fit the limits. + let s = figcraft_engine::file_access::escape_device_names(&cap(s)); + if s.is_empty() { "layer".into() } else { cap(&s) } } /// What `export` exports and how. @@ -558,6 +560,16 @@ mod tests { assert_eq!(sanitize(&"\u{1F600}".repeat(100)), "\u{1F600}".repeat(50), "at most 200 bytes, whole characters"); } + #[test] + fn sanitizes_names_that_become_devices_at_the_character_limit() { + assert_eq!(sanitize(&format!("CON{}X", " ".repeat(97))), format!("_CON{}", " ".repeat(96))); + } + + #[test] + fn sanitizes_names_that_become_devices_at_the_byte_limit() { + assert_eq!(sanitize(&format!("NUL{} X", "\u{2003}".repeat(65))), format!("_NUL{} ", "\u{2003}".repeat(65))); + } + #[test] fn default_page_skips_leading_divider() { let mut doc = Document::new("divider"); From 3c4111bacbcc01bb496bc417151890e5dd5bab6a Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Sun, 15 Nov 2026 17:25:32 +0100 Subject: [PATCH 052/129] i18n(sv): translate 1 new string, remove 1 obsolete Brings the Swedish catalog up to date with upstream main (0015eb5f). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/sv.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index f9f63c836..43fa665dc 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -1893,7 +1893,6 @@ name = "Svenska" "set-variable actions without a value were skipped" = "åtgärder för att ange variabel utan värde hoppades över" "set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" = "åtgärder för att ange variabelläge på samlingar eller lägen som inte finns i variabel-JSON:en hoppades över" "shape generated outline is missing or damaged; using its rectangle" = "konturen som genererats av en form saknas eller är skadad; dess rektangel används" -"shape with text layers import as frames with their text" = "lager med form och text importeras som frames med sin text" "slot content assignment target is missing or is not slot content" = "målet för tilldelningen av fackinnehåll saknas eller är inte fackinnehåll" "slot content assignment uses the empty GUID sentinel and was skipped" = "tilldelningen av fackinnehåll använder det tomma GUID:t som markörvärde och hoppades över" "slot layers without a matching slot property were imported as frames" = "facklager utan en motsvarande fackegenskap importerades som frames" @@ -1903,6 +1902,7 @@ name = "Svenska" "stars and polygons without point counts or geometry use the default point count" = "stjärnor och polygoner utan antal punkter eller geometri använder standardantalet punkter" "sticky layers import as frames with their text" = "fästlappslager importeras som frames med sin text" "style settings of some vector segments aren't supported; those segments use the layer's stroke" = "stilinställningar för vissa vektorsegment stöds inte; de segmenten använder lagrets kontur" +"swapped instances whose previous component isn't in the file took the new component's look" = "utbytta instanser vars tidigare komponent inte finns i filen fick den nya komponentens utseende" "text path underline or strikethrough decoration is not rendered" = "understrykning eller genomstrykning av text på bana ritas inte" "text style overrides refer to missing table entries" = "overrides av textstilar hänvisar till tabellposter som saknas" "the file has no pages" = "filen har inga sidor" From d5018e736e727c93ed956187a5efe4e201d99443 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 11:41:29 -0500 Subject: [PATCH 053/129] M5: while the view moves, the presenter's detail is drawn only while it covers the view (#2133 review) Past the detail's edge the capped whole-frame texture is drawn alone until the view settles, and then a detail for the new view is rendered, so no sharp/soft boundary crosses the view while it pans. The presenter row and the #2127 revision note describe the fallback. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- crates/ui-egui/src/present/actions.rs | 5 +++-- crates/ui-egui/src/present/tests.rs | 31 +++++++++++++++++++++++++++ docs/prototyping-parity.md | 4 ++-- docs/target-app-parity.md | 2 +- 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index d3386da0a..bb1ca5c25 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -269,7 +269,8 @@ impl Presenter { /// The part of the frame `id` (its whole texture covering `whole`, page units) in view /// (`visible`) at the full pixel scale `px`, for a frame whose whole texture is capped below it /// (see [`detail_plan`]). While the view moves (`moving`) it only returns a detail already - /// rendered, the capped texture showing under it. + /// rendered, and only while it covers the whole view: past it the capped texture shows alone + /// (no sharp edge across the view) until the view settles and a detail for it is rendered. pub(super) fn detail_texture( &mut self, ctx: &egui::Context, @@ -291,7 +292,7 @@ impl Presenter { if let Some((did, d)) = &self.detail && *did == id && d.key == key - && (moving || covers(&d.bounds)) + && covers(&d.bounds) { return Some(d.clone()); } diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index 4a6eab7df..9b4504bdb 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -527,6 +527,37 @@ fn a_view_a_rounding_error_past_the_frame_keeps_its_detail() { assert_eq!(again, first, "the same view reuses its detail instead of rendering a new one"); } +/// While the view moves, the detail is drawn only while it covers the whole view: past its edge +/// the capped whole-frame texture shows alone, so no sharp/soft boundary crosses the view, and +/// once the view settles a detail for it is rendered. +#[test] +fn a_moving_view_past_its_detail_shows_the_capped_frame_alone_until_it_settles() { + use figcraft_geom::Rect as R; + let mut ui = tall_hidpi(16_384); + let ctx = ui.ctx.clone(); + let doc = ui.app.session.doc().unwrap().clone(); + let now = ui.time; + let p = ui.app.ui.present.as_mut().unwrap(); + let id = p.current; + let whole = R::new(0.0, 0.0, 1440.0, 9701.0); + let covers = |b: R, v: R| b.x0 <= v.x0 && b.y0 <= v.y0 && b.x1 >= v.x1 && b.y1 >= v.y1; + let first = p.detail_texture(&ctx, &doc, id, 2.0, whole, R::new(0.0, 0.0, 1440.0, 860.0), false, now).expect("a detail"); + // Moving within the detail's margin: it is reused. + let shift = (first.bounds.y1 - 860.0) / 2.0; + assert!(shift > 0.0, "{:?}", first.bounds); + let inside = R::new(0.0, shift, 1440.0, 860.0 + shift); + let moved = p.detail_texture(&ctx, &doc, id, 2.0, whole, inside, true, now).expect("still covered"); + assert_eq!(moved.tex.id(), first.tex.id()); + // Moving past its edge: no detail, the capped texture shows alone. + let past = R::new(0.0, first.bounds.y1 - 430.0, 1440.0, first.bounds.y1 + 430.0); + assert!(!covers(first.bounds, past)); + assert!(p.detail_texture(&ctx, &doc, id, 2.0, whole, past, true, now).is_none(), "the old detail is not drawn over part of the view"); + // Settled there: a new detail for that view. + let settled = p.detail_texture(&ctx, &doc, id, 2.0, whole, past, false, now).expect("a new detail"); + assert_ne!(settled.tex.id(), first.tex.id()); + assert!(covers(settled.bounds, past), "{:?} covers {past:?}", settled.bounds); +} + #[test] fn a_still_view_keeps_its_detail_at_fractional_scales() { // Frame widths that give fractional fit-width scales: the view's page rect then comes back diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index af062cd1f..6863a4c7d 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -92,7 +92,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Widgets react to clicks in a presented prototype | done | clicks only, like on the canvas | | Interactive components: instances play their variant's interactions, overridden per trigger | done | | | Drag-driven animations that follow the pointer, in their direction | done | | -| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537); a frame too big for one texture at device scale (taller than about 2900 units at 1440 wide on a 2x display) shows the part in view from a second texture at device scale over the capped whole-frame one, drawn again when it stops covering the view and not while the view moves (#2127). Devices not compared with Figma's | +| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537); a frame too big for one texture at device scale (taller than about 2900 units at 1440 wide on a 2x display) shows the part in view from a second texture at device scale over the capped whole-frame one, drawn again when it stops covering the view and not while the view moves, when past it the capped texture shows alone until the view settles (#2127). Devices not compared with Figma's | | Hotspot hints, inspect panel in the presenter, comments in the presenter | done | | | Hide UI in the presenter (Options menu, Cmd/Ctrl+\) | done | the bar above the prototype and the navigation bar under it go away and the prototype takes their room; a toast names the key that brings them back; `proto.presentOptions {hideUi}`, kept for later presentations (#1820) | | Preview pane following edits live | done | | @@ -109,7 +109,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| | 2026-11-09 | patch | M7, #2158: a connection dragged from a variant (or a layer in it) onto a sibling variant of its set did nothing, because the drop looked only for top-level frames and a variant's top-level frame is its set. It now creates Change to the sibling (On click, Instant, as measured in Figma's web app) and outlines the sibling while dragging; the set's background and the variant itself still add nothing, and a frame outside the set still gets Navigate to | -| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | +| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it (while the view moves, a detail is drawn only while it covers the whole view: past it the capped texture shows alone, with no sharp edge across the view, until the view settles); transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` | | 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. | | 2026-10-30 | minor | Opening a link in place: Open link has "Open in new tab", on by default; off, the web build's own tab goes to the link after the notice (or at once with it skipped); the desktop app has no tab of its own and opens the browser either way. Saved in files only when off (`openInNewTab`) and read from REST files. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 363697182..6edc89451 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -649,7 +649,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| -| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it; transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | +| 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it (while the view moves, a detail is drawn only while it covers the whole view: past it the capped texture shows alone, with no sharp edge across the view, until the view settles); transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-10 | minor | M4, #2222: a boolean group's corner radius rounds every sharp corner of its result (row 4). Numbers unchanged | | 2026-11-08 | minor | M8: measured in Figma on 2026-11-08, vector edit mode's Point section: X and Y show the value the selected points share, or Mixed when they differ, and a typed value sets every selected point's own coordinate in the layer being edited, points of other edited layers left as they are (it moved the group's top-left before); a relative edit (`+10`, `*2`, `/2`) typed into a Mixed field applies to each point's own value (`vector.edit.position` takes a number or `{add}`, `{mul}`, `{div}` per axis); the W and H row and other edited layers' points are unchanged. | | 2026-11-11 | patch | M4: typing a number, a full stop and a space at the start of a plain paragraph starts a numbered list at that number (`5. ` then "x", Enter, "y" reads 5. then 6.), as measured in Figma web on 2026-11-11 (it has no start-number field: the start comes only from the typed number); before, only `1. ` and `1)` started a list. `0. `, `12a. ` and a bracket after a number other than 1 stay text (not measured), and the number is capped at 9999. Also measured: a plain paragraph or a bullet item between numbered items restarts the count at 1, and an indented sub-item does not break the outer count; those rows were pinned as silent. Tests: `text_tail_tests::typed_list_starts`, `typed_number_starts_the_list_there`, `tail_tests` restart rows. Numbers unchanged | From fff48fc4415d6d4925bc466ba421361e8e11f756 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:52:03 +0100 Subject: [PATCH 054/129] M0.9: escape terminal controls in CLI operation errors Apply the existing printable-text rule at the final Usage and Failed error output boundary, preserving exit codes and the help footer. --- apps/figcraft-cli/src/main.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/figcraft-cli/src/main.rs b/apps/figcraft-cli/src/main.rs index 2d3596bca..44bdd4520 100644 --- a/apps/figcraft-cli/src/main.rs +++ b/apps/figcraft-cli/src/main.rs @@ -38,14 +38,15 @@ fn main() -> ExitCode { return ExitCode::from(u8::try_from(e.exit_code()).unwrap_or(2)); } }; + // Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable. match run(cli) { Ok(code) => code, Err(CliError::Usage(msg)) => { - eprintln!("error: {msg}\n\nFor more information, try '--help'."); + eprintln!("error: {}\n\nFor more information, try '--help'.", files::plain(&msg)); ExitCode::from(2) } Err(CliError::Failed(msg)) => { - eprintln!("error: {msg}"); + eprintln!("error: {}", files::plain(&msg)); ExitCode::from(1) } } From 6b272dc857c1c1be431d9a8d760a3bdceda55692 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:52:54 +0100 Subject: [PATCH 055/129] M0.9: reuse printable diagnostic text at the CLI boundary Expose the existing plain helper within the crate so final CLI errors use exactly the same escaping rule as file and script diagnostics. --- apps/figcraft-cli/src/files.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/figcraft-cli/src/files.rs b/apps/figcraft-cli/src/files.rs index 165057086..59dec2abf 100644 --- a/apps/figcraft-cli/src/files.rs +++ b/apps/figcraft-cli/src/files.rs @@ -12,7 +12,7 @@ use crate::{CliError, CliResult}; /// A document's or plugin's text as a terminal should show it: control characters escaped, and /// everything else (quotes, backslashes in paths) left as it is. -fn plain(text: &str) -> String { +pub(crate) fn plain(text: &str) -> String { text.chars().map(|c| if c.is_control() { c.escape_default().to_string() } else { c.to_string() }).collect() } From b7b4773639afc142c77958824cb2fd34c8c16fd4 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:53:28 +0100 Subject: [PATCH 056/129] M0.9: cover printable post-parse CLI diagnostics Cover control-bearing missing-file failures and invalid connect-publish extensions through the binary, retaining exit codes 1 and 2 and no stdout. --- apps/figcraft-cli/tests/it/cli.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/apps/figcraft-cli/tests/it/cli.rs b/apps/figcraft-cli/tests/it/cli.rs index 77d816b60..efc1f0e29 100644 --- a/apps/figcraft-cli/tests/it/cli.rs +++ b/apps/figcraft-cli/tests/it/cli.rs @@ -106,6 +106,22 @@ fn bad_arguments_exit_2_without_panicking() { assert_eq!(out.status.code(), Some(1)); } +#[test] +fn post_parse_errors_escape_terminal_controls() { + let missing = format!("__figcraft_missing_diagnostic_{}_\u{1b}[31m\n.figcraft", std::process::id()); + let failed = ["info", missing.as_str()]; + let usage = ["connect", "publish", "invalid-\u{1b}[31m\n.txt"]; + for (args, expected) in [(&failed[..], 1), (&usage[..], 2)] { + let out = bin().arg("--no-system-fonts").args(args).output().unwrap(); + let error = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(expected), "{args:?}: {error:?}"); + assert!(error.starts_with("error: "), "{args:?}: {error:?}"); + assert!(!error.contains('\u{1b}'), "{args:?}: {error:?}"); + assert!(error.contains(r"\u{1b}[31m\n"), "{args:?}: {error:?}"); + assert!(out.stdout.is_empty(), "{args:?}"); + } +} + /// `--help` / `-h` after a subcommand prints that subcommand's help on stdout and exits 0, as it /// does first (#1155), whatever else is on the line; nothing runs. #[test] From f0fea55d261df9120e78b6967a79da50b151cc24 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:53:59 +0100 Subject: [PATCH 057/129] M0.9: record printable CLI operation errors Record final diagnostic-boundary escaping in the status line and revision history, retaining prior entries and the existing exit-code contract. --- ROADMAP.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 54921fb11..4422f1197 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (CLI post-parse errors escape terminal controls in paths and failure text; a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | From 6d2b386b60eadb29529364fb90c6981d64b9f254 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 16 Nov 2026 04:37:46 -0500 Subject: [PATCH 058/129] docs: status lines are main's summary with this PR's entry in front The main merge kept the old summary in front of main's rewritten one; this takes main's line and puts back only the PR's own entry. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 327d07589..5d615175e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (; 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; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; an exported layer with a background blur or glass keeps the blurred content behind it within its bounds (#2213); a typed number and a full stop at the start of a paragraph starts a numbered list at that number, as measured in Figma 2026-11-11; justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS); M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is From b97e30a50e3e5cd2d395eb82c96f32f74535d673 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Mon, 16 Nov 2026 20:05:15 +0530 Subject: [PATCH 059/129] Contributors: gmrmad1's name for the About window --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 34f849ed7..03122b978 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -118,3 +118,6 @@ real_name = "Ashok Ram" [people.GiovanniBot] sync_github_name = true + +[people.gmrmad1] +real_name = "Madhav Agarwal" From 0322e2a2c85a6e5eb78a70fe0b6cd63fa89adf9b Mon Sep 17 00:00:00 2001 From: Aathish <101638624+Aathish-D@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:52:24 +0530 Subject: [PATCH 060/129] M8: Copy link to page in the page context menu (#2379) --- contributors/people.toml | 4 ++ crates/ui-egui/locales/en.toml | 1 + crates/ui-egui/src/layers_behaviour_tests.rs | 65 ++++++++++++++++++++ crates/ui-egui/src/panels/layers.rs | 6 ++ 4 files changed, 76 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 34f849ed7..68355f063 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -118,3 +118,7 @@ real_name = "Ashok Ram" [people.GiovanniBot] sync_github_name = true + +[people.Aathish-D] +real_name = "Aathish Duraiswamy" +sync_github_name = true diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 47db9eab4..0a15c3e44 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -360,6 +360,7 @@ name = "English" "Copy fill" = "Copy fill" "Copy for AI" = "Copy for AI" "Copy link" = "Copy link" +"Copy link to page" = "Copy link to page" "Copy stroke" = "Copy stroke" "Copy the {label}" = "Copy the {label}" "Copy {value}" = "Copy {value}" diff --git a/crates/ui-egui/src/layers_behaviour_tests.rs b/crates/ui-egui/src/layers_behaviour_tests.rs index 467bb9fd3..d5dff9bd0 100644 --- a/crates/ui-egui/src/layers_behaviour_tests.rs +++ b/crates/ui-egui/src/layers_behaviour_tests.rs @@ -4,11 +4,14 @@ //! list (dragging pages, dividers). Rows the documentation is silent on say so and pin today's //! behaviour. What the gestures do to the document is in the engine's `panels_behaviour_tests`. +use std::sync::{Arc, Mutex}; + use egui::{Event, Id, Modifiers, Pos2}; use figcraft_doc::NodeId; use figcraft_engine::Session; use serde_json::json; +use crate::Services; use crate::layers_drag_tests::Ui; fn id(v: serde_json::Value) -> NodeId { @@ -687,6 +690,68 @@ fn the_page_menu_sets_the_opening_page_and_not_on_dividers() { assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); } +/// Right-clicks `at` in the pages list and returns the menu's "Copy link to page" item, if shown. +fn copy_link_item(u: &mut Ui, at: Pos2) -> Option { + u.frame(vec![ + Event::PointerMoved(at), + Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, + ]); + u.frame(vec![Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]); + let shapes: Vec = u.frame_output(vec![]).shapes.into_iter().map(|c| c.shape).collect(); + crate::live_tests::has_text(&shapes, "Copy link to page").then(|| crate::live_tests::text_center(&shapes, "Copy link to page")) +} + +/// The pages list's menu offers "Copy link to page" on a page and not on a divider, and using it +/// copies the page's node link to the clipboard and shows a toast without moving the viewer's page (#2379). +#[test] +fn the_page_menu_copies_link_to_page_and_not_on_dividers() { + let mut s = Session::new(); + let p1 = s.page().unwrap(); + let p2 = id(s.execute("page.add", &json!({})).unwrap()); + let div = id(s.execute("page.add", &json!({"name": "-"})).unwrap()); + s.execute("page.move", &json!({"id": div, "index": 1})).unwrap(); + s.execute("page.select", &json!({"id": p1})).unwrap(); + let mut u = Ui::new(s); + let copied = Arc::new(Mutex::new(Vec::new())); + struct Clip(Arc>>); + impl Services for Clip { + fn clipboard_set_text(&mut self, s: &str) { + self.0.lock().unwrap().push(s.to_string()); + } + } + u.app.services = Box::new(Clip(copied.clone())); + let (r1, r2) = (page_row(&mut u, p1, p2), page_row(&mut u, p2, p1)); + let mid = Pos2::new(r1.x, (r1.y + r2.y) / 2.0); + u.app.session.execute("page.select", &json!({"id": p1})).unwrap(); + u.frame(vec![]); + + // A divider has no "Copy link to page" menu item. + assert_eq!(copy_link_item(&mut u, mid), None, "a divider has no such item"); + u.frame(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + for _ in 0..5 { + u.frame(vec![]); + } + + // A normal page has "Copy link to page". + let item = copy_link_item(&mut u, r2).expect("a page has the item (and its menu is open)"); + u.frame(vec![Event::PointerMoved(item)]); + u.button(item, true); + u.button(item, false); + for _ in 0..3 { + u.frame(vec![]); + } + + // Checks: + // 1. Link format is `figcraft://node/` + assert_eq!(*copied.lock().unwrap(), vec![format!("figcraft://node/{}", p2.0)]); + // 2. Toast "Link copied" is shown + assert_eq!(u.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("Link copied")); + // 3. Document opening page and viewer's current page are unaffected + assert_ne!(u.app.session.doc().unwrap().current_page, Some(p2)); + assert_eq!(u.app.session.page().unwrap(), p1); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); +} + /// The y of the line between the pages and the layers, above the layers' row at `layer` (found by /// the resize cursor it shows when hovered). fn pages_edge_at(u: &mut Ui, layer: f32) -> f32 { diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index d20fafe32..b7fe8c308 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -333,6 +333,12 @@ fn pages(app: &mut FigApp, ui: &mut Ui) { } ui.close(); } + // Copy link to page (#2379); a divider can't be linked. + if !divider && ui.button(tr("Copy link to page")).clicked() { + app.clipboard_set_text(&format!("figcraft://node/{}", id.0)); + app.toast(tr("Link copied")); + ui.close(); + } // The page the file opens on, for everyone (#1817); a divider can't be one. if !divider && ui.button(tr("Set as opening page")).clicked() { if !crate::menus::dev_mode_refuses(app, "page.setOpening") { From 2451cc34e420e6b6df21353d80c7c941bd11f91c Mon Sep 17 00:00:00 2001 From: Faridul Date: Tue, 17 Nov 2026 08:15:34 +0600 Subject: [PATCH 061/129] M8: the desktop refines a zoom only once it pauses After a zoom step's preview the render thread only checked once, right away, for a newer request, then started the full render. That render can't be stopped, so on a heavy page every later step of a held zoom waited for it (110-520 ms per render on a 9,000-layer page with images and shadows). It now waits like the browser worker does: SETTLE_MS, or the last full render's time when that's shorter. Pans and edits have no preview and are refined straight away as before. --- crates/ui-egui/src/canvas/render_worker.rs | 23 ++++++++++----- .../ui-egui/src/canvas/zoom_preview_tests.rs | 28 +++++++++++++++++++ docs/gaps.md | 9 +++++- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 44a478807..27c9cc32b 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -32,9 +32,9 @@ use web_time::Instant; pub const PREVIEW_FACTOR: f64 = 4.0; /// Full renders quicker than this (about a frame) show without a preview. pub const PREVIEW_AFTER_MS: f64 = 12.0; -/// The browser refines a zoom's preview only once no newer request came for this long (or for as -/// long as the last full render took, when shorter): a full render there blocks the page, and one -/// between every two wheel steps of a zoom held it up for seconds. +/// A zoom's preview is refined only once no newer request came for this long (or for as long as +/// the last full render took, when shorter): in the browser a full render blocks the page, and on +/// the desktop it can't be stopped, so one between every two wheel steps of a zoom held it up. pub const SETTLE_MS: u64 = 120; /// The browser draws a full render a band at a time ([`figcraft_render::Steps`]): at least one /// band a frame, and more while they fit in this long, so input is handled while it draws. A @@ -481,10 +481,19 @@ impl Worker { break; } ctx.request_repaint_of(viewport); - // A newer request makes refining this one moot: it gets its own preview. - if let Ok(newer) = jobs.try_recv() { - next = Some(newer); - continue; + // A newer request makes refining this one moot: it gets its own preview. Wait + // for one as the browser does ([`SETTLE_MS`], or the last full render's time + // when shorter): a full render can't be stopped, so one started between two + // steps of a zoom held every later step up for as long as it took. + let wait = std::time::Duration::try_from_secs_f64(renders.full_ms_so_far() / 1000.0) + .map_or(std::time::Duration::ZERO, |full| full.min(std::time::Duration::from_millis(SETTLE_MS))); + match jobs.recv_timeout(wait) { + Ok(newer) => { + next = Some(newer); + continue; + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, } } if renders.wants_late_preview(&job) { diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index bb36c0aae..bef17fe59 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -405,6 +405,34 @@ fn a_slow_first_render_gets_a_preview_beside_it_and_a_quick_one_none() { assert_eq!(drain(&mut w), [(1, false)], "done before the threshold: no preview"); } +#[test] +fn the_render_thread_refines_a_zoom_only_once_it_pauses() { + // A full render can't be stopped: a zoom step's started as soon as its preview was out held the + // next step up for as long as it took. The next step coming while the preview shows skips it. + let views: Vec = [1.0, 0.5, 0.25].into_iter().map(|s| view_at((300.0, 200.0), s, 1200, 1200)).collect(); + let s = slow_scene(&views, 4.0 * PREVIEW_AFTER_MS); + let ds = s.ds().unwrap(); + let at = |i: usize| job(&ds.doc, ds.page, ds.uid, views[i].clone()); + let mut w = Worker::new(egui::Context::default()); + w.submit(at(0)); + drain(&mut w); + // A zoom out: its preview, then the next step while that preview is on screen. + w.submit(at(1)); + let start = std::time::Instant::now(); + let preview = loop { + assert!(start.elapsed() < Duration::from_secs(60), "no preview came"); + if let Some(d) = w.poll() { + break d; + } + std::thread::sleep(Duration::from_millis(1)); + }; + assert_eq!((preview.seq, preview.coarse), (2, true)); + w.submit(at(2)); + let got = drain(&mut w); + assert!(!got.contains(&(2, false)), "the step zoomed past is never refined: {got:?}"); + assert_eq!(got.last(), Some(&(3, false)), "the last step is: {got:?}"); +} + #[test] fn a_preview_replaces_a_refined_image_of_the_same_zoom_elsewhere_on_the_page() { // 800 × 600: A at 100% from the page origin, B at 800% about its top-left, A' back at 100% diff --git a/docs/gaps.md b/docs/gaps.md index 66ac5bb9f..30d4e2304 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -306,6 +306,12 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe write lock, went from about 45 µs to 0.2 µs (the lookup logic timed alone). The faces drawn are those drawn before, except where two are equally near the run's style (the one read already is kept) and for Hiragino's W3-style names (read as their weight). +- **Landed (2026-11-17):** the desktop's render thread waits the same way after a zoom's preview + (`SETTLE_MS`, or the last full render's time when shorter) before refining it. A full render + there can't be stopped, so one started between two steps of a held zoom made every later step + wait for it: on a 29,000 × 12,600 page of 9,000 layers with images and shadows (M1 Pro, 2x + display) full renders took 110–520 ms, and the preview stood in for that long. Pans and edits are + refined at once, as before. - **Landed (2026-10-28):** the browser refines a zoom's preview only once no newer request has come for 120 ms (`SETTLE_MS`), or for as long as its last full render took when that is shorter: its full renders run on the UI thread, and one between every two wheel steps held the page up @@ -595,6 +601,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Gap 7: the desktop refines a zoom's preview only once the zoom has paused, as the browser does, so a full render that can't be stopped no longer holds up the next steps of a held zoom. Numbers unchanged. Test: `zoom_preview_tests::the_render_thread_refines_a_zoom_only_once_it_pauses` | | 2026-11-12 | minor | Gap 1: the `.fig` export writes vector region paints (#2302); the 2026-10-26 "Landed" bullet no longer says the export drops them | | 2026-11-10 | minor | Gap 13: a boolean group's corner radius rounds every sharp corner of its result (#2222); the boolean clause leaves the 2026-10-12 "Left" list | | 2026-11-10 | minor | Gap 24: mind maps, first step (`board.mindMap`, `board.mindMapAdd`; the map lays itself out again after every edit, #2226); the toolbar entry, shortcuts, drag to re-parent and `.jam` import are what is missing of them. | From 87e43cccf0d059415b7c5e22842d29a3ae8001f1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:22:16 -0500 Subject: [PATCH 062/129] format: write Penpot containers through shared incremental writer --- Cargo.lock | 22 +++++++++++++++ Cargo.toml | 3 ++ crates/format/Cargo.toml | 1 + crates/format/src/penpot/export.rs | 35 +++++++++--------------- crates/format/src/penpot/export_tests.rs | 16 +++++++++++ 5 files changed, 55 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d6d010579..07e4fa1b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1131,6 +1131,17 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-penpot" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e#f7c87b3b3a90fffd44b4a414acee966e66cb006e" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e)", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-quit" version = "0.1.0" @@ -1265,6 +1276,16 @@ dependencies = [ "zip 9.1.1", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e#f7c87b3b3a90fffd44b4a414acee966e66cb006e" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -2017,6 +2038,7 @@ dependencies = [ "craft-fig", "craft-figcraft-format", "craft-figma-rest", + "craft-penpot", "figcraft-doc", "figcraft-layout", "figcraft-pathops", diff --git a/Cargo.toml b/Cargo.toml index 05aa2d393..75995debf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,9 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae # Where the settings live: the suite's folder rules, portable mode included (craft-libs). craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } +# Penpot export container only; JSON values cross this boundary, not shared model types. +craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "f7c87b3b3a90fffd44b4a414acee966e66cb006e" } + # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share # types, so they stay on one rev; they share none with the crates above. diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 9424b95e0..46869824c 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -20,6 +20,7 @@ ruzstd = { workspace = true } sha1 = { workspace = true } sha2 = { workspace = true } image = { workspace = true } +craft-penpot = { workspace = true } craft-fig = { workspace = true } craft-figcraft-format = { workspace = true } craft-figma-rest = { workspace = true } diff --git a/crates/format/src/penpot/export.rs b/crates/format/src/penpot/export.rs index d0b9d3046..10811022a 100644 --- a/crates/format/src/penpot/export.rs +++ b/crates/format/src/penpot/export.rs @@ -1,5 +1,4 @@ use std::collections::{BTreeMap, BTreeSet}; -use std::io::{Cursor, Write}; use figcraft_doc::color::{BlendMode, Color, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind}; use figcraft_doc::geom::kurbo::PathEl; @@ -13,7 +12,7 @@ use figcraft_doc::{ use serde_json::{Map, Value, json}; use super::{ROOT_ID, fingerprint, layout_fingerprint, strokes_fingerprint, text_fingerprint, tokens_fingerprint, uuid}; -use crate::{FormatError, io_err, json_options}; +use crate::{FormatError, io_err}; const DEFAULT_FEATURES: &[&str] = &["fdata/path-data", "design-tokens/v1", "variants/v1", "layout/grid", "components/v2", "fdata/shape-data-type"]; @@ -565,27 +564,19 @@ impl<'a> Exporter<'a> { "files": [{"id": self.file_id, "name": name, "features": file.get("features").cloned().unwrap_or(Value::Null)}], "relations": [], }); - let mut buf = Cursor::new(Vec::new()); - { - let mut z = zip::ZipWriter::new(&mut buf); - let mut put = |path: &str, bytes: &[u8]| -> Result<(), FormatError> { - z.start_file(path, json_options()).map_err(io_err)?; - z.write_all(bytes).map_err(io_err) - }; - put("manifest.json", &serde_json::to_vec_pretty(&manifest).map_err(io_err)?)?; - put(&format!("{base}.json"), &serde_json::to_vec_pretty(&file).map_err(io_err)?)?; - if let Some(tokens) = tokens { - put(&format!("{base}/tokens.json"), tokens.as_bytes())?; - } - for (path, value) in &entries { - put(path, &serde_json::to_vec_pretty(value).map_err(io_err)?)?; - } - for (path, bytes) in &blobs { - put(path, bytes)?; - } - z.finish().map_err(io_err)?; + let mut writer = craft_penpot::Writer::new(); + writer.add("manifest.json", &serde_json::to_vec_pretty(&manifest).map_err(io_err)?).map_err(io_err)?; + writer.add(&format!("{base}.json"), &serde_json::to_vec_pretty(&file).map_err(io_err)?).map_err(io_err)?; + if let Some(tokens) = tokens { + writer.add(&format!("{base}/tokens.json"), tokens.as_bytes()).map_err(io_err)?; } - Ok((buf.into_inner(), self.warnings)) + for (path, value) in &entries { + writer.add(path, &serde_json::to_vec_pretty(value).map_err(io_err)?).map_err(io_err)?; + } + for (path, bytes) in &blobs { + writer.add(path, bytes).map_err(io_err)?; + } + Ok((writer.finish().map_err(io_err)?, self.warnings)) } fn page_json(&self, page: NodeId, page_id: &str, index: usize, background: Color) -> Value { diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index 1e9e95638..e3ad744ef 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -1027,3 +1027,19 @@ fn stored_variable_ids_keep_penpot_token_identity() { assert_eq!(width, &expected); } } + +#[test] +fn shared_writer_keeps_manifest_first_and_deflated_members() { + let doc = Document::new("Shared container"); + let (bytes, _) = export(&doc).unwrap(); + let mut zip = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + assert_eq!(zip.by_index(0).unwrap().name(), "manifest.json"); + for index in 0..zip.len() { + assert_eq!(zip.by_index(index).unwrap().compression(), zip::CompressionMethod::Deflated); + } + let archive = craft_penpot::Archive::open(&bytes).unwrap(); + assert_eq!(archive.files.len(), 1); + assert_eq!(archive.files[0].name.as_deref(), Some("Shared container")); + assert_eq!(archive.manifest["generatedBy"], format!("figcraft/{}", env!("CARGO_PKG_VERSION"))); + assert!(import(&bytes).is_ok()); +} From 26fa159c0c7771095df4e963736ec994bdda480c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:24:19 -0500 Subject: [PATCH 063/129] deps: pin documented Penpot writer error contract --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 07e4fa1b4..8adab0b43 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1134,9 +1134,9 @@ dependencies = [ [[package]] name = "craft-penpot" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e#f7c87b3b3a90fffd44b4a414acee966e66cb006e" +source = "git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3#8418f9a9e846d27bb4f5e854f370405fd013e9e3" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3)", "serde", "serde_json", "thiserror 2.0.21", @@ -1279,7 +1279,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f7c87b3b3a90fffd44b4a414acee966e66cb006e#f7c87b3b3a90fffd44b4a414acee966e66cb006e" +source = "git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3#8418f9a9e846d27bb4f5e854f370405fd013e9e3" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 75995debf..ac3aedee2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,7 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } # Penpot export container only; JSON values cross this boundary, not shared model types. -craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "f7c87b3b3a90fffd44b4a414acee966e66cb006e" } +craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "8418f9a9e846d27bb4f5e854f370405fd013e9e3" } # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share From 931a1467b20eac928fae2f293c0413c606af55fa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:50:31 -0500 Subject: [PATCH 064/129] fix(format): retain Cursor import for embedded Penpot PNG encoding --- crates/format/src/penpot/export.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/format/src/penpot/export.rs b/crates/format/src/penpot/export.rs index 10811022a..071809cab 100644 --- a/crates/format/src/penpot/export.rs +++ b/crates/format/src/penpot/export.rs @@ -1,4 +1,5 @@ use std::collections::{BTreeMap, BTreeSet}; +use std::io::Cursor; use figcraft_doc::color::{BlendMode, Color, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind}; use figcraft_doc::geom::kurbo::PathEl; From 6963e0d5ce7d08c1166f947cff750aebfd74ec24 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:58:13 -0500 Subject: [PATCH 065/129] Use shared Sketch container while retaining Fig document projection (#2418) --- Cargo.lock | 37 +++++- Cargo.toml | 1 + crates/format/Cargo.toml | 1 + crates/format/src/sketch.rs | 184 ++---------------------------- crates/format/src/sketch/tests.rs | 18 +++ 5 files changed, 67 insertions(+), 174 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d6d010579..083d59554 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1016,7 +1016,7 @@ name = "craft-fig" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" dependencies = [ - "craft-figma-rest", + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", "craft-kiwi", "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", "flate2", @@ -1048,6 +1048,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-figma-rest" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-font-catalog" version = "0.1.0" @@ -1153,6 +1163,18 @@ dependencies = [ "toml_edit", ] +[[package]] +name = "craft-sketch" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd)", + "kurbo", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1265,6 +1287,16 @@ dependencies = [ "zip 9.1.1", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -2016,7 +2048,8 @@ version = "0.18.1" dependencies = [ "craft-fig", "craft-figcraft-format", - "craft-figma-rest", + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", + "craft-sketch", "figcraft-doc", "figcraft-layout", "figcraft-pathops", diff --git a/Cargo.toml b/Cargo.toml index 05aa2d393..57cc46f7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,6 +61,7 @@ craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9 # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share # types, so they stay on one rev; they share none with the crates above. +craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd" } craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "976eb51c59edb0a37f24105850f52d921c8518ee" } craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 9424b95e0..b5673119d 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -20,6 +20,7 @@ ruzstd = { workspace = true } sha1 = { workspace = true } sha2 = { workspace = true } image = { workspace = true } +craft-sketch = { workspace = true } craft-fig = { workspace = true } craft-figcraft-format = { workspace = true } craft-figma-rest = { workspace = true } diff --git a/crates/format/src/sketch.rs b/crates/format/src/sketch.rs index 182447015..2389813bb 100644 --- a/crates/format/src/sketch.rs +++ b/crates/format/src/sketch.rs @@ -43,48 +43,15 @@ mod tree_tests; use std::collections::BTreeSet; use figcraft_doc::Document; -use serde_json::{Value, json}; +use serde_json::Value; + +// Container parsing is shared; FigCraft document projection remains in this module. +pub(crate) use craft_sketch::Archive; use crate::FormatError; -/// The oldest Sketch whose files open: from 48 on, text is plain JSON too. -pub const MIN_SKETCH: u32 = 48; -/// The newest `meta.json` format version checked against real files (Sketch 83); newer files -/// open with a warning. -pub const NEWEST_TESTED_VERSION: u64 = 139; -/// What opening a file saved by an older Sketch says. -pub const TOO_OLD: &str = "saved by a Sketch older than 48; open it in a newer Sketch and save it again"; -/// Largest JSON member read (a real page of a few thousand layers takes 33 MB). -const MAX_JSON_MEMBER: u64 = 512 * 1024 * 1024; -/// Most bytes a member may unpack to, per compressed byte (real JSON packs 5–20 times and images -/// barely; a zero-filled member a thousand times), with a floor for small members. -const MAX_RATIO: u64 = 100; -const MIN_ALLOWANCE: u64 = 16 * 1024 * 1024; -/// Most JSON read from one file in all. -#[cfg(not(target_pointer_width = "32"))] -const MAX_JSON_TOTAL: u64 = 2 * 1024 * 1024 * 1024; -#[cfg(target_pointer_width = "32")] -const MAX_JSON_TOTAL: u64 = 512 * 1024 * 1024; -/// Largest image member read. -const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES; -/// Most image bytes read from one file in all. -#[cfg(not(target_pointer_width = "32"))] -const MAX_IMAGE_TOTAL: u64 = 1024 * 1024 * 1024; -#[cfg(target_pointer_width = "32")] -const MAX_IMAGE_TOTAL: u64 = 256 * 1024 * 1024; -/// Most pages read from one file. -const MAX_PAGES: usize = 1000; - -/// Whether `bytes` look like a `.sketch` file: a zip holding `document.json` and `meta.json`, or -/// the SQLite database Sketch wrote before version 43 (so that it gets the "too old" message). -pub fn is_sketch(bytes: &[u8]) -> bool { - bytes.starts_with(b"SQLite format 3\0") - || (bytes.starts_with(b"PK") - && zip::ZipArchive::new(std::io::Cursor::new(bytes)).is_ok_and(|z| { - let names: BTreeSet<&str> = z.file_names().collect(); - names.contains("document.json") && names.contains("meta.json") - })) -} +pub use craft_sketch::{MIN_SKETCH, NEWEST_TESTED_VERSION, TOO_OLD, is_sketch}; +const MAX_JSON_MEMBER: u64 = craft_sketch::MAX_JSON_MEMBER; /// Finds the installed face a PostScript name belongs to: its family and style. pub type FontLookup = Box Option<(String, String)>>; @@ -133,7 +100,12 @@ fn import_parts( if bytes.starts_with(b"SQLite format 3\0") { return Err(FormatError::Io(TOO_OLD.into())); } - let archive = Archive::open(bytes, max_member)?; + let archive = + Archive::open_with(bytes, craft_sketch::Limits { max_page: max_member, max_image: figcraft_doc::ImageData::MAX_BYTES, ..Default::default() }) + .map_err(|error| match error { + craft_sketch::Error::TooOld => FormatError::Io(TOO_OLD.into()), + craft_sketch::Error::Corrupt(message) => FormatError::Corrupt(format!("Sketch file: {message}")), + })?; let map = tree::to_rest(&archive, name, max_nodes, fonts); if map.too_old { return Err(FormatError::Io(TOO_OLD.into())); @@ -172,135 +144,3 @@ fn embedded_fonts(document: &Value) -> Option { let list: Vec<&str> = families.iter().map(String::as_str).collect(); Some(format!("the file has embedded fonts FigCraft doesn't use ({}); install them to see the text as designed", list.join(", "))) } - -fn corrupt(msg: impl Into) -> FormatError { - FormatError::Corrupt(format!("Sketch file: {}", msg.into())) -} - -/// The parts of a `.sketch` archive: the document, the pages in document order and the images. -pub(crate) struct Archive<'b> { - pub document: Value, - /// `meta.json`'s format version (0 when missing). - pub version: u64, - /// `(id, page JSON)` in the document's order. - pub pages: Vec<(String, Value)>, - /// Problems met while reading (pages skipped). - pub warnings: Vec, - zip: zip::ZipArchive>, - /// Image bytes read so far. - image_total: std::cell::Cell, -} - -impl<'b> Archive<'b> { - fn open(bytes: &'b [u8], max_member: u64) -> Result { - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| corrupt(e.to_string()))?; - let mut total = 0u64; - let meta = json_member(&mut z, "meta.json", MAX_JSON_MEMBER, &mut total)?; - if !meta.is_object() { - return Err(corrupt("meta.json is not an object")); - } - if app_major(&meta).is_some_and(|v| v < MIN_SKETCH) { - return Err(FormatError::Io(TOO_OLD.into())); - } - let mut warnings = Vec::new(); - if meta.get("version").and_then(Value::as_u64).is_some_and(|v| v > NEWEST_TESTED_VERSION) { - warnings.push("the file was saved by a newer Sketch than the import was checked with; some layers may differ".to_string()); - } - // A document.json that can't be read (nested too deep, damaged) loses its shared styles and - // library copies, not the pages: they are then taken in archive order. - let document = match json_member(&mut z, "document.json", MAX_JSON_MEMBER, &mut total) { - Ok(d) if d.is_object() => d, - other => { - let why = other.err().map_or_else(|| "not an object".to_string(), |e| e.to_string()); - warnings.push(format!( - "the document's shared styles and library symbols were skipped: {}", - why.trim_start_matches("not a valid FigCraft file: ") - )); - let pages: Vec = z - .file_names() - .filter_map(|n| n.strip_prefix("pages/")?.strip_suffix(".json")) - .map(|id| json!({"_ref": format!("pages/{id}")})) - .collect(); - json!({"pages": pages}) - } - }; - let refs = document.get("pages").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); - let mut pages = Vec::new(); - let mut seen = std::collections::HashSet::new(); - for r in refs.iter().take(MAX_PAGES) { - let Some(id) = r.get("_ref").and_then(Value::as_str).and_then(|s| s.strip_prefix("pages/")).filter(|id| valid_id(id)) else { - warnings.push("pages the document lists without a valid reference were skipped".into()); - continue; - }; - // A page listed twice is read once: a repeated reference must not repeat the unpacking. - if !seen.insert(id) { - continue; - } - match json_member(&mut z, &format!("pages/{id}.json"), max_member, &mut total) { - Ok(page) if page.is_object() => pages.push((id.to_string(), page)), - Ok(_) => warnings.push("pages that aren't JSON objects were skipped".into()), - Err(e) => warnings.push(format!("a page was skipped: {}", e.to_string().trim_start_matches("not a valid FigCraft file: "))), - } - } - if refs.len() > MAX_PAGES { - warnings.push(format!("the file has more than {MAX_PAGES} pages; the rest were skipped")); - } - let version = meta.get("version").and_then(Value::as_u64).unwrap_or(0); - Ok(Archive { document, version, pages, warnings, zip: z, image_total: std::cell::Cell::new(0) }) - } - - /// The bytes of the image a layer references (`images/`). - pub(crate) fn image(&self, r: &str) -> Option> { - let name = r.strip_prefix("images/").unwrap_or(r); - if !valid_id(name.split('.').next().unwrap_or("")) || name.split('.').count() > 2 { - return None; - } - // A clone shares the parsed directory and the bytes; the resolver only has shared access. - let mut z = self.zip.clone(); - let mut total = self.image_total.get(); - let data = capped_member(&mut z, &format!("images/{name}"), MAX_IMAGE, &mut total, MAX_IMAGE_TOTAL).ok(); - self.image_total.set(total); - data - } -} - -/// Member `name`, refused before unpacking when it would be larger than `limit`, than -/// [`MAX_RATIO`] times what it takes in the archive (past a floor), or than what is left of -/// `max_total` (`total`: read so far, counted up). -fn capped_member( - z: &mut zip::ZipArchive>, - name: &str, - limit: u64, - total: &mut u64, - max_total: u64, -) -> Result, FormatError> { - let (size, packed) = { - let f = z.by_name(name).map_err(|e| corrupt(format!("{name}: {e}")))?; - (f.size(), f.compressed_size()) - }; - let allowed = limit.min(packed.saturating_mul(MAX_RATIO).max(MIN_ALLOWANCE)).min(max_total.saturating_sub(*total)); - if size > allowed { - return Err(corrupt(format!("{name} is too large"))); - } - let data = crate::read_member(z, name, allowed); - // A failed read (a bad checksum at the end, say) unpacked all the same: charged in full, so - // a page list naming the member again can't repeat it within the budget. - *total += data.as_ref().map_or(size, |d| d.len() as u64); - data -} - -/// JSON member `name`, read by [`capped_member`] within the file's [`MAX_JSON_TOTAL`]. -fn json_member(z: &mut zip::ZipArchive>, name: &str, limit: u64, total: &mut u64) -> Result { - let data = capped_member(z, name, limit, total, MAX_JSON_TOTAL)?; - serde_json::from_slice(&data).map_err(|e| corrupt(format!("{name}: {e}"))) -} - -/// The major version of the Sketch that saved the file (`meta.json` `appVersion`, "50.2" → 50). -fn app_major(meta: &Value) -> Option { - meta.get("appVersion").and_then(Value::as_str)?.split('.').next()?.trim().parse().ok() -} - -/// Ids name archive members: letters, digits, `-` and `_` only, never a path. -fn valid_id(id: &str) -> bool { - !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') -} diff --git a/crates/format/src/sketch/tests.rs b/crates/format/src/sketch/tests.rs index d8ace8be9..784c542bd 100644 --- a/crates/format/src/sketch/tests.rs +++ b/crates/format/src/sketch/tests.rs @@ -206,3 +206,21 @@ fn members_over_budget_are_skipped() { assert!(warnings.iter().any(|w| w.contains("too large")), "{warnings:?}"); assert!(!page_names(&doc).contains(&"Big".to_string())); } + +/// The shared container refuses ambiguous member names instead of selecting one silently. +#[test] +fn duplicate_archive_members_are_refused() { + let mut z = sketch_zip("50.2", 103, document(&["A", "B"]), &[page("A", "Alpha", vec![]), page("B", "Beta", vec![])], &[]); + let from = b"pages/B.json"; + let to = b"pages/A.json"; + let mut replaced = 0; + for i in 0..z.len().saturating_sub(from.len()).saturating_add(1) { + if z.get(i..i + from.len()) == Some(from.as_slice()) { + z[i..i + from.len()].copy_from_slice(to); + replaced += 1; + } + } + assert_eq!(replaced, 2, "local and central directory names changed"); + let error = import(&z, "ambiguous").unwrap_err().to_string(); + assert!(error.contains("two entries of the archive share a name"), "{error}"); +} From be44cb1ab6a35a61c3ef369489768d84b04fad65 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:58:17 -0500 Subject: [PATCH 066/129] docs: prefer craft-libs for reusable formats, codecs, protocols and UI (#2408) --- AGENTS.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index e63e92c7c..cc4ea91e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,7 @@ inspection. It runs natively on macOS, Windows, Linux and FreeBSD, and in the br Siblings: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop-class), `../designcraft` (InDesign-class) and the other Crafting Apps; same conventions. -Repos don't share code. +Share reusable code through craft-libs; do not depend on sibling application crates. ## Start every session here 1. Read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, estimates) and @@ -182,3 +182,7 @@ commit. Grade by behaviour against the incumbent, not by whether a menu item exi - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +## Shared Craft libraries + +Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage. From 954687fcf7c15fdb94d5343d72be95c5832e4710 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:58:22 -0500 Subject: [PATCH 067/129] ci: lock workflow actions through an actions.lock lockfile (#2300) --- .github/workflows/actions.lock | 29 ++++++++++++++++++++++++ .github/workflows/lockfile.yml | 34 ++++++++++++++++++++++++++++ .github/workflows/packaging-lint.yml | 4 ++-- sonar-project.properties | 10 +++++++- 4 files changed, 74 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/actions.lock create mode 100644 .github/workflows/lockfile.yml diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 000000000..6917bde73 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,29 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/ci.yml': [] + '.github/workflows/freebsd.yml': [] + '.github/workflows/house-rules.yml': [] + '.github/workflows/lockfile.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nix.yml': [] + '.github/workflows/packaging-lint.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/release.yml': [] + '.github/workflows/sonarcloud.yml': [] + '.github/workflows/windows-arm64.yml': [] +dependencies: + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'step-security/harden-runner@v2.22.4': + ref: 'v2.22.4' + commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' + owner_id: 88700172 + repo_id: 422287306 diff --git a/.github/workflows/lockfile.yml b/.github/workflows/lockfile.yml new file mode 100644 index 000000000..e630c9a8f --- /dev/null +++ b/.github/workflows/lockfile.yml @@ -0,0 +1,34 @@ +name: Lockfile + +# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin +# no longer verifies upstream, so a moved tag cannot slip a different commit into a run. +# Docs: https://gh.io/actions-lockfile +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + GH_TOKEN: ${{ github.token }} + +jobs: + lockfile: + name: Lockfile is in sync + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Install gh-actions-lock + run: gh extension install github/gh-actions-lock --pin v0.4.1 + - name: Verify the lockfile + run: gh actions-lock --verify diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 0a91cc050..f442059bb 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -30,10 +30,10 @@ jobs: runs-on: windows-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Install the pinned packaging toolchain diff --git a/sonar-project.properties b/sonar-project.properties index 7bd9e8ce6..8c36accaf 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -6,6 +6,14 @@ sonar.exclusions=craft-fonts/** # S4790 (weak hash): a .fig file names each image by the SHA-1 of its bytes (20 bytes, the only # length readers accept). It is an identifier the format fixes, not a security choice. -sonar.issue.ignore.multicriteria=fig_image_sha1 +sonar.issue.ignore.multicriteria=fig_image_sha1,gha-lockfile sonar.issue.ignore.multicriteria.fig_image_sha1.ruleKey=rust:S4790 sonar.issue.ignore.multicriteria.fig_image_sha1.resourceKey=crates/format/src/fig/export.rs + +# githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by +# .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned +# and the lockfile covers the actions those actions use too. Sonar does not read lockfiles yet, so +# the rule flags the tag refs anyway: +# https://community.sonarsource.com/t/githubactions-s7637-false-positives-for-actions-pinned-through-native-actions-lock/190814 +sonar.issue.ignore.multicriteria.gha-lockfile.ruleKey=githubactions:S7637 +sonar.issue.ignore.multicriteria.gha-lockfile.resourceKey=.github/workflows/** From 5ee60ec708201fe93b44ea5dacbce49b96b3598e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:01:33 -0500 Subject: [PATCH 068/129] fix(format): keep legacy ZIP options only for remaining test fixture --- crates/format/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 167444c62..1c246bb89 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -47,6 +47,7 @@ pub use craft_figcraft_format::{ MAX_VERSION_INDEX, MAX_VERSION_NAME, MAX_VERSIONS, ReadBudget, VERSION, VersionEntry as NativeVersionEntry, VersionIndex as NativeVersionIndex, clip, document_limit, is_valid_version_id, }; +#[cfg(test)] const JSON_LEVEL: i64 = 3; /// The export warning for colour calculations that resolve to nothing (an operand missing, or more /// than 32 variables to read), shared by the Penpot and `.fig` exports. @@ -411,7 +412,8 @@ pub(crate) fn io_err(e: impl std::fmt::Display) -> FormatError { FormatError::Io(e.to_string()) } -/// JSON compression for Penpot and external ZIP exporters. +/// JSON compression for legacy Penpot test fixtures. +#[cfg(test)] pub(crate) fn json_options() -> zip::write::SimpleFileOptions { zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).compression_level(Some(JSON_LEVEL)) } From 4aae3f2733a3fb1e42c80ab5ba81730a4a55339e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:11:07 -0500 Subject: [PATCH 069/129] chore(penpot): pin merged writer and canonicalize lock order --- Cargo.lock | 24 ++++++++++++------------ Cargo.toml | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 77abcfa01..879856783 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1144,9 +1144,9 @@ dependencies = [ [[package]] name = "craft-penpot" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3#8418f9a9e846d27bb4f5e854f370405fd013e9e3" +source = "git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a#064afccce82b01cbf85da5e265bcf897553bea2a" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a)", "serde", "serde_json", "thiserror 2.0.21", @@ -1278,6 +1278,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a#064afccce82b01cbf85da5e265bcf897553bea2a" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -1298,16 +1308,6 @@ dependencies = [ "zip 9.1.1", ] -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8418f9a9e846d27bb4f5e854f370405fd013e9e3#8418f9a9e846d27bb4f5e854f370405fd013e9e3" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip 9.1.1", -] - [[package]] name = "craft-zip" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index dd33c406c..82831e556 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,7 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } # Penpot export container only; JSON values cross this boundary, not shared model types. -craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "8418f9a9e846d27bb4f5e854f370405fd013e9e3" } +craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "064afccce82b01cbf85da5e265bcf897553bea2a" } # The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of # a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share From e9a47777362739b2ce634310c599f9f81aa24cad Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 17 Nov 2026 06:15:50 +0100 Subject: [PATCH 070/129] Keep library variables that styles bind when accepting updates Fixes #2416 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/assets/library.rs | 4 +- crates/engine/src/library_variables_tests.rs | 52 ++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 2fb64a26d..785e6c748 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -1158,10 +1158,12 @@ pub fn prune(doc: &mut Document, library: &str) -> Result<()> { doc.styles.retain(|s| !unused.contains(&s.id)); doc.libraries_mut().styles.retain(|r| !unused.contains(&r.local)); } - // Variables layers bind or set, local variables alias or extend (with what those alias). + // Variables layers bind or set, styles bind, local variables alias or extend (with what those + // alias). let seeds = doc .nodes() .flat_map(|n| n.bound.values().map(String::as_str).chain(action_variables(n))) + .chain(doc.styles.iter().flat_map(|s| s.bound.values().map(String::as_str))) .chain(doc.variables.variables.iter().filter_map(|v| v.extends.as_deref())) .map(str::to_string) .chain( diff --git a/crates/engine/src/library_variables_tests.rs b/crates/engine/src/library_variables_tests.rs index bc82f7a94..67a2b2129 100644 --- a/crates/engine/src/library_variables_tests.rs +++ b/crates/engine/src/library_variables_tests.rs @@ -550,3 +550,55 @@ fn stored_variable_ids_keep_library_alias_dependencies() { assert!(copy.values.values().all(|v| *v == VariableValue::Alias(map.variables[target].clone()))); assert!(dest.variables.collections.iter().any(|c| c.name == "Base")); } + +/// A library with collection `coll` (Main/Alt), a colour variable `var` and a paint style `var` +/// bound to it, published to `path`; returns (the library session, its id). +fn styled_library(path: &str, coll: &str, var: &str, main: &str, alt: &str) -> (Session, String) { + let mut lib = Session::new(); + ex(&mut lib, "variable.createCollection", json!({"name": coll, "modes": ["Main", "Alt"]})); + let v = ex(&mut lib, "variable.create", json!({"collection": coll, "name": var, "type": "color", "values": {"Main": main, "Alt": alt}}))["id"] + .clone(); + let style = ex(&mut lib, "style.create", json!({"type": "paint", "name": var, "value": main}))["id"].clone(); + ex(&mut lib, "style.bind", json!({"style": style, "field": "fill", "variable": v})); + let lid = publish_to(&mut lib, path); + (lib, lid) +} + +#[test] +fn accepting_updates_keeps_variables_only_library_styles_use() { + let d = dir("accept-style-vars"); + let (pa, pb) = (path_str(&d.join("a.figcraft")), path_str(&d.join("b.figcraft"))); + let (mut a, la) = styled_library(&pa, "TokensA", "accent", "#1565c0", "#2e7d32"); + let (_b, lb) = styled_library(&pb, "TokensB", "primary", "#7b1fa2", "#00838f"); + + let mut s = Session::new(); + let frame = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 200}))); + let ra = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20, "parent": frame}))); + let rb = idv(&ex(&mut s, "shape.rectangle", json!({"x": 50, "y": 10, "width": 20, "height": 20, "parent": frame}))); + ex(&mut s, "library.add", json!({"path": pa})); + ex(&mut s, "library.add", json!({"path": pb})); + ex(&mut s, "library.applyStyle", json!({"library": la, "style": "accent", "id": ra})); + ex(&mut s, "library.applyStyle", json!({"library": lb, "style": "primary", "id": rb})); + ex(&mut s, "library.setVariableMode", json!({"library": la, "collection": "TokensA", "mode": "Alt", "ids": [frame]})); + ex(&mut s, "library.setVariableMode", json!({"library": lb, "collection": "TokensB", "mode": "Alt", "ids": [frame]})); + assert_eq!(fill(&s, ra), "2E7D32"); + assert_eq!(fill(&s, rb), "00838F"); + healthy(&s); + + ex(&mut a, "variable.set", json!({"variable": "accent", "mode": "Alt", "value": "#ef6c00"})); + republish(&mut a); + let r = ex(&mut s, "library.acceptUpdates", json!({})); + assert_eq!(r["variables"], 1, "{r}"); + + let doc = s.doc().unwrap(); + for name in ["accent", "primary"] { + let v = doc.variables.variables.iter().find(|v| v.name == name && is_remote_variable(doc, &v.id)); + assert!(v.is_some(), "library variable copy `{name}` was deleted"); + let id = &v.unwrap().id; + assert!(doc.libraries.variables.iter().any(|r| &r.local == id), "record of `{name}` was deleted"); + } + assert_eq!(fill(&s, ra), "EF6C00"); + assert_eq!(fill(&s, rb), "00838F"); + healthy(&s); + let _ = std::fs::remove_dir_all(&d); +} From 3c9293022491c8687747053dcc2d1f892890a866 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 17 Nov 2026 17:14:57 +0700 Subject: [PATCH 071/129] M8: the strips a pan uncovers render in parallel bands, as full renders do --- crates/render/src/band_tests.rs | 51 +++++++++++++++++++++++ crates/render/src/lib.rs | 54 ++++++++++++++++++++++++ crates/render/src/pan_bench_tests.rs | 62 ++++++++++++++++++++++++++++ crates/render/src/retained.rs | 2 +- docs/gaps.md | 11 ++++- 5 files changed, 178 insertions(+), 2 deletions(-) create mode 100644 crates/render/src/pan_bench_tests.rs diff --git a/crates/render/src/band_tests.rs b/crates/render/src/band_tests.rs index 6cdf2cd88..5af2f353f 100644 --- a/crates/render/src/band_tests.rs +++ b/crates/render/src/band_tests.rs @@ -163,3 +163,54 @@ fn huge_backdrop_blur_renders_in_one_piece() { assert!(render_bands(&d, p, &view(1.0), &Options::default(), 4).is_none()); assert!(render_view(&d, p, &view(1.0), &Options::default()).is_some()); } + +/// [`row_diffs`] down the columns: an artifact of column bands runs down a whole column. +fn col_diffs(a: &Pixmap, b: &Pixmap) -> Vec<(f64, usize)> { + let (w, h) = (a.width() as usize, a.height() as usize); + let column = |p: &Pixmap, x: usize| -> Vec { (0..h).flat_map(|y| p.data()[(y * w + x) * 4..(y * w + x) * 4 + 4].to_vec()).collect() }; + (0..w).map(|x| row_stats(&column(a, x), &column(b, x))).collect() +} + +#[test] +fn columns_match_one_piece_rendering() { + let (d, p) = scene(true, true); + for scale in [1.0, 2.0] { + let v = view(scale); + let one = render_view_single(&d, p, &v, &Options::default()).unwrap(); + for bands in [2, 3, 7] { + let banded = render_columns(&d, p, &v, &Options::default(), bands).unwrap(); + assert_eq!((banded.width(), banded.height()), (one.width(), one.height())); + for (x, (mean, off)) in col_diffs(&one, &banded).into_iter().enumerate() { + assert!( + row_ok(mean, off, v.height as usize), + "scale {scale}, {bands} columns: column {x} differs ({off} pixels, {mean:.2} on average)" + ); + } + } + } + let (mut d, p) = scene(true, true); + let g = d.find_by_name("Glass", None)[0]; + d.get_mut(g).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(1e6)), visible: true }]; + assert!(render_columns(&d, p, &view(1.0), &Options::default(), 4).is_none(), "a blur past a whole column: in one piece"); +} + +/// The strips a pan uncovers render in bands along their longer side, and match one piece: no row +/// or column where a band's edge shows (a seam differs along all of it). A strip is too narrow for +/// [`row_ok`]'s mean: the edge antialiasing every band render has (a few pixels along a curve) +/// outweighs it there, so this counts the pixels that differ at all. +#[test] +fn a_tall_or_wide_part_of_a_view_matches_one_piece_rendering() { + let (d, p) = scene(true, true); + for (w, h) in [(60, 480), (880, 60), (200, 200)] { + let v = View { origin: (35.0, -10.0), scale: 2.0, width: w, height: h }; + let one = render_view_single(&d, p, &v, &Options::default()).unwrap(); + let part = render_part(&d, p, &v, &Options::default()).unwrap(); + assert_eq!((part.width(), part.height()), (w, h)); + for (y, (_, off)) in row_diffs(&one, &part).into_iter().enumerate() { + assert!(off * 20 <= w as usize, "{w} x {h}: row {y} differs in {off} pixels"); + } + for (x, (_, off)) in col_diffs(&one, &part).into_iter().enumerate() { + assert!(off * 20 <= h as usize, "{w} x {h}: column {x} differs in {off} pixels"); + } + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6700fbc72..8d0710cda 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -138,6 +138,58 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) -> render_one(doc, page, view, opts) } +/// [`render_view`] for a part of a view a retained render redraws (the strips a pan uncovers, the +/// area of an edit): in parallel bands however few pixels it has, along its longer side (rows of a +/// tall strip, columns of a wide one), since what it costs is the layers it crosses (a shadow is +/// drawn whole for a sliver of it), not its pixels. +pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option { + start_render(); + #[cfg(not(target_arch = "wasm32"))] + if let Some(pool) = band_pool() { + let threads = pool.current_num_threads().clamp(1, 16) as u32; + let rendered = if view.height >= view.width { + let bands = threads.min(view.height / 96); + (bands > 1).then(|| pool.install(|| render_bands(doc, page, view, opts, bands))).flatten() + } else { + let bands = threads.min(view.width / 96); + (bands > 1).then(|| pool.install(|| render_columns(doc, page, view, opts, bands))).flatten() + }; + if rendered.is_some() { + return rendered; + } + } + render_one(doc, page, view, opts) +} + +/// [`render_bands`] across: `bands` columns, overlapping by what background blurs read. +#[cfg(not(target_arch = "wasm32"))] +fn render_columns(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option { + use rayon::prelude::*; + let band_w = view.width.div_ceil(bands.max(1)); + let overlap = band_overlap(doc, view, band_w)?; + let s = view.scale.max(1e-9); + let parts: Vec<(u32, Option)> = (0..bands) + .into_par_iter() + .map(|i| { + let x0 = i * band_w; + let w = band_w.min(view.width.saturating_sub(x0)).max(1); + let left = x0.saturating_sub(overlap); + let right = (x0 + w + overlap).min(view.width).max(x0 + w); + let v = + View { origin: (view.origin.0 + f64::from(left) / s, view.origin.1), scale: view.scale, width: right - left, height: view.height }; + let own = tiny_skia::IntRect::from_xywh((x0 - left) as i32, 0, w, view.height.clamp(1, 16_384)); + (x0, render_one(doc, page, &v, opts).zip(own).and_then(|(p, r)| p.clone_rect(r))) + }) + .collect(); + let mut out = new_pixmap(view.width, view.height)?; + let copy = tiny_skia::PixmapPaint { blend_mode: tiny_skia::BlendMode::Source, ..Default::default() }; + for (x0, part) in parts { + let part = part?; + out.draw_pixmap(x0 as i32, 0, part.as_ref(), ©, tiny_skia::Transform::identity(), None); + } + Some(out) +} + /// The stack a thread that renders needs (#1082). A level of the layer tree takes about 6.5 KB of /// stack in a render (6.8 KB in a debug build), so the deepest render [`MAX_EXPORT_DEPTH`] allows, /// pattern sources included, needs about 1.7 MB: more than the 2 MiB threads get by default once @@ -590,6 +642,8 @@ mod mask_bounds_tests; #[cfg(test)] mod paint_behaviour_tests; #[cfg(test)] +mod pan_bench_tests; +#[cfg(test)] mod progressive_tests; #[cfg(test)] mod render_depth_tests; diff --git a/crates/render/src/pan_bench_tests.rs b/crates/render/src/pan_bench_tests.rs new file mode 100644 index 000000000..aca3d60ad --- /dev/null +++ b/crates/render/src/pan_bench_tests.rs @@ -0,0 +1,62 @@ +//! Pan render timings: a page of 60 × 60 cards, each with a drop shadow and an inner shadow, seen +//! at 100% through a 1600 × 1100 device-pixel view. Run in release: +//! `cargo test --release -p figcraft-render --lib pan_render_timings -- --ignored --nocapture`. +//! +//! "full" renders the whole view; "pan" rows go through `Retained` as the canvas does, each step +//! moving the view by `step` device pixels and redrawing only the strips it uncovers. + +use std::sync::Arc; +use std::time::Instant; + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind, Shadow}; + +use crate::{Options, Retained, View, render_view}; + +const STEPS: u32 = 12; + +/// The cards: (document, page). +fn cards() -> (Arc, NodeId) { + let mut d = Document::new("pan bench"); + let p = d.first_page().unwrap(); + for y in 0..60u32 { + for x in 0..60u32 { + let c = d.create(p, NodeKind::Rectangle, "Card", f64::from(x) * 140.0, f64::from(y) * 110.0, 120.0, 90.0).unwrap(); + let n = d.get_mut(c).unwrap(); + n.fills = vec![Paint::solid(Color::new(x as f32 / 60.0, y as f32 / 60.0, 0.7, 1.0))]; + n.corners.radii = [12.0; 4]; + n.effects = vec![ + Effect { kind: EffectKind::DropShadow(Shadow { radius: 18.0, offset: (0.0, 6.0), ..Shadow::default() }), visible: true }, + Effect { kind: EffectKind::InnerShadow(Shadow { radius: 8.0, ..Shadow::default() }), visible: true }, + ]; + } + } + (Arc::new(d), p) +} + +fn view(origin: (f64, f64)) -> View { + View { origin, scale: 1.0, width: 1600, height: 1100 } +} + +#[test] +#[ignore = "timing; run in release with --ignored --nocapture"] +fn pan_render_timings() { + let (d, p) = cards(); + let opts = Options { lod: true, ..Options::default() }; + let t0 = Instant::now(); + for _ in 0..4 { + render_view(&d, p, &view((1000.0, 1000.0)), &opts).unwrap(); + } + println!("full: {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0 / 4.0); + for (name, step) in [("pan right", (60.0, 0.0)), ("pan down", (0.0, 60.0)), ("pan diagonally", (60.0, 24.0)), ("pan right fast", (240.0, 0.0))] { + let mut r = Retained::default(); + let mut at = (1000.0, 1000.0); + r.render(&d, p, &view(at), &opts).unwrap(); + let t0 = Instant::now(); + for _ in 0..STEPS { + at = (at.0 + step.0, at.1 + step.1); + r.render(&d, p, &view(at), &opts).unwrap(); + } + println!("{name} ({:?} px a step): {:.1} ms a step", step, t0.elapsed().as_secs_f64() * 1000.0 / f64::from(STEPS)); + } +} diff --git a/crates/render/src/retained.rs b/crates/render/src/retained.rs index f345e21d6..e8a711fc6 100644 --- a/crates/render/src/retained.rs +++ b/crates/render/src/retained.rs @@ -553,7 +553,7 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) -> let (rw, rh) = (u32::try_from(ex - ox).ok()?, u32::try_from(ey - oy).ok()?); // The same pixel grid as the frame: origin (px + offset) / scale. let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh }; - let part = render_view(doc, page, &sub, opts)?; + let part = crate::render_part(doc, page, &sub, opts)?; let inner = IntRect::from_xywh( i32::try_from(d.x0 - ox).ok()?, i32::try_from(d.y0 - oy).ok()?, diff --git a/docs/gaps.md b/docs/gaps.md index 30d4e2304..584d7f3a0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -312,6 +312,14 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe wait for it: on a 29,000 × 12,600 page of 9,000 layers with images and shadows (M1 Pro, 2x display) full renders took 110–520 ms, and the preview stood in for that long. Pans and edits are refined at once, as before. +- **Landed (2026-11-17):** the strips a pan uncovers, and the areas an edit redraws, render in + parallel bands as full renders do (`render_part`): rows of a tall strip, columns of a wide one, + however few pixels they have. A strip costs the layers it crosses, not its pixels (a card's + shadow is drawn whole for a sliver of it), and was drawn on one thread: on a page of 3,600 cards + with a drop and an inner shadow each, a 60 px pan took 33 ms right and 47 ms down where the + whole view took 80 ms; now 9 and 11 ms (`pan_bench_tests`, release, a 32-thread desktop; bands stop at 16). In the app + (release) a pan step on that page went from 150–170 ms to 17–27 ms. The browser renders on one + thread and is unchanged. - **Landed (2026-10-28):** the browser refines a zoom's preview only once no newer request has come for 120 ms (`SETTLE_MS`), or for as long as its last full render took when that is shorter: its full renders run on the UI thread, and one between every two wheel steps held the page up @@ -601,6 +609,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` | | 2026-11-17 | minor | Gap 7: the desktop refines a zoom's preview only once the zoom has paused, as the browser does, so a full render that can't be stopped no longer holds up the next steps of a held zoom. Numbers unchanged. Test: `zoom_preview_tests::the_render_thread_refines_a_zoom_only_once_it_pauses` | | 2026-11-12 | minor | Gap 1: the `.fig` export writes vector region paints (#2302); the 2026-10-26 "Landed" bullet no longer says the export drops them | | 2026-11-10 | minor | Gap 13: a boolean group's corner radius rounds every sharp corner of its result (#2222); the boolean clause leaves the 2026-10-12 "Left" list | From 5baf4d80b37169fb83064e33b2fd5728b7ae2178 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 17 Nov 2026 17:41:27 +0700 Subject: [PATCH 072/129] MCP: the instructions tell agents to place copies as instances and use properties and variants --- crates/mcp/src/prompts.rs | 26 ++++++++++++++++++++++++++ crates/mcp/src/server.rs | 11 ++++++++++- docs/mcp.md | 12 ++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 59b4ee818..3e82b1865 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -187,4 +187,30 @@ mod tests { assert!(out.contains(&bomb)); assert!(out.len() < 3 * bomb.len(), "{}", out.len()); } + + /// Every command the server's instructions and the prompts name exists: an agent told to run a + /// renamed or misspelt one gets an error instead of the workflow. + #[test] + fn the_commands_the_instructions_and_prompts_name_exist() { + let ids: Vec<&str> = figcraft_engine::all_commands().iter().map(|c| c.id).collect(); + let namespaces: Vec<&str> = ids.iter().filter_map(|id| id.split('.').next()).collect(); + let texts = std::iter::once(crate::INSTRUCTIONS).chain(PROMPTS.iter().map(|p| p.template)); + let mut named = 0; + for text in texts { + for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '.')).map(|w| w.trim_end_matches('.')) { + let Some((ns, rest)) = word.split_once('.') else { continue }; + // wait_for_changes events, which the prompts name too. + let event = matches!(word, "comment.added" | "comment.replied"); + if event || rest.is_empty() || !rest.starts_with(|c: char| c.is_ascii_lowercase()) || !namespaces.contains(&ns) { + continue; + } + named += 1; + assert!(ids.contains(&word), "`{word}` is not a command"); + } + } + assert!(named > 10, "the check found the command ids ({named})"); + for id in ["component.create", "instance.create", "component.addProperty", "instance.setProperties", "component.combineVariants"] { + assert!(crate::INSTRUCTIONS.contains(id), "the instructions name {id}"); + } + } } diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 70ac05999..58eb6b2e2 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -36,7 +36,16 @@ reports both x/y relative to the parent frame (groups don't count) and absoluteB positioned by the layout (set layout, gap, padding, mainAlign, crossAlign, sizingH/sizingV instead). \ Every menu item, panel action and shortcut is a command: find ids and params with list_commands (use a filter) \ and run them with run_command, or several as one undo step with batch. Commands act on `ids` when given, else \ -on the selection; new layers become the selection. Colours are \"#RRGGBB\" or \"#RRGGBBAA\". Verify your work: \ +on the selection; new layers become the selection. Colours are \"#RRGGBB\" or \"#RRGGBBAA\". \ +Repeated UI (buttons, inputs, cards, list rows, tab bars, icons) is a component: build it once, make it one with \ +component.create (or create_node type component), then place every other copy with \ +instance.create {component, parent?, x?, y?} instead of duplicating layers, so every copy follows its main component. \ +States and sizes are variants of one set: name the mains Property=value (State=Default, State=Hover) and run \ +component.combineVariants on them; component.addVariant {id} adds one more. What changes from copy to copy is a \ +component property: component.addProperty {id, name, type: text|boolean|instanceSwap, layer} on the component (on the \ +set once its variants are combined, then component.bindProperty {layer, property} for each other variant's layer), and \ +instance.setProperties {ids, properties} sets it on each copy. get_node shows whether a layer is an instance and of \ +which main. Verify your work: \ inspect_document / get_node return the layer tree as JSON (check sizes, fills, layout, overrides), and \ screenshot returns a PNG of the page or of given layers to look at. undo/redo step through history. \ Comments: comment.list returns threads (text, anchor node id, frame, page, x/y, replies); fix open ones, \ diff --git a/docs/mcp.md b/docs/mcp.md index c032b93ab..46e729fc0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -182,6 +182,18 @@ Or in a project's `.mcp.json`: leaves its contents where they are, and so does resizing a frame with `cmd` held (constraints ignored); a layer a mask hides can't be clicked there, and a mask group's box and exports are the mask's (plus any layers under the mask). +- Repeated UI (buttons, inputs, cards, list rows, tab bars, icons) is a component and its copies + are instances: make it once with `component.create` (or `create_node` type `component`) and place + each other copy with `instance.create {component, parent?, x?, y?}` rather than duplicating the + layers, so every copy follows the main. States and sizes are variants of one set: name the mains + `Property=value` (`State=Default`, `State=Hover`) and run `component.combineVariants` on them; + `component.addVariant {id}` adds one more. What changes per copy is a component property: + `component.addProperty {id, name, type: text|boolean|instanceSwap, layer}` on the component, or + on the set once its variants are combined, then `component.bindProperty {layer, property}` for + each other variant's layer (a property added to one variant before combining stays that + variant's, so an instance switched to another variant loses it); `instance.setProperties {ids, + properties}` sets it on each copy. The server's `initialize` instructions say this too, since + agents otherwise tend to copy layers. - Children of an auto-layout frame are positioned by the layout: set `layout`, `gap`, `padding`, `mainAlign`, `crossAlign`, `sizingH`/`sizingV` instead of x/y. In one call, `layout` applies before the keys that tune it, so `{"layout": {"mode": "vertical"}, "gap": 8}` keeps the gap; From 3451d4211898e7195cff89bcfb407217acbe3d73 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 17 Nov 2026 17:43:41 +0700 Subject: [PATCH 073/129] M8: a test that a textured layer renders the same in column and row bands --- crates/render/src/band_tests.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/render/src/band_tests.rs b/crates/render/src/band_tests.rs index 5af2f353f..630f48bce 100644 --- a/crates/render/src/band_tests.rs +++ b/crates/render/src/band_tests.rs @@ -214,3 +214,24 @@ fn a_tall_or_wide_part_of_a_view_matches_one_piece_rendering() { } } } +/// A textured layer scatters its pixels up to the texture's radius, past where a band cuts the +/// view; it is drawn off screen whole before it is cut, so column and row bands show it exactly as +/// one piece does, clipped to its shape or not. +#[test] +fn a_textured_layer_renders_the_same_in_bands() { + for clip_to_shape in [false, true] { + let mut d = Document::new("texture"); + let p = d.first_page().unwrap(); + let r = d.create(p, NodeKind::Rectangle, "T", 20.0, 20.0, 400.0, 200.0).unwrap(); + let n = d.get_mut(r).unwrap(); + n.fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())]; + let texture = figcraft_doc::Texture { size: 0.5, radius: 12.0, clip_to_shape, ..Default::default() }; + n.effects = vec![Effect { kind: EffectKind::Texture(texture), visible: true }]; + let v = View { origin: (0.0, 0.0), scale: 1.7, width: 760, height: 400 }; + let one = render_view_single(&d, p, &v, &Options::default()).unwrap(); + for bands in [2, 3, 7] { + assert!(render_columns(&d, p, &v, &Options::default(), bands).unwrap().data() == one.data(), "{bands} columns"); + assert!(render_bands(&d, p, &v, &Options::default(), bands).unwrap().data() == one.data(), "{bands} rows"); + } + } +} From c391f13ccd7d56490fc3638a7392a57f60c18f65 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 17 Nov 2026 17:05:56 +0700 Subject: [PATCH 074/129] M8: a pan past the canvas image shows a coarse image of the area around the view, not the bare page colour --- crates/ui-egui/src/app/control.rs | 2 + crates/ui-egui/src/canvas.rs | 36 ++++- crates/ui-egui/src/canvas/background.rs | 89 ++++++++++-- crates/ui-egui/src/canvas/render_worker.rs | 134 +++++++++++++++++- crates/ui-egui/src/canvas/surround_tests.rs | 79 +++++++++++ .../ui-egui/src/canvas/zoom_preview_tests.rs | 6 +- docs/control-protocol.md | 4 +- docs/gaps.md | 11 +- 8 files changed, 340 insertions(+), 21 deletions(-) create mode 100644 crates/ui-egui/src/canvas/surround_tests.rs diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index f63ab334a..b76ac91aa 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -90,6 +90,8 @@ impl FigApp { "quality": if self.canvas.tex_coarse { "preview" } else { "refined" }, "previewLatencyMs": self.canvas.preview_latency_ms, "refineLatencyMs": self.canvas.refine_latency_ms, + // The share of the canvas only the page colour covered last frame (no render reached it). + "uncovered": self.canvas.uncovered, }, "live": live::inspect(self), "window": self.windows.current, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 51507b0a5..5de28c832 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -62,6 +62,9 @@ pub struct CanvasState { /// shows its image at once while it renders again, instead of a blank canvas (and, where /// renders are slow, a coarse preview). kept: Vec, + /// The coarse image of the area around the view ([`render_worker::Surround`]), shown where + /// the texture doesn't reach, and the file and page it is of. + surround: Option<(egui::TextureHandle, figcraft_render::View, (u64, NodeId))>, submitted: Option, /// The view of the last render asked for. want_view: Option, @@ -71,6 +74,8 @@ pub struct CanvasState { /// canvas texture (ms; the texture is uploaded when that frame is painted). pub preview_latency_ms: Option, pub refine_latency_ms: Option, + /// The share of the canvas no render covered last frame: the page background showed there. + pub uncovered: f32, dragging: bool, space_pan: bool, middle_pan: Option<(Pos2, f64, f64)>, @@ -104,11 +109,13 @@ impl Default for CanvasState { tex_coarse: false, tex_seq: 0, kept: Vec::new(), + surround: None, submitted: None, want_view: None, render_work: None, preview_latency_ms: None, refine_latency_ms: None, + uncovered: 0.0, dragging: false, space_pan: false, middle_pan: None, @@ -339,6 +346,21 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_coarse = done.coarse; app.canvas.tex_seq = done.seq; } + if let Some(around) = worker.surround() + && shown == Some((around.uid, around.page)) + { + let of = (around.uid, around.page); + match &mut app.canvas.surround { + Some((t, view, at)) => { + t.set(around.image, egui::TextureOptions::LINEAR); + (*view, *at) = (around.view, of); + } + None => { + let t = ctx.load_texture("figcraft-canvas-surround", around.image, egui::TextureOptions::LINEAR); + app.canvas.surround = Some((t, around.view, of)); + } + } + } let painter = ui.painter_at(rect); crate::theme::set_canvas_page(&ctx, bg); let image = if let (Some(tex), Some(v), true) = (&app.canvas.texture, &app.canvas.tex_view, shown.is_some() && app.canvas.tex_of == shown) { @@ -351,7 +373,16 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { } else { None }; - background::paint(&painter, rect, bg, image.map(|(_, r)| r)); + // Not in pixel preview: its pixels are the point, and it keeps no image around the view. + let pixel_preview = app.session.ds().ok().and_then(|ds| ds.view.pixel_preview_scale()).is_some(); + let surround = match (&app.canvas.surround, pixel_preview) { + (Some((tex, v, of)), false) if shown == Some(*of) => { + let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0); + Some((tex.id(), presented_image_rect(app.to_screen(v.origin.0, v.origin.1), v, zoom, ppp, false))) + } + _ => None, + }; + app.canvas.uncovered = background::paint(&painter, rect, bg, image.map(|(_, r)| r), surround); if let Some((texture, image_rect)) = image { painter.image(texture, image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } @@ -461,5 +492,8 @@ mod wheel_zoom_tests; #[cfg(test)] mod zoom_preview_tests; +#[cfg(test)] +mod surround_tests; + #[cfg(test)] mod tab_switch_tests; diff --git a/crates/ui-egui/src/canvas/background.rs b/crates/ui-egui/src/canvas/background.rs index f7eadd640..cac9e2179 100644 --- a/crates/ui-egui/src/canvas/background.rs +++ b/crates/ui-egui/src/canvas/background.rs @@ -1,6 +1,6 @@ //! The transparency grid behind the page; rendered pixels already contain the page colour. -use egui::{Color32, CornerRadius, Id, Painter, Rect, TextureHandle, pos2}; +use egui::{Color32, CornerRadius, Id, Painter, Rect, TextureHandle, TextureId, pos2}; /// Reuse the checkerboard texture, updating its pixels when the active theme changes. fn grid_texture(ctx: &egui::Context) -> TextureHandle { @@ -25,18 +25,40 @@ fn grid_texture(ctx: &egui::Context) -> TextureHandle { texture } -/// Draw the transparency grid and apply page colour only outside the rendered image. -pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered: Option) { +/// Draw the transparency grid, and where the rendered image doesn't reach the coarse image around +/// the view (`surround`: its texture and screen rect), and the page colour past that. Returns the +/// share of `rect` that only the page colour covers. +pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered: Option, surround: Option<(TextureId, Rect)>) -> f32 { if background.a() < 255 { // Repeat four pixels instead of allocating one shape per square on a large canvas. let texture = grid_texture(painter.ctx()); let uv = Rect::from_min_size(egui::Pos2::ZERO, rect.size() / 16.0); painter.image(texture.id(), rect, uv, Color32::WHITE); } - // The render contains the page colour and its alpha. Painting that colour beneath it - // applies alpha twice (50% becomes 75%). Only uncovered areas need the fallback colour. - let covered = rendered.map(|r| r.intersect(rect)).filter(|r| r.is_positive()); - let areas = match covered { + // Renders contain the page colour and its alpha. Painting that colour (or the coarse image) + // beneath one applies alpha twice (50% becomes 75%): each area gets exactly one of them. + let mut bare = 0.0; + for area in outside(rect, rendered) { + let rest = match surround { + Some((texture, at)) => { + if area.intersect(at).is_positive() { + painter.with_clip_rect(area).image(texture, at, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + outside(area, Some(at)) + } + None => outside(area, None), + }; + for r in rest { + painter.rect_filled(r, CornerRadius::ZERO, background); + bare += r.area(); + } + } + if rect.area() > 0.0 { (bare / rect.area()).clamp(0.0, 1.0) } else { 0.0 } +} + +/// The parts of `rect` outside `covered`: at most four strips that don't overlap. +fn outside(rect: Rect, covered: Option) -> impl Iterator { + let areas = match covered.map(|r| r.intersect(rect)).filter(|r| r.is_positive()) { Some(r) => [ Rect::from_min_max(rect.min, pos2(rect.right(), r.top())), Rect::from_min_max(pos2(rect.left(), r.bottom()), rect.max), @@ -45,9 +67,7 @@ pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered ], None => [rect, Rect::NOTHING, Rect::NOTHING, Rect::NOTHING], }; - for area in areas.into_iter().filter(|r| r.is_positive()) { - painter.rect_filled(area, CornerRadius::ZERO, background); - } + areas.into_iter().filter(|r| r.is_positive()) } #[cfg(test)] @@ -59,7 +79,7 @@ mod tests { fn shapes(alpha: u8, rendered: Option) -> egui::FullOutput { let ctx = egui::Context::default(); let mut out = ctx.run_ui(Default::default(), |ui| { - paint(ui.painter(), canvas(), Color32::from_rgba_unmultiplied(255, 0, 0, alpha), rendered); + paint(ui.painter(), canvas(), Color32::from_rgba_unmultiplied(255, 0, 0, alpha), rendered, None); }); out.textures_delta.clear(); out @@ -169,7 +189,9 @@ mod tests { let mut previous_id = None; for tokens in [crate::theme::Tokens::light(), crate::theme::Tokens::dark(), crate::theme::Tokens::light()] { crate::theme::apply(&ctx, tokens); - let mut out = ctx.run_ui(Default::default(), |ui| paint(ui.painter(), canvas(), Color32::TRANSPARENT, None)); + let mut out = ctx.run_ui(Default::default(), |ui| { + paint(ui.painter(), canvas(), Color32::TRANSPARENT, None, None); + }); let (tile, _) = ctx.data(|d| d.get_temp::<(TextureHandle, [Color32; 2])>(Id::unique("canvas_transparency_grid"))).expect("drawn checkerboard"); let grid_index = assert_grid(&out, tile.id(), canvas()); @@ -227,4 +249,47 @@ mod tests { } } } + + /// Past the rendered image the coarse image around the view shows, clipped to outside the + /// image, and the page colour only past both: nothing is painted twice, and what is left bare + /// is what the call returns. + #[test] + fn the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest() { + let ctx = egui::Context::default(); + let around = TextureId::User(7); + // The render covers the left half; the coarse image reaches 80 to the right. + let rendered = Rect::from_min_max(pos2(0.0, 0.0), pos2(50.0, 100.0)); + let at = Rect::from_min_max(pos2(-100.0, -100.0), pos2(80.0, 200.0)); + let mut bare = -1.0; + let mut out = ctx.run_ui(Default::default(), |ui| { + bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), Some((around, at))); + }); + out.textures_delta.clear(); + let coarse: Vec<_> = out.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id == around)).collect(); + assert_eq!(coarse.len(), 1, "one strip of the canvas lies past the render"); + assert_eq!(coarse[0].clip_rect, Rect::from_min_max(pos2(50.0, 0.0), pos2(100.0, 100.0)), "clipped to past the render"); + let fills: Vec = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Rect(r) => Some(r.rect), + _ => None, + }) + .collect(); + assert_eq!(fills, [Rect::from_min_max(pos2(80.0, 0.0), pos2(100.0, 100.0))], "the page colour only past both"); + assert!((bare - 0.2).abs() < 1e-6, "a fifth of the canvas is bare: {bare}"); + // Without one the page colour fills all of it; with one reaching everywhere nothing. + let mut out = ctx.run_ui(Default::default(), |ui| { + bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), None); + }); + out.textures_delta.clear(); + assert!((bare - 0.5).abs() < 1e-6, "{bare}"); + let everywhere = Rect::from_min_max(pos2(-100.0, -100.0), pos2(200.0, 200.0)); + let mut out = ctx.run_ui(Default::default(), |ui| { + bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), Some((around, everywhere))); + }); + out.textures_delta.clear(); + assert_eq!(bare, 0.0); + assert!(!out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(_))), "no page colour under the coarse image"); + } } diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 27c9cc32b..8a2e1c5dc 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -19,6 +19,9 @@ //! ([`figcraft_render::Steps`]), at least a band a frame and more while they fit in [`STEP_MS`], //! so input is handled while it draws (on a page whose render takes seconds, a band is a //! fraction of that: eight at most). +//! On the desktop a third thread keeps a coarse image of the area around the view +//! ([`Surround`]): where the canvas image doesn't reach (a pan past its edge before the strips are +//! drawn, a zoom out) the canvas shows that, blurred, instead of the bare page colour. use std::sync::Arc; @@ -145,6 +148,74 @@ fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool) Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 } } +/// The coarse image around the view is this many views wide and tall, centred on it. +const SURROUND_SPAN: f64 = 3.0; + +/// The area [`SURROUND_SPAN`] times as wide and tall as `view`, centred on it, with +/// [`PREVIEW_FACTOR`] times fewer pixels per page unit (`view` is at most as large as a texture, +/// so this is too). +pub fn surround_view(view: &View) -> View { + let c = coarse_view(view); + let s = c.scale.max(1e-9); + let (w, h) = (f64::from(c.width), f64::from(c.height)); + let pad = (SURROUND_SPAN - 1.0) / 2.0; + let side = |n: f64| (n * SURROUND_SPAN).ceil().max(1.0) as u32; + View { origin: (view.origin.0 - pad * w / s, view.origin.1 - pad * h / s), scale: c.scale, width: side(w), height: side(h) } +} + +/// Whether `around` reaches a third of `view`'s size past each of its sides: a pan that far shows +/// no edge. +fn reaches(around: &View, view: &View) -> bool { + let (a, v) = (around.page_rect(), view.page_rect()); + let (mx, my) = (v.width() / 3.0, v.height() / 3.0); + a.x0 <= v.x0 - mx && a.y0 <= v.y0 - my && a.x1 >= v.x1 + mx && a.y1 >= v.y1 + my +} + +/// Whether `a` and `b` are the same view, bit for bit. +fn same_view(a: &View, b: &View) -> bool { + (a.origin.0.to_bits(), a.origin.1.to_bits(), a.scale.to_bits(), a.width, a.height) + == (b.origin.0.to_bits(), b.origin.1.to_bits(), b.scale.to_bits(), b.width, b.height) +} + +/// The coarse image of the area around the view ([`surround_view`]), kept between requests. +#[derive(Default)] +pub struct Surround { + retained: Retained, + /// The file, page and view of the image handed over last. + of: Option<(u64, NodeId, View)>, +} + +impl Surround { + /// The image around `job`'s view when the one handed over last no longer stands for it (of + /// another file, page or zoom, short of a third of a view past an edge, or the document + /// changed), drawn on the kept one: a pan shifts it and redraws the strips, an edit the areas + /// that changed. `None` in pixel preview, whose pixels are the point. + pub fn render(&mut self, job: &Job) -> Option { + if !job.zoom_preview { + return None; + } + let want = surround_view(&job.view); + let view = match &self.of { + Some((uid, page, have)) + if *uid == job.uid && *page == job.page && have.scale.to_bits() == want.scale.to_bits() && reaches(have, &job.view) => + { + have.clone() + } + _ => want, + }; + let same = self.of.as_ref().is_some_and(|(uid, page, have)| *uid == job.uid && *page == job.page && same_view(have, &view)); + let t0 = Instant::now(); + let d = guarded(&mut self.retained, |r| { + let (snapped, pix, work) = r.render(&job.doc, job.page, &view, &options(job))?; + (!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true)) + }); + if d.is_some() { + self.of = Some((job.uid, job.page, view)); + } + d + } +} + /// `view` with [`PREVIEW_FACTOR`] times fewer pixels each way, showing at least the same area. pub fn coarse_view(view: &View) -> View { let shrink = |n: u32| (f64::from(n) / PREVIEW_FACTOR).ceil().max(1.0) as u32; @@ -413,6 +484,12 @@ pub struct Worker { finished: Arc, /// The watchdog is drawing a late preview, or has one to hand over and wake the UI for. previewing: Arc, + /// The images around the view ([`Surround`]) from their thread. + surround_rx: std::sync::mpsc::Receiver, + /// The newest request handed to the surround thread, and the newest it is done with (its image + /// handed over and the UI woken, or none needed). + surround_asked: Arc, + surround_done: Arc, } #[cfg(not(target_arch = "wasm32"))] @@ -467,6 +544,33 @@ impl Worker { if let Err(e) = watchdog { log::error!("render preview thread: {e}"); } + // The image around the view, on a thread of its own so it never holds up the canvas image: + // the render thread hands it each request it has refined, the newest queued one wins. + let (around_tx, around) = std::sync::mpsc::channel::<(u64, Job)>(); + let (surround_tx, surround_rx) = std::sync::mpsc::channel::(); + let surround_ctx = ctx.clone(); + let surround_asked = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let surround_done = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let (asked, surrounded) = (surround_asked.clone(), surround_done.clone()); + let surrounding = + std::thread::Builder::new().name("figcraft-render-surround".into()).stack_size(figcraft_render::RENDER_STACK).spawn(move || { + let mut surround = Surround::default(); + while let Ok((mut seq, mut job)) = around.recv() { + while let Ok(newer) = around.try_recv() { + (seq, job) = newer; + } + if let Some(d) = surround.render(&job) { + if surround_tx.send(d).is_err() { + break; + } + surround_ctx.request_repaint_of(viewport); + } + surrounded.store(seq, std::sync::atomic::Ordering::SeqCst); + } + }); + if let Err(e) = surrounding { + log::error!("render surround thread: {e}"); + } let spawned = std::thread::Builder::new().name("figcraft-render".into()).stack_size(figcraft_render::RENDER_STACK).spawn(move || { let mut renders = Renders::default(); let mut next = None; @@ -502,11 +606,21 @@ impl Worker { } let done = renders.refine(&job); refined.store(seq, std::sync::atomic::Ordering::SeqCst); + let refined_job = done.is_some(); if let Some(d) = done && done_tx.send(answering(d, seq)).is_err() { break; } + if refined_job { + // Asked before the send (and before this request counts as done), so `in_flight` + // holds until the surround thread is done with it. Without that thread (it failed + // to start) the page colour shows past the edge. + asked.store(seq, std::sync::atomic::Ordering::SeqCst); + if around_tx.send((seq, job)).is_err() { + asked.store(0, std::sync::atomic::Ordering::SeqCst); + } + } ctx.request_repaint_of(viewport); done_with.store(seq, std::sync::atomic::Ordering::SeqCst); } @@ -514,7 +628,7 @@ impl Worker { if let Err(e) = spawned { log::error!("render thread: {e}"); } - Self { tx, rx, submitted: 0, finished, previewing } + Self { tx, rx, submitted: 0, finished, previewing, surround_rx, surround_asked, surround_done } } pub fn submit(&mut self, job: Job) { @@ -524,9 +638,13 @@ impl Worker { } /// Whether a submitted job is still rendering or hasn't woken the UI yet, the watchdog's late - /// preview included (a finished image may still wait for [`Self::poll`]). + /// preview and the image around the view included (a finished image may still wait for + /// [`Self::poll`] or [`Self::surround`]). pub fn in_flight(&self) -> bool { - self.finished.load(std::sync::atomic::Ordering::SeqCst) < self.submitted || self.previewing.load(std::sync::atomic::Ordering::SeqCst) + use std::sync::atomic::Ordering::SeqCst; + self.finished.load(SeqCst) < self.submitted + || self.previewing.load(SeqCst) + || self.surround_done.load(SeqCst) < self.surround_asked.load(SeqCst) } /// The best of the renders finished since the last poll ([`better`]). @@ -537,6 +655,11 @@ impl Worker { } best } + + /// The newest image around the view ([`Surround`]) finished since the last call. + pub fn surround(&mut self) -> Option { + self.surround_rx.try_iter().last() + } } /// The browser's worker: renders inline, one image a frame: a preview first when one is due, the @@ -599,6 +722,11 @@ impl Inline { pub fn in_flight(&self) -> bool { self.pending.is_some() } + /// shortcut: the browser renders on the page's own thread, so it keeps no image around the view + /// (one would hold the page up); draw one there once the canvas renders on a wasm thread (#1500). + pub fn surround(&mut self) -> Option { + None + } pub fn poll(&mut self) -> Option { self.poll_at(Instant::now()) } diff --git a/crates/ui-egui/src/canvas/surround_tests.rs b/crates/ui-egui/src/canvas/surround_tests.rs new file mode 100644 index 000000000..246d428e1 --- /dev/null +++ b/crates/ui-egui/src/canvas/surround_tests.rs @@ -0,0 +1,79 @@ +//! The coarse image around the view ([`Surround`]): three views wide and tall at a quarter of the +//! pixels each way, kept while the view stays a third of a view inside it, moved (a shift and the +//! strips) when a pan goes further, patched after an edit, none in pixel preview; and the desktop +//! worker hands one over after each refined render, so a pan past the canvas image shows that +//! instead of the bare page colour. + +use std::time::Duration; + +use figcraft_render::{View, Work}; +use serde_json::json; + +use super::zoom_preview_tests::{document, job, view_at}; +use crate::render_worker::{Job, PREVIEW_FACTOR, Surround, Worker, surround_view}; + +/// Whether `outer` shows all of the page `inner` does, give or take the snapping to whole pixels. +fn contains(outer: &View, inner: &View) -> bool { + let (o, i) = (outer.page_rect(), inner.page_rect()); + let eps = 2.0 / outer.scale; + o.x0 <= i.x0 + eps && o.y0 <= i.y0 + eps && o.x1 >= i.x1 - eps && o.y1 >= i.y1 - eps +} + +#[test] +fn the_area_around_a_view_is_three_views_wide_at_a_quarter_of_the_pixels() { + let v = view_at((400.0, 300.0), 2.0, 800, 600); + let a = surround_view(&v); + assert_eq!(a.scale, v.scale / PREVIEW_FACTOR); + assert_eq!((a.width, a.height), (600, 450), "3 × 800 / 4 by 3 × 600 / 4"); + let (pa, pv) = (a.page_rect(), v.page_rect()); + assert!((pa.center().x - pv.center().x).abs() < 1e-9 && (pa.center().y - pv.center().y).abs() < 1e-9, "centred on the view"); + assert!((pa.width() - 3.0 * pv.width()).abs() < 1e-9 && (pa.height() - 3.0 * pv.height()).abs() < 1e-9); +} + +#[test] +fn the_image_around_the_view_is_kept_for_small_pans_and_moved_for_far_ones() { + let (s, rect) = document(); + let ds = s.ds().unwrap(); + let at = |c: (f64, f64)| job(&ds.doc, ds.page, ds.uid, view_at(c, 1.0, 400, 300)); + let mut around = Surround::default(); + let first = around.render(&at((250.0, 150.0))).expect("the first one"); + assert_eq!(first.work, Work::Full); + assert!(first.coarse && contains(&first.view, &surround_view(&at((250.0, 150.0)).view))); + assert!(around.render(&at((250.0, 150.0))).is_none(), "the same request: nothing new"); + // A quarter of a view: it still reaches more than a third of a view past every side. + assert!(around.render(&at((350.0, 225.0))).is_none(), "kept for a small pan"); + // Most of a view: moved to centre on the view again, built on the kept image. + let moved = around.render(&at((570.0, 150.0))).expect("moved for a far pan"); + assert!(matches!(moved.work, Work::Partial { .. }), "a shift and the strips: {:?}", moved.work); + assert!(contains(&moved.view, &surround_view(&at((570.0, 150.0)).view))); + // An edit redraws its area. + let mut s = s; + s.execute("node.set", &json!({"id": rect, "props": {"x": 140}})).unwrap(); + let ds = s.ds().unwrap(); + let edited = job(&ds.doc, ds.page, ds.uid, view_at((570.0, 150.0), 1.0, 400, 300)); + assert!(matches!(around.render(&edited).expect("after an edit").work, Work::Partial { .. })); + // Another zoom starts over; pixel preview has none. + let zoomed = job(&ds.doc, ds.page, ds.uid, view_at((570.0, 150.0), 2.0, 400, 300)); + assert_eq!(around.render(&zoomed).expect("another zoom").work, Work::Full); + assert!(around.render(&Job { zoom_preview: false, ..job(&ds.doc, ds.page, ds.uid, view_at((0.0, 0.0), 8.0, 400, 300)) }).is_none()); +} + +#[test] +fn the_worker_hands_over_the_image_around_each_refined_view() { + let (s, _) = document(); + let ds = s.ds().unwrap(); + let j = job(&ds.doc, ds.page, ds.uid, view_at((250.0, 150.0), 1.0, 400, 300)); + let mut w = Worker::new(egui::Context::default()); + w.submit(j.clone()); + let start = std::time::Instant::now(); + let around = loop { + assert!(start.elapsed() < Duration::from_secs(60), "no image around the view came"); + if let Some(d) = w.surround() { + break d; + } + std::thread::sleep(Duration::from_millis(2)); + }; + assert_eq!((around.uid, around.page), (ds.uid, ds.page)); + assert!(contains(&around.view, &surround_view(&j.view)), "it reaches a view past every side"); + assert!(w.poll().is_some_and(|d| !d.coarse), "the refined image came through as before"); +} diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index bef17fe59..af9914b74 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -27,7 +27,7 @@ use crate::render_worker::{ /// scanned first (once per process, and a concurrent caller waits for it): the scan another test /// starts bumps the global font generation, and a render kept from before it is stale, so a pan /// or an edit meanwhile would redraw in full instead of patching. -fn document() -> (Session, NodeId) { +pub(super) fn document() -> (Session, NodeId) { figcraft_text::scan_system_fonts(); let mut s = Session::new(); for k in 0..12 { @@ -69,11 +69,11 @@ fn slow_scene(views: &[View], ms: f64) -> Session { } /// A `w` × `h` device-pixel view at `scale` centred on page point `c`. -fn view_at(c: (f64, f64), scale: f64, w: u32, h: u32) -> View { +pub(super) fn view_at(c: (f64, f64), scale: f64, w: u32, h: u32) -> View { View { origin: (c.0 - f64::from(w) / scale / 2.0, c.1 - f64::from(h) / scale / 2.0), scale, width: w, height: h } } -fn job(doc: &Arc, page: NodeId, uid: u64, view: View) -> Job { +pub(super) fn job(doc: &Arc, page: NodeId, uid: u64, view: View) -> Job { Job { doc: doc.clone(), page, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b06d79932..381992c55 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -236,7 +236,9 @@ zoom preview or the refined image (`canvas.quality`: `preview` or `refined`) and asking for a render to its preview and its refined image being handed to egui as the canvas texture (`canvas.previewLatencyMs`, `canvas.refineLatencyMs`, on a monotonic clock, rendering included in the browser too; the GPU upload and presenting the frame come after; `null` until -there was one). `importReport` holds the Import report window's content (`{name, pages, layers, images, appended, placed, warnings, warningCount}`, +there was one), and the share of the canvas only the page colour covered last frame, no render +reaching it (`canvas.uncovered`, 0 to 1: past the canvas image the desktop shows a coarse image of the +area around the view). `importReport` holds the Import report window's content (`{name, pages, layers, images, appended, placed, warnings, warningCount}`, `null` while none is open). The window opens only for a file the user opened or imported in the app (File ▸ Open or Import, Open recent, a recent file on the home screen, a drop, a paste, the system's open event). Emulated user input counts as the user's action: `ui.input` and `ui.key` (for example a Cmd+V paste or a click diff --git a/docs/gaps.md b/docs/gaps.md index 584d7f3a0..2971d9bf0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -312,6 +312,14 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe wait for it: on a 29,000 × 12,600 page of 9,000 layers with images and shadows (M1 Pro, 2x display) full renders took 110–520 ms, and the preview stood in for that long. Pans and edits are refined at once, as before. +- **Landed (2026-11-17):** the desktop keeps a coarse image of the area around the view, three + views wide and tall at a quarter of the pixels each way (`render_worker::Surround`, on a thread of + its own after each refined render, built on the last one: a pan shifts it, an edit patches it). + Where the canvas image doesn't reach, a pan past its edge before the strips are drawn or a zoom + out, the canvas shows that, blurred, then sharp, instead of the bare page colour. On a page of + 3,600 cards with shadows panned at 60 pt a step (debug build), the canvas was 36% bare on + average and at 77 of 80 steps; now none of it is. `ui.inspect` reports the bare share + (`canvas.uncovered`). The browser keeps none (it renders on the page's thread). - **Landed (2026-11-17):** the strips a pan uncovers, and the areas an edit redraws, render in parallel bands as full renders do (`render_part`): rows of a tall strip, columns of a wide one, however few pixels they have. A strip costs the layers it crosses, not its pixels (a card's @@ -609,6 +617,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` | | 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` | | 2026-11-17 | minor | Gap 7: the desktop refines a zoom's preview only once the zoom has paused, as the browser does, so a full render that can't be stopped no longer holds up the next steps of a held zoom. Numbers unchanged. Test: `zoom_preview_tests::the_render_thread_refines_a_zoom_only_once_it_pauses` | | 2026-11-12 | minor | Gap 1: the `.fig` export writes vector region paints (#2302); the 2026-10-26 "Landed" bullet no longer says the export drops them | From a7355eed5ed23b654bf73353c4e8dd331441a314 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 17 Nov 2026 17:45:22 +0700 Subject: [PATCH 075/129] M8: turning soft proof on or off redraws the image around the view --- crates/ui-egui/src/canvas/render_worker.rs | 14 +++++++++----- crates/ui-egui/src/canvas/surround_tests.rs | 4 ++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 8a2e1c5dc..c0fc8f312 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -181,8 +181,9 @@ fn same_view(a: &View, b: &View) -> bool { #[derive(Default)] pub struct Surround { retained: Retained, - /// The file, page and view of the image handed over last. - of: Option<(u64, NodeId, View)>, + /// The file, page and view of the image handed over last, and whether it was soft-proofed + /// (marked after the render, so the kept image can't tell). + of: Option<(u64, NodeId, View, bool)>, } impl Surround { @@ -196,21 +197,24 @@ impl Surround { } let want = surround_view(&job.view); let view = match &self.of { - Some((uid, page, have)) + Some((uid, page, have, _)) if *uid == job.uid && *page == job.page && have.scale.to_bits() == want.scale.to_bits() && reaches(have, &job.view) => { have.clone() } _ => want, }; - let same = self.of.as_ref().is_some_and(|(uid, page, have)| *uid == job.uid && *page == job.page && same_view(have, &view)); + let same = self + .of + .as_ref() + .is_some_and(|(uid, page, have, proof)| *uid == job.uid && *page == job.page && *proof == job.proof && same_view(have, &view)); let t0 = Instant::now(); let d = guarded(&mut self.retained, |r| { let (snapped, pix, work) = r.render(&job.doc, job.page, &view, &options(job))?; (!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true)) }); if d.is_some() { - self.of = Some((job.uid, job.page, view)); + self.of = Some((job.uid, job.page, view, job.proof)); } d } diff --git a/crates/ui-egui/src/canvas/surround_tests.rs b/crates/ui-egui/src/canvas/surround_tests.rs index 246d428e1..f869c860c 100644 --- a/crates/ui-egui/src/canvas/surround_tests.rs +++ b/crates/ui-egui/src/canvas/surround_tests.rs @@ -52,6 +52,10 @@ fn the_image_around_the_view_is_kept_for_small_pans_and_moved_for_far_ones() { let ds = s.ds().unwrap(); let edited = job(&ds.doc, ds.page, ds.uid, view_at((570.0, 150.0), 1.0, 400, 300)); assert!(matches!(around.render(&edited).expect("after an edit").work, Work::Partial { .. })); + // Soft proof marks the image after it renders: turning it on or off hands over a new one. + assert!(around.render(&Job { proof: true, ..edited.clone() }).is_some(), "proof on"); + assert!(around.render(&Job { proof: true, ..edited.clone() }).is_none()); + assert!(around.render(&edited).is_some(), "proof off"); // Another zoom starts over; pixel preview has none. let zoomed = job(&ds.doc, ds.page, ds.uid, view_at((570.0, 150.0), 2.0, 400, 300)); assert_eq!(around.render(&zoomed).expect("another zoom").work, Work::Full); From bbb12d7b7407be358bf14bca5cb52b10fb902560 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 17 Nov 2026 17:24:35 +0700 Subject: [PATCH 076/129] M8: going back to a page shows it where it was left, not fitted again --- crates/engine/src/cmd/page.rs | 6 ++--- crates/engine/src/cmd/view.rs | 3 +-- crates/engine/src/doc_state.rs | 23 +++++++++++++++++- crates/engine/src/lib.rs | 2 ++ crates/engine/src/page_view_tests.rs | 35 ++++++++++++++++++++++++++++ docs/ui-parity.md | 5 ++-- 6 files changed, 65 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/page_view_tests.rs diff --git a/crates/engine/src/cmd/page.rs b/crates/engine/src/cmd/page.rs index 0648dedd2..3883c3f39 100644 --- a/crates/engine/src/cmd/page.rs +++ b/crates/engine/src/cmd/page.rs @@ -53,9 +53,8 @@ pub fn specs() -> Vec { return Ok(json!({"id": id, "divider": true})); } let ds = s.ds_mut()?; - ds.page = id; + ds.open_page(id); ds.selection.clear(); - ds.zoom_to_fit(); Ok(json!({"id": id})) }), spec!("page.select", "Go to page", "{id | index}", false, |s, p| { @@ -74,10 +73,9 @@ pub fn specs() -> Vec { return Err(bad("page.select", "a divider isn't a page to open")); } let ds = s.ds_mut()?; - ds.page = id; + ds.open_page(id); ds.selection.clear(); ds.text_edit = None; - ds.zoom_to_fit(); ok() }), spec!("page.rename", "Rename page", "{id?, name} (an empty page named with a leading hyphen becomes a divider)", true, |s, p| { diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 56f4aff27..7edf1372a 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -187,9 +187,8 @@ fn page_step(s: &mut Session, dir: i64) -> Result { } }; let ds = s.ds_mut()?; - ds.page = pg; + ds.open_page(pg); ds.selection.clear(); - ds.zoom_to_fit(); Ok(json!({"page": pg})) } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 3a1f72e50..12dfefe32 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -1,5 +1,7 @@ use super::view_state::ViewState; -use super::{Arc, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit}; +use super::{ + Arc, BTreeMap, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit, +}; /// One undo step. #[derive(Clone, Debug)] @@ -114,6 +116,9 @@ pub struct DocState { /// The file on disk as this tab last read or wrote it: a save refuses to replace what another /// app (figcraft-cli, say) wrote to it since (#1330). pub(crate) on_disk: Option, + /// Where each page's view was left in this session (its centre and zoom; see + /// [`Self::open_page`]; not saved). + page_views: BTreeMap, } /// A version shown on the canvas in place of the document: read-only until it's restored or the @@ -178,6 +183,7 @@ impl DocState { last_duplicate: None, images_left_in_file: None, on_disk: None, + page_views: BTreeMap::new(), }; st.zoom_to_fit(); st @@ -311,6 +317,21 @@ impl DocState { } /// Fit the current page's content (or centre on the origin when empty). + /// Show `page` at the view it was left at in this session, or one that fits its content the + /// first time; the page shown till now keeps its view for when it comes back. The page shown + /// already keeps its view. + pub fn open_page(&mut self, page: NodeId) { + if page == self.page { + return; + } + self.page_views.insert(self.page, (self.view.cx, self.view.cy, self.view.zoom)); + self.page = page; + match self.page_views.get(&page) { + Some(&(cx, cy, zoom)) => (self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom), + None => self.zoom_to_fit(), + } + } + pub fn zoom_to_fit(&mut self) { match self.doc.page_content_bounds(self.page) { Some(b) => self.view.fit(b, 1.0), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f7d8b029f..3c81b9147 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -668,6 +668,8 @@ mod widget_shapes_tests; #[cfg(test)] mod widgets_tests; +#[cfg(test)] +mod page_view_tests; #[cfg(test)] mod selection_reorder_tests; #[cfg(test)] diff --git a/crates/engine/src/page_view_tests.rs b/crates/engine/src/page_view_tests.rs new file mode 100644 index 000000000..c08d6772f --- /dev/null +++ b/crates/engine/src/page_view_tests.rs @@ -0,0 +1,35 @@ +//! Each page keeps its view in a session: going back to a page shows it where it was left, not +//! fitted again (a new page is still fitted); going to the page shown changes nothing. + +use serde_json::{Value, json}; + +use crate::Session; + +fn view(s: &mut Session) -> (f64, f64, f64) { + let v: Value = s.execute("view.get", &json!({})).unwrap(); + (v["cx"].as_f64().unwrap(), v["cy"].as_f64().unwrap(), v["zoom"].as_f64().unwrap()) +} + +#[test] +fn going_back_to_a_page_shows_it_where_it_was_left() { + let mut s = Session::new(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 400, "height": 300})).unwrap(); + let first = s.page().unwrap(); + s.execute("view.set", &json!({"zoom": 2.5, "cx": 1000, "cy": 500})).unwrap(); + let second = crate::params::id_of(&s.execute("page.add", &json!({})).unwrap()["id"]).unwrap(); + assert_ne!(view(&mut s), (1000.0, 500.0, 2.5), "a new page is fitted, not shown at the last page's view"); + s.execute("shape.ellipse", &json!({"x": 5000, "y": 5000, "width": 100, "height": 100})).unwrap(); + s.execute("view.set", &json!({"zoom": 0.5, "cx": -200, "cy": 40})).unwrap(); + + s.execute("page.select", &json!({"id": first})).unwrap(); + assert_eq!(view(&mut s), (1000.0, 500.0, 2.5), "the first page as it was left"); + s.execute("view.nextPage", &json!({})).unwrap(); + assert_eq!(s.page().unwrap(), second); + assert_eq!(view(&mut s), (-200.0, 40.0, 0.5), "the second page as it was left"); + // The page shown: nothing moves. + s.execute("view.set", &json!({"zoom": 3.0, "cx": 7, "cy": 8})).unwrap(); + s.execute("page.select", &json!({"id": second})).unwrap(); + assert_eq!(view(&mut s), (7.0, 8.0, 3.0)); + s.execute("view.prevPage", &json!({})).unwrap(); + assert_eq!(view(&mut s), (1000.0, 500.0, 2.5)); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a8b07f2e4..0137c49c1 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-12 · **Change:** minor (Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -49,7 +49,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Eye and padlock: click, or drag across rows to set several in one step; layers in a locked frame show a faint padlock | done | the toggles no longer vanish under the pointer (clicks on them could miss) (a child's padlock can't be toggled while its parent is locked) | | Rename: double click, F2 / Cmd+R, Tab to the next row; several layers open Rename layers (match, regular expressions, current name and number codes, start value, preview) | done | numbered in stacking order, pinned; Tab on the last row wraps to the first row's rename, measured in Figma's web app on 2026-11-12 (`tab_on_the_last_row_commits_and_wraps_to_the_first`); Shift+Tab on the first row ends the rename (not measured); Tab and Shift+Tab move only the rename, the selection stays on the layer first renamed, measured in Figma's web app on 2026-11-12 (`tab_while_renaming_leaves_the_selection_on_the_first_layer`); a double-click on a row's icon zooms to the layer (selecting it first) and renames nothing, while a double-click on the name or elsewhere on the row still renames, measured in Figma's web app on 2026-11-12 (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`) | | Find layers (filter by name) | done | not covered by the documentation | -| Pages: add, rename, drag to reorder, duplicate ("Copy of"), delete, dividers (a blank page named with a hyphen) | done | the line between Pages and Layers drags to size the pages list, kept in the preferences; a long list scrolls in its own area and a page dropped outside the visible list stays put (#272) (`layers_behaviour_tests`) | +| Pages: add, rename, drag to reorder, duplicate ("Copy of"), delete, dividers (a blank page named with a hyphen) | done | the line between Pages and Layers drags to size the pages list, kept in the preferences; a long list scrolls in its own area and a page dropped outside the visible list stays put (#272) (`layers_behaviour_tests`); going back to a page shows it where it was left in the session, only a page not shown yet is fitted to its content (`page.select`, Previous/Next page; `page_view_tests`) | | Assets panel: folders from page, frames and slash names (fold away), search, thumbnails, drag onto the canvas or into frames and auto layout, Alt-drop swap, enabled libraries | done | Shift+I (Quick insert), Alt+2 and View ▸ Panels ▸ Assets open it; the toolbar's Resources button was removed (the left rail's Assets tab and those shortcuts are the ways in) | | Hide when publishing from the Assets panel's context menu | done | a right-click on one of this file's components (also Libraries ▸ Hide when publishing for the selection, `component.hideWhenPublishing {ids?, on?}`): the model's sign of it is the name, so hiding puts a `.` before the name and showing takes the leading `.` and `_` away (one undo step, saved and synced like a rename; a variant or a layer inside hides its whole component or set); a hidden component shows a crossed eye on its tile and a dimmer name, the menu item its check mark; the next publish leaves it out and brings it back when shown again (`hide_publishing_tests`). Library components (read-only here) have no such menu | @@ -207,6 +207,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-17 | patch | M8: each page keeps its view in a session: going back to a page (the Pages list, `page.select`, Previous/Next page) shows it where it was left instead of fitting it again; a new page is still fitted, and going to the page shown moves nothing (`page_view_tests`) | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): UI3 layout, Light and dark themes, Rotate just outside a corner, Selection colors, Keyboard box selection, Boolean groups, Text: point, auto height, fixed, Text: wrap style, Bound as documented, Pan/zoom. | | 2026-11-12 | patch | M8: a double-click on a layer's icon in the Layers panel selects the layer and zooms the canvas to it (`view.zoomSelection`) and starts no rename, as measured in Figma's web app on 2026-11-12; a double-click on the name or elsewhere on the row still renames; the icon's hit area is the rect the row paints the icon in (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`), Rename row | | 2026-11-12 | minor | M8: Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12. A row or column evens one gap (the most common one, the smaller of a tie, else the mean rounded half up) and keeps the other axis, layers of a row may overlap along X (also in a chain, and a negative gap is raised so no layer reaches the one two before it, measured in Figma's web app on 2026-11-13), and a grid is packed along the axis with more groups; fewer than three layers, layers that all overlap, a diagonal and an irregular layout grey the row out and move nothing. Measured: those rules and the unavailable cases; FigCraft's choices: a 2 x 2 grid as columns, auto layout flow children, the 2,000 layer cap, rotated layers by their box, `spacing` with two layers, and no rounding with pixel snapping off. Tests: tidy_tests (a_row_keeps_its_order_sizes_and_y_and_evens_the_gaps, gaps_that_all_differ_take_their_mean_taken_down, a_mean_is_rounded_half_up, two_equally_common_gaps_give_the_smaller, an_overlapping_pair_in_a_row_is_tidied_and_its_negative_gap_counts, a_grid_is_tidied_by_columns, a_transposed_grid_is_tidied_by_rows, layers_on_a_diagonal_are_unavailable, an_irregular_selection_is_unavailable and the rest). | From 5897a41a7f96350b9953fe4a48f566ddc1514f37 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:21:26 +0000 Subject: [PATCH 077/129] Clip text gradient fills to the glyphs in inspect.code Fixes #2429 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/dev/codegen/css.rs | 12 +++++++- crates/engine/src/dev/tailwind.rs | 3 ++ crates/engine/src/inspect_behaviour_tests.rs | 32 ++++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/dev/codegen/css.rs b/crates/engine/src/dev/codegen/css.rs index a5e6726a3..b2b398bd5 100644 --- a/crates/engine/src/dev/codegen/css.rs +++ b/crates/engine/src/dev/codegen/css.rs @@ -162,6 +162,7 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo } if matches!(n.kind, NodeKind::Text(_)) { // Text: a solid is the ink (`color`), one per fill, so the last (top) one wins. + let top = n.fills.iter().rposition(|p| p.visible); for (i, p) in n.fills.iter().enumerate().filter(|(_, p)| p.visible) { match &p.kind { PaintKind::Solid { color } => { @@ -169,7 +170,16 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo // A variable binds the first paint's colour. put("color", if i == 0 { tok(doc, n, &["fill"], c, t) } else { c }); } - PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)), + PaintKind::Gradient(g) => { + put("background", css_gradient(g, n.width, n.height, p.opacity)); + // A gradient on top fills the glyphs: clip the background to the text and clear the ink. + // Under a later paint it must not hide that paint's colour, so it stays a plain background. + if Some(i) == top { + put("-webkit-background-clip", "text".into()); + put("background-clip", "text".into()); + put("color", "transparent".into()); + } + } PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()), PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()), } diff --git a/crates/engine/src/dev/tailwind.rs b/crates/engine/src/dev/tailwind.rs index fcc98a9a8..b8629e6b3 100644 --- a/crates/engine/src/dev/tailwind.rs +++ b/crates/engine/src/dev/tailwind.rs @@ -293,6 +293,9 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> { // An image shorthand (`url(…) center / cover`) is a whole `background`, not a bg colour. ("background", v) if v.starts_with("url(") => one(format!("[background:{}]", arb(v).trim_matches(['[', ']']))), ("background", v) => one(util("bg", "color", v, "color:")), + ("-webkit-background-clip", "text") => Vec::new(), + ("background-clip", "text") => kw("bg-clip-text"), + ("color", "transparent") => kw("text-transparent"), ("color", v) => one(util("text", "color", v, "color:")), ("border", v) => border("", v), ("border-top", v) => border("t", v), diff --git a/crates/engine/src/inspect_behaviour_tests.rs b/crates/engine/src/inspect_behaviour_tests.rs index ec6a89bcf..5da4ec62b 100644 --- a/crates/engine/src/inspect_behaviour_tests.rs +++ b/crates/engine/src/inspect_behaviour_tests.rs @@ -355,3 +355,35 @@ fn rem_conversion_keeps_the_original_pixels() { assert_eq!(f("padding: 3px;", 16.0), "padding: 0.1875rem;"); assert_eq!(f("gap: 0.5px;", 16.0), "gap: 0.03125rem;"); } + +#[test] +fn text_gradient_fill_clips_to_the_glyphs() { + let mut s = Session::new(); + let fills = json!([{"type": "linearGradient", "stops": ["#D98200", "#FF6B4A"]}]); + let t = id(&ex(&mut s, "node.create", json!({"type": "text", "text": "Gradient", "props": {"fontSize": 48, "fills": fills}}))); + let c = css(&mut s, t); + assert!(c.contains("background: linear-gradient("), "{c}"); + assert!(c.contains("-webkit-background-clip: text;"), "{c}"); + assert!(c.contains("\nbackground-clip: text;"), "{c}"); + assert!(c.contains("color: transparent;"), "{c}"); + let tw = code(&mut s, t, json!({"language": "tailwind"})); + assert!(tw.contains("bg-clip-text") && tw.contains("text-transparent"), "{tw}"); + // A box keeps its gradient as a plain background. + let r = rect(&mut s, 0.0, 0.0, 50.0, 50.0, None); + let set = s.execute("node.set", &json!({"id": r, "props": {"fills": fills}})); + assert!(set.is_ok(), "{set:?}"); + let box_css = css(&mut s, r); + assert!(box_css.contains("background: linear-gradient("), "{box_css}"); + assert!(!box_css.contains("background-clip"), "{box_css}"); +} + +#[test] +fn text_gradient_under_a_solid_fill_keeps_the_solid_ink() { + let mut s = Session::new(); + let fills = json!([{"type": "linearGradient", "stops": ["#D98200", "#FF6B4A"]}, {"type": "solid", "color": "#112233"}]); + let t = id(&ex(&mut s, "node.create", json!({"type": "text", "text": "Gradient", "props": {"fontSize": 48, "fills": fills}}))); + let c = css(&mut s, t); + assert!(!c.contains("color: transparent;"), "{c}"); + assert!(!c.contains("background-clip"), "{c}"); + assert!(c.contains("color: #112233;"), "{c}"); +} From 4b853f455af2c83d629de7321c1204ac35bec9b2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 15:49:46 -0500 Subject: [PATCH 078/129] M6: serialize Android drawables through craft-vectordrawable --- Cargo.lock | 2 +- Cargo.toml | 2 +- ROADMAP.md | 3 +- crates/vectordrawable/src/lib.rs | 2 +- crates/vectordrawable/src/xml.rs | 274 +++++------------- crates/vectordrawable/src/xml_legacy_test.rs | 213 ++++++++++++++ crates/vectordrawable/src/xml_parity_tests.rs | 136 +++++++++ docs/file-format-parity.md | 5 +- 8 files changed, 430 insertions(+), 207 deletions(-) create mode 100644 crates/vectordrawable/src/xml_legacy_test.rs create mode 100644 crates/vectordrawable/src/xml_parity_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 879856783..bd8070ef6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1236,7 +1236,7 @@ dependencies = [ [[package]] name = "craft-vectordrawable" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" +source = "git+https://github.com/storytold/craft-libs?rev=1d5255e07f2463ea784860505e1f7ce68d6adffd#1d5255e07f2463ea784860505e1f7ce68d6adffd" dependencies = [ "kurbo", ] diff --git a/Cargo.toml b/Cargo.toml index 82831e556..479e77d32 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ repository = "https://github.com/storytold/figcraft" [workspace.dependencies] craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } -craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } +craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1d5255e07f2463ea784860505e1f7ce68d6adffd" } # internal figcraft-geom = { path = "crates/geom" } figcraft-color = { path = "crates/color" } diff --git a/ROADMAP.md b/ROADMAP.md index fc03c5385..bebcd9168 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-17 · **Change:** minor (CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | diff --git a/crates/vectordrawable/src/lib.rs b/crates/vectordrawable/src/lib.rs index f12e91585..c79c6a9a3 100644 --- a/crates/vectordrawable/src/lib.rs +++ b/crates/vectordrawable/src/lib.rs @@ -103,7 +103,7 @@ pub fn try_export(doc: &Document, ids: &[NodeId], opts: &VdOptions) -> Result String { - let [r, g, b, a] = c.sanitized().to_rgba8(); - if a == 255 { format!("#{r:02X}{g:02X}{b:02X}") } else { format!("#{a:02X}{r:02X}{g:02X}{b:02X}") } -} +// One document level can add a frame clip, a mask clip and a named group, plus the leaf gradient's +// transform group. Keep every layer admitted by check_export_depth, not just 256 XML groups. +const XML_DEPTH: usize = 3 * (figcraft_render::MAX_EXPORT_DEPTH + 1) + 2; +const _: () = assert!(XML_DEPTH <= craft_vectordrawable::write::MAX_CONFIGURED_DEPTH); -struct Out { - s: String, -} - -impl Out { - /// ``, else `>`. - fn open(&mut self, depth: usize, tag: &str, attrs: &[(&str, String)], close: bool) { - let pad = " ".repeat(depth); - let _ = write!(self.s, "{pad}<{tag}"); - for (i, (k, v)) in attrs.iter().enumerate() { - if i == 0 && attrs.len() == 1 { - let _ = write!(self.s, " {k}=\"{v}\""); - } else { - let _ = write!(self.s, "\n{pad} {k}=\"{v}\""); - } - } - self.s.push_str(if close { " />\n" } else { ">\n" }); - } - - fn close(&mut self, depth: usize, tag: &str) { - let _ = writeln!(self.s, "{}", " ".repeat(depth)); - } -} - -fn uses_gradient(items: &[Item]) -> bool { - items.iter().any(|it| match &it.kind { - ItemKind::Path(p) => matches!(p.fill, Some(Fill::Gradient(_))), - ItemKind::Group(g) => uses_gradient(&g.children), - }) -} - -/// The whole file: a `width`×`height` dp drawable with a viewport of the same size. -pub(crate) fn document(width: f64, height: f64, items: &[Item]) -> String { - let mut o = Out { s: String::from("\n") }; - let mut attrs = vec![("xmlns:android", ANDROID.to_string())]; - if uses_gradient(items) { - attrs.push(("xmlns:aapt", AAPT.to_string())); - } - attrs.extend([ - ("android:width", format!("{}dp", num(width))), - ("android:height", format!("{}dp", num(height))), - ("android:viewportWidth", num(width)), - ("android:viewportHeight", num(height)), - ]); - o.open(0, "vector", &attrs, false); - if items.is_empty() { - // Android refuses a without a ("no path defined"): one empty, unfilled path. - o.open(1, "path", &[("android:pathData", "M0,0".to_string())], true); - } - for it in items { - item(&mut o, 1, it); - } - o.close(0, "vector"); - o.s -} - -fn item(o: &mut Out, depth: usize, it: &Item) { - match &it.kind { - ItemKind::Path(p) => path(o, depth, p), - ItemKind::Group(g) => group(o, depth, g), - } -} - -fn group(o: &mut Out, depth: usize, g: &GroupItem) { - let mut attrs = Vec::new(); - if let Some(n) = &g.name { - attrs.push(("android:name", esc(n))); - } - if let Some(x) = &g.xf { - let (sx, sy) = x.scale; - if num(x.rotation) != "0" { - attrs.push(("android:rotation", num(x.rotation))); - } - if num(sx) != "1" { - attrs.push(("android:scaleX", num(sx))); - } - if num(sy) != "1" { - attrs.push(("android:scaleY", num(sy))); - } - if num(x.translate.0) != "0" { - attrs.push(("android:translateX", num(x.translate.0))); - } - if num(x.translate.1) != "0" { - attrs.push(("android:translateY", num(x.translate.1))); - } - } - if g.children.is_empty() && g.clip.is_none() { - o.open(depth, "group", &attrs, true); - return; - } - o.open(depth, "group", &attrs, false); - if let Some(c) = &g.clip { - o.open(depth + 1, "clip-path", &[("android:pathData", path_data(c))], true); - } - for c in &g.children { - item(o, depth + 1, c); - } - o.close(depth, "group"); -} - -fn stroke_attrs(attrs: &mut Vec<(&str, String)>, s: &NativeStroke) { - attrs.push(("android:strokeColor", color(s.color))); - attrs.push(("android:strokeWidth", num(s.width))); - if s.cap != "butt" { - attrs.push(("android:strokeLineCap", s.cap.to_string())); - } - if s.join != "miter" { - attrs.push(("android:strokeLineJoin", s.join.to_string())); - } else if num(s.miter) != "4" { - attrs.push(("android:strokeMiterLimit", num(s.miter))); - } -} - -fn path(o: &mut Out, depth: usize, p: &PathItem) { - let mut attrs = Vec::new(); - if let Some(n) = &p.name { - attrs.push(("android:name", esc(n))); - } - attrs.push(("android:pathData", path_data(&p.data))); - if let Some(Fill::Solid(c)) = &p.fill { - attrs.push(("android:fillColor", color(*c))); - } - if let Some(s) = &p.stroke { - stroke_attrs(&mut attrs, s); - } - if p.even_odd && p.fill.is_some() { - attrs.push(("android:fillType", "evenOdd".to_string())); - } - let Some(Fill::Gradient(g)) = &p.fill else { - o.open(depth, "path", &attrs, true); - return; - }; - o.open(depth, "path", &attrs, false); - o.open(depth + 1, "aapt:attr", &[("name", "android:fillColor".to_string())], false); - let mut ga = Vec::new(); - match g.kind { - GradKind::Linear { start, end } => { - ga.push(("android:type", "linear".to_string())); - ga.push(("android:startX", num(start.0))); - ga.push(("android:startY", num(start.1))); - ga.push(("android:endX", num(end.0))); - ga.push(("android:endY", num(end.1))); - } - GradKind::Radial { center, radius } => { - ga.push(("android:type", "radial".to_string())); - ga.push(("android:centerX", num(center.0))); - ga.push(("android:centerY", num(center.1))); - ga.push(("android:gradientRadius", num(radius))); - } - GradKind::Sweep { center } => { - ga.push(("android:type", "sweep".to_string())); - ga.push(("android:centerX", num(center.0))); - ga.push(("android:centerY", num(center.1))); - } - } - o.open(depth + 2, "gradient", &ga, false); - for (off, c) in &g.stops { - o.open(depth + 3, "item", &[("android:offset", num(*off)), ("android:color", color(*c))], true); - } - o.close(depth + 2, "gradient"); - o.close(depth + 1, "aapt:attr"); - o.close(depth, "path"); +fn wire_color(c: Color) -> wire::Color { + // FigCraft clamps positive infinity to one (the neutral writer maps non-finite to zero). + // Preserve the application's sanitization before passing its finite components onward. + let c = c.sanitized(); + [c.r, c.g, c.b, c.a] } #[cfg(test)] -mod shared_wire_tests { - use super::*; - use figcraft_geom::BezPath; - - #[test] - fn shared_attributes_preserve_exact_xml() { - assert_eq!(esc("<&>\"'\t\n\r\0\u{ffff}é𝄞 "), "<&>"' é𝄞&#9;"); - } - - #[test] - fn shared_numbers_and_paths_preserve_android_syntax() { - assert_eq!(num(-0.0001), "0"); - assert_eq!(num(f64::NAN), "0"); - assert_eq!(num(f64::INFINITY), "0"); - assert_eq!(num(1.23456), "1.235"); - let mut p = BezPath::new(); - p.move_to((0.0, -0.0)); - p.line_to((1.23456, 2.0)); - p.quad_to((3.0, 4.0), (5.0, 6.0)); - p.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0)); - p.close_path(); - assert_eq!(path_data(&p), "M0,0 L1.235,2 Q3,4 5,6 C7,8 9,10 11,12 Z"); - } +pub(crate) fn color(c: Color) -> String { + craft_vectordrawable::write::color(wire_color(c)) } + +fn item(it: Item, depth: usize) -> wire::Item { + let kind = match it.kind { + ItemKind::Path(p) => wire::ItemKind::Path(wire::Path { + name: p.name, + data: p.data, + even_odd: p.even_odd, + fill: p.fill.map(|f| match f { + Fill::Solid(c) => wire::Fill::Solid(wire_color(c)), + Fill::Gradient(g) => wire::Fill::Gradient(wire::Gradient { + kind: match g.kind { + GradKind::Linear { start, end } => wire::GradientKind::Linear { start, end }, + GradKind::Radial { center, radius } => wire::GradientKind::Radial { center, radius }, + GradKind::Sweep { center } => wire::GradientKind::Sweep { center }, + }, + stops: g.stops.into_iter().map(|(offset, c)| (offset, wire_color(c))).collect(), + }), + }), + stroke: p.stroke.map(|s| wire::Stroke { + color: wire_color(s.color), + width: s.width, + miter: s.miter, + cap: match s.cap { + "round" => wire::Cap::Round, + "square" => wire::Cap::Square, + _ => wire::Cap::Butt, + }, + join: match s.join { + "round" => wire::Join::Round, + "bevel" => wire::Join::Bevel, + _ => wire::Join::Miter, + }, + }), + }), + ItemKind::Group(g) => wire::ItemKind::Group(wire::Group { + name: g.name, + clip: g.clip, + transform: g.xf.map(|x| wire::GroupTransform { translate: x.translate, rotation: x.rotation, scale: x.scale }), + // Bound adaptation as well as writing. Production trees are bounded by the source + // layer guard and generated wrappers; don't recurse beyond that invariant. + children: if depth < XML_DEPTH { g.children.into_iter().map(|it| item(it, depth + 1)).collect() } else { Vec::new() }, + }), + }; + wire::Item { kind, bbox: it.bbox } +} + +pub(crate) fn document(width: f64, height: f64, items: Vec) -> String { + let items: Vec<_> = items.into_iter().map(|it| item(it, 1)).collect(); + craft_vectordrawable::write::document_with_depth_limit(width, height, &items, XML_DEPTH) +} + +#[cfg(test)] +#[path = "xml_legacy_test.rs"] +mod legacy; +#[cfg(test)] +#[path = "xml_parity_tests.rs"] +mod parity_tests; diff --git a/crates/vectordrawable/src/xml_legacy_test.rs b/crates/vectordrawable/src/xml_legacy_test.rs new file mode 100644 index 000000000..5e8b008d1 --- /dev/null +++ b/crates/vectordrawable/src/xml_legacy_test.rs @@ -0,0 +1,213 @@ +// Test-only parity oracle: FigCraft XML writer before shared cutover. +// Original writer by Filip Strajnar (8b5441eb), with subsequent contributor fixes. +//! The pretty-printed XML: elements two spaces deeper per level, one attribute per line four +//! spaces past its element (as Android Studio formats drawables). Numbers are compact (at most +//! three decimals, no `-0`) and always finite; text is escaped for attribute values. + +use std::fmt::Write as _; + +use figcraft_color::Color; + +use crate::model::{Fill, GradKind, GroupItem, Item, ItemKind, NativeStroke, PathItem}; + +const ANDROID: &str = "http://schemas.android.com/apk/res/android"; +const AAPT: &str = "http://schemas.android.com/aapt"; + +// Shared wire primitives; app-specific drawable projection and colour policy stay here. +pub(crate) use craft_vectordrawable::write::{esc, num, path_data}; + +/// `#RRGGBB`, or `#AARRGGBB` when not opaque. +pub(crate) fn color(c: Color) -> String { + let [r, g, b, a] = c.sanitized().to_rgba8(); + if a == 255 { format!("#{r:02X}{g:02X}{b:02X}") } else { format!("#{a:02X}{r:02X}{g:02X}{b:02X}") } +} + +struct Out { + s: String, +} + +impl Out { + /// ``, else `>`. + fn open(&mut self, depth: usize, tag: &str, attrs: &[(&str, String)], close: bool) { + let pad = " ".repeat(depth); + let _ = write!(self.s, "{pad}<{tag}"); + for (i, (k, v)) in attrs.iter().enumerate() { + if i == 0 && attrs.len() == 1 { + let _ = write!(self.s, " {k}=\"{v}\""); + } else { + let _ = write!(self.s, "\n{pad} {k}=\"{v}\""); + } + } + self.s.push_str(if close { " />\n" } else { ">\n" }); + } + + fn close(&mut self, depth: usize, tag: &str) { + let _ = writeln!(self.s, "{}", " ".repeat(depth)); + } +} + +fn uses_gradient(items: &[Item]) -> bool { + items.iter().any(|it| match &it.kind { + ItemKind::Path(p) => matches!(p.fill, Some(Fill::Gradient(_))), + ItemKind::Group(g) => uses_gradient(&g.children), + }) +} + +/// The whole file: a `width`×`height` dp drawable with a viewport of the same size. +pub(crate) fn document(width: f64, height: f64, items: &[Item]) -> String { + let mut o = Out { s: String::from("\n") }; + let mut attrs = vec![("xmlns:android", ANDROID.to_string())]; + if uses_gradient(items) { + attrs.push(("xmlns:aapt", AAPT.to_string())); + } + attrs.extend([ + ("android:width", format!("{}dp", num(width))), + ("android:height", format!("{}dp", num(height))), + ("android:viewportWidth", num(width)), + ("android:viewportHeight", num(height)), + ]); + o.open(0, "vector", &attrs, false); + if items.is_empty() { + // Android refuses a without a ("no path defined"): one empty, unfilled path. + o.open(1, "path", &[("android:pathData", "M0,0".to_string())], true); + } + for it in items { + item(&mut o, 1, it); + } + o.close(0, "vector"); + o.s +} + +fn item(o: &mut Out, depth: usize, it: &Item) { + match &it.kind { + ItemKind::Path(p) => path(o, depth, p), + ItemKind::Group(g) => group(o, depth, g), + } +} + +fn group(o: &mut Out, depth: usize, g: &GroupItem) { + let mut attrs = Vec::new(); + if let Some(n) = &g.name { + attrs.push(("android:name", esc(n))); + } + if let Some(x) = &g.xf { + let (sx, sy) = x.scale; + if num(x.rotation) != "0" { + attrs.push(("android:rotation", num(x.rotation))); + } + if num(sx) != "1" { + attrs.push(("android:scaleX", num(sx))); + } + if num(sy) != "1" { + attrs.push(("android:scaleY", num(sy))); + } + if num(x.translate.0) != "0" { + attrs.push(("android:translateX", num(x.translate.0))); + } + if num(x.translate.1) != "0" { + attrs.push(("android:translateY", num(x.translate.1))); + } + } + if g.children.is_empty() && g.clip.is_none() { + o.open(depth, "group", &attrs, true); + return; + } + o.open(depth, "group", &attrs, false); + if let Some(c) = &g.clip { + o.open(depth + 1, "clip-path", &[("android:pathData", path_data(c))], true); + } + for c in &g.children { + item(o, depth + 1, c); + } + o.close(depth, "group"); +} + +fn stroke_attrs(attrs: &mut Vec<(&str, String)>, s: &NativeStroke) { + attrs.push(("android:strokeColor", color(s.color))); + attrs.push(("android:strokeWidth", num(s.width))); + if s.cap != "butt" { + attrs.push(("android:strokeLineCap", s.cap.to_string())); + } + if s.join != "miter" { + attrs.push(("android:strokeLineJoin", s.join.to_string())); + } else if num(s.miter) != "4" { + attrs.push(("android:strokeMiterLimit", num(s.miter))); + } +} + +fn path(o: &mut Out, depth: usize, p: &PathItem) { + let mut attrs = Vec::new(); + if let Some(n) = &p.name { + attrs.push(("android:name", esc(n))); + } + attrs.push(("android:pathData", path_data(&p.data))); + if let Some(Fill::Solid(c)) = &p.fill { + attrs.push(("android:fillColor", color(*c))); + } + if let Some(s) = &p.stroke { + stroke_attrs(&mut attrs, s); + } + if p.even_odd && p.fill.is_some() { + attrs.push(("android:fillType", "evenOdd".to_string())); + } + let Some(Fill::Gradient(g)) = &p.fill else { + o.open(depth, "path", &attrs, true); + return; + }; + o.open(depth, "path", &attrs, false); + o.open(depth + 1, "aapt:attr", &[("name", "android:fillColor".to_string())], false); + let mut ga = Vec::new(); + match g.kind { + GradKind::Linear { start, end } => { + ga.push(("android:type", "linear".to_string())); + ga.push(("android:startX", num(start.0))); + ga.push(("android:startY", num(start.1))); + ga.push(("android:endX", num(end.0))); + ga.push(("android:endY", num(end.1))); + } + GradKind::Radial { center, radius } => { + ga.push(("android:type", "radial".to_string())); + ga.push(("android:centerX", num(center.0))); + ga.push(("android:centerY", num(center.1))); + ga.push(("android:gradientRadius", num(radius))); + } + GradKind::Sweep { center } => { + ga.push(("android:type", "sweep".to_string())); + ga.push(("android:centerX", num(center.0))); + ga.push(("android:centerY", num(center.1))); + } + } + o.open(depth + 2, "gradient", &ga, false); + for (off, c) in &g.stops { + o.open(depth + 3, "item", &[("android:offset", num(*off)), ("android:color", color(*c))], true); + } + o.close(depth + 2, "gradient"); + o.close(depth + 1, "aapt:attr"); + o.close(depth, "path"); +} + +#[cfg(test)] +mod shared_wire_tests { + use super::*; + use figcraft_geom::BezPath; + + #[test] + fn shared_attributes_preserve_exact_xml() { + assert_eq!(esc("<&>\"'\t\n\r\0\u{ffff}é𝄞 "), "<&>"' é𝄞&#9;"); + } + + #[test] + fn shared_numbers_and_paths_preserve_android_syntax() { + assert_eq!(num(-0.0001), "0"); + assert_eq!(num(f64::NAN), "0"); + assert_eq!(num(f64::INFINITY), "0"); + assert_eq!(num(1.23456), "1.235"); + let mut p = BezPath::new(); + p.move_to((0.0, -0.0)); + p.line_to((1.23456, 2.0)); + p.quad_to((3.0, 4.0), (5.0, 6.0)); + p.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0)); + p.close_path(); + assert_eq!(path_data(&p), "M0,0 L1.235,2 Q3,4 5,6 C7,8 9,10 11,12 Z"); + } +} diff --git a/crates/vectordrawable/src/xml_parity_tests.rs b/crates/vectordrawable/src/xml_parity_tests.rs new file mode 100644 index 000000000..52b89de43 --- /dev/null +++ b/crates/vectordrawable/src/xml_parity_tests.rs @@ -0,0 +1,136 @@ +use super::*; +use crate::model::{Grad, GroupItem, GroupXf, NativeStroke, PathItem}; +use figcraft_geom::{BezPath, Rect}; + +fn path(fill: Option, cap: &'static str, join: &'static str, c: Color) -> Item { + let mut data = BezPath::new(); + data.move_to((0.0, -0.0)); + data.line_to((1.23456, 2.0)); + data.quad_to((3.0, 4.0), (5.0, 6.0)); + data.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0)); + data.close_path(); + Item { + bbox: Rect::ZERO, + kind: ItemKind::Path(PathItem { + name: Some("<&>\"'\t\n\r\0\u{ffff}é𝄞 ".into()), + data, + fill, + stroke: Some(NativeStroke { color: c, width: 2.34567, cap, join, miter: 3.0 }), + even_odd: true, + }), + } +} + +fn parity(w: f64, h: f64, items: &[Item]) { + let actual = document(w, h, items.to_vec()); + assert_eq!(actual, legacy::document(w, h, items)); + let parsed = roxmltree::Document::parse(&actual).unwrap(); + assert_eq!(parsed.root_element().tag_name().name(), "vector"); +} + +#[test] +fn complete_documents_preserve_exact_bytes_and_app_colour_policy() { + parity(0.0, f64::INFINITY, &[]); + let colours = [ + Color::BLACK, + Color::from_rgba8(26, 43, 60, 128), + Color { r: f32::INFINITY, g: f32::NEG_INFINITY, b: f32::NAN, a: f32::INFINITY }, + Color { r: 0.49999, g: 0.50001, b: 2.0, a: -1.0 }, + ]; + for c in colours { + let fills = [ + None, + Some(Fill::Solid(c)), + Some(Fill::Gradient(Grad { kind: GradKind::Linear { start: (0.0, 1.0), end: (3.0, 4.0) }, stops: vec![(0.0, c), (1.0, Color::WHITE)] })), + Some(Fill::Gradient(Grad { kind: GradKind::Radial { center: (5.0, 6.0), radius: 7.0 }, stops: vec![(f64::NAN, c)] })), + Some(Fill::Gradient(Grad { kind: GradKind::Sweep { center: (8.0, 9.0) }, stops: vec![] })), + ]; + for fill in fills { + for cap in ["butt", "round", "square"] { + for join in ["miter", "round", "bevel"] { + let leaf = path(fill.clone(), cap, join, c); + parity(24.12345, 18.0, std::slice::from_ref(&leaf)); + let group = Item { + bbox: Rect::ZERO, + kind: ItemKind::Group(GroupItem { + name: Some("group&\"".into()), + xf: Some(GroupXf { translate: (2.0, -3.0), rotation: 45.0, scale: (1.0, 2.0) }), + clip: Some(BezPath::new()), + children: vec![leaf], + }), + }; + parity(24.0, 18.0, &[group]); + } + } + } + } +} + +#[test] +fn source_depth_wrappers_do_not_lose_the_deepest_accepted_leaf() { + let mut leaf = path(Some(Fill::Gradient(Grad { kind: GradKind::Sweep { center: (0.0, 0.0) }, stops: vec![] })), "butt", "miter", Color::BLACK); + for _ in 0..XML_DEPTH - 2 { + leaf = Item { bbox: Rect::ZERO, kind: ItemKind::Group(GroupItem { name: None, xf: None, clip: None, children: vec![leaf] }) }; + } + let items = [leaf]; + let xml = document(1.0, 1.0, items.to_vec()); + assert_eq!(xml, legacy::document(1.0, 1.0, &items)); + assert!(xml.contains("aapt") && xml.contains(" **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.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-17 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.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 @@ -57,7 +57,7 @@ export limit, not a native document nesting limit. | SVG | yes (outline text option, ids) | yes | alpha/luminance masks kept; noise, texture, progressive and background blur, glass embedded as images; outline text (off: `` with one `` per line, one style per layer), unique id attributes from layer names, explicit depth-limit refusal, nested frames clipped by their parent's clip (#327), simplified strokes (stroke attributes for centred strokes and for inside and outside strokes on boxes and ellipses) | — | | PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal; RGB is always sRGB (no color profile setting and no output intent) | CMYK output intent 2–4 | | WebP | — | yes (ours) | a color profile per setting as for PNG; sRGB files untagged, Display P3 files with the generated ICC profile | — | -| Android Vector Drawable (XML) | — | yes (ours) | an `.xml` drawable resource (`file.export {format: "xml"}`, export settings, File ▸ Export…, the CLI and MCP), pretty-printed, sized in dp with the viewport in layer units, for AndroidX (VectorDrawableCompat: gradients and even-odd need API 24 without it). Shapes, booleans and text as path data with transforms baked in; solid fills and linear, radial and sweep gradients (`aapt:attr`, exact for any handles: radial and sweep in a `` that maps the unit circle); centred strokes as stroke attributes where Android draws them the same (uniform scale, one cap, no dashes or variable width), other strokes as filled outlines; clipping frames and masks as `` with ``; `android:name` from layer names with the id attribute option. What the format can't hold goes by the compatibility mode (`vdCompat`): best effort (default) applies layer opacity to each shape, rewrites even-odd fills and clip outlines as non-zero, draws diamond gradients as radial and alpha masks as outline clips, each with a warning; exact leaves out what it can't draw exactly, with a warning; ignore writes what maps without warnings: layer opacity over overlapping shapes is dropped (drawn opaque), even-odd fills keep `fillType="evenOdd"`, even-odd clip outlines clip as non-zero, diamond gradients are left out and alpha masks clip to their outline. Effects, image and pattern fills and blend modes are always left out (warned except in ignore); an export that draws nothing writes one empty path (Android refuses a drawable without a path), with a warning. Checked by parsing the XML, against FigCraft's renderer (gradients pixel by pixel), with `aapt2 compile` and `link`, and by rendering samples (linear, skewed radial and sweep gradients, a sweep with mirrored handles, even-odd booleans, centred and inside strokes, rotated text, a clipping frame, an alpha mask, a translucent group, each compatibility mode) with Android 13's (API 33) VectorDrawable on an emulator, next to FigCraft's PNG export: they match, including where the sweep starts and which way it turns, except what the compatibility mode and its warnings say (best effort: overlapping shapes in a translucent group look denser; exact and ignore leave out or draw opaque what they list). Not checked on API 21–23 (VectorDrawableCompat) | — | +| Android Vector Drawable (XML) | — | yes (ours) | an `.xml` drawable resource serialized by `craft-vectordrawable` through an app-model adapter (`file.export {format: "xml"}`, export settings, File ▸ Export…, the CLI and MCP), pretty-printed, sized in dp with the viewport in layer units, for AndroidX (VectorDrawableCompat: gradients and even-odd need API 24 without it). Shapes, booleans and text as path data with transforms baked in; solid fills and linear, radial and sweep gradients (`aapt:attr`, exact for any handles: radial and sweep in a `` that maps the unit circle); centred strokes as stroke attributes where Android draws them the same (uniform scale, one cap, no dashes or variable width), other strokes as filled outlines; clipping frames and masks as `` with ``; `android:name` from layer names with the id attribute option. What the format can't hold goes by the compatibility mode (`vdCompat`): best effort (default) applies layer opacity to each shape, rewrites even-odd fills and clip outlines as non-zero, draws diamond gradients as radial and alpha masks as outline clips, each with a warning; exact leaves out what it can't draw exactly, with a warning; ignore writes what maps without warnings: layer opacity over overlapping shapes is dropped (drawn opaque), even-odd fills keep `fillType="evenOdd"`, even-odd clip outlines clip as non-zero, diamond gradients are left out and alpha masks clip to their outline. Effects, image and pattern fills and blend modes are always left out (warned except in ignore); an export that draws nothing writes one empty path (Android refuses a drawable without a path), with a warning. Checked by parsing the XML, against FigCraft's renderer (gradients pixel by pixel), with `aapt2 compile` and `link`, and by rendering samples (linear, skewed radial and sweep gradients, a sweep with mirrored handles, even-odd booleans, centred and inside strokes, rotated text, a clipping frame, an alpha mask, a translucent group, each compatibility mode) with Android 13's (API 33) VectorDrawable on an emulator, next to FigCraft's PNG export: they match, including where the sweep starts and which way it turns, except what the compatibility mode and its warnings say (best effort: overlapping shapes in a translucent group look denser; exact and ignore leave out or draw opaque what they list). Not checked on API 21–23 (VectorDrawableCompat) | — | | Copy as CSS / SVG / PNG / text / link | yes | yes | Copy as PNG: the whole selection at 2x | — | | Dev Mode code (CSS, iOS SwiftUI, Android Compose) | yes | yes, plus HTML, React, Vue, Leptos, ArkUI and Flutter | see [dev-mode-parity](dev-mode-parity.md) | — | | `.fig` ("Save local copy") | yes | **experimental** | the whole file, also as a copy from File ▸ Save as… (the document keeps its `.figcraft` path and unsaved state); see [Export to `.fig`](#export-to-fig-experimental). Round trips through our own importer; written files checked by opening them in other software: layers, fills, gradients, strokes, shadows, vectors, components and text draw as in FigCraft; resized and scaled instances keep their size and lay their layers out for it, variables with their modes and colour bindings resolve there (a frame set to another mode shows that mode's colours, also inside instances), colour, text, effect and grid styles are listed, and variable-width strokes that are the same on both sides of the path draw with their width | 5–15 (non-colour bindings as bindings, checks of effects, images and prototypes, and against real files) | @@ -196,6 +196,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. | | 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software | | 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 | From 0148633267b601ca8cffdc56c16248c9923b4034 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 16:35:18 -0500 Subject: [PATCH 079/129] Avoid recursive VectorDrawable adaptation and destruction --- crates/vectordrawable/src/xml.rs | 66 +++++++++++++++++-- crates/vectordrawable/src/xml_parity_tests.rs | 19 ++++++ 2 files changed, 78 insertions(+), 7 deletions(-) diff --git a/crates/vectordrawable/src/xml.rs b/crates/vectordrawable/src/xml.rs index 466e57fd6..40a13761c 100644 --- a/crates/vectordrawable/src/xml.rs +++ b/crates/vectordrawable/src/xml.rs @@ -25,7 +25,7 @@ pub(crate) fn color(c: Color) -> String { craft_vectordrawable::write::color(wire_color(c)) } -fn item(it: Item, depth: usize) -> wire::Item { +fn item(it: Item) -> wire::Item { let kind = match it.kind { ItemKind::Path(p) => wire::ItemKind::Path(wire::Path { name: p.name, @@ -62,17 +62,69 @@ fn item(it: Item, depth: usize) -> wire::Item { name: g.name, clip: g.clip, transform: g.xf.map(|x| wire::GroupTransform { translate: x.translate, rotation: x.rotation, scale: x.scale }), - // Bound adaptation as well as writing. Production trees are bounded by the source - // layer guard and generated wrappers; don't recurse beyond that invariant. - children: if depth < XML_DEPTH { g.children.into_iter().map(|it| item(it, depth + 1)).collect() } else { Vec::new() }, + children: Vec::new(), }), }; wire::Item { kind, bbox: it.bbox } } -pub(crate) fn document(width: f64, height: f64, items: Vec) -> String { - let items: Vec<_> = items.into_iter().map(|it| item(it, 1)).collect(); - craft_vectordrawable::write::document_with_depth_limit(width, height, &items, XML_DEPTH) +// Explicit iterator frames keep traversal scratch proportional to depth, not sibling count. +fn items(input: Vec) -> Vec { + let mut frames = vec![(input.into_iter(), Vec::new(), None::)]; + loop { + let depth = frames.len(); + let frame = frames.last_mut().unwrap(); + if let Some(mut source) = frame.0.next() { + let children = match &mut source.kind { + ItemKind::Group(g) => std::mem::take(&mut g.children), + ItemKind::Path(_) => Vec::new(), + }; + let mapped = item(source); + if !children.is_empty() && depth < XML_DEPTH { + frames.push((children.into_iter(), Vec::new(), Some(mapped))); + } else { + discard_items(children); + frame.1.push(mapped); + } + } else { + let (_, children, parent) = frames.pop().unwrap(); + let Some(mut parent) = parent else { return children }; + if let wire::ItemKind::Group(g) = &mut parent.kind { + g.children = children; + } + frames.last_mut().unwrap().1.push(parent); + } + } +} + +fn discard_items(items: Vec) { + let mut frames = vec![items.into_iter()]; + while let Some(frame) = frames.last_mut() { + if let Some(mut item) = frame.next() { + if let ItemKind::Group(g) = &mut item.kind { + frames.push(std::mem::take(&mut g.children).into_iter()); + } + } else { + frames.pop(); + } + } +} + +pub(crate) fn document(width: f64, height: f64, input: Vec) -> String { + let items = items(input); + let output = craft_vectordrawable::write::document_with_depth_limit(width, height, &items, XML_DEPTH); + // Recursive enum destruction also consumes stack, even with an iterative writer. + let mut frames = vec![items.into_iter()]; + while let Some(frame) = frames.last_mut() { + if let Some(mut item) = frame.next() { + if let wire::ItemKind::Group(g) = &mut item.kind { + frames.push(std::mem::take(&mut g.children).into_iter()); + } + } else { + frames.pop(); + } + } + output } #[cfg(test)] diff --git a/crates/vectordrawable/src/xml_parity_tests.rs b/crates/vectordrawable/src/xml_parity_tests.rs index 52b89de43..bb2d8aa99 100644 --- a/crates/vectordrawable/src/xml_parity_tests.rs +++ b/crates/vectordrawable/src/xml_parity_tests.rs @@ -134,3 +134,22 @@ fn mixed_siblings_nested_empty_and_clipped_groups_keep_closing_order() { ]; parity(48.0, 32.0, &items); } + +#[test] +fn over_depth_input_is_discarded_without_recursive_destruction() { + std::thread::Builder::new() + .stack_size(1024 * 1024) + .spawn(|| { + let mut leaf = path(Some(Fill::Solid(Color::BLACK)), "butt", "miter", Color::BLACK); + for _ in 0..XML_DEPTH * 3 { + leaf = Item { bbox: Rect::ZERO, kind: ItemKind::Group(GroupItem { name: None, xf: None, clip: None, children: vec![leaf] }) }; + } + let output = document(1.0, 1.0, vec![leaf]); + assert_eq!(output.matches("").count(), XML_DEPTH - 1); + assert!(!output.contains(" Date: Tue, 17 Nov 2026 17:01:51 -0500 Subject: [PATCH 080/129] Represent active XML adaptation frame without unwraps --- crates/vectordrawable/src/xml.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/vectordrawable/src/xml.rs b/crates/vectordrawable/src/xml.rs index 40a13761c..fce744f8b 100644 --- a/crates/vectordrawable/src/xml.rs +++ b/crates/vectordrawable/src/xml.rs @@ -70,29 +70,30 @@ fn item(it: Item) -> wire::Item { // Explicit iterator frames keep traversal scratch proportional to depth, not sibling count. fn items(input: Vec) -> Vec { - let mut frames = vec![(input.into_iter(), Vec::new(), None::)]; + let mut parents = Vec::new(); + let mut current = (input.into_iter(), Vec::new()); loop { - let depth = frames.len(); - let frame = frames.last_mut().unwrap(); - if let Some(mut source) = frame.0.next() { + let depth = parents.len() + 1; + if let Some(mut source) = current.0.next() { let children = match &mut source.kind { ItemKind::Group(g) => std::mem::take(&mut g.children), ItemKind::Path(_) => Vec::new(), }; let mapped = item(source); if !children.is_empty() && depth < XML_DEPTH { - frames.push((children.into_iter(), Vec::new(), Some(mapped))); + let previous = std::mem::replace(&mut current, (children.into_iter(), Vec::new())); + parents.push((previous, mapped)); } else { discard_items(children); - frame.1.push(mapped); + current.1.push(mapped); } } else { - let (_, children, parent) = frames.pop().unwrap(); - let Some(mut parent) = parent else { return children }; + let Some((mut previous, mut parent)) = parents.pop() else { return current.1 }; if let wire::ItemKind::Group(g) = &mut parent.kind { - g.children = children; + g.children = current.1; } - frames.last_mut().unwrap().1.push(parent); + previous.1.push(parent); + current = previous; } } } From 9e6a1ba314766eae0400c8951233311239960ed5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 17:44:09 -0500 Subject: [PATCH 081/129] Pin VectorDrawable writer to merged shared depth support --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bd8070ef6..68ac647da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1236,7 +1236,7 @@ dependencies = [ [[package]] name = "craft-vectordrawable" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1d5255e07f2463ea784860505e1f7ce68d6adffd#1d5255e07f2463ea784860505e1f7ce68d6adffd" +source = "git+https://github.com/storytold/craft-libs?rev=5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7#5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7" dependencies = [ "kurbo", ] diff --git a/Cargo.toml b/Cargo.toml index 479e77d32..49dbee61a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ repository = "https://github.com/storytold/figcraft" [workspace.dependencies] craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } -craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1d5255e07f2463ea784860505e1f7ce68d6adffd" } +craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7" } # internal figcraft-geom = { path = "crates/geom" } figcraft-color = { path = "crates/color" } From 33c697e712df3a0ccb3ba7331221a11f06533692 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 31 Oct 2026 09:54:06 +0700 Subject: [PATCH 082/129] M9: the browser build uses team libraries and plugin directories on a server The browser's requests to a server now open library and plugin directory connections, so the panels work there as on the desktop. A plugin installed in the browser lasts as long as the page. --- ROADMAP.md | 3 +- crates/collab-net/src/exchange.rs | 110 +++++++++++++++++++++--- crates/collab-net/src/exchange_tests.rs | 88 ++++++++++++++++++- crates/collab-net/src/lib.rs | 5 +- crates/collab-net/src/manage.rs | 5 +- crates/collab-net/src/requests.rs | 6 ++ crates/collab-net/src/web.rs | 31 +++++-- docs/gaps.md | 6 +- docs/hardware-parity.md | 3 +- docs/plugins.md | 9 +- docs/roadmap.md | 3 +- docs/server.md | 5 +- docs/target-app-parity.md | 3 +- 13 files changed, 238 insertions(+), 39 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index bebcd9168..5536c5b08 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-17 · **Change:** minor (CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | diff --git a/crates/collab-net/src/exchange.rs b/crates/collab-net/src/exchange.rs index b0d103ae1..89e2225b6 100644 --- a/crates/collab-net/src/exchange.rs +++ b/crates/collab-net/src/exchange.rs @@ -7,11 +7,17 @@ //! Publishing ([`publish`]) uploads the document, makes the links and codes others join with when //! it shares, then joins the new file with its edit link; [`background`] sends the hosting and //! sharing requests the engine sends in the background (asking a server about its hosting, -//! starting and stopping a share). +//! starting and stopping a share) and those about team libraries and plugin directories; +//! [`libraries`] the checks of a file's team libraries. use std::collections::VecDeque; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; -use figcraft_collab::message::{self, Admin, AdminReply, ClientMsg, HostInfo, Manage, OpenHosting, PROTOCOL, ServerMsg}; +use figcraft_collab::message::{ + self, Admin, AdminReply, ClientMsg, HostInfo, LibraryReply, LibraryReq, Manage, OpenHosting, OpenLibrary, OpenPlugins, PROTOCOL, PluginReply, + PluginReq, ServerMsg, +}; use figcraft_engine::live::{Event, NetReply, NetRequest, Shared, Status}; use crate::invite::{Endpoint, Invite}; @@ -21,7 +27,7 @@ use crate::requests::{self, Publish, REFUSED}; pub(crate) struct Exchange { pub(crate) server: Endpoint, open: ClientMsg, - requests: VecDeque, + requests: VecDeque, answers: Answers, /// The server let the connection in (its first answer came). ready: bool, @@ -35,6 +41,9 @@ pub(crate) struct Exchange { pub(crate) struct Answers { pub(crate) hosting: Option, pub(crate) replies: Vec, + /// The answer on a library or plugin directory connection. + pub(crate) library: Option, + pub(crate) plugins: Option, } /// What follows an exchange's answers (or why it failed). @@ -61,7 +70,23 @@ impl Exchange { owner: owner.to_string(), }), }; - Self { server, open, requests: requests.into(), answers: Answers::default(), ready: false, asked: false } + Self::opened(server, open, requests.into_iter().map(ClientMsg::Admin).collect()) + } + + /// Ask the library of the file behind `invite` one thing. + pub(crate) fn library(invite: Invite, req: LibraryReq) -> Self { + let open = OpenLibrary { protocol: PROTOCOL, file: invite.file, token: invite.token, client_version: message::client_version() }; + Self::opened(invite.server, ClientMsg::OpenLibrary(open), VecDeque::from([ClientMsg::Library(req)])) + } + + /// Ask the plugin directory of `server` one thing, with its `key` (empty: only browsing). + pub(crate) fn plugins(server: Endpoint, key: String, req: PluginReq) -> Self { + let open = OpenPlugins { protocol: PROTOCOL, key, client_version: message::client_version() }; + Self::opened(server, ClientMsg::OpenPlugins(open), VecDeque::from([ClientMsg::Plugins(req)])) + } + + fn opened(server: Endpoint, open: ClientMsg, requests: VecDeque) -> Self { + Self { server, open, requests, answers: Answers::default(), ready: false, asked: false } } /// The connection's first message. @@ -81,7 +106,11 @@ impl Exchange { /// Why the exchange failed with `e`, as the app says it: a server older than open hosting /// can't read the opening. pub(crate) fn failed(&self, e: String) -> String { - if self.ready || !matches!(self.open, ClientMsg::OpenHosting(_)) { e } else { requests::hosting_error(&self.server, e) } + match self.open { + ClientMsg::OpenHosting(_) if !self.ready => requests::hosting_error(&self.server, e), + ClientMsg::OpenPlugins(_) if !self.ready => requests::directory_error(&self.server, e), + _ => e, + } } /// Take in one message from the server: the next request to send, if one is due; an error @@ -99,13 +128,22 @@ impl Exchange { self.ready = true; self.answers.hosting = Some(*info); } + ServerMsg::Library(r) if self.asked => self.answers.library = Some(*r), + ServerMsg::Library(r) if !self.ready => match *r { + LibraryReply::Ready { .. } => self.ready = true, + other => return Err(format!("the server answered {other:?} instead of opening the library")), + }, + ServerMsg::Plugins(r) if self.asked => self.answers.plugins = Some(*r), + ServerMsg::Plugins(r) if !self.ready => match *r { + PluginReply::Ready { .. } => self.ready = true, + other => return Err(format!("the server answered {other:?} instead of opening its plugin directory")), + }, _ => return Err("the server sent something other than an answer".into()), } self.asked = false; - Ok(self.requests.pop_front().map(|r| { - self.asked = true; - ClientMsg::Admin(r) - })) + let next = self.requests.pop_front(); + self.asked = next.is_some(); + Ok(next) } } @@ -204,9 +242,42 @@ fn codes(s: Sharing, links: requests::Links, then: LinksThen) -> Next { ) } +/// The answer to a library request, from what its exchange got. +fn library_reply(answers: Result) -> Result { + answers.and_then(|a| a.library.ok_or_else(|| "the server didn't answer".to_string())) +} + +/// Ask about the team libraries `jobs` `(link, request)`, in order, each on a connection of its +/// own: the events their fetches end in, with the others' answers left out (a report's says +/// nothing, and an older server refuses it). `fetching` goes down at the end. +pub(crate) fn libraries(mut jobs: VecDeque<(String, LibraryReq)>, mut events: Vec, fetching: Arc) -> Next { + let Some((link, req)) = jobs.pop_front() else { + fetching.store(false, Ordering::SeqCst); + return Next::Done(events, None); + }; + let fetch = matches!(req, LibraryReq::Fetch { .. }); + match Invite::parse(&link) { + Err(reply) => { + if fetch { + events.push(Event::Library { link, reply: Err(reply) }); + } + libraries(jobs, events, fetching) + } + Ok(invite) => Next::Ask( + Box::new(Exchange::library(invite, req)), + Box::new(move |answers| { + if fetch { + events.push(Event::Library { link, reply: library_reply(answers) }); + } + libraries(jobs, events, fetching) + }), + ), + } +} + /// Background request `req` (answered as [`Event::Net`] with `job`), for the requests the -/// browser sends: about a server's hosting, and changing who else gets into a file. `None` for -/// the others. +/// browser sends: about a server's hosting, changing who else gets into a file, its team libraries +/// and its plugin directory. `None` for the others. pub(crate) fn background(job: u64, req: NetRequest) -> Option { let answer = move |reply: NetReply| Next::Done(vec![Event::Net { job, reply: Box::new(reply) }], None); Some(match req { @@ -231,6 +302,21 @@ pub(crate) fn background(job: u64, req: NetRequest) -> Option { share_links(Sharing { server, key, file, owner, revoke, create }, Box::new(move |r| answer(NetReply::Share(r)))) } }, - NetRequest::Plugins { .. } | NetRequest::Library { .. } | NetRequest::Upload(_) => return None, + NetRequest::Library { link, req } => match Invite::parse(&link) { + Err(e) => answer(NetReply::Library(Err(e))), + Ok(invite) => Next::Ask(Box::new(Exchange::library(invite, req)), Box::new(move |a| answer(NetReply::Library(library_reply(a))))), + }, + NetRequest::Plugins { server, req } => match Endpoint::parse(&server) { + Err(e) => answer(NetReply::Plugins(Err(e))), + Ok((server, query)) => { + let key = query.into_iter().find(|(k, _)| k == "key").map(|(_, v)| v).unwrap_or_default(); + let ex = Exchange::plugins(server, key.trim().to_string(), req); + Next::Ask( + Box::new(ex), + Box::new(move |a| answer(NetReply::Plugins(a.and_then(|a| a.plugins.ok_or_else(|| "the server didn't answer".to_string()))))), + ) + } + }, + NetRequest::Upload(_) => return None, }) } diff --git a/crates/collab-net/src/exchange_tests.rs b/crates/collab-net/src/exchange_tests.rs index 85274e411..5e58d8376 100644 --- a/crates/collab-net/src/exchange_tests.rs +++ b/crates/collab-net/src/exchange_tests.rs @@ -4,9 +4,13 @@ //! background requests the browser can send. use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; -use figcraft_collab::message::{self, Access, Admin, AdminReply, ClientMsg, FileInfo, HostInfo, LinkInfo, NewLink, Presence, ServerMsg}; +use figcraft_collab::message::{ + self, Access, Admin, AdminReply, ClientMsg, Detached, FileInfo, HostInfo, LibraryReply, LibraryReq, LinkInfo, NewLink, PluginReply, PluginReq, + Presence, ServerMsg, +}; use figcraft_doc::{Document, NodeId}; use figcraft_engine::live::{Event, NetReply, NetRequest, Shared, Status}; @@ -344,6 +348,84 @@ fn background_requests_ask_about_hosting_and_sharing() { let Some(Next::Done(events, None)) = exchange::background(1, bad) else { panic!("not answered at once") }; assert!(matches!(events.as_slice(), [Event::Net { reply, .. }] if matches!(**reply, NetReply::Hosting(Err(_)) | NetReply::Share(Err(_))))); } - let plugins = NetRequest::Plugins { server: SERVER.into(), req: figcraft_collab::message::PluginReq::List { query: String::new() } }; - assert!(exchange::background(1, plugins).is_none()); +} + +fn library(r: LibraryReply) -> ServerMsg { + ServerMsg::Library(Box::new(r)) +} + +fn directory(r: PluginReply) -> ServerMsg { + ServerMsg::Plugins(Box::new(r)) +} + +fn link() -> String { + format!("figcraft://join?host=127.0.0.1:47910&file={FILE}&token={TOKEN}") +} + +/// The browser opens a team library, asks, and takes the answer; failures come back as answers. +#[test] +fn background_requests_ask_a_team_library() { + let ready = library(LibraryReply::Ready { access: Access::View }); + let req = |req| NetRequest::Library { link: link(), req }; + let (reply, sent) = background(req(LibraryReq::Usage), &[ready.clone(), library(LibraryReply::Usage(Vec::new()))]); + assert!(matches!(reply, NetReply::Library(Ok(LibraryReply::Usage(u))) if u.is_empty())); + assert!(matches!(sent.as_slice(), [ClientMsg::OpenLibrary(o), ClientMsg::Library(LibraryReq::Usage)] if o.file == FILE && o.token == TOKEN)); + // A refusal, and a link that isn't one. + let (reply, _) = background(req(LibraryReq::Usage), &[ServerMsg::Refused { reason: "that link was revoked".into() }]); + assert!(matches!(reply, NetReply::Library(Err(e)) if e.contains("revoked"))); + let bad = NetRequest::Library { link: "nope".into(), req: LibraryReq::Usage }; + let Some(Next::Done(events, None)) = exchange::background(1, bad) else { panic!("not answered at once") }; + assert!(matches!(events.as_slice(), [Event::Net { reply, .. }] if matches!(**reply, NetReply::Library(Err(_))))); + // Anything but the opening's answer first is no answer. + let (reply, _) = background(req(LibraryReq::Usage), &[library(LibraryReply::Empty)]); + assert!(matches!(reply, NetReply::Library(Err(e)) if e.contains("instead of opening the library"))); +} + +/// The browser asks a plugin directory, with the address's key when it has one. +#[test] +fn background_requests_ask_a_plugin_directory() { + let ready = directory(PluginReply::Ready { publisher: true }); + let req = PluginReq::List { query: String::new() }; + let ask = NetRequest::Plugins { server: format!("{SERVER}?key=k3y"), req: req.clone() }; + let (reply, sent) = background(ask, &[ready, directory(PluginReply::List(Vec::new()))]); + assert!(matches!(reply, NetReply::Plugins(Ok(PluginReply::List(entries))) if entries.is_empty())); + assert!(matches!(sent.as_slice(), [ClientMsg::OpenPlugins(o), ClientMsg::Plugins(_)] if o.key == "k3y")); + // A server from before directories can't read the opening. + let older = NetRequest::Plugins { server: SERVER.into(), req }; + let (reply, _) = background(older, &[ServerMsg::Refused { reason: "that couldn't be read".into() }]); + assert!(matches!(reply, NetReply::Plugins(Err(e)) if e.contains("has no plugin directory"))); + let bad = NetRequest::Plugins { server: "nope".into(), req: PluginReq::List { query: String::new() } }; + assert!(matches!(exchange::background(1, bad), Some(Next::Done(..)))); +} + +/// A file's check of its team libraries runs its requests in order, each on a connection of its +/// own; only fetches come back, whatever a report's answer, and a bad link doesn't stop the rest. +#[test] +fn a_library_check_runs_in_order_and_answers_only_its_fetches() { + let fetch = LibraryReq::Fetch { have: None, usage: None }; + let jobs = vec![ + ("nope".to_string(), fetch.clone()), + (link(), fetch), + (link(), LibraryReq::ReportDetached(Detached::default())), + (link(), LibraryReq::ReportInserted(Detached::default())), + ]; + let fetching = Arc::new(AtomicBool::new(true)); + let t0 = Instant::now(); + let (mut d, inbox) = run(exchange::libraries(jobs.into(), Vec::new(), fetching.clone()), t0); + let ready = library(LibraryReply::Ready { access: Access::View }); + d.opened(t0); + say(&mut d, &ready, t0); + say(&mut d, &library(LibraryReply::Empty), t0); + d.opened(t0); + say(&mut d, &ready, t0); + // An older server refuses the report: the check goes on. + say(&mut d, &library(LibraryReply::Failed { reason: "no".into() }), t0); + d.opened(t0); + say(&mut d, &ServerMsg::Refused { reason: "couldn't be read".into() }, t0); + assert!(!fetching.load(Ordering::SeqCst), "the next check may start"); + let events = inbox.drain(); + let replies: Vec<_> = events.iter().filter_map(|e| if let Event::Library { reply, .. } = e { Some(reply) } else { None }).collect(); + assert_eq!(replies.len(), 2, "{events:#?}"); + assert!(replies[0].is_err()); + assert!(matches!(replies[1], Ok(LibraryReply::Empty))); } diff --git a/crates/collab-net/src/lib.rs b/crates/collab-net/src/lib.rs index 3696dbc30..982d8a036 100644 --- a/crates/collab-net/src/lib.rs +++ b/crates/collab-net/src/lib.rs @@ -8,8 +8,9 @@ //! engine's `collab.*` commands drive it and the UI reads the engine's live state. Network //! threads wake the UI through a [`Waker`] only when something arrives; nothing polls. //! -//! The browser build's [`NetLink`] joins sessions and publishes files to servers through the -//! browser's WebSocket API (`web-sys`); hosting a session needs the desktop app. Its connection +//! The browser build's [`NetLink`] joins sessions, publishes files to servers and asks them about +//! team libraries and plugin directories through the browser's WebSocket API (`web-sys`); hosting +//! a session needs the desktop app. Its connection //! logic (`driver.rs`, `exchange.rs`) is target-independent and tested natively. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] diff --git a/crates/collab-net/src/manage.rs b/crates/collab-net/src/manage.rs index aa73a2ec5..96146f830 100644 --- a/crates/collab-net/src/manage.rs +++ b/crates/collab-net/src/manage.rs @@ -17,7 +17,7 @@ use crate::invite::{Endpoint, Invite, Lookup}; use crate::join::ask; use crate::net::{Duplex, NetLimits, config, open}; pub(crate) use crate::requests::REFUSED; -use crate::requests::{code_requests, comment_request, hosting_error, link_requests, made_comment, made_links, shared}; +use crate::requests::{code_requests, comment_request, directory_error, hosting_error, link_requests, made_comment, made_links, shared}; type Ws = WebSocket; @@ -165,8 +165,7 @@ pub fn plugins(server: &Endpoint, key: &str, req: PluginReq, limits: &NetLimits, match reply(&mut ws, limits, pick) { Ok(PluginReply::Ready { .. }) => {} // An older server can't read the request at all. - Err(e) if e.contains("couldn't be read") => return Err(format!("{} has no plugin directory (update the server)", server.display())), - Err(e) => return Err(e), + Err(e) => return Err(directory_error(server, e)), Ok(other) => return Err(format!("the server answered {other:?} instead of opening its plugin directory")), } send(&mut ws, &ClientMsg::Plugins(req))?; diff --git a/crates/collab-net/src/requests.rs b/crates/collab-net/src/requests.rs index a2c7f9439..cb5802d57 100644 --- a/crates/collab-net/src/requests.rs +++ b/crates/collab-net/src/requests.rs @@ -43,6 +43,12 @@ pub(crate) fn key_over_tls(server: &Endpoint, key: Option<&str>) -> Result<(), S /// Why asking `server` about its hosting failed with `e`: a server older than open hosting can't /// read the question. +/// Why opening `server`'s plugin directory failed with `e`: a server from before directories can't +/// read the opening. +pub(crate) fn directory_error(server: &Endpoint, e: String) -> String { + if e.contains("couldn't be read") { format!("{} has no plugin directory (update the server)", server.display()) } else { e } +} + pub(crate) fn hosting_error(server: &Endpoint, e: String) -> String { if e.contains("couldn't be read") { format!("{} takes files only with its key (it is older than this app): add ?key=… to the address", server.display()) diff --git a/crates/collab-net/src/web.rs b/crates/collab-net/src/web.rs index 8c54f6c23..404ca13c7 100644 --- a/crates/collab-net/src/web.rs +++ b/crates/collab-net/src/web.rs @@ -17,8 +17,10 @@ use std::cell::{Cell, RefCell}; use std::collections::BTreeMap; use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; -use figcraft_collab::message::{ClientMsg, Presence}; +use figcraft_collab::message::{ClientMsg, LibraryReq, Presence}; use figcraft_engine::live::{Event, HostOptions, LiveLink, NO_SESSION, NetRequest, PublishOptions, SessionId, SessionInfo}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; @@ -163,19 +165,29 @@ fn socket() -> (u64, BrowserSocket) { (id, BrowserSocket { id, ws: None }) } -/// The browser's [`LiveLink`]: joins sessions and publishes files to servers; hosting a session -/// needs the desktop app. +/// The browser's [`LiveLink`]: joins sessions, publishes files to servers and asks them about team +/// libraries and plugin directories; hosting a session needs the desktop app. pub struct NetLink { /// Each session's number in the thread-local table. sessions: Sessions, /// Answers to requests sent in the background (outlives sessions). background: Inbox, + /// A check of the team libraries is out. + fetching: Arc, } impl NetLink { /// `wake` is called whenever something arrives for the UI (egui's `request_repaint`). pub fn new(wake: Waker) -> Self { - Self { background: Inbox::new(wake.clone()), sessions: Sessions::new(wake) } + Self { background: Inbox::new(wake.clone()), sessions: Sessions::new(wake), fetching: Arc::default() } + } + + /// Run `next` on a connection of its own, its answers for the background. + fn ask(&self, next: exchange::Next) { + let (id, sock) = socket(); + // The exchanges name their own servers. + let cfg = GuestConfig::new(Invite::new("", "", ""), String::new()); + run(id, Driver::asking(sock, cfg, next, self.background.clone(), Instant::now())); } /// Session `session` runs on connection `id` now (the one it had ends). @@ -229,13 +241,16 @@ impl LiveLink for NetLink { fn background(&mut self, job: u64, req: NetRequest) -> bool { let Some(next) = exchange::background(job, req) else { return false }; - let (id, sock) = socket(); - // The exchanges name their own servers. - let cfg = GuestConfig::new(Invite::new("", "", ""), String::new()); - run(id, Driver::asking(sock, cfg, next, self.background.clone(), Instant::now())); + self.ask(next); true } + fn library_background(&mut self, jobs: Vec<(String, LibraryReq)>) { + if !jobs.is_empty() && !self.fetching.swap(true, Ordering::SeqCst) { + self.ask(exchange::libraries(jobs.into(), Vec::new(), self.fetching.clone())); + } + } + fn leave(&mut self, session: SessionId) { if let Some(id) = self.sessions.remove(session) { with_driver(id, |d, now| d.leave(now)); diff --git a/docs/gaps.md b/docs/gaps.md index 2971d9bf0..8e1d60686 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -272,7 +272,8 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe Lines and SVG (plugin API 6, 2026-10-31): a widget layer can be a `line` or an `svg`, whose picture comes in as locked layers, scaled to fit a size. - **Missing:** a public catalogue and Community files, publisher accounts and signatures, ratings - and install counts, background update checks, the directory in the browser build; widgets have no + and install counts, background update checks, keeping plugins installed in the browser past the + page (the directory works there since 2026-10-31); widgets have no timers. Figma's own plugins are JavaScript against Figma's plugin API and don't run. - **Impact:** teams that depend on specific Figma plugins (icons, content, accessibility checks) @@ -617,6 +618,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. | | 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` | | 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` | | 2026-11-17 | minor | Gap 7: the desktop refines a zoom's preview only once the zoom has paused, as the browser does, so a full render that can't be stopped no longer holds up the next steps of a held zoom. Numbers unchanged. Test: `zoom_preview_tests::the_render_thread_refines_a_zoom_only_once_it_pauses` | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index fec7dae37..89ddd48b7 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware and platform parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (unused; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; under Wayland a minimised window answers control and MCP requests in about half a second instead of timing out after 60 s (#1906); images copied in other apps paste in the browser (#492); text reads only the fallback fonts it draws with; `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); a batch keeps one undo snapshot, not one per step (#1099); one depth cap bounds a whole render, pattern sources included, and render threads get 8 MiB stacks (#1082); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); macOS: the Quit menu and ⌘Q ask about unsaved changes (#857); egui/eframe 0.37 dependency migration; hidden-window screenshot deadlines; zoom previews; hidden windows answer control requests; macOS file opening, the Windows start-up message, Linux packaging; copy and paste in the browser; Windows QA pass; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; pen pressure for the Pencil and brushes on Windows and from browser styluses; macOS: quitting ends the process once everything is kept, avoiding the Touch Bar teardown crash (#781); Linux and BSD clipboard: images under Wayland, reads time out; minimised windows under Wayland; window controls on Wayland without server decorations; canvas textures on device pixels) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; unused; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; under Wayland a minimised window answers control and MCP requests in about half a second instead of timing out after 60 s (#1906); images copied in other apps paste in the browser (#492); text reads only the fallback fonts it draws with; `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); a batch keeps one undo snapshot, not one per step (#1099); one depth cap bounds a whole render, pattern sources included, and render threads get 8 MiB stacks (#1082); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); macOS: the Quit menu and ⌘Q ask about unsaved changes (#857); egui/eframe 0.37 dependency migration; hidden-window screenshot deadlines; zoom previews; hidden windows answer control requests; macOS file opening, the Windows start-up message, Linux packaging; copy and paste in the browser; Windows QA pass; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; pen pressure for the Pencil and brushes on Windows and from browser styluses; macOS: quitting ends the process once everything is kept, avoiding the Touch Bar teardown crash (#781); Linux and BSD clipboard: images under Wayland, reads time out; minimised windows under Wayland; window controls on Wayland without server decorations; canvas textures on device pixels) · **Target:** Figma Design (desktop app 126.10.7) How FigCraft uses hardware and which platforms it runs on, against Figma. Figma's desktop app is Electron with a GPU helper process; its canvas renders on the GPU (WebGL, with WebGPU rolling out @@ -50,6 +50,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import). | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | | 2026-11-10 | patch | M10, #1343 (also #1422, #2233): Windows: the window no longer draws below a hidden caption. FigCraft draws its own title bar on Windows and opens undecorated windows, but winit 0.30 still gives them `WS_CAPTION` and `WS_BORDER`; on some systems the desktop compositor reserves that caption, so the content was drawn about 30 px low (a black band above it) while clicks kept the client coordinates and landed above what was drawn. A per-frame step (`apps/figcraft/src/window_frame.rs`, safe `winsafe` calls, Windows only) clears `WS_CAPTION` and `WS_BORDER` from every FigCraft window, the main one and the others, keeping the sizing border and window buttons so edge resizing and snap work, and writes only when a style changed (winit puts them back on maximize and restore). The same fix as DesignCraft #2139 and PhotoCraft #2401; the maximize-to-work-area trim from DesignCraft is left for a later change. Not run on a Windows machine that shows the offset: the style math and the per-frame hook are tested, the window itself needs a live check. Tests: `window_frame_tests`. Numbers unchanged | | 2026-11-06 | patch | M8, #1906: under Wayland (seen on GNOME and KDE Plasma) a minimised FigCraft window still reports itself visible and the compositor stops asking it to draw, so every control or attached-MCP request waited for a frame and timed out after 60 s ("it was not applied"), though eframe kept running the app's logic. `control::background` now treats a window that drew no frame for `NOT_DRAWING_AFTER` (0.2 s) while a request waited for it as hidden: state-only requests are answered from the logic passes (0.54 s each, measured on GNOME Wayland; they took 13.7 s or timed out before), the wait starts again when the window draws, and screenshots and `ui.input` still wait for a frame. Test: `idle_tests::a_window_that_stopped_drawing_answers_from_its_logic_passes` | diff --git a/docs/plugins.md b/docs/plugins.md index ea70c3130..1d1cb1267 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -214,9 +214,10 @@ whole bundle before keeping it, refuses a version that isn't newer than the one the new version at once. `plugin.directory.unpublish` (or the operator's `figcraft-server plugins remove`) takes a version, or the whole plugin, down; installed copies keep working. -**In the browser** the directory isn't available yet: the browser build's network link has no -plugin directory requests (`plugin.directory.*` says so). Import plugins with `plugin.import -{manifest, wasm}` there. +**In the browser** Manage plugins browses a directory and installs from it as the desktop app +does, but there is no folder to keep a plugin in, so it lasts as long as the page. Scripts through +`window.figcraft` can't reach a directory (commands there don't wait for the server, and +`plugin.directory.*` says so): import plugins with `plugin.import {manifest, wasm}` there. ## The manifest: `figcraft-plugin.json` @@ -548,7 +549,7 @@ import what you need from `figcraft`. - Distribution: directories live on your own `figcraft-server`; there is no public catalogue, no publisher accounts or signatures (the server's key is the publisher), no ratings, reviews or install counts, and updates are found when you browse, not in the background. The browser build - can't use a directory yet. + keeps what it installs only as long as the page. - Plugins written for other apps (JavaScript plugins) don't run. - Widgets: clicks, field edits and menu items are their only events (no hover or timers), a field is plain text (no placeholder, length or single-line setting), and their layers are frames, text, rectangles, ellipses and images only (no diff --git a/docs/roadmap.md b/docs/roadmap.md index 1ba946bb2..78f4d4df3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -76,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | diff --git a/docs/server.md b/docs/server.md index 3a229e495..37f0182d9 100644 --- a/docs/server.md +++ b/docs/server.md @@ -268,7 +268,10 @@ send their requests on a thread of their own, show that they're on their way (wi finish when the answer arrives, acting on the file they started in. Scripts, the CLI and the MCP server run the same commands and wait for the answer. -The browser build can't use team libraries yet (it has no library support of its own). +The browser build uses team libraries through the same panel: adding one by its link, its styles +and components, publishing a file that is on the server, Show usage and the reports a file sends. +A browser can't keep a library file, and scripts through `window.figcraft` can't reach a server +(commands there don't wait for it), so those stay with the desktop app, the CLI and MCP. ## Plugin directory diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c88776361..8fb0abec1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-15 | minor | M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured | | 2026-11-10 | minor | M4, #2222: a boolean group's corner radius rounds every sharp corner of its result (row 4). Numbers unchanged | | 2026-11-08 | minor | M8: measured in Figma on 2026-11-08, vector edit mode's Point section: X and Y show the value the selected points share, or Mixed when they differ, and a typed value sets every selected point's own coordinate in the layer being edited, points of other edited layers left as they are (it moved the group's top-left before); a relative edit (`+10`, `*2`, `/2`) typed into a Mixed field applies to each point's own value (`vector.edit.position` takes a number or `{add}`, `{mul}`, `{div}` per axis); the W and H row and other edited layers' points are unchanged. | From 6dace8c570d375820ece3bd4fcbf3535a2dd3efa Mon Sep 17 00:00:00 2001 From: B-uchi Date: Wed, 18 Nov 2026 08:00:03 +0100 Subject: [PATCH 083/129] M8: get_node reports text and stroke settings it stores A layer stored its vertical text alignment, text case, paragraph spacing and indent, OpenType features, start and end caps, a frame's variable modes, which component property controls a field, and whether a nested instance is exposed, but node.get and document.inspect left them out. They are reported now, under the names node.set takes so a value read can be written back, and only when they aren't the default. --- crates/engine/src/automation/inspect.rs | 40 +++++++++++++++- crates/engine/src/inspect_fields_tests.rs | 56 +++++++++++++++++++++++ docs/control-protocol.md | 3 ++ 3 files changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index c74829961..a3c0b94e5 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -1,6 +1,6 @@ //! Document inspection as JSON, so agents can verify their work without screenshots. -use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeJoin, TextData, TextDecoration}; +use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, StrokeJoin, TextAlignV, TextCase, TextData, TextDecoration}; use serde_json::{Value, json}; use crate::Session; @@ -34,7 +34,10 @@ pub const NODE_KEYS: &[&str] = &[ "devResources", "devStatus", "effects", + "endCap", "exports", + "exposedInstance", + "features", "fills", "flows", "fontFamily", @@ -76,13 +79,17 @@ pub const NODE_KEYS: &[&str] = &[ "opacity", "operandOperation", "overrides", + "paragraphIndent", + "paragraphSpacing", "pluginData", "pointCount", + "propertyReferences", "rotation", "sectionContentsHidden", "segments", "sizing", "slot", + "startCap", "strokeAlign", "strokeJoin", "strokeSides", @@ -91,7 +98,9 @@ pub const NODE_KEYS: &[&str] = &[ "styledRuns", "styles", "textAlign", + "textAlignVertical", "textAutoResize", + "textCase", "textDecoration", "textDecorationColor", "textDecorationOffset", @@ -102,6 +111,7 @@ pub const NODE_KEYS: &[&str] = &[ "textPath", "textStyleRanges", "type", + "variableModes", "vertices", "visible", "width", @@ -263,6 +273,11 @@ fn paint_props(n: &Node, o: &mut serde_json::Map, options: &Inspe if !n.stroke.dashes.is_empty() { insert_prop(o, options, "dashes", || json!(n.stroke.dashes)); } + for (k, cap) in [("startCap", n.stroke.cap_start), ("endCap", n.stroke.cap_end)] { + if cap != StrokeCap::None { + insert_prop(o, options, k, || json!(cap)); + } + } if let Some(cap) = n.stroke.dash_cap { insert_prop(o, options, "dashCap", || json!(cap)); } @@ -383,6 +398,15 @@ fn dev_props(doc: &Document, n: &Node, o: &mut serde_json::Map, o if !n.bound.is_empty() { insert_prop(o, options, "boundVariables", || json!(n.bound)); } + if !n.var_modes.is_empty() { + insert_prop(o, options, "variableModes", || json!(n.var_modes)); + } + if !n.prop_refs.is_empty() { + insert_prop(o, options, "propertyReferences", || json!(n.prop_refs)); + } + if n.exposed { + insert_prop(o, options, "exposedInstance", || json!(true)); + } if !n.overrides.is_empty() { insert_prop(o, options, "overrides", || json!(n.overrides)); } @@ -417,7 +441,21 @@ fn text_props(t: &TextData, o: &mut serde_json::Map, options: &In insert_prop(o, options, "lineHeight", || json!(t.style.line_height.label())); insert_prop(o, options, "letterSpacing", || json!(t.style.letter_spacing.label())); insert_prop(o, options, "textAlign", || json!(t.align_h)); + if t.align_v != TextAlignV::default() { + insert_prop(o, options, "textAlignVertical", || json!(t.align_v)); + } insert_prop(o, options, "textAutoResize", || json!(t.auto_resize)); + if t.style.case != TextCase::default() { + insert_prop(o, options, "textCase", || json!(t.style.case)); + } + for (k, v) in [("paragraphSpacing", t.paragraph_spacing), ("paragraphIndent", t.paragraph_indent)] { + if v != 0.0 { + insert_prop(o, options, k, || json!(v)); + } + } + if !t.features.is_empty() { + insert_prop(o, options, "features", || json!(t.features)); + } if t.max_lines > 0 { insert_prop(o, options, "maxLines", || json!(t.max_lines)); } diff --git a/crates/engine/src/inspect_fields_tests.rs b/crates/engine/src/inspect_fields_tests.rs index 2083a5108..592ca8b94 100644 --- a/crates/engine/src/inspect_fields_tests.rs +++ b/crates/engine/src/inspect_fields_tests.rs @@ -505,3 +505,59 @@ fn node_get_uses_options_but_keeps_its_existing_depth_and_selection() { assert_eq!(s.selection(), selection); assert_eq!(s.undo_depth(), history); } + +/// Text and stroke settings a layer stores are reported, under the names `node.set` takes, so a +/// value read can be written back unchanged. +#[test] +fn stored_text_and_stroke_settings_are_read_back_as_set() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = s.execute("node.create", &json!({"type": "text", "text": "Hi", "width": 120})).unwrap()["id"].clone(); + let line = + s.execute("node.create", &json!({"type": "line", "width": 80, "props": {"strokes": ["#000000"], "strokeWeight": 2}})).unwrap()["id"].clone(); + let set = json!({ + "textAlignVertical": "middle", "textCase": "upper", "paragraphSpacing": 8.0, "paragraphIndent": 12.0, "features": {"liga": false}, + }); + s.execute("node.set", &json!({"ids": [text.clone()], "props": set})).unwrap(); + s.execute("node.set", &json!({"ids": [line.clone()], "props": {"startCap": "round", "endCap": "triangleArrow"}})).unwrap(); + let got = s.execute("node.get", &json!({"id": text})).unwrap(); + for (key, value) in set.as_object().unwrap() { + assert_eq!(&got[key], value, "{key}: {got}"); + // Written back as read, it changes nothing. + s.execute("node.set", &json!({"ids": [text.clone()], "props": {key.as_str(): got[key].clone()}})).unwrap(); + assert_eq!(s.execute("node.get", &json!({"id": text})).unwrap()[key], *value, "{key}"); + } + let got = s.execute("node.get", &json!({"id": line})).unwrap(); + assert_eq!((got["startCap"].as_str(), got["endCap"].as_str()), (Some("round"), Some("triangleArrow")), "{got}"); + // Defaults stay out, as they do for other keys. + let plain = s.execute("node.create", &json!({"type": "text", "text": "x"})).unwrap()["id"].clone(); + let got = s.execute("node.get", &json!({"id": plain})).unwrap(); + for key in ["textAlignVertical", "textCase", "paragraphSpacing", "paragraphIndent", "features", "startCap", "endCap", "variableModes"] { + assert!(got.get(key).is_none(), "{key} at its default: {got}"); + } +} + +/// A frame's variable modes, a layer's component property bindings and an exposed nested instance +/// are reported. +#[test] +fn modes_property_bindings_and_exposed_instances_are_read() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let c = s.execute("variable.createCollection", &json!({"name": "Theme", "modes": ["Light", "Dark"]})).unwrap(); + let frame = s.execute("node.create", &json!({"type": "frame", "width": 100, "height": 100})).unwrap()["id"].clone(); + s.execute("variable.setMode", &json!({"ids": [frame.clone()], "collection": c["id"], "mode": "Dark"})).unwrap(); + let modes = s.execute("node.get", &json!({"id": frame})).unwrap()["variableModes"].clone(); + assert_eq!(modes.as_object().map(|m| m.len()), Some(1), "{modes}"); + let card = s.execute("node.create", &json!({"type": "frame", "name": "Card", "width": 100, "height": 50})).unwrap()["id"].clone(); + let title = s.execute("node.create", &json!({"type": "text", "parent": card.clone(), "text": "Title"})).unwrap()["id"].clone(); + let main = s.execute("component.create", &json!({"ids": [card]})).unwrap()["id"].clone(); + s.execute("component.addProperty", &json!({"id": main.clone(), "name": "Label", "type": "text", "layer": title.clone()})).unwrap(); + let refs = s.execute("node.get", &json!({"id": title})).unwrap()["propertyReferences"].clone(); + assert!(refs.as_object().is_some_and(|r| r.values().any(|v| v.as_str().is_some_and(|p| p.starts_with("Label")))), "{refs}"); + let tag = s.execute("node.create", &json!({"type": "frame", "name": "Tag", "x": 300, "width": 40, "height": 20})).unwrap()["id"].clone(); + let tag_main = s.execute("component.create", &json!({"ids": [tag]})).unwrap()["id"].clone(); + let nested = s.execute("instance.create", &json!({"component": tag_main})).unwrap()["id"].clone(); + s.execute("node.reparent", &json!({"ids": [nested.clone()], "parent": main})).unwrap(); + s.execute("component.exposeInstance", &json!({"id": nested.clone()})).unwrap(); + assert_eq!(s.execute("node.get", &json!({"id": nested})).unwrap()["exposedInstance"], true); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 381992c55..325b67b24 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -195,6 +195,9 @@ layout (including grid `columnTracks` / `rowTracks`), sizing, `minWidth` / `maxW children), `gridCell` (a grid auto layout child's column, row and spans), clip, text properties, component/instance links, overrides, `slot` (a slot layer's property name), boundVariables, interactions, exports, `devStatus` (handoff status), `devChanged` (changed since it was marked ready for dev), +`textAlignVertical`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `features` (OpenType +toggles), `startCap` and `endCap` (when not none), `variableModes` (a frame's collection → mode), +`propertyReferences` (which component property controls a field), `exposedInstance`, `annotations` (Developer Mode notes: `[{label, properties, category?}]`), `codeLinks` (a component's links to code: `[{language, importPath, name, template}]`), `devResources` (links for developers, its own and inherited: `[{name, url, index?, from?}]`), `measurements` (Developer Mode measurements From 546808a03db010ffc0376b2d62b5955b7316db5f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 14:11:11 +0700 Subject: [PATCH 084/129] M9: the browser hands each team library over as it comes, not after the whole check exchange::libraries kept the fetches' answers until every job had run, and Driver::follow handed them over only at Next::Done, so a library that had answered waited behind later libraries and reports that connected or timed out. A new Next::Tell gives the UI its events, then goes on; libraries ends each fetch with it, before connecting for the next job, as the desktop's library_background does. Test: exchange_tests::a_library_check_hands_each_fetch_over_as_it_comes (the first library is in the inbox while a later report's server never answers). --- crates/collab-net/src/driver.rs | 6 +++++ crates/collab-net/src/exchange.rs | 35 +++++++++++-------------- crates/collab-net/src/exchange_tests.rs | 29 +++++++++++++++++++- crates/collab-net/src/web.rs | 2 +- 4 files changed, 50 insertions(+), 22 deletions(-) diff --git a/crates/collab-net/src/driver.rs b/crates/collab-net/src/driver.rs index e55eba957..526cf0941 100644 --- a/crates/collab-net/src/driver.rs +++ b/crates/collab-net/src/driver.rs @@ -152,6 +152,12 @@ impl Driver { None => self.done = true, } } + exchange::Next::Tell(events, then) => { + for e in events { + self.inbox.push(e); + } + self.follow(*then, now); + } } } diff --git a/crates/collab-net/src/exchange.rs b/crates/collab-net/src/exchange.rs index 89e2225b6..5a75e382c 100644 --- a/crates/collab-net/src/exchange.rs +++ b/crates/collab-net/src/exchange.rs @@ -55,6 +55,8 @@ pub(crate) enum Next { Ask(Box, Then), /// Done: tell the UI these, then join the file this invite names (`None`: nothing to join). Done(Vec, Option), + /// Tell the UI these now, then go on with what follows. + Tell(Vec, Box), } impl Exchange { @@ -248,30 +250,23 @@ fn library_reply(answers: Result) -> Result, mut events: Vec, fetching: Arc) -> Next { +/// own. A fetch's answer goes to the UI as it comes, before the next connection, as the desktop's +/// does, so a slow or silent server further on holds no library back; the others' answers are left +/// out (a report's says nothing, and an older server refuses it). `fetching` goes down at the end. +pub(crate) fn libraries(mut jobs: VecDeque<(String, LibraryReq)>, fetching: Arc) -> Next { let Some((link, req)) = jobs.pop_front() else { fetching.store(false, Ordering::SeqCst); - return Next::Done(events, None); + return Next::Done(Vec::new(), None); }; let fetch = matches!(req, LibraryReq::Fetch { .. }); - match Invite::parse(&link) { - Err(reply) => { - if fetch { - events.push(Event::Library { link, reply: Err(reply) }); - } - libraries(jobs, events, fetching) - } - Ok(invite) => Next::Ask( - Box::new(Exchange::library(invite, req)), - Box::new(move |answers| { - if fetch { - events.push(Event::Library { link, reply: library_reply(answers) }); - } - libraries(jobs, events, fetching) - }), - ), + let invite = Invite::parse(&link); + let then = move |reply: Result| { + let rest = libraries(jobs, fetching); + if fetch { Next::Tell(vec![Event::Library { link, reply }], Box::new(rest)) } else { rest } + }; + match invite { + Err(e) => then(Err(e)), + Ok(invite) => Next::Ask(Box::new(Exchange::library(invite, req)), Box::new(move |answers| then(library_reply(answers)))), } } diff --git a/crates/collab-net/src/exchange_tests.rs b/crates/collab-net/src/exchange_tests.rs index 5e58d8376..ecebdc8f7 100644 --- a/crates/collab-net/src/exchange_tests.rs +++ b/crates/collab-net/src/exchange_tests.rs @@ -411,7 +411,7 @@ fn a_library_check_runs_in_order_and_answers_only_its_fetches() { ]; let fetching = Arc::new(AtomicBool::new(true)); let t0 = Instant::now(); - let (mut d, inbox) = run(exchange::libraries(jobs.into(), Vec::new(), fetching.clone()), t0); + let (mut d, inbox) = run(exchange::libraries(jobs.into(), fetching.clone()), t0); let ready = library(LibraryReply::Ready { access: Access::View }); d.opened(t0); say(&mut d, &ready, t0); @@ -429,3 +429,30 @@ fn a_library_check_runs_in_order_and_answers_only_its_fetches() { assert!(replies[0].is_err()); assert!(matches!(replies[1], Ok(LibraryReply::Empty))); } + +/// A fetch's answer reaches the UI as it comes, not at the end of the check: a report after it +/// whose server never answers holds the first library back no longer than its own connection. +#[test] +fn a_library_check_hands_each_fetch_over_as_it_comes() { + let fetch = LibraryReq::Fetch { have: None, usage: None }; + let jobs = vec![(link(), fetch.clone()), (link(), LibraryReq::ReportDetached(Detached::default())), (link(), fetch)]; + let fetching = Arc::new(AtomicBool::new(true)); + let t0 = Instant::now(); + let (mut d, inbox) = run(exchange::libraries(jobs.into(), fetching.clone()), t0); + let fetched = |events: &[Event]| events.iter().filter(|e| matches!(e, Event::Library { .. })).count(); + let ready = library(LibraryReply::Ready { access: Access::View }); + d.opened(t0); + say(&mut d, &ready, t0); + say(&mut d, &library(LibraryReply::Empty), t0); + assert_eq!(fetched(&inbox.drain()), 1, "the first library is in while the report's server is asked"); + // The report's connection never opens: the check gives up on it and goes on, saying nothing. + let t1 = t0 + Duration::from_secs(5); + d.tick(t1); + assert_eq!(fetched(&inbox.drain()), 0); + assert!(fetching.load(Ordering::SeqCst), "the check is still running"); + d.opened(t1); + say(&mut d, &ready, t1); + say(&mut d, &library(LibraryReply::Empty), t1); + assert_eq!(fetched(&inbox.drain()), 1); + assert!(!fetching.load(Ordering::SeqCst) && d.done()); +} diff --git a/crates/collab-net/src/web.rs b/crates/collab-net/src/web.rs index 404ca13c7..602665dc6 100644 --- a/crates/collab-net/src/web.rs +++ b/crates/collab-net/src/web.rs @@ -247,7 +247,7 @@ impl LiveLink for NetLink { fn library_background(&mut self, jobs: Vec<(String, LibraryReq)>) { if !jobs.is_empty() && !self.fetching.swap(true, Ordering::SeqCst) { - self.ask(exchange::libraries(jobs.into(), Vec::new(), self.fetching.clone())); + self.ask(exchange::libraries(jobs.into(), self.fetching.clone())); } } From ed8df474f06aa2c2b874a6c1cb623bcf14cf7da2 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 15:45:37 -0500 Subject: [PATCH 085/129] M3: a text field shows a value too long for it with an ellipsis and a tooltip (#2368) A text field that isn't being edited painted its whole value clipped to the field, so the variant value "Down left" read "Down lef". It now paints the value shortened with an ellipsis to fit, and hovering shows the whole value (not for a secret field). Editing and screen readers keep the whole value. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/field_ellipsis_tests.rs | 105 +++++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/widgets.rs | 9 +- docs/components-parity.md | 3 +- 4 files changed, 116 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/field_ellipsis_tests.rs diff --git a/crates/ui-egui/src/field_ellipsis_tests.rs b/crates/ui-egui/src/field_ellipsis_tests.rs new file mode 100644 index 000000000..8ea13c80c --- /dev/null +++ b/crates/ui-egui/src/field_ellipsis_tests.rs @@ -0,0 +1,105 @@ +//! A text field that isn't being edited ends a value too long for it with an ellipsis, shows the +//! whole value on hover, and keeps it whole for screen readers (#2368: the variant value "Down +//! left" showed as "Down lef" in a 62 px chip). + +use egui::accesskit::Node; +use egui::epaint::{ClippedShape, Shape}; +use egui::{Event, Pos2, pos2}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::component_swap_default_tests::tree; +use crate::layers_drag_tests::Ui; + +fn id(v: serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// A selected component set with a "Looking" property of `values`. +fn set_with(values: &[&str]) -> Ui { + let mut s = Session::new(); + let mut variants = Vec::new(); + for (k, v) in values.iter().enumerate() { + let f = id(s.execute("frame.create", &json!({"x": 0, "y": k * 60, "width": 80, "height": 40, "name": format!("Looking={v}")})).unwrap()); + variants.push(id(s.execute("component.create", &json!({"ids": [f]})).unwrap())); + } + let set = id(s.execute("component.combineVariants", &json!({"ids": variants})).unwrap()); + s.execute("select.set", &json!({"ids": [set]})).unwrap(); + let u = Ui::new(s); + u.ctx.enable_accesskit(); + u +} + +/// How many painted texts read `text`. +fn count(shapes: &[String], text: &str) -> usize { + shapes.iter().filter(|t| *t == text).count() +} + +/// Frames with a still pointer on `at`, long enough for egui's tooltip delay; the last one's texts. +fn hover(u: &mut Ui, at: Pos2) -> Vec { + let mut shown = Vec::new(); + u.frame(vec![Event::PointerMoved(at)]); + for _ in 0..90 { + shown = texts(&u.frame_output(vec![]).shapes); + } + shown +} + +fn texts(shapes: &[ClippedShape]) -> Vec { + fn walk(s: &Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + Shape::Text(t) => out.push(t.galley.text().to_owned()), + _ => {} + } + } + let mut out = Vec::new(); + shapes.iter().for_each(|c| walk(&c.shape, &mut out)); + out +} + +/// The accesskit node of the value chip showing `value`. +fn chip(nodes: &[Node], value: &str) -> Pos2 { + let n = nodes.iter().find(|n| n.value() == Some(value) && n.bounds().is_some()).unwrap_or_else(|| panic!("a chip for {value}")); + let b = n.bounds().unwrap(); + pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) +} + +#[test] +fn a_variant_value_too_long_for_its_chip_ends_with_an_ellipsis() { + let mut u = set_with(&["Top right", "Down left"]); + let shown = texts(&u.frame_output(vec![]).shapes); + let cut: Vec<&String> = shown.iter().filter(|t| t.starts_with("Down l")).collect(); + assert!(!cut.is_empty(), "the value is painted: {shown:?}"); + assert!(cut.iter().all(|t| t.ends_with('…')), "ends with an ellipsis: {cut:?}"); + assert!(!shown.iter().any(|t| t == "Down lef"), "not cut mid-letter: {shown:?}"); +} + +#[test] +fn the_shortened_value_shows_whole_on_hover() { + let mut u = set_with(&["Top right", "Down left"]); + let at = chip(&tree(&mut u), "Down left"); + let before = count(&texts(&u.frame_output(vec![]).shapes), "Down left"); + let shown = hover(&mut u, at); + assert_eq!(count(&shown, "Down left"), before + 1, "the whole value is painted again, in a tooltip: {shown:?}"); +} + +#[test] +fn a_value_that_fits_is_shown_whole_without_a_tooltip() { + let mut u = set_with(&["Top", "Down left"]); + let nodes = tree(&mut u); + let shown = texts(&u.frame_output(vec![]).shapes); + let before = count(&shown, "Top"); + assert!(before > 0, "Top is painted as it is: {shown:?}"); + let after = hover(&mut u, chip(&nodes, "Top")); + assert_eq!(count(&after, "Top"), before, "no tooltip repeats it: {after:?}"); +} + +#[test] +fn screen_readers_keep_the_whole_value() { + let mut u = set_with(&["Top right", "Down left"]); + let nodes = tree(&mut u); + assert!(nodes.iter().any(|n| n.value() == Some("Down left")), "the chip's value is the whole text"); + assert!(!nodes.iter().any(|n| n.value().is_some_and(|v| v.ends_with('…'))), "no node announces a shortened value"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 692b55ff0..63b04079c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -110,6 +110,8 @@ mod export_name_tests; #[cfg(test)] mod export_preview_tests; #[cfg(test)] +mod field_ellipsis_tests; +#[cfg(test)] mod field_tests; #[cfg(test)] mod font_menu_regrow_tests; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 3cd1bf3f3..c1f8614b4 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -718,9 +718,14 @@ fn text_field_in(ui: &mut Ui, id: Id, value: &str, rect: Rect, placeholder: &str } None => { let (s, col) = if value.is_empty() { (placeholder, t.text_tertiary) } else { (&*shown, t.text) }; - // Long text stays inside the field. + // Long text ends in an ellipsis inside the field; hovering shows the whole value (not + // of a secret one: that is a key). + let fitted = elide(ui, s, rect.width() - 16.0); let painter = ui.painter().with_clip_rect(rect.shrink2(vec2(8.0, 0.0))); - painter.text(pos2(rect.min.x + 8.0, rect.center().y), Align2::LEFT_CENTER, s, regular(11.0), col); + painter.text(pos2(rect.min.x + 8.0, rect.center().y), Align2::LEFT_CENTER, &fitted, regular(11.0), col); + if fitted != s && !secret && !value.is_empty() { + resp.on_hover_text(value); + } } } out diff --git a/docs/components-parity.md b/docs/components-parity.md index 61598ab9a..72311593c 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -22,7 +22,7 @@ accounts). | A component can't contain its own instance, directly or through other components | done | refused with the loop named (creating, placing, swapping, switching variants, moving, pasting, an instance-swap value); each variant counts as its own component, so a variant may hold a sibling variant's instance unless that one leads back to it; a dropped instance lands on the page; a file holding a loop opens with one instance detached and a note, any other file unchanged; a loop merged in a live session stops expanding where an instance would show itself again (#1084) | | Switching variants keeps overrides where names match and both variants had the same value; text layers keep theirs | done | | | Default variant: the top-left one (new instances, Assets thumbnail, generated code) | done | | -| Variant property order (names rewritten), duplicate combinations reported | done | drag a property in the Properties section to reorder it, one undo step (#679), or `component.editProperty {index}` | +| Variant property order (names rewritten), duplicate combinations reported | done | drag a property in the Properties section to reorder it, one undo step (#679), or `component.editProperty {index}`; a variant value too long for its field ends with an ellipsis and shows whole on hover (#2368) | | Properties: boolean, text, instance swap (preferred values), variant | done | listed in the order they were made, a rename keeping the place (#1536; the shared ones don't reorder by drag yet); every component menu scrolls past 320 pt, the default of an instance-swap property's too (#1338); the instance-swap menus (an instance's property and swap menus, a property's default, the playground) open with a search field that filters by name as you type, with Up, Down and Enter to pick and Escape to clear then close; the slot and preferred components menus have no search yet; an instance lists the properties its variant's layers use, so a set with one text property per variant shows one text field per instance (#2022; measured in Figma's web app, 2026-11-11); long names are cut to one line, the full name on hover | | Slots (preferred components, fill menu, kept across updates) | done | Figma 2025 feature; Make slot asks for the name first (a field under the frame's Slot row), and slots are renamed in the component's Properties list (#1537); no rename with only the slot's frame selected yet | | Exposed nested instances | done | hidden ones hide their properties | @@ -80,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | patch | M3, #2368: a text field that isn't being edited ends a value too long for it with an ellipsis and shows the whole value on hover (a secret field shows none), so the variant value "Down left" no longer reads "Down lef"; screen readers and editing keep the whole value (`field_ellipsis_tests`). Grade unchanged. | | 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Create component, instances, detach, reset, go to main, restore main, push changes. | | 2026-11-14 | patch | M3, #2353: renaming a group in the Local variables window to a path with `/` nests it, as in Figma: `Orange` renamed to `Palette/Orange` moves its variables to `Palette/Orange/100`… and the sidebar shows Orange indented under a new Palette group, where the slash used to become a hyphen (`Palette-Orange`). The typed path replaces the group's last part (a nested group stays in its parent), each part is trimmed and empty parts are dropped; a rename onto a variable name that stays is refused with nothing changed, and it is one undo step. Tests: `variables_select_tests::renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step` and the group rename tests beside it, `variables_panel::tests`. Grade unchanged. | From d332c18a2c166f5d6ed6c1bf52370c8315d2c282 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 18 Nov 2026 15:44:42 +0500 Subject: [PATCH 086/129] REST import: variables bound to stroke sides bind each side's weight (#2441) boundVariables.individualStrokeWeights was skipped with a warning, so a 1 px bottom divider bound to a variable came across as a plain number. Each side now binds strokeTopWeight ... strokeLeftWeight, read from the live API's BORDER_TOP_WEIGHT ... keys or the published spec's top ... keys. --- .../format/src/rest/proto_variable_tests.rs | 38 +++++++++++++++++++ crates/format/src/rest/variables.rs | 13 +++++++ 2 files changed, 51 insertions(+) diff --git a/crates/format/src/rest/proto_variable_tests.rs b/crates/format/src/rest/proto_variable_tests.rs index 133d45de2..3c89d8a41 100644 --- a/crates/format/src/rest/proto_variable_tests.rs +++ b/crates/format/src/rest/proto_variable_tests.rs @@ -188,6 +188,44 @@ fn bound_variables_and_explicit_modes() { assert!(has(&warnings, "pass the local variables JSON"), "{warnings:?}"); } +/// #2441: a variable bound to one or more stroke sides (`individualStrokeWeights`) binds that +/// side's weight. The live API names the sides `BORDER_TOP_WEIGHT` …, the published spec `top` …; +/// both are read, and neither is reported as skipped. +#[test] +fn variables_bound_to_stroke_sides_bind_each_sides_weight() { + let rect = |id: &str, name: &str, sides: Value| { + json!({"id": id, "name": name, "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20}, + "strokes": [{"type": "SOLID", "color": rgba(0.0, 0.0, 0.0)}], "strokeWeight": 1, + "individualStrokeWeights": {"top": 1, "right": 1, "bottom": 1, "left": 1}, + "boundVariables": {"individualStrokeWeights": sides}}) + }; + let file = json!({"name": "Sides", "document": {"id": "0:0", "type": "DOCUMENT", "children": [ + {"id": "0:1", "name": "Page", "type": "CANVAS", "children": [ + rect("1:1", "Row", json!({"BORDER_BOTTOM_WEIGHT": alias(SPACE)})), + rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(SPACE), "BORDER_RIGHT_WEIGHT": alias(SPACE), + "BORDER_BOTTOM_WEIGHT": alias(SPACE), "BORDER_LEFT_WEIGHT": alias(SPACE)})), + rect("1:3", "Spec", json!({"top": alias(SPACE), "left": alias(SPACE)})), + rect("1:4", "Colour", json!({"BORDER_LEFT_WEIGHT": alias(BRAND)})) + ]} + ]}}); + let (doc, warnings) = import_with(&file, Some(&variables_json()), &no_images).unwrap(); + let sides = |name: &str| -> Vec<(String, String)> { + let n = named(&doc, name); + ["strokeTopWeight", "strokeRightWeight", "strokeBottomWeight", "strokeLeftWeight"] + .iter() + .filter_map(|f| n.bound.get(*f).map(|v| (f.to_string(), v.clone()))) + .collect() + }; + let b = |f: &str| (f.to_string(), SPACE.to_string()); + assert_eq!(sides("Row"), [b("strokeBottomWeight")], "one side bound"); + assert_eq!(sides("Card"), [b("strokeTopWeight"), b("strokeRightWeight"), b("strokeBottomWeight"), b("strokeLeftWeight")]); + assert_eq!(sides("Spec"), [b("strokeTopWeight"), b("strokeLeftWeight")], "the spec's names"); + assert_eq!(sides("Colour"), [], "a colour variable can't be a weight"); + assert!(!has(&warnings, "`individualStrokeWeights`"), "{warnings:?}"); + assert!(has(&warnings, "type doesn't fit"), "{warnings:?}"); + assert!(doc.validate().is_empty(), "{:?}", doc.validate()); +} + #[test] fn embedded_variables_match_separate_ones() { let mut embedded = file_json(); diff --git a/crates/format/src/rest/variables.rs b/crates/format/src/rest/variables.rs index ba2467423..a962ded0f 100644 --- a/crates/format/src/rest/variables.rs +++ b/crates/format/src/rest/variables.rs @@ -427,6 +427,19 @@ fn node_binding<'v>(k: &str, v: &'v Value, n: &Node, out: &mut Vec<(String, &'v push(f, v.get(key).and_then(alias)); } } + // Each stroke side's weight (#2441). The live `/nodes` response names the sides + // `BORDER_TOP_WEIGHT` and so on, as `rectangleCornerRadii` names its corners; Figma's + // published OpenAPI spec names them `top` … `left`. Either is read. + "individualStrokeWeights" => { + for (keys, f) in [ + (["BORDER_TOP_WEIGHT", "top"], "strokeTopWeight"), + (["BORDER_RIGHT_WEIGHT", "right"], "strokeRightWeight"), + (["BORDER_BOTTOM_WEIGHT", "bottom"], "strokeBottomWeight"), + (["BORDER_LEFT_WEIGHT", "left"], "strokeLeftWeight"), + ] { + push(f, keys.iter().find_map(|key| v.get(*key)).and_then(alias)); + } + } "fills" | "strokes" => { let field = if k == "fills" { "fill" } else { "stroke" }; match v.as_array().and_then(|a| a.first()).and_then(alias) { From d7fcbf94caf24325f748c8e19838e17b1b2e4beb Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 18 Nov 2026 15:57:39 +0500 Subject: [PATCH 087/129] REST import test: each of Card's sides is bound to a variable of its own So a side read into another side's field fails the test (review). --- .../format/src/rest/proto_variable_tests.rs | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/format/src/rest/proto_variable_tests.rs b/crates/format/src/rest/proto_variable_tests.rs index 3c89d8a41..e54a4fbf7 100644 --- a/crates/format/src/rest/proto_variable_tests.rs +++ b/crates/format/src/rest/proto_variable_tests.rs @@ -193,6 +193,10 @@ fn bound_variables_and_explicit_modes() { /// both are read, and neither is reported as skipped. #[test] fn variables_bound_to_stroke_sides_bind_each_sides_weight() { + const TOP: &str = "VariableID:9:1"; + const RIGHT: &str = "VariableID:9:2"; + const BOTTOM: &str = "VariableID:9:3"; + const LEFT: &str = "VariableID:9:4"; let rect = |id: &str, name: &str, sides: Value| { json!({"id": id, "name": name, "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20}, "strokes": [{"type": "SOLID", "color": rgba(0.0, 0.0, 0.0)}], "strokeWeight": 1, @@ -202,13 +206,19 @@ fn variables_bound_to_stroke_sides_bind_each_sides_weight() { let file = json!({"name": "Sides", "document": {"id": "0:0", "type": "DOCUMENT", "children": [ {"id": "0:1", "name": "Page", "type": "CANVAS", "children": [ rect("1:1", "Row", json!({"BORDER_BOTTOM_WEIGHT": alias(SPACE)})), - rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(SPACE), "BORDER_RIGHT_WEIGHT": alias(SPACE), - "BORDER_BOTTOM_WEIGHT": alias(SPACE), "BORDER_LEFT_WEIGHT": alias(SPACE)})), + rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(TOP), "BORDER_RIGHT_WEIGHT": alias(RIGHT), + "BORDER_BOTTOM_WEIGHT": alias(BOTTOM), "BORDER_LEFT_WEIGHT": alias(LEFT)})), rect("1:3", "Spec", json!({"top": alias(SPACE), "left": alias(SPACE)})), rect("1:4", "Colour", json!({"BORDER_LEFT_WEIGHT": alias(BRAND)})) ]} ]}}); - let (doc, warnings) = import_with(&file, Some(&variables_json()), &no_images).unwrap(); + // A variable of its own for each of Card's sides, so a side read into another's field fails. + let mut vars = variables_json(); + for id in [TOP, RIGHT, BOTTOM, LEFT] { + vars["meta"]["variables"][id] = json!({"id": id, "name": id, "variableCollectionId": THEME, "resolvedType": "FLOAT", + "valuesByMode": {"1:0": 1}, "scopes": ["ALL_SCOPES"]}); + } + let (doc, warnings) = import_with(&file, Some(&vars), &no_images).unwrap(); let sides = |name: &str| -> Vec<(String, String)> { let n = named(&doc, name); ["strokeTopWeight", "strokeRightWeight", "strokeBottomWeight", "strokeLeftWeight"] @@ -217,8 +227,12 @@ fn variables_bound_to_stroke_sides_bind_each_sides_weight() { .collect() }; let b = |f: &str| (f.to_string(), SPACE.to_string()); + let on = |f: &str, v: &str| (f.to_string(), v.to_string()); assert_eq!(sides("Row"), [b("strokeBottomWeight")], "one side bound"); - assert_eq!(sides("Card"), [b("strokeTopWeight"), b("strokeRightWeight"), b("strokeBottomWeight"), b("strokeLeftWeight")]); + assert_eq!( + sides("Card"), + [on("strokeTopWeight", TOP), on("strokeRightWeight", RIGHT), on("strokeBottomWeight", BOTTOM), on("strokeLeftWeight", LEFT)] + ); assert_eq!(sides("Spec"), [b("strokeTopWeight"), b("strokeLeftWeight")], "the spec's names"); assert_eq!(sides("Colour"), [], "a colour variable can't be a weight"); assert!(!has(&warnings, "`individualStrokeWeights`"), "{warnings:?}"); From 11b896699f0d5fa6fcd3e56068211e7b6afcf107 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 18 Nov 2026 16:24:41 +0500 Subject: [PATCH 088/129] REST import test: the spec's four side names each bind a variable of their own --- crates/format/src/rest/proto_variable_tests.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/format/src/rest/proto_variable_tests.rs b/crates/format/src/rest/proto_variable_tests.rs index e54a4fbf7..f89466194 100644 --- a/crates/format/src/rest/proto_variable_tests.rs +++ b/crates/format/src/rest/proto_variable_tests.rs @@ -208,7 +208,7 @@ fn variables_bound_to_stroke_sides_bind_each_sides_weight() { rect("1:1", "Row", json!({"BORDER_BOTTOM_WEIGHT": alias(SPACE)})), rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(TOP), "BORDER_RIGHT_WEIGHT": alias(RIGHT), "BORDER_BOTTOM_WEIGHT": alias(BOTTOM), "BORDER_LEFT_WEIGHT": alias(LEFT)})), - rect("1:3", "Spec", json!({"top": alias(SPACE), "left": alias(SPACE)})), + rect("1:3", "Spec", json!({"top": alias(TOP), "right": alias(RIGHT), "bottom": alias(BOTTOM), "left": alias(LEFT)})), rect("1:4", "Colour", json!({"BORDER_LEFT_WEIGHT": alias(BRAND)})) ]} ]}}); @@ -233,7 +233,11 @@ fn variables_bound_to_stroke_sides_bind_each_sides_weight() { sides("Card"), [on("strokeTopWeight", TOP), on("strokeRightWeight", RIGHT), on("strokeBottomWeight", BOTTOM), on("strokeLeftWeight", LEFT)] ); - assert_eq!(sides("Spec"), [b("strokeTopWeight"), b("strokeLeftWeight")], "the spec's names"); + assert_eq!( + sides("Spec"), + [on("strokeTopWeight", TOP), on("strokeRightWeight", RIGHT), on("strokeBottomWeight", BOTTOM), on("strokeLeftWeight", LEFT)], + "the spec's names" + ); assert_eq!(sides("Colour"), [], "a colour variable can't be a weight"); assert!(!has(&warnings, "`individualStrokeWeights`"), "{warnings:?}"); assert!(has(&warnings, "type doesn't fit"), "{warnings:?}"); From d494fad166c2fe9b4a15a131122c0a34c37b4826 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 18 Nov 2026 06:31:20 -0500 Subject: [PATCH 089/129] M2: Fill across a hugging axis takes the line, as Figma does In a hugging parent, Fill on the other axis follows the line the way Figma does, instead of forcing the parent Fixed. This also covers item 2 of #2090 on both axes: a hugging main that becomes Fixed is followed by its instances' roots. Fixes #2091 item 3. Fixes #2034. Fixes item 2 of #2090. --- crates/engine/src/al_behaviour_tests.rs | 121 ++++++++++++ crates/engine/src/assets/components/sync.rs | 24 ++- crates/engine/src/cmd/edit/props.rs | 17 ++ crates/engine/src/cmd/props.rs | 103 +++++++++-- .../engine/src/components_behaviour_tests.rs | 174 ++++++++++++++++++ crates/engine/src/instance_resizing_tests.rs | 32 +++- .../src/fig/auto_layout_sizing_tests.rs | 123 ++++++++++++- crates/layout/src/behaviour_tests.rs | 122 +++++++++++- crates/layout/src/lib.rs | 165 +++++++++++++++-- crates/layout/src/nested_tests.rs | 98 +++++++++- crates/ui-egui/src/panels/layout_panel.rs | 5 +- docs/auto-layout-parity.md | 7 +- docs/components-parity.md | 3 +- docs/mcp.md | 8 +- 14 files changed, 949 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index 49950de6d..2e1f01b4e 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -72,6 +72,127 @@ fn fill_on_a_child_turns_the_hugging_parent_fixed() { assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug)); } +fn name_of(s: &Session, node: NodeId) -> String { + s.doc().unwrap().node(node).unwrap().name.clone() +} + +/// Measured in Figma web (2026-11-08): across the flow a Fill child +/// leaves its hugging parent hugging and takes the line's cross size; the parent turns Fixed (with +/// a notice) only when no non-Fill child is left on that axis. +#[test] +fn fill_across_a_hugging_parent_keeps_it_hugging_and_takes_the_line() { + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"})); + let a = rect(&mut s, f, 4.0, 20.0, "#FF0000"); + let b = rect(&mut s, f, 50.0, 40.0, "#0000FF"); + assert_eq!(size(&s, f), (54.0, 40.0)); + s.message = None; + set(&mut s, a, json!({"sizingV": "fill"})); + assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug), "a non-Fill sibling is left: the parent keeps hugging"); + assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fill)); + assert_eq!((size(&s, a), size(&s, f)), ((4.0, 40.0), (54.0, 40.0))); + assert_eq!(s.message, None, "no notice"); + // The sibling grows: the bar and the parent follow. + set(&mut s, b, json!({"height": 60})); + assert_eq!((size(&s, a), size(&s, f)), ((4.0, 60.0), (54.0, 60.0))); + // The last non-Fill child fills too: the parent turns Fixed at its current height, with a notice. + set(&mut s, b, json!({"sizingV": "fill"})); + assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Fixed)); + assert_eq!(s.message, Some(format!("Height set to Fixed for {}", name_of(&s, f)))); + assert_eq!((size(&s, a), size(&s, b), size(&s, f)), ((4.0, 60.0), (50.0, 60.0), (54.0, 60.0))); + set(&mut s, f, json!({"height": 80})); + assert_eq!((size(&s, a), size(&s, b)), ((4.0, 80.0), (50.0, 80.0))); + // One undo step puts the sizing back. + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug)); + assert_eq!(sizing(&s, b), (Sizing::Fixed, Sizing::Fixed)); +} + +#[test] +fn fill_along_a_hugging_parent_notes_that_the_width_is_fixed() { + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"})); + let a = rect(&mut s, f, 50.0, 20.0, "#FF0000"); + rect(&mut s, f, 30.0, 40.0, "#0000FF"); + s.message = None; + set(&mut s, a, json!({"sizingH": "fill"})); + assert_eq!(sizing(&s, f), (Sizing::Fixed, Sizing::Hug)); + assert_eq!(s.message, Some(format!("Width set to Fixed for {}", name_of(&s, f)))); + // A Fill that changes nothing about the parent has no notice. + s.message = None; + set(&mut s, a, json!({"sizingV": "fill"})); + assert_eq!(s.message, None); +} + +#[test] +fn hugging_a_row_notes_the_child_that_filled_its_width_turned_fixed() { + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"sizingH": "fixed", "sizingV": "fixed"})); + let a = rect(&mut s, f, 50.0, 20.0, "#FF0000"); + rect(&mut s, f, 30.0, 40.0, "#0000FF"); + set(&mut s, a, json!({"sizingH": "fill"})); + assert_eq!(sizing(&s, a).0, Sizing::Fill); + s.message = None; + set(&mut s, f, json!({"sizingH": "hug"})); + assert_eq!(sizing(&s, a).0, Sizing::Fixed); + assert_eq!(s.message, Some(format!("Width set to Fixed for {}", name_of(&s, a)))); +} + +#[test] +fn hugging_a_row_keeps_and_does_not_note_the_child_that_fills_across_it() { + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"sizingH": "fixed", "sizingV": "fixed"})); + let a = rect(&mut s, f, 50.0, 20.0, "#FF0000"); + rect(&mut s, f, 30.0, 40.0, "#0000FF"); + set(&mut s, a, json!({"sizingV": "fill"})); + s.message = None; + set(&mut s, f, json!({"sizingV": "hug"})); + assert_eq!(sizing(&s, a).1, Sizing::Fill); + assert_eq!(s.message, None); +} + +#[test] +fn a_fill_childs_min_counts_toward_the_hugging_size() { + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"})); + let a = rect(&mut s, f, 4.0, 20.0, "#FF0000"); + let b = rect(&mut s, f, 50.0, 40.0, "#0000FF"); + set(&mut s, a, json!({"sizingV": "fill"})); + set(&mut s, a, json!({"minHeight": 50})); + assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug)); + assert_eq!((size(&s, a), size(&s, b), size(&s, f)), ((4.0, 50.0), (50.0, 40.0), (54.0, 50.0))); +} + +#[test] +fn a_parent_set_back_to_hug_keeps_the_child_that_fills_across_it() { + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "fixed", "height": 100})); + let a = rect(&mut s, f, 4.0, 20.0, "#FF0000"); + rect(&mut s, f, 50.0, 40.0, "#0000FF"); + set(&mut s, a, json!({"sizingV": "fill"})); + assert_eq!(size(&s, a), (4.0, 100.0)); + set(&mut s, f, json!({"sizingV": "hug"})); + assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fill), "a non-Fill sibling is left on that axis"); + assert_eq!((size(&s, a), size(&s, f)), ((4.0, 40.0), (54.0, 40.0))); +} + +#[test] +fn fill_across_a_wrapping_row_that_hugs_that_axis_is_not_offered() { + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"wrap": true, "sizingH": "fixed", "sizingV": "hug", "width": 120})); + let a = rect(&mut s, f, 40.0, 20.0, "#FF0000"); + let r = s.execute("node.set", &json!({"id": a, "props": {"sizingV": "fill"}})); + assert!(r.is_err(), "Fill height in a wrapping row that hugs its height"); + assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fixed)); + assert_eq!(sizing(&s, f), (Sizing::Fixed, Sizing::Hug)); + // Along the flow a wrapping row still takes Fill width, and with a fixed height Fill height. + set(&mut s, a, json!({"sizingH": "fill"})); + set(&mut s, f, json!({"sizingV": "fixed"})); + set(&mut s, a, json!({"sizingV": "fill"})); + assert_eq!(sizing(&s, a), (Sizing::Fill, Sizing::Fill)); +} + #[test] fn a_child_resized_to_the_full_available_space_becomes_fill() { // Documented: "Child objects of an auto layout frame will also be set to Fill container if diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs index 513f4f7c8..b8c9bdf8d 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -336,6 +336,28 @@ fn index_old_layers(doc: &Document, inst: NodeId, spare: BTreeMap figcraft_doc::ChildLayout { + let mut cl = root.child_layout.clone(); + // One "size" override covers both axes, as in Figma ("Reset size"): it keeps both. + if root.overrides.contains("size") || root.overrides.contains("resizing") { + return cl; + } + let in_flow = root.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some()); + let take = |own: &mut figcraft_doc::Sizing, main: figcraft_doc::Sizing| { + if !(in_flow && *own == figcraft_doc::Sizing::Fill) && main != figcraft_doc::Sizing::Fill { + *own = main; + } + }; + take(&mut cl.sizing_h, comp.child_layout.sizing_h); + take(&mut cl.sizing_v, comp.child_layout.sizing_v); + cl +} + /// The rebuilt root of instance `inst` of `comp`. fn fresh_root(doc: &Document, root: &mut Node, comp: &Node, inst: NodeId, component: NodeId, map: &BTreeMap) -> Node { // Root: follows the main except its own placement, name, size and overrides. @@ -351,7 +373,7 @@ fn fresh_root(doc: &Document, root: &mut Node, comp: &Node, inst: NodeId, compon let nested_copy = inside_instance(doc, inst); fresh.source = if nested_copy { root.source } else { Some(component) }; fresh.constraints = root.constraints; - fresh.child_layout = root.child_layout.clone(); + fresh.child_layout = instance_child_layout(doc, root, comp); fresh.interactions = root.interactions.clone(); fresh.exports = root.exports.clone(); fresh.prop_refs = root.prop_refs.clone(); diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index c39f8abe2..5bd6710af 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -163,6 +163,9 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result { names.join(", ") )); } + let mut hugging = crate::cmd::props::hugging_parents(&s.ds()?.doc, &ids, &props); + let filling = crate::cmd::props::filling_children(&s.ds()?.doc, &ids, &props); + let targets = ids.clone(); let doc = s.doc_mut()?; let before = crate::cmd::styles::bound_before(doc, &ids); let mut ids = ids; @@ -182,6 +185,20 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result { } } } + // A child that filled a hugging parent along its flow turned the parent Fixed: say so. + // A frame set to Hug turns the children that filled it along its flow Fixed. That is the + // coherence pass `normalize` runs once the command returns; run it here for those frames + // (idempotent) so the notice sees the demotion. + if !filling.is_empty() { + let doc = s.doc_mut()?; + for f in &targets { + figcraft_layout::coherent_sizing(doc, *f); + } + hugging.extend(filling); + } + if let Some(notice) = crate::cmd::props::fixed_notice(&s.ds()?.doc, &hugging) { + s.message = Some(notice); + } if warnings.is_empty() { ok() } else { Ok(json!({"ok": true, "warnings": warnings})) } } diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 75889bb53..94b681381 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1234,14 +1234,16 @@ pub fn apply(cmd: &str, doc: &mut Document, id: NodeId, props: &Map {} } - // A child can't fill an axis its parent hugs: the parent becomes fixed at its current size. - // (The other way round, a parent that starts to hug fixes the children that filled it: see - // `figcraft_layout::coherent_sizing`, applied after every edit.) + // A child can't fill the axis its parent hugs along the flow: the parent becomes fixed at its + // current size. Across the flow the parent keeps hugging and the child takes the line's size + // (the largest sibling that doesn't fill); the parent becomes fixed only when no such sibling + // is left. (The other way round, a parent that starts to hug fixes the children that filled it + // along the flow: see `figcraft_layout::coherent_sizing`, applied after every edit.) if s == Sizing::Fill && let Some(p) = parent { - let cl = &mut doc.get_mut(p)?.child_layout; - let ps = if horizontal { &mut cl.sizing_h } else { &mut cl.sizing_v }; - if *ps == Sizing::Hug { - *ps = Sizing::Fixed; + let pn = doc.get(p)?; + if figcraft_layout::wrapping_row_hugs_across(pn, horizontal) { + return Err(bad(cmd, "Fill container across a wrapping row is not offered")); + } + let along = match pn.layout.as_ref().map(|al| al.mode) { + Some(LayoutMode::Horizontal) => horizontal, + Some(LayoutMode::Vertical) => !horizontal, + _ => true, + }; + let others_fill = figcraft_layout::flow_children(doc, p) + .into_iter() + .filter(|c| *c != id) + .all(|c| doc.node(c).is_some_and(|c| (if horizontal { c.child_layout.sizing_h } else { c.child_layout.sizing_v }) == Sizing::Fill)); + if along || others_fill { + let cl = &mut doc.get_mut(p)?.child_layout; + let ps = if horizontal { &mut cl.sizing_h } else { &mut cl.sizing_v }; + if *ps == Sizing::Hug { + *ps = Sizing::Fixed; + // An instance's own root, or a layer inside one, turned Fixed by this edit: that + // is its resizing now, an override, or the next rebuild from the main would take + // the main's Hug back and the child would stop filling. + if doc.get(p)?.source.is_some() { + doc.get_mut(p)?.overrides.insert("resizing".to_string()); + } + } } } // Start from the sizing the layer has in effect (an auto-width text hugs both axes), so the @@ -1517,6 +1542,60 @@ fn set_sizing(cmd: &str, doc: &mut Document, id: NodeId, s: Sizing, horizontal: Ok(()) } +/// The hugging parents that `props` setting Fill on `ids` may turn Fixed, as (parent, horizontal): +/// taken before the edit, for [`fixed_notice`]. +pub(crate) fn hugging_parents(doc: &Document, ids: &[NodeId], props: &Map) -> Vec<(NodeId, bool)> { + let mut out = Vec::new(); + for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] { + if !keys.iter().any(|k| props.get(*k).and_then(sizing) == Some(Sizing::Fill)) { + continue; + } + for p in ids.iter().filter_map(|i| doc.node(*i)).filter_map(|n| n.parent) { + let hugs = doc + .node(p) + .is_some_and(|p| p.layout.is_some() && (if horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v }) == Sizing::Hug); + if hugs && !out.contains(&(p, horizontal)) { + out.push((p, horizontal)); + } + } + } + out +} + +/// The children, as (child, horizontal), that fill an axis of a frame in `ids` which `props` sets +/// to Hug: taken before the edit, for [`fixed_notice`] (the coherence pass turns them Fixed). +pub(crate) fn filling_children(doc: &Document, ids: &[NodeId], props: &Map) -> Vec<(NodeId, bool)> { + let mut out = Vec::new(); + for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] { + if !keys.iter().any(|k| props.get(*k).and_then(sizing) == Some(Sizing::Hug)) { + continue; + } + for f in ids.iter().filter_map(|i| doc.node(*i)).filter(|n| n.layout.is_some() && n.kind.is_frame_like()) { + for c in f.children.iter().filter_map(|c| doc.node(*c)) { + let fills = (if horizontal { c.child_layout.sizing_h } else { c.child_layout.sizing_v }) == Sizing::Fill; + if fills && !out.contains(&(c.id, horizontal)) { + out.push((c.id, horizontal)); + } + } + } + } + out +} + +/// The notice for the layers of [`hugging_parents`] or [`filling_children`] that the edit turned +/// Fixed ("Height set to Fixed for Frame 1"), `None` when every one kept its sizing. +pub(crate) fn fixed_notice(doc: &Document, before: &[(NodeId, bool)]) -> Option { + let notes: Vec = before + .iter() + .filter_map(|(p, horizontal)| { + let p = doc.node(*p)?; + let now = if *horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v }; + (now == Sizing::Fixed).then(|| format!("{} set to Fixed for {}", if *horizontal { "Width" } else { "Height" }, p.name)) + }) + .collect(); + (!notes.is_empty()).then(|| notes.join("; ")) +} + /// Resize a node's box from its top-left, applying constraints / group scaling to children. /// The page transforms of `id`'s children, to put back with [`restore_worlds`] once a container /// whose contents stay where they are on the page (a section; a frame resized with Cmd/Ctrl held) diff --git a/crates/engine/src/components_behaviour_tests.rs b/crates/engine/src/components_behaviour_tests.rs index 3565a3165..e8dda9e95 100644 --- a/crates/engine/src/components_behaviour_tests.rs +++ b/crates/engine/src/components_behaviour_tests.rs @@ -1002,6 +1002,180 @@ fn deleting_a_layer_inside_an_instance_hides_it_instead() { assert!(s.doc().unwrap().node(k.inst).is_none()); } +/// Issue 2090 item 2: after a main's child is set to fill, the instance's copy must match the main's +/// child (sizing, size) and the copy's parent must match the main's parent sizing. Relative, not +/// absolute, so it holds whatever the cross-axis rule is. +fn fill_matches_main(horizontal: bool, axis: &str) { + let hug_axis = if horizontal { "sizingV" } else { "sizingH" }; + fill_matches_main_hugging(horizontal, axis, hug_axis); +} + +/// As `fill_matches_main`, with the axis the main root hugs given explicitly. +fn fill_matches_main_hugging(horizontal: bool, axis: &str, hug_axis: &str) { + let mut s = Session::new(); + let mode = if horizontal { "horizontal" } else { "vertical" }; + let comp = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "name": "Note"}))); + let bar = idv(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 20, "parent": comp, "props": {"name": "Bar"}}))); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 40, "parent": comp, "props": {"name": "Body"}})); + ex(&mut s, "node.set", json!({"id": comp, "props": {"layout": mode, "gap": 12, "padding": 10, hug_axis: "hug"}})); + let comp = idv(&ex(&mut s, "component.create", json!({"ids": [comp]}))); + let inst = idv(&ex(&mut s, "instance.create", json!({"component": comp, "x": 400, "y": 0}))); + let bar = if node(&s, bar).parent.is_some() { bar } else { kids(&s, comp)[0] }; + ex(&mut s, "node.set", json!({"id": bar, "props": {axis: "fill"}})); + let ibar = copy_of(&s, inst, bar); + let (m, c) = (node(&s, bar), node(&s, ibar)); + let (mp, cp) = (node(&s, comp), node(&s, inst)); + eprintln!( + "{axis}: main bar {}x{} sizing {:?}/{:?}; copy {}x{} sizing {:?}/{:?}; main parent {}x{} {:?}/{:?}; inst {}x{} {:?}/{:?}", + m.width, + m.height, + m.child_layout.sizing_h, + m.child_layout.sizing_v, + c.width, + c.height, + c.child_layout.sizing_h, + c.child_layout.sizing_v, + mp.width, + mp.height, + mp.child_layout.sizing_h, + mp.child_layout.sizing_v, + cp.width, + cp.height, + cp.child_layout.sizing_h, + cp.child_layout.sizing_v + ); + assert_eq!((c.child_layout.sizing_h, c.child_layout.sizing_v), (m.child_layout.sizing_h, m.child_layout.sizing_v), "copy sizing"); + assert_eq!((c.width, c.height), (m.width, m.height), "copy size matches main child"); + assert_eq!( + (cp.child_layout.sizing_h, cp.child_layout.sizing_v), + (mp.child_layout.sizing_h, mp.child_layout.sizing_v), + "parent sizing matches main parent" + ); +} + +#[test] +fn instance_follows_main_child_fill_on_the_cross_axis() { + fill_matches_main(true, "sizingV"); +} + +#[test] +fn instance_follows_main_child_fill_on_the_main_axis() { + fill_matches_main(true, "sizingH"); +} + +#[test] +fn instance_follows_main_child_fill_along_a_hugging_main_axis() { + fill_matches_main_hugging(true, "sizingH", "sizingH"); +} + +/// A horizontal auto layout main hugging its width, with a "Bar" and a "Body" child, and an instance. +fn hugging_note(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let comp = idv(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "name": "Note"}))); + let bar = idv(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 20, "parent": comp, "props": {"name": "Bar"}}))); + ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 40, "parent": comp, "props": {"name": "Body"}})); + ex(s, "node.set", json!({"id": comp, "props": {"layout": "horizontal", "gap": 12, "padding": 10, "sizingH": "hug"}})); + let comp = idv(&ex(s, "component.create", json!({"ids": [comp]}))); + let inst = idv(&ex(s, "instance.create", json!({"component": comp, "x": 400, "y": 0}))); + let bar = if node(s, bar).parent.is_some() { bar } else { kids(s, comp)[0] }; + (comp, inst, bar) +} + +fn sizing_h(s: &Session, id: NodeId) -> Sizing { + node(s, id).child_layout.sizing_h +} + +/// Measured in Figma: the main's root turning Fixed (set directly) reaches a plain instance, and +/// the main going back to Hug brings it back. +#[test] +fn a_plain_instances_resizing_follows_the_mains_root_both_ways() { + let mut s = Session::new(); + let (comp, inst, _) = hugging_note(&mut s); + assert_eq!(sizing_h(&s, inst), Sizing::Hug); + ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "fixed"}})); + assert_eq!(sizing_h(&s, comp), Sizing::Fixed); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "the instance turns Fixed with its main"); + ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Hug, "and back to Hug with it"); +} + +/// Measured in Figma: a child set to Fill along the hugging axis turns the main Fixed; the plain +/// instance follows it, and follows it back to Hug. +#[test] +fn a_plain_instance_goes_fixed_and_back_to_hug_with_its_main() { + let mut s = Session::new(); + let (comp, inst, bar) = hugging_note(&mut s); + ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}})); + assert_eq!(sizing_h(&s, comp), Sizing::Fixed); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed); + ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Hug); +} + +/// Measured in Figma: an instance whose width was typed keeps that Fixed width through both +/// changes, while its height kept hugging its content. Figma keeps one size override for both +/// axes, as FigCraft does: with the width typed, a change to a fixed main's height does not reach +/// the instance, and the only size reset is "Reset size" (measured 2026-11-09). +#[test] +fn an_instance_with_a_typed_width_keeps_it_when_the_main_turns_fixed_and_back() { + let mut s = Session::new(); + let (comp, inst, bar) = hugging_note(&mut s); + ex(&mut s, "node.set", json!({"id": inst, "props": {"width": 200}})); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed); + assert_eq!(node(&s, inst).width, 200.0); + ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed); + assert_eq!(node(&s, inst).width, 200.0, "the typed width stays"); + ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "still Fixed after the main hugs again"); + assert_eq!(node(&s, inst).width, 200.0); +} + +/// An instance placed in an auto layout frame and set to Fill there keeps Fill when its main changes. +#[test] +fn an_instance_filling_its_auto_layout_parent_keeps_fill_when_the_main_changes() { + let mut s = Session::new(); + let (comp, inst, bar) = hugging_note(&mut s); + let row = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 500, "height": 100, "name": "Row"}))); + ex(&mut s, "node.set", json!({"id": row, "props": {"layout": "horizontal"}})); + ex(&mut s, "node.reparent", json!({"ids": [inst], "parent": row})); + ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fill"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Fill); + ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}})); + assert_eq!(sizing_h(&s, comp), Sizing::Fixed); + assert_eq!(sizing_h(&s, inst), Sizing::Fill, "its own Fill in the row is kept"); + ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Fill); +} + +/// Inferred (Figma was measured only with a typed width): a Fixed set directly on an instance's +/// root, with no width typed, is an override the sync keeps when the main's root turns Hug, Fixed +/// and Hug again. +#[test] +fn an_instance_root_set_to_fixed_keeps_it_through_the_mains_resizing_changes() { + let mut s = Session::new(); + let (comp, inst, _) = hugging_note(&mut s); + ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fixed"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed); + assert!(node(&s, inst).overrides.contains("resizing"), "{:?}", node(&s, inst).overrides); + ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "fixed"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed); + ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}})); + assert_eq!(sizing_h(&s, comp), Sizing::Hug); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "its own Fixed stays after the main hugs again"); +} + +/// Resetting that instance brings its resizing back to the main's. +#[test] +fn resetting_an_instance_brings_its_own_resizing_back_to_the_mains() { + let mut s = Session::new(); + let (_, inst, _) = hugging_note(&mut s); + ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fixed"}})); + assert_eq!(sizing_h(&s, inst), Sizing::Fixed); + ex(&mut s, "component.resetInstance", json!({"ids": [inst]})); + assert!(!node(&s, inst).overrides.contains("resizing")); + assert_eq!(sizing_h(&s, inst), Sizing::Hug, "the main hugs"); +} + /// Create multiple components (#2088): each selected layer becomes its own component in place, /// keeping its name and position; all stay selected and one undo reverts them all. #[test] diff --git a/crates/engine/src/instance_resizing_tests.rs b/crates/engine/src/instance_resizing_tests.rs index 43386af96..489fcbb1b 100644 --- a/crates/engine/src/instance_resizing_tests.rs +++ b/crates/engine/src/instance_resizing_tests.rs @@ -77,6 +77,34 @@ fn a_layer_in_an_instance_fills_and_keeps_it_through_main_edits() { healthy(&s); } +/// A child set to Fill along a hugging instance root turns the root Fixed: that is the root's own +/// resizing now, recorded as an override, so a later rebuild from the main (an edit of the main's +/// resizing or structure) keeps it Fixed and the child keeps filling. +#[test] +fn a_child_filling_a_hugging_instance_root_keeps_the_root_fixed_through_a_rebuild() { + let mut s = Session::new(); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 120, "height": 40, "name": "Row"}))); + ex(&mut s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug"}})); + let atom = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": f, "name": "Atom"}))); + ex(&mut s, "node.set", json!({"id": atom, "props": {"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug"}})); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": atom, "props": {"name": "Dot"}})); + let c = idv(&ex(&mut s, "component.create", json!({"ids": [f]}))); + let i = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 0, "y": 100}))); + let ia = copy_of(&s, i, atom); + assert_eq!((sizing_h(&s, i), sizing_h(&s, ia), node(&s, i).width), (Sizing::Hug, Sizing::Hug, 50.0)); + ex(&mut s, "node.set", json!({"id": ia, "props": {"sizingH": "fill"}})); + assert_eq!((sizing_h(&s, i), sizing_h(&s, ia)), (Sizing::Fixed, Sizing::Fill), "the root turned Fixed, the child fills"); + // The main's resizing changes, and its structure: both rebuild the instance. + ex(&mut s, "node.set", json!({"id": c, "props": {"minWidth": 60}})); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5, "parent": c})); + assert_eq!((sizing_h(&s, i), sizing_h(&s, ia)), (Sizing::Fixed, Sizing::Fill), "the root stays Fixed through the rebuild"); + assert!(node(&s, i).overrides.contains("resizing"), "{:?}", node(&s, i).overrides); + // Reset instance gives the main's Hug back. + ex(&mut s, "component.resetInstance", json!({"ids": [i]})); + assert_eq!(sizing_h(&s, i), Sizing::Hug); + healthy(&s); +} + #[test] fn size_and_resizing_overrides_undo_reset_and_detach() { let mut s = Session::new(); @@ -123,8 +151,10 @@ fn layers_in_instances_resize_but_keep_their_place() { for props in [json!({"x": 50}), json!({"rotation": 15}), json!({"constraints": {"horizontal": "right"}})] { assert!(s.execute("node.set", &json!({"id": it, "props": props})).is_err(), "{props} is refused"); } - // The instance's own resizing is its own, not an override. + // The instance's own resizing is recorded as an override (inferred), which Reset instance clears. ex(&mut s, "node.set", json!({"id": i, "props": {"minWidth": 100}})); + assert!(node(&s, i).overrides.contains("resizing")); + ex(&mut s, "component.resetInstance", json!({"ids": [i]})); assert!(!node(&s, i).overrides.contains("resizing")); healthy(&s); } diff --git a/crates/format/src/fig/auto_layout_sizing_tests.rs b/crates/format/src/fig/auto_layout_sizing_tests.rs index 29580afb9..4e04ebafa 100644 --- a/crates/format/src/fig/auto_layout_sizing_tests.rs +++ b/crates/format/src/fig/auto_layout_sizing_tests.rs @@ -8,18 +8,20 @@ use serde_json::{Value, json}; use super::kiwi::{Kv, Schema}; const SCHEMA: &str = " -enum NodeType NONE DOCUMENT CANVAS FRAME TEXT SYMBOL INSTANCE +enum NodeType NONE DOCUMENT CANVAS FRAME TEXT SYMBOL INSTANCE ROUNDED_RECTANGLE enum StackMode NONE HORIZONTAL VERTICAL enum StackSize FIXED RESIZE_TO_FIT RESIZE_TO_FIT_WITH_IMPLICIT_SIZE enum StackJustify MIN CENTER MAX SPACE_EVENLY SPACE_BETWEEN SPACE_AROUND SPACE_EVENLY_CSS +enum StackCounterAlign MIN CENTER MAX STRETCH AUTO BASELINE enum TextAutoResize NONE WIDTH_AND_HEIGHT HEIGHT struct GUID uint sessionID, uint localID struct Vector float x, float y struct Matrix float m00, float m01, float m02, float m10, float m11, float m12 message ParentIndex GUID guid, string position +message GUIDPath GUID[] guids message TextData string characters message SymbolData GUID symbolID -message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, Vector size, Matrix transform, StackMode stackMode, StackSize stackPrimarySizing, StackSize stackCounterSizing, StackJustify stackPrimaryAlignItems, TextAutoResize textAutoResize, float fontSize, TextData textData, SymbolData symbolData +message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, Vector size, Matrix transform, StackMode stackMode, StackSize stackPrimarySizing, StackSize stackCounterSizing, StackJustify stackPrimaryAlignItems, TextAutoResize textAutoResize, float fontSize, TextData textData, SymbolData symbolData, StackCounterAlign stackChildAlignSelf, NodeChange[] derivedSymbolData, GUIDPath guidPath message Message NodeChange[] nodeChanges "; @@ -216,3 +218,120 @@ fn distributed_alignment_reads_the_older_evenly_name_as_space_between() { assert_eq!(n.layout.as_ref().map(|l| l.main_align), Some(want), "{name}"); } } + +/// Issue 2091 item 3: a child with `stackChildAlignSelf: STRETCH` fills the cross axis. +#[test] +fn stretch_children_import_as_fill_on_the_cross_axis() { + use Sizing::Fill; + let stretch = || vec![("stackChildAlignSelf", Kv::Enum("STRETCH"))]; + let mut nodes = Vec::new(); + // (a) plain frame / (b) component, fixed and hug cross axis (d) + for (k, (ty, counter)) in + [("FRAME", "FIXED"), ("SYMBOL", "FIXED"), ("FRAME", "RESIZE_TO_FIT"), ("SYMBOL", "RESIZE_TO_FIT")].into_iter().enumerate() + { + let id = 100 * (k as u64 + 1); + let mut f = vec![("size", xy(100.0, 40.0)), ("transform", at(0.0, 60.0 * k as f64))]; + f.extend(stack("HORIZONTAL", Some("FIXED"), Some(counter))); + nodes.push(node(id, 1, &format!("{id}"), ty, &format!("Row{k}"), f)); + // (e) a rectangle and a text + nodes.push(node( + id + 1, + id, + "!", + "ROUNDED_RECTANGLE", + &format!("Bar{k}"), + [vec![("size", xy(3.0, 20.0)), ("transform", at(0.0, 0.0))], stretch()].concat(), + )); + let mut t = label(id + 2, id, &format!("Msg{k}"), Some("WIDTH_AND_HEIGHT")); + if let Kv::Object(fields) = &mut t { + fields.extend(stretch()); + } + nodes.push(t); + } + // (c) an instance of Row1 (a component) and its copy of the bar + nodes.push(node( + 900, + 1, + "~", + "INSTANCE", + "Inst", + vec![("size", xy(100.0, 40.0)), ("transform", at(200.0, 0.0)), ("symbolData", o(vec![("symbolID", g(200))]))], + )); + // (c2) same-size instance whose derived data gives the bar Figma's stretched 40 px; (c3) a taller + // instance (60) whose derived data gives 60. + for (id, name, h, bar_h) in [(901, "InstDerived", 40.0, 40.0), (902, "InstTall", 60.0, 60.0)] { + let row = o(vec![("guidPath", o(vec![("guids", Kv::Array(vec![g(201)]))])), ("size", xy(3.0, bar_h))]); + nodes.push(node( + id, + 1, + &format!("~{id}"), + "INSTANCE", + name, + vec![ + ("size", xy(100.0, h)), + ("transform", at(300.0, 0.0)), + ("symbolData", o(vec![("symbolID", g(200))])), + ("derivedSymbolData", Kv::Array(vec![row])), + ], + )); + } + let doc = import(nodes); + let get = |n: &str| doc.nodes().find(|x| x.name == n).unwrap_or_else(|| panic!("no layer {n}")); + let mut bad = Vec::new(); + for k in 0..4 { + for what in ["Bar", "Msg text"] { + let n = get(&if what == "Bar" { format!("Bar{k}") } else { format!("Msg{k} text") }); + if n.child_layout.sizing_v != Fill { + bad.push(format!("{what}{k} (row {k}): sizing_v {:?}, h {}", n.child_layout.sizing_v, n.size().1)); + } + } + } + let inst = get("Inst"); + let copy = inst.children.first().and_then(|c| doc.node(*c)).unwrap(); + if copy.child_layout.sizing_v != Fill { + bad.push(format!("instance copy of the bar: sizing_v {:?}, h {}", copy.child_layout.sizing_v, copy.size().1)); + } + for (name, want_h) in [("InstDerived", 40.0), ("InstTall", 60.0)] { + let inst = get(name); + let bar = inst.children.first().and_then(|c| doc.node(*c)).unwrap(); + if bar.child_layout.sizing_v != Fill || (bar.size().1 - want_h).abs() > 1e-6 { + bad.push(format!("{name} copy of the bar: sizing_v {:?}, h {} (want Fill, {want_h})", bar.child_layout.sizing_v, bar.size().1)); + } + } + assert!(bad.is_empty(), "{bad:#?}"); +} + +/// Issue 2091 item 3, after a layout pass: the stretched bar takes the row's cross size, also +/// when the row hugs (the bar next to a two-line text, whose height makes the row's). +#[test] +fn stretch_children_take_the_row_height_after_a_layout_pass() { + let mut nodes = Vec::new(); + // (name, counter sizing, row height, expected bar height after layout) + let rows = [("Fixed row", "FIXED", 40.0, 40.0), ("Hug row", "RESIZE_TO_FIT", 16.0, 16.0)]; + for (k, (name, counter, h, _)) in rows.iter().enumerate() { + let id = 100 * (k as u64 + 1); + let mut f = vec![("size", xy(100.0, *h)), ("transform", at(0.0, 60.0 * k as f64))]; + f.extend(stack("HORIZONTAL", Some("FIXED"), Some(counter))); + nodes.push(node(id, 1, &format!("{id}"), "FRAME", name, f)); + let bar = vec![("size", xy(3.0, 10.0)), ("transform", at(0.0, 0.0)), ("stackChildAlignSelf", Kv::Enum("STRETCH"))]; + nodes.push(node(id + 1, id, "!", "ROUNDED_RECTANGLE", &format!("Bar {name}"), bar)); + // The text sets the row's height: 16 px tall, fixed box. + let mut t = label(id + 2, id, name, Some("NONE")); + if let Kv::Object(fields) = &mut t { + fields.push(("transform", at(10.0, 0.0))); + } + nodes.push(t); + } + let mut doc = import(nodes); + let page = doc.first_page().unwrap(); + figcraft_layout::layout_page(&mut doc, page, &figcraft_layout::NoMeasure); + let mut bad = Vec::new(); + for (name, _, _, want) in rows { + let bar = doc.nodes().find(|n| n.name == format!("Bar {name}")).unwrap(); + let got = bar.size().1; + if (got - want).abs() > 1e-6 { + bad.push(format!("{name}: bar sizing_v {:?}, height {got}, want {want}", bar.child_layout.sizing_v)); + } + } + assert!(bad.is_empty(), "{bad:#?}"); +} diff --git a/crates/layout/src/behaviour_tests.rs b/crates/layout/src/behaviour_tests.rs index c0b9b983b..a17a563df 100644 --- a/crates/layout/src/behaviour_tests.rs +++ b/crates/layout/src/behaviour_tests.rs @@ -234,12 +234,13 @@ fn sizing_rules() { rects: &[(10.0, 10.0, 20.0, 80.0)], }, Case { - rule: "fill on an axis the frame hugs has nothing to fill: the child keeps its size", - // A hugging frame has no free space; it hugs 50 + 30. + rule: "fill along an axis the frame hugs has nothing to fill (the child keeps its size); across it the child takes the line", + // A hugging frame has no free space along the flow: it hugs 50 + 30. Across the flow the + // frame keeps hugging and the child takes the line's 20, the other child's height. frame: Frame { sizing: (Hug, Hug), ..FRAME }, kids: &[kid(50.0, 20.0), Kid { size: (30.0, 40.0), sizing: (Fill, Fill), ..KID }], - want: (80.0, 40.0), - rects: &[(0.0, 0.0, 50.0, 20.0), (50.0, 0.0, 30.0, 40.0)], + want: (80.0, 20.0), + rects: &[(0.0, 0.0, 50.0, 20.0), (50.0, 0.0, 30.0, 20.0)], }, Case { rule: "min width: a fixed child is never narrower than its minimum", @@ -290,6 +291,119 @@ fn sizing_rules() { ]); } +/// Measured in Figma web (2026-11-08): along the flow a Fill child turns +/// a hugging parent Fixed, but across the flow the parent keeps hugging and the Fill child takes +/// the line's cross size (the largest non-Fill sibling, its min counted, padding outside). +#[test] +fn fill_across_a_hugging_axis_rules() { + let bar = |w: f64, h: f64| Kid { size: (w, h), sizing: (Fixed, Fill), ..KID }; + let hug = Frame { sizing: (Hug, Hug), ..FRAME }; + check(&[ + Case { + rule: "round 1: a bar filling the height beside a taller sibling stretches to it, the row keeps hugging", + frame: hug, + kids: &[bar(4.0, 20.0), kid(50.0, 40.0)], + want: (54.0, 40.0), + rects: &[(0.0, 0.0, 4.0, 40.0), (4.0, 0.0, 50.0, 40.0)], + }, + Case { + rule: "round 1: the sibling grows to 60, the bar and the row follow", + frame: hug, + kids: &[bar(4.0, 20.0), kid(50.0, 60.0)], + want: (54.0, 60.0), + rects: &[(0.0, 0.0, 4.0, 60.0), (4.0, 0.0, 50.0, 60.0)], + }, + Case { + rule: "round 2 case 2: in a vertical stack hugging its width a Fill width takes the widest sibling", + frame: Frame { mode: V, ..hug }, + kids: &[Kid { size: (20.0, 10.0), sizing: (Fill, Fixed), ..KID }, kid(100.0, 30.0)], + want: (100.0, 40.0), + rects: &[(0.0, 0.0, 100.0, 10.0), (0.0, 10.0, 100.0, 30.0)], + }, + Case { + rule: "round 2 case 2: the sibling widens to 150, the Fill child follows", + frame: Frame { mode: V, ..hug }, + kids: &[Kid { size: (20.0, 10.0), sizing: (Fill, Fixed), ..KID }, kid(150.0, 30.0)], + want: (150.0, 40.0), + rects: &[(0.0, 0.0, 150.0, 10.0), (0.0, 10.0, 150.0, 30.0)], + }, + Case { + rule: "round 2 case 3: padding is outside the line: the bar gets the content box", + // 10 + 40 + 10. + frame: Frame { pad: [10.0, 0.0, 10.0, 0.0], ..hug }, + kids: &[bar(4.0, 20.0), kid(50.0, 40.0)], + want: (54.0, 60.0), + rects: &[(0.0, 10.0, 4.0, 40.0), (4.0, 10.0, 50.0, 40.0)], + }, + Case { + rule: "round 2 case 5: a Fill child's min counts toward the hug size", + frame: hug, + kids: &[Kid { min: (None, Some(50.0)), ..bar(4.0, 20.0) }, kid(50.0, 40.0)], + want: (54.0, 50.0), + rects: &[(0.0, 0.0, 4.0, 50.0), (4.0, 0.0, 50.0, 40.0)], + }, + Case { + rule: "round 2 case 6: beside a text the bar is as tall as the text (two lines)", + frame: hug, + kids: &[bar(3.0, 20.0), Kid { text: Some((80.0, 64.0, 24.0)), ..KID }], + want: (83.0, 64.0), + rects: &[(0.0, 0.0, 3.0, 64.0), (3.0, 0.0, 80.0, 64.0)], + }, + Case { + rule: "round 2 case 6: a third line and the bar and the row follow the text", + frame: hug, + kids: &[bar(3.0, 20.0), Kid { text: Some((80.0, 96.0, 24.0)), ..KID }], + want: (83.0, 96.0), + rects: &[(0.0, 0.0, 3.0, 96.0), (3.0, 0.0, 80.0, 96.0)], + }, + Case { + rule: "shrinking is real: a Fill child taller than the tallest non-Fill sibling comes down to it", + frame: hug, + kids: &[bar(4.0, 90.0), kid(50.0, 40.0)], + want: (54.0, 40.0), + rects: &[(0.0, 0.0, 4.0, 40.0), (4.0, 0.0, 50.0, 40.0)], + }, + Case { + rule: "round 2 case 1 (import-only state): nothing but Fill children across a hugging axis keep their own sizes", + frame: hug, + kids: &[bar(4.0, 20.0), bar(50.0, 40.0)], + want: (54.0, 40.0), + rects: &[(0.0, 0.0, 4.0, 20.0), (4.0, 0.0, 50.0, 40.0)], + }, + Case { + rule: "a text stretched to the line's width reflows taller: the Fill-height sibling takes what is left, not what it got before", + // The stack is 100 tall and hugs its width: the wider sibling makes the line 100, the text + // (200 wide) is 2 lines (40) at that width, so the Fill-height bar gets 100 - 40 - 10 = 50. + frame: Frame { mode: V, size: (100.0, 100.0), sizing: (Hug, Fixed), ..FRAME }, + kids: &[ + Kid { text: Some((200.0, 20.0, 15.0)), sizing: (Fill, Hug), ..KID }, + Kid { size: (30.0, 20.0), sizing: (Fixed, Fill), ..KID }, + kid(100.0, 10.0), + ], + want: (100.0, 100.0), + rects: &[(0.0, 0.0, 100.0, 40.0), (0.0, 40.0, 30.0, 50.0), (0.0, 90.0, 100.0, 10.0)], + }, + Case { + rule: "the same with a child that fills both axes: it takes the line's width and the left-over height", + frame: Frame { mode: V, size: (100.0, 100.0), sizing: (Hug, Fixed), ..FRAME }, + kids: &[ + Kid { text: Some((200.0, 20.0, 15.0)), sizing: (Fill, Hug), ..KID }, + Kid { size: (30.0, 20.0), sizing: (Fill, Fill), ..KID }, + kid(100.0, 10.0), + ], + want: (100.0, 100.0), + rects: &[(0.0, 0.0, 100.0, 40.0), (0.0, 40.0, 100.0, 50.0), (0.0, 90.0, 100.0, 10.0)], + }, + Case { + rule: "round 2 case 4: in a wrapping row hugging its height a Fill height still reads as fixed", + frame: Frame { size: (120.0, 100.0), sizing: (Fixed, Hug), wrap: true, ..FRAME }, + kids: &[bar(40.0, 30.0), kid(40.0, 10.0)], + want: (120.0, 30.0), + rects: &[(0.0, 0.0, 40.0, 30.0), (40.0, 0.0, 40.0, 10.0)], + }, + ]); +} + #[test] fn padding_and_stroke_rules() { let inside = Some((4.0, StrokeAlign::Inside, None)); diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 443cc9310..38141584a 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -6,8 +6,9 @@ //! gap, padding and alignment; each child is Fixed, Hug (its own content) or Fill (shares the //! free space), within its min/max size. A Hug container sizes to its children. Absolute //! children (ignoring auto layout) are not placed; they follow their constraints instead. -//! - [`coherent_sizing`]: Fill and Hug only where they can apply (Fill in an auto layout flow on an -//! axis the parent doesn't hug; Hug on auto layout frames and text), else Fixed. +//! - [`coherent_sizing`]: Fill and Hug only where they can apply (Fill in an auto layout flow, except +//! along an axis the parent hugs and across a wrapping row that hugs that axis; Hug on auto layout +//! frames and text), else Fixed. //! - [`apply_constraints`]: children of a regular frame follow their constraints when it resizes. //! - [`grid_lines`]: the column/row rectangles of a layout grid, for drawing and snapping. //! @@ -167,9 +168,29 @@ pub fn flow_children(doc: &Document, frame: NodeId) -> Vec { f.children.iter().copied().filter(|c| doc.node(*c).is_some_and(|n| n.visible && !n.child_layout.absolute)).collect() } +/// Whether the parent frame `p` wraps and hugs `horizontal`'s axis, which is the cross axis of its +/// flow: Fill container is not offered there (Figma greys it out; a grid has no flow to wrap). +pub fn wrapping_row_hugs_across(p: &figcraft_doc::Node, horizontal: bool) -> bool { + let Some(al) = &p.layout else { return false }; + let hugs = if horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v } == Sizing::Hug; + al.wrap && hugs && axis_is_main(al.mode, horizontal) == Some(false) +} + +/// Whether the horizontal (or vertical) axis is the main axis of a flow; `None` for a grid. +fn axis_is_main(mode: LayoutMode, horizontal: bool) -> Option { + match mode { + LayoutMode::Horizontal => Some(horizontal), + LayoutMode::Vertical => Some(!horizontal), + LayoutMode::Grid => None, + } +} + /// Make a layer's sizing coherent with where it sits (after an edit). Fill needs room to fill: a /// layer that isn't in an auto layout flow (no auto layout parent, or ignoring auto layout), or -/// whose parent hugs that axis, gets Fixed at its current size instead. Hug needs auto layout or +/// whose parent hugs the axis it is laid out along (a grid: either axis), gets Fixed at its +/// current size instead. Across the flow of a hugging parent Fill stays: the child takes the +/// line's cross size (the largest sibling that doesn't fill), except in a wrapping row, where +/// Fill across a hugging axis is not offered and reads as Fixed. Hug needs auto layout or /// text; otherwise it is Fixed too. A text hugs what its resize mode grows. The same applies to the /// layer's own children, so a frame that starts to hug (or loses auto layout) fixes the children /// that filled it. Returns whether anything changed. @@ -188,8 +209,18 @@ fn coherent_own_sizing(doc: &mut Document, id: NodeId) -> bool { let parent_hugs = |horizontal: bool| flow_parent.map(|p| if horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v } == Sizing::Hug); let can_hug = (n.layout.is_some() && n.kind.is_frame_like()) || matches!(n.kind, NodeKind::Text(_)); + // Fill has nothing to fill without a flow parent, along an axis the parent hugs (it hugs the + // children), or across a wrapping row that hugs that axis. Across a hugging flow it stays. + let no_fill = |horizontal: bool| match (flow_parent, parent_hugs(horizontal)) { + (None, _) => true, + (Some(p), Some(true)) => { + let main = p.layout.as_ref().and_then(|al| axis_is_main(al.mode, horizontal)); + main != Some(false) || wrapping_row_hugs_across(p, horizontal) + } + _ => false, + }; let coherent = |s: Sizing, horizontal: bool| match s { - Sizing::Fill if parent_hugs(horizontal) != Some(false) => Sizing::Fixed, + Sizing::Fill if no_fill(horizontal) => Sizing::Fixed, Sizing::Hug if !can_hug => Sizing::Fixed, s => s, }; @@ -378,7 +409,11 @@ fn flow_line_extents(items: &mut [Item], lines: &[Vec], gap: f64) -> Vec< let in_line = || line.iter().filter_map(|i| items.get(*i)); let main_used = in_line().map(|item| item.main).sum::() + gaps; let all_fill = in_line().all(|item| item.fill_cross); - let cross = in_line().filter(|item| all_fill || !item.fill_cross).map(|item| item.base_off + item.cross).fold(0.0, f64::max); + // A child filling the cross axis takes the line's size, so it only counts with its min + // (nothing but fill children keep their own sizes). + let cross = in_line() + .map(|item| if !item.fill_cross || all_fill { item.base_off + item.cross } else { item.min_cross.unwrap_or(0.0) }) + .fold(0.0, f64::max); extents.push((main_used, cross)); } extents @@ -411,7 +446,7 @@ fn align_flow_lines(items: &[Item], extents: &mut [(f64, f64)], al: &AutoLayout, } /// Collect the size and sizing constraints of the children in flow order. -fn flow_items(doc: &Document, kids: &[NodeId], horizontal: bool, hug_main: bool, hug_cross: bool) -> Vec { +fn flow_items(doc: &Document, kids: &[NodeId], horizontal: bool, hug_main: bool, cross_fill_off: bool) -> Vec { let mut items = Vec::with_capacity(kids.len()); for child in kids { let Some(node) = doc.node(*child) else { continue }; @@ -428,9 +463,12 @@ fn flow_items(doc: &Document, kids: &[NodeId], horizontal: bool, hug_main: bool, id: *child, main: if horizontal { w } else { h }, cross: if horizontal { h } else { w }, - // Fill needs room to fill: on an axis the frame hugs it reads as fixed. + // Along an axis the frame hugs, Fill has nothing to fill and reads as fixed. Across the + // flow of a hugging frame the child takes the line's size (the largest sibling that + // doesn't fill: `stretch_fill_across_hug_line`), except in a wrapping row, where Fill + // across a hugging axis is not offered and reads as fixed too. fill_main: sm == Sizing::Fill && !hug_main, - fill_cross: sc == Sizing::Fill && !hug_cross, + fill_cross: sc == Sizing::Fill && !cross_fill_off, min_main, max_main, min_cross, @@ -443,6 +481,89 @@ fn flow_items(doc: &Document, kids: &[NodeId], horizontal: bool, hug_main: bool, items } +/// Size the children that fill the cross axis of a hugging frame's single line, whose children +/// that don't fill make it `line` across, to that size (the frame's own min/max, its `cross_pads` +/// outside the line, applied; the children's own min/max too), laying out a nested auto layout at +/// its new size. Nothing happens unless some children fill and some don't (a line of nothing but +/// fill children keeps their own sizes). Returns whether a child's main size changed (a text +/// filling the width of a vertical stack reflows to a new height), so the caller measures the line +/// again. +fn stretch_fill_across_hug_line( + doc: &mut Document, + items: &mut [Item], + line: f64, + (frame, cross_pads): (&figcraft_doc::ChildLayout, f64), + horizontal: bool, + m: &dyn Measure, +) -> bool { + if !items.iter().any(|it| it.fill_cross) || items.iter().all(|it| it.fill_cross) { + return false; + } + let (lo, hi) = if horizontal { (frame.min_h, frame.max_h) } else { (frame.min_w, frame.max_w) }; + let line_cross = clamp_size(line + cross_pads, lo, hi).max(cross_pads) - cross_pads; + let mut main_changed = false; + for it in items.iter_mut().filter(|it| it.fill_cross) { + let cross = clamp_size(line_cross, it.min_cross, it.max_cross); + let (w, h) = if horizontal { (it.main, cross) } else { (cross, it.main) }; + resize_child(doc, it.id, w, h, m); + let (w, h) = outer_size(doc, it.id); + let (main, cross) = if horizontal { (w, h) } else { (h, w) }; + main_changed |= (main - it.main).abs() > 1e-9; + (it.main, it.cross) = (main, cross); + } + main_changed +} + +/// Resize a child that fills the main axis to its distributed main size and the given cross size, +/// and take the size it ends up with across (wrapped text, a hugging frame). +fn resize_fill_main_item(doc: &mut Document, it: &mut Item, cross: f64, horizontal: bool, m: &dyn Measure) { + let (w, h) = if horizontal { (it.main, cross) } else { (cross, it.main) }; + resize_child(doc, it.id, w, h, m); + let (w, h) = outer_size(doc, it.id); + it.cross = if horizontal { h } else { w }; +} + +/// What `stretch_hug_line` needs to know about the frame: its limits and the padding across, the +/// flow direction, and the main-axis inner size, gap and auto gap the lines are distributed with. +struct HugStretch<'a> { + frame: (&'a figcraft_doc::ChildLayout, f64), + horizontal: bool, + flow: (f64, f64, bool), +} + +/// Stretch the cross-Fill children to a hugging frame's line (`stretch_fill_across_hug_line`). When +/// a main size changed (a text reflowed), the space the main-Fill children were given is stale: +/// share it again, resize them (a child filling both axes keeps the line's size across), measure +/// again, and follow the line if their cross sizes moved it. One extra pass. +fn stretch_hug_line( + doc: &mut Document, + items: &mut [Item], + lines: &[Vec], + line_extents: &mut Vec<(f64, f64)>, + st: &HugStretch<'_>, + m: &dyn Measure, +) { + let (frame, cross_pads) = st.frame; + let (inner_main, gap, auto_gap) = st.flow; + let line = line_extents.first().map_or(0.0, |l| l.1); + if !stretch_fill_across_hug_line(doc, items, line, (frame, cross_pads), st.horizontal, m) { + return; + } + *line_extents = flow_line_extents(items, lines, gap); + if !items.iter().any(|it| it.fill_main) { + return; + } + distribute_flow_lines(items, lines, inner_main, gap, auto_gap); + for it in items.iter_mut().filter(|it| it.fill_main) { + resize_fill_main_item(doc, it, it.cross, st.horizontal, m); + } + *line_extents = flow_line_extents(items, lines, gap); + let line = line_extents.first().map_or(0.0, |l| l.1); + if stretch_fill_across_hug_line(doc, items, line, (frame, cross_pads), st.horizontal, m) { + *line_extents = flow_line_extents(items, lines, gap); + } +} + /// Position one resolved flow line, resizing wrapped fill children across the line. fn place_flow_line(doc: &mut Document, items: &[Item], line: &[usize], al: &AutoLayout, m: &dyn Measure, geometry: FlowLineGeometry) { let FlowLineGeometry { horizontal, wraps, main_start, inner_main, cross_pos, line_cross, used, gap } = geometry; @@ -523,15 +644,16 @@ pub fn layout_frame(doc: &mut Document, frame: NodeId, m: &dyn Measure) { let hug_cross = if horizontal { hug_h } else { hug_w }; let baseline = horizontal && al.cross_align == CrossAlign::Baseline; - let mut items = flow_items(doc, &kids, horizontal, hug_main, hug_cross); - let gap = finite_or_zero(al.gap); let auto_gap = al.main_align.is_auto_gap(); let wraps = al.wrap && !hug_main; + let mut items = flow_items(doc, &kids, horizontal, hug_main, hug_cross && wraps); - // Fill across a single line: the size is the frame's inner cross size, known up front. Resize - // those children first, so text that wraps (or a frame hugging it) reports its final main size. - if !wraps { + // Fill across a single line of a frame that doesn't hug that axis: the size is the frame's + // inner cross size, known up front. Resize those children first, so text that wraps (or a + // frame hugging it) reports its final main size. A hugging frame's line is only known once + // the other children are measured (`stretch_fill_across_hug_line`). + if !wraps && !hug_cross { for it in items.iter_mut().filter(|it| it.fill_cross && !it.fill_main) { let cross = clamp_size(inner_cross_fixed, it.min_cross, it.max_cross); let (w, h) = if horizontal { (it.main, cross) } else { (cross, it.main) }; @@ -549,11 +671,8 @@ pub fn layout_frame(doc: &mut Document, frame: NodeId, m: &dyn Measure) { // Fill children take their main size now, so their cross size (wrapped text, a hugging frame) // is final before the lines and the frame are sized. for it in items.iter_mut().filter(|it| it.fill_main) { - let cross = if it.fill_cross && !wraps { clamp_size(inner_cross_fixed, it.min_cross, it.max_cross) } else { it.cross }; - let (w, h) = if horizontal { (it.main, cross) } else { (cross, it.main) }; - resize_child(doc, it.id, w, h, m); - let (w, h) = outer_size(doc, it.id); - it.cross = if horizontal { h } else { w }; + let cross = if it.fill_cross && !wraps && !hug_cross { clamp_size(inner_cross_fixed, it.min_cross, it.max_cross) } else { it.cross }; + resize_fill_main_item(doc, it, cross, horizontal, m); } if baseline { // A layer without a text baseline (an icon, a shape, a frame holding no text) sits on the @@ -566,6 +685,14 @@ pub fn layout_frame(doc: &mut Document, frame: NodeId, m: &dyn Measure) { // Line extents: (main used, cross size). let mut line_extents = flow_line_extents(&mut items, &lines, gap); + // A hugging frame's single line: children filling the cross axis take its size now (the + // largest child that doesn't fill, a fill child's min counted, the frame's own min/max + // applied). A text that reflows at its new width changes the main sizes, so measure again. + let cross_pads = if horizontal { pt + pb } else { pl + pr }; + if hug_cross && !wraps { + let stretch = HugStretch { frame: (&fcl, cross_pads), horizontal, flow: (inner_main_fixed, gap, auto_gap) }; + stretch_hug_line(doc, &mut items, &lines, &mut line_extents, &stretch, m); + } // Container size (on a hugging axis fill children can't fill: they count with their own size). let content_main = line_extents.iter().map(|l| l.0).fold(0.0, f64::max); @@ -581,7 +708,7 @@ pub fn layout_frame(doc: &mut Document, frame: NodeId, m: &dyn Measure) { } } if hug_cross { - let v = content_cross + if horizontal { pt + pb } else { pl + pr }; + let v = content_cross + cross_pads; if horizontal { nh = v; } else { diff --git a/crates/layout/src/nested_tests.rs b/crates/layout/src/nested_tests.rs index 2a51e282e..5eea12e88 100644 --- a/crates/layout/src/nested_tests.rs +++ b/crates/layout/src/nested_tests.rs @@ -48,7 +48,7 @@ fn fill_text(d: &mut Document, parent: NodeId) -> NodeId { } #[test] -fn hug_parent_treats_fill_children_as_fixed() { +fn hug_parent_treats_fill_along_the_flow_as_fixed_and_takes_the_line_across() { let mut d = Document::new("t"); let p = page(&d); let f = al(&mut d, p, LayoutMode::Horizontal, (10.0, 10.0), (Sizing::Hug, Sizing::Hug)); @@ -56,17 +56,18 @@ fn hug_parent_treats_fill_children_as_fixed() { let b = rect(&mut d, f, 30.0, 40.0); sizing(&mut d, b, Sizing::Fill, Sizing::Fill); layout_frame(&mut d, f, &NoMeasure); - // Nothing to fill: the fill child keeps its size and the frame gets the content size. - assert_eq!(size(&d, f), (90.0, 40.0)); - assert_eq!(pos(&d, b), (60.0, 0.0, 30.0, 40.0)); - // Vertical, fill on the cross axis. + // Nothing to fill along the flow: the fill child keeps its width. Across it the frame keeps + // hugging and the child takes the line, the 20 of the sibling. + assert_eq!(size(&d, f), (90.0, 20.0)); + assert_eq!(pos(&d, b), (60.0, 0.0, 30.0, 20.0)); + // Vertical, fill on the cross axis: the child is as wide as the widest sibling. let g = al(&mut d, p, LayoutMode::Vertical, (10.0, 10.0), (Sizing::Hug, Sizing::Hug)); let c = rect(&mut d, g, 60.0, 20.0); sizing(&mut d, c, Sizing::Fill, Sizing::Fixed); rect(&mut d, g, 40.0, 30.0); layout_frame(&mut d, g, &NoMeasure); - assert_eq!(size(&d, g), (60.0, 60.0)); - assert_eq!(size(&d, c), (60.0, 20.0)); + assert_eq!(size(&d, g), (40.0, 60.0)); + assert_eq!(size(&d, c), (40.0, 20.0)); } #[test] @@ -377,6 +378,89 @@ fn fill_in_a_plain_frame_behaves_as_fixed() { assert_eq!((cl.sizing_h, cl.sizing_v), (Sizing::Fixed, Sizing::Fixed)); } +/// Fill is kept across a hugging flow (the child takes the line), turned Fixed along it, and +/// turned Fixed across a wrapping row that hugs that axis (Fill height is not offered there). +#[test] +fn coherent_sizing_keeps_fill_across_a_hugging_flow() { + let mut d = Document::new("t"); + let p = page(&d); + let cl = |d: &Document, id: NodeId| { + let c = &d.node(id).unwrap().child_layout; + (c.sizing_h, c.sizing_v) + }; + // Vertical stack hugging its width: the main axis is the height, so Fill width (across) stays. + let v = al(&mut d, p, LayoutMode::Vertical, (100.0, 100.0), (Sizing::Hug, Sizing::Fixed)); + let a = rect(&mut d, v, 10.0, 10.0); + sizing(&mut d, a, Sizing::Fill, Sizing::Fill); + assert!(!coherent_sizing(&mut d, v)); + assert_eq!(cl(&d, a), (Sizing::Fill, Sizing::Fill)); + // Both axes hugged: along the flow (height) Fill is fixed, across it (width) it stays. + sizing(&mut d, v, Sizing::Hug, Sizing::Hug); + assert!(coherent_sizing(&mut d, v)); + assert_eq!(cl(&d, a), (Sizing::Fill, Sizing::Fixed)); + // Horizontal row hugging both: the width (main) is fixed, the height (across) stays Fill. + let h = al(&mut d, p, LayoutMode::Horizontal, (100.0, 100.0), (Sizing::Hug, Sizing::Hug)); + let b = rect(&mut d, h, 10.0, 10.0); + sizing(&mut d, b, Sizing::Fill, Sizing::Fill); + assert!(coherent_sizing(&mut d, h)); + assert_eq!(cl(&d, b), (Sizing::Fixed, Sizing::Fill)); + // A wrapping row hugging its height: Fill height is not offered, so it is fixed. + let w = al(&mut d, p, LayoutMode::Horizontal, (120.0, 100.0), (Sizing::Fixed, Sizing::Hug)); + layout_mut(&mut d, w).wrap = true; + let c = rect(&mut d, w, 10.0, 10.0); + sizing(&mut d, c, Sizing::Fixed, Sizing::Fill); + assert!(coherent_sizing(&mut d, w)); + assert_eq!(cl(&d, c), (Sizing::Fixed, Sizing::Fixed)); + // The same wrapping row with a fixed height keeps Fill height. + sizing(&mut d, w, Sizing::Fixed, Sizing::Fixed); + sizing(&mut d, c, Sizing::Fixed, Sizing::Fill); + assert!(!coherent_sizing(&mut d, w)); + assert_eq!(cl(&d, c), (Sizing::Fixed, Sizing::Fill)); + // A grid keeps the old rule on both axes. + let g = al(&mut d, p, LayoutMode::Grid, (100.0, 100.0), (Sizing::Hug, Sizing::Hug)); + let e = rect(&mut d, g, 10.0, 10.0); + sizing(&mut d, e, Sizing::Fill, Sizing::Fill); + assert!(coherent_sizing(&mut d, g)); + assert_eq!(cl(&d, e), (Sizing::Fixed, Sizing::Fixed)); + // No flow parent: Fixed, as before. + let r = rect(&mut d, p, 10.0, 10.0); + sizing(&mut d, r, Sizing::Fill, Sizing::Fill); + assert!(coherent_sizing(&mut d, r)); + assert_eq!(cl(&d, r), (Sizing::Fixed, Sizing::Fixed)); +} + +/// Fill across the flow of a hugging frame, with nesting: a hugging frame child fills the line, +/// a nested layout is laid out at the new size, and a text that fills the width of a hugging +/// stack reflows to its new height before the stack hugs. +#[test] +fn fill_across_a_hugging_line_lays_out_nested_children_and_reflowing_text() { + let mut d = Document::new("t"); + let p = page(&d); + // Row hugging both: a nested frame filling the height takes the 40 px of its tall sibling and + // its own children keep their places (they are laid out again at the new size). + let row = al(&mut d, p, LayoutMode::Horizontal, (10.0, 10.0), (Sizing::Hug, Sizing::Hug)); + layout_mut(&mut d, row).gap = 0.0; + let inner = al(&mut d, row, LayoutMode::Horizontal, (30.0, 20.0), (Sizing::Fixed, Sizing::Fill)); + layout_mut(&mut d, inner).cross_align = CrossAlign::Max; + let dot = rect(&mut d, inner, 10.0, 10.0); + rect(&mut d, row, 50.0, 40.0); + layout_frame(&mut d, row, &NoMeasure); + assert_eq!(size(&d, row), (80.0, 40.0)); + assert_eq!(size(&d, inner), (30.0, 40.0)); + assert_eq!(pos(&d, dot), (0.0, 30.0, 10.0, 10.0), "laid out again at 40 high, bottom aligned"); + // Vertical stack hugging both: a text filling the width beside a 60 wide rectangle wraps to + // the line (60), and the stack hugs the height of the wrapped text. + let col = al(&mut d, p, LayoutMode::Vertical, (10.0, 10.0), (Sizing::Hug, Sizing::Hug)); + layout_mut(&mut d, col).gap = 0.0; + let t = fill_text(&mut d, col); + rect(&mut d, col, 60.0, 30.0); + // 150 wide natural, 20 high lines: at 60 wide it needs 3 lines. + let m = FakeMeasure([(t, (150.0, 20.0, 15.0))].into_iter().collect()); + layout_frame(&mut d, col, &m); + assert_eq!(size(&d, t), (60.0, 60.0)); + assert_eq!(size(&d, col), (60.0, 90.0)); +} + #[test] fn coherent_sizing_rules() { let mut d = Document::new("t"); diff --git a/crates/ui-egui/src/panels/layout_panel.rs b/crates/ui-egui/src/panels/layout_panel.rs index 2629e97f4..e77d5a1f1 100644 --- a/crates/ui-egui/src/panels/layout_panel.rs +++ b/crates/ui-egui/src/panels/layout_panel.rs @@ -219,7 +219,10 @@ fn dimensions(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], has if has_al || is_text { opts.push((tr("Hug contents"), "hug")); } - if can_fill { + // Across a wrapping row that hugs this axis Fill is not offered, as Hug is not + // offered on a layer that can't hug. + let wrapped = sel.iter().any(|i| parent_of(doc, *i).is_some_and(|p| figcraft_layout::wrapping_row_hugs_across(p, horizontal))); + if can_fill && !wrapped { opts.push((tr("Fill container"), "fill")); } for (l, v) in opts { diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 691936b65..a18894efc 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** patch (padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** patch (Fill on a child turns its hugging parent Fixed along the flow only; across the flow the parent keeps hugging and the child takes the line's cross size, as measured in Figma (#2091, #2034); padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -53,7 +53,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Fixed: the frame keeps its size whatever its children need | pass | `sizing_rules` | | Fill: children share the space left after padding, gaps and fixed siblings; across the flow they stretch | pass | `sizing_rules` | | Fill children share by their content area (border-box): a child with more padding or a thicker included inside stroke takes a little more, so the content areas come out the same | **fixed** | "Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model. A layer with a thicker stroke will take up slightly more of the available width or height, so that its inner content area matches its sibling's" (Use auto layout with CSS Flexbox in mind); the split went by outer size before. Min and max still clamp the outer size; a child's own insets are its padding and its included inside stroke (`nested_tests::fill_children_share_by_content_area`; #1824) | -| Fill on a child turns its hugging parent Fixed on that axis | pass | `al_behaviour_tests::fill_on_a_child_turns_the_hugging_parent_fixed` | +| Fill on a child turns its hugging parent Fixed along the flow only; across the flow the parent keeps hugging and the child takes the line's cross size (the largest non-Fill sibling, a Fill child's min counted, padding outside); the parent turns Fixed when no non-Fill child is left (toast); Fill across a wrapping row that hugs that axis is not offered | **fixed** | Measured in Figma web (2026-11-08): A 4×20 Fill height beside B 50×40 in a hugging row: A 40, parent height 40 Hug, no notice; B 60: A 60, parent 60 Hug; min height 50 on A: A 50, parent 50 Hug, B 40; both Fill: parent Fixed 40 with the notice "Height set to Fixed for Frame 1"; along the flow (A's width Fill): parent Fixed, "Width set to Fixed for Frame 1"; in a wrapping row hugging its height Fill height is greyed out. FigCraft turned the parent Fixed on both axes, so a `.fig` STRETCH bar beside a two-line text kept its own height (#2091) and a Fill bar froze its row at the text's height of that moment (#2034). `al_behaviour_tests::fill_on_a_child_turns_the_hugging_parent_fixed`, `fill_across_a_hugging_parent_keeps_it_hugging_and_takes_the_line`, `fill_along_a_hugging_parent_notes_that_the_width_is_fixed`, `a_fill_childs_min_counts_toward_the_hugging_size`, `a_parent_set_back_to_hug_keeps_the_child_that_fills_across_it`, `fill_across_a_wrapping_row_that_hugs_that_axis_is_not_offered`; `behaviour_tests::fill_across_a_hugging_axis_rules`; `nested_tests::coherent_sizing_keeps_fill_across_a_hugging_flow`; `auto_layout_sizing_tests::stretch_children_take_the_row_height_after_a_layout_pass`. Unmeasured: a grid keeps the old rule on both axes; deleting or hiding the last non-Fill child changes no sizing (the children keep their own sizes and the parent hugs the largest) | | A child resized to the full available space becomes Fill container on that axis | **fixed** | "Child objects of an auto layout frame will also be set to Fill container if they are manually resized to the full available space of the parent frame": a width or height given by a resize, the W/H fields or a canvas handle that equals the frame's size less its padding sets Fill there: across the flow for any child, along the flow for a lone child (beside siblings what is left depends on the gaps, the alignment and overflow, so it is left alone); not in a hugging or wrapping frame or a grid. It stayed Fixed before (`al_behaviour_tests::a_child_resized_to_the_full_available_space_becomes_fill`) | | Hug only on auto layout frames (and text); Fill only in an auto layout flow, never on a top-level frame | pass | `al_behaviour_tests::hug_and_fill_only_where_they_apply` | | Double-click an edge of an auto layout frame's box: Hug contents on that axis; Alt+double-click an edge of a child's box: Fill container | **fixed** | "Tip: Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents."; "Hold ⌥ Option or Alt and double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Fill container." A vertical edge sizes the width, a horizontal one the height; any other layer keeps the double-click's old meaning (#1838). `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills` | @@ -97,7 +97,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Grid auto layout: fixed / hug / `fr` tracks, cells, spans, gaps, cell alignment | done | `fr` as measured | | Gap, auto gap (between / evenly / around), padding (per side), alignment 3×3 | done | a Cmd/Ctrl-click on a padding field (the pair or a side) makes the value typed go to all four sides in one undo step (Guide to auto layout, Keyboard shortcut guide; `padding_individual_tests`) | | Text baseline alignment | done | | -| Hug / Fill / Fixed sizing with coherent rules (Fill turns a hugging parent Fixed) | done | `al_nesting_tests.rs`, `al_behaviour_tests.rs` | +| Hug / Fill / Fixed sizing with coherent rules (Fill along a hugging axis turns the parent Fixed; across it the child takes the line) | done | `al_nesting_tests.rs`, `al_behaviour_tests.rs` | | Min/max width and height, redistribution | done | hugging text wraps at its max | | Nested hug/fill settling in one pass (three levels, wrapping fill text, grid rows) | done | | | Absolute position (ignore auto layout) with constraints | done | | @@ -118,6 +118,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver |---|---|---| | 2026-11-13 | patch | M2, #2152: Padding grip fills and outlines come from dedicated theme tokens, preserving linked-state emphasis and border widths. A rendering regression checks custom light and dark palettes. | | 2026-11-13 | patch | M2, #2152: Padding grips preserve canvas hover and secondary-click context menus while retaining their resize cursor. Only primary presses and active handle drags capture input. Regressions reproduce both stale layer hover and blocked right-click menus. | +| 2026-11-08 | patch | M2, #2091, #2034: Fill on a child of a hugging auto layout frame turns the frame Fixed only along the flow, as measured in Figma; across the flow the frame keeps hugging and the child takes the line's cross size (the largest child that doesn't fill, a Fill child's min counted, padding outside, the frame's own min/max applied), re-laid out at that size, and a text filling the width of a hugging stack reflows before the stack hugs it. The frame turns Fixed (notice "Height set to Fixed for ", also "Width ..." along the flow) only when no non-Fill child is left; in a wrapping row that hugs the axis Fill is refused (`node.set`), not offered (Layout panel) and read as Fixed by `coherent_sizing`. A `.fig` STRETCH bar beside a two-line text now takes the text's height. | | 2026-11-11 | patch | M2.1: grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) (this replaces the 2026-10-11 rule from the documentation). Layout behaviour suite: three cases flipped, three added | | 2026-11-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. | | 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | diff --git a/docs/components-parity.md b/docs/components-parity.md index 61598ab9a..ab7b4547a 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -15,7 +15,7 @@ accounts). | 2026-11-11 | minor | M3, #2022: an instance lists only the properties its variant's layers use (its variant properties, slots, and the boolean, text and instance swap properties a layer of its current variant reads), as measured in Figma's web app: an instance of variant A lists `State` and `A label`, never `B label` or a property no layer reads. The set and its variants still list every definition, so unused ones can be deleted there. A long property name in the panel is cut to one line with an ellipsis, the full name on hover, instead of wrapping over the rows around it. Tests: `prop_order_tests::an_instance_lists_only_the_properties_its_variant_uses`, `component_props_reorder_tests::a_long_property_name_stays_on_one_line`, `prop_value_tests::a_set_keeps_each_named_text_definition_and_layers_read_their_own`. Grade unchanged. | | Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main; with two or more layers selected the Design panel header's component button opens a menu with Create component, Create multiple components (each layer its own component in place, one undo step) and Create component set (each layer a component, wrapped in place in a set 20 px around: variants `Property 1=` left to right, `prop=value` names kept, layers that all share a name give a set of that name with `Property 1=Default` variants; measured in Figma), one layer keeps the plain click (#2088) | | Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances | -| What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | +| What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it; an instance's own resizing (hug or fixed) follows its main's unless its size is overridden, measured: a plain instance turns Fixed when its main does (a child set to Fill along the hugging axis) and back to Hug with it, one whose width was typed keeps it, and Fill in its own auto layout parent is its own | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | | What it doesn't: position, rotation, constraints and absolute or grid placement of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out (Delete on a layer inside an instance hides it instead of removing it, as the help center says it does); the instance itself resizes and its layers follow the main's constraints | | Component sets / variants, add variant, switch | done | Combine as variants is in the Object menu, and the canvas and layers context menu and the Design panel offer it when two or more main components are selected; Add variant on a main component not in a set yet makes it a set of itself and the new variant, one undo step (#903); components that are variants already aren't combined again (it used to put a set inside a set) | | A main's copy within its file is an instance of it: Duplicate, Alt-drag, Copy then Paste | done | a variant duplicated in its set stays a new variant and a whole set copies as a new set; only the copied roots become instances (a main inside a copied frame is copied as a main); Cut then Paste and pastes into other files keep the component (#892) | @@ -81,6 +81,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| | 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. | +| 2026-11-07 | patch | M3, #2090: an instance's own resizing follows its main's unless its size is overridden. Measured in Figma: a plain instance turns Fixed when its main's width does (a child set to Fill along it) and back to Hug with it; an instance whose width was typed keeps it; Fill in its own auto layout parent is kept. Tests: `components_behaviour_tests::a_plain_instances_resizing_follows_the_mains_root_both_ways` and the instance resizing tests beside it. | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Create component, instances, detach, reset, go to main, restore main, push changes. | | 2026-11-14 | patch | M3, #2353: renaming a group in the Local variables window to a path with `/` nests it, as in Figma: `Orange` renamed to `Palette/Orange` moves its variables to `Palette/Orange/100`… and the sidebar shows Orange indented under a new Palette group, where the slash used to become a hyphen (`Palette-Orange`). The typed path replaces the group's last part (a nested group stays in its parent), each part is trimmed and empty parts are dropped; a rename onto a variable name that stays is refused with nothing changed, and it is one undo step. Tests: `variables_select_tests::renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step` and the group rename tests beside it, `variables_panel::tests`. Grade unchanged. | | 2026-11-07 | minor | M3, #2084: a group's context menu in the Local variables window has Duplicate group (after Rename group, before Delete group). It adds a group named after the original plus " 2" (the next free number when taken: " 3"), whose variables are copies of the originals with the same leaf names, values in every mode, description, scopes, hidden-from-publishing and code syntax, each sent as `variable.duplicate` plus a rename in one `command.batch` labelled Duplicate group, so one undo step. Measured in the incumbent with one mode; an alias to a variable of the same group keeps pointing at the original. Ungroup is not built. Tests: `variables_select_tests` (headless UI). Grade unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index b94c5a56e..0a557c6b2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -205,8 +205,12 @@ Or in a project's `.mcp.json`: before the keys that tune it, so `{"layout": {"mode": "vertical"}, "gap": 8}` keeps the gap; auto layout keys beside a `layout` of `null` or `"none"` are refused. More auto layout props: - `sizingH` / `sizingV`: `fixed`, `hug` (auto layout frames and text) or `fill` (children in an - auto layout flow). A child can't fill an axis its parent hugs: setting `fill` turns the parent - `fixed` on that axis, and a parent set to `hug` turns the children that filled it `fixed`. A + auto layout flow). A child can't fill the axis its parent hugs along the flow: setting `fill` + turns the parent `fixed` on that axis (the session notice reads "Width set to Fixed for "), + and a parent set to `hug` turns the children that filled it `fixed`. Across the flow the parent keeps + hugging and the child takes the line's cross size (the largest sibling that doesn't fill, its min + counted, padding outside); the parent turns `fixed` ("Height set to Fixed for ") only when no + such sibling is left, and `fill` across a wrapping row that hugs that axis is refused. A layer moved out of auto layout (or whose frame loses it) keeps its size as `fixed`. Fill children share the space like CSS flexbox, within their min/max. - `minWidth` / `maxWidth` / `minHeight` / `maxHeight` (px, `null` removes) bound Hug, Fill and From 4c71211e2f06090eff172927026f147cc7c9fef3 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 18 Nov 2026 07:06:24 -0500 Subject: [PATCH 090/129] M8: points align and distribute in vector edit mode, as in Figma In vector edit mode, align.* and distribute.* act on the selected points instead of moving the whole vector. The Design panel shows the alignment row, and the existing shortcuts apply to those points. Closes #2109. --- crates/engine/src/canvas/vectoredit.rs | 2 + .../src/canvas/vectoredit/align_tests.rs | 261 ++++++++++++++++++ .../engine/src/canvas/vectoredit/transform.rs | 120 ++++++++ .../src/canvas/vectoredit/transform_tests.rs | 20 +- crates/engine/src/cmd/arrange.rs | 79 +++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/right.rs | 39 ++- crates/ui-egui/src/panels/vector_panel.rs | 9 +- crates/ui-egui/src/vector_align_tests.rs | 99 +++++++ docs/target-app-parity.md | 5 +- docs/ui-parity.md | 4 +- 11 files changed, 614 insertions(+), 26 deletions(-) create mode 100644 crates/engine/src/canvas/vectoredit/align_tests.rs create mode 100644 crates/ui-egui/src/vector_align_tests.rs diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs index ab9fcb79f..ff8af30a4 100644 --- a/crates/engine/src/canvas/vectoredit.rs +++ b/crates/engine/src/canvas/vectoredit.rs @@ -7,6 +7,8 @@ //! the transform box around several points (in one layer or several) in [`transform`], point snapping in `point_snap.rs` and //! hovering, hatching and selecting filled regions in [`regions`]. +#[cfg(test)] +mod align_tests; pub mod ops; pub(crate) mod point_snap; mod pointer; diff --git a/crates/engine/src/canvas/vectoredit/align_tests.rs b/crates/engine/src/canvas/vectoredit/align_tests.rs new file mode 100644 index 000000000..323929563 --- /dev/null +++ b/crates/engine/src/canvas/vectoredit/align_tests.rs @@ -0,0 +1,261 @@ +//! Align and distribute the selected points in vector edit mode. + +use serde_json::json; + +use super::tests::{ex, net, pt, ve}; +use super::*; + +/// The measured path: points at (330, 480), (480, 430), (560, 560), (380, 620), in edit mode. +fn path(s: &mut Session) -> NodeId { + let r = ex(s, "vector.create", json!({"points": [[330, 480], [480, 430], [560, 560], [380, 620]], "closed": false})); + let id = crate::params::id_of(&r["id"]).unwrap(); + ex(s, "vector.edit.begin", json!({"id": id})); + id +} + +fn page(s: &Session, id: NodeId) -> Vec { + let w = s.doc().unwrap().world_transform(id); + net(s, id).vertices.iter().map(|v| w * v.point()).collect() +} + +fn page_of(s: &Session, id: NodeId, p: Point) -> Point { + s.doc().unwrap().world_transform(id) * p +} + +fn select(s: &mut Session, v: &[usize]) { + ex(s, "vector.edit.select", json!({"vertices": v})); +} + +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-6 +} + +#[test] +fn each_alignment_moves_the_points_along_one_axis_to_their_box() { + // Points 0 and 1: box x 330..480, y 430..480. + let cases = [ + ("align.left", [pt(330.0, 480.0), pt(330.0, 430.0)]), + ("align.hcenter", [pt(405.0, 480.0), pt(405.0, 430.0)]), + ("align.right", [pt(480.0, 480.0), pt(480.0, 430.0)]), + ("align.top", [pt(330.0, 430.0), pt(480.0, 430.0)]), + ("align.vcenter", [pt(330.0, 455.0), pt(480.0, 455.0)]), + ("align.bottom", [pt(330.0, 480.0), pt(480.0, 480.0)]), + ]; + for (cmd, want) in cases { + let mut s = Session::new(); + let id = path(&mut s); + let before = page(&s, id); + select(&mut s, &[0, 1]); + ex(&mut s, cmd, json!({})); + let after = page(&s, id); + assert!(near(after[0], want[0]) && near(after[1], want[1]), "{cmd}: {after:?}"); + assert!(near(after[2], before[2]) && near(after[3], before[3]), "{cmd} left the others"); + } +} + +#[test] +fn one_point_does_not_move() { + let mut s = Session::new(); + let id = path(&mut s); + let before = page(&s, id); + select(&mut s, &[1]); + for c in ["align.left", "align.bottom", "distribute.horizontal"] { + ex(&mut s, c, json!({})); + } + assert_eq!(page(&s, id), before); +} + +#[test] +fn two_points_do_not_distribute() { + let mut s = Session::new(); + let id = path(&mut s); + let before = page(&s, id); + select(&mut s, &[0, 1]); + for c in ["distribute.horizontal", "distribute.vertical"] { + ex(&mut s, c, json!({})); + } + assert_eq!(page(&s, id), before); +} + +/// A vector inside a frame at (100, 100), its left (150) well inside the frame. +fn framed(s: &mut Session) -> (NodeId, NodeId) { + let f = crate::params::id_of(&ex(s, "frame.create", json!({"x": 100, "y": 100, "width": 400, "height": 400}))["id"]).unwrap(); + let r = ex(s, "vector.create", json!({"points": [[50, 100], [150, 50], [200, 200]], "closed": false, "parent": f})); + (f, crate::params::id_of(&r["id"]).unwrap()) +} + +const ALIGNS: [&str; 6] = ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom"]; + +#[test] +fn no_points_selected_moves_nothing_and_not_the_layer() { + let mut s = Session::new(); + let (frame, v) = framed(&mut s); + ex(&mut s, "vector.edit.begin", json!({"id": v})); + ex(&mut s, "vector.edit.select", json!({"vertices": []})); + assert_eq!(transform::edit_point_count(s.doc().unwrap(), &ve(&s)), 0); + let (points, bounds, local) = (page(&s, v), s.doc().unwrap().world_bounds(v), net(&s, v).vertices); + assert!(bounds.unwrap().x0 > s.doc().unwrap().world_bounds(frame).unwrap().x0 + 10.0, "starts well inside the frame"); + for c in ALIGNS.into_iter().chain(["distribute.horizontal", "distribute.vertical"]) { + ex(&mut s, c, json!({})); + assert_eq!(page(&s, v), points, "{c}"); + assert_eq!(s.doc().unwrap().world_bounds(v), bounds, "{c} moved the layer"); + assert_eq!(net(&s, v).vertices, local, "{c}"); + } +} + +#[test] +fn points_of_several_layers_align_and_one_undo_restores_all() { + let mut s = Session::new(); + let mut line = |p: serde_json::Value| crate::params::id_of(&ex(&mut s, "vector.create", json!({"points": p, "closed": false}))["id"]).unwrap(); + let (a, b) = (line(json!([[0, 100], [100, 150]])), line(json!([[300, 40], [400, 90]]))); + ex(&mut s, "vector.edit.begin", json!({"ids": [a, b]})); + ex(&mut s, "vector.edit.select", json!({"id": a, "vertices": [0]})); + ex(&mut s, "vector.edit.select", json!({"id": b, "vertices": [1], "add": true})); + let (pa, pb) = (page(&s, a), page(&s, b)); + ex(&mut s, "align.top", json!({})); + let (na, nb) = (page(&s, a), page(&s, b)); + let top = pa[0].y.min(pb[1].y); + assert!(near(na[0], pt(pa[0].x, top)) && near(nb[1], pt(pb[1].x, top)), "{na:?} {nb:?}"); + assert!(near(na[1], pa[1]) && near(nb[0], pb[0]), "unselected points stay"); + s.undo().unwrap(); + let (ua, ub) = (page(&s, a), page(&s, b)); + assert!(pa.iter().zip(&ua).chain(pb.iter().zip(&ub)).all(|(x, y)| near(*x, *y)), "{ua:?} {ub:?}"); +} + +#[test] +fn a_rotated_layer_aligns_in_the_boxs_own_frame() { + let mut s = Session::new(); + let id = path(&mut s); + ex(&mut s, "node.set", json!({"id": id, "props": {"rotation": 30}})); + select(&mut s, &[0, 1]); + let b = transform::point_box(s.doc().unwrap(), &ve(&s)).unwrap(); + let inv = b.frame.inverse(); + let before: Vec = page(&s, id).iter().map(|p| inv * *p).collect(); + assert!((before[0].x - before[1].x).abs() > 1.0, "the points differ in box x"); + ex(&mut s, "align.left", json!({})); + let after: Vec = page(&s, id).iter().map(|p| inv * *p).collect(); + for i in 0..2 { + assert!(after[i].x.abs() < 1e-6, "box x is the box's left: {after:?}"); + assert!((after[i].y - before[i].y).abs() < 1e-6, "box y unchanged: {after:?}"); + } +} + +#[test] +fn id_in_edit_mode_moves_the_layer_not_the_points() { + let mut s = Session::new(); + let (frame, v) = framed(&mut s); + ex(&mut s, "vector.edit.begin", json!({"id": v})); + select(&mut s, &[0, 1]); + let local = net(&s, v).vertices; + ex(&mut s, "align.left", json!({"id": v})); + let d = s.doc().unwrap(); + assert!((d.world_bounds(v).unwrap().x0 - d.world_bounds(frame).unwrap().x0).abs() < 1e-6, "layer at the frame's left"); + assert_eq!(net(&s, v).vertices, local, "points were not aligned to each other"); +} + +#[test] +fn ids_distribute_layers_and_leave_the_edited_layers_points() { + let mut s = Session::new(); + let mut rect = |x: f64| crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": x, "y": 0, "width": 50, "height": 50}))["id"]).unwrap(); + let (r1, r2, r3) = (rect(0.0), rect(60.0), rect(400.0)); + ex(&mut s, "vector.edit.begin", json!({"id": r2})); + select(&mut s, &[0, 1]); + let local = net(&s, r2).vertices; + ex(&mut s, "distribute.horizontal", json!({"ids": [r1, r2, r3]})); + let x0 = s.doc().unwrap().world_bounds(r2).unwrap().x0; + assert!((x0 - 200.0).abs() < 1e-6, "middle layer centred between the outer two: {x0}"); + assert_eq!(net(&s, r2).vertices, local); +} + +#[test] +fn distribute_spaces_the_points_evenly_between_the_outermost() { + let mut s = Session::new(); + let id = path(&mut s); + select(&mut s, &[0, 1, 2, 3]); + ex(&mut s, "distribute.horizontal", json!({})); + let p = page(&s, id); + let want_x = [330.0, 483.0 + 1.0 / 3.0, 560.0, 380.0 + 80.0 / 3.0]; + for (q, x) in p.iter().zip(want_x) { + assert!((q.x - x).abs() < 1e-6, "{p:?}"); + } + let want_y = [480.0, 430.0, 560.0, 620.0]; + assert!(p.iter().zip(want_y).all(|(q, y)| (q.y - y).abs() < 1e-6), "y unchanged: {p:?}"); + + ex(&mut s, "distribute.vertical", json!({})); + let p = page(&s, id); + // y sorted 430, 480, 560, 620 spread over 430..620. + let step = 190.0 / 3.0; + let want_y = [430.0 + step, 430.0, 430.0 + 2.0 * step, 620.0]; + assert!(p.iter().zip(want_y).all(|(q, y)| (q.y - y).abs() < 1e-6), "{p:?}"); +} + +#[test] +fn a_curved_points_handles_move_with_it() { + let mut s = Session::new(); + let r = ex(&mut s, "vector.create", json!({"path": "M 0 0 C 0 50 50 100 100 100 L 200 0", "x": 0, "y": 0})); + let id = crate::params::id_of(&r["id"]).unwrap(); + ex(&mut s, "vector.edit.begin", json!({"id": id})); + let before = net(&s, id); + let page_before = page(&s, id); + let handle = |s: &Session, n: &VectorNetwork, v: usize, t: (f64, f64)| page_of(s, id, n.vertices[v].point() + Vec2::new(t.0, t.1)); + let (h1_before, h0_before) = (handle(&s, &before, 1, before.segments[0].tb), handle(&s, &before, 0, before.segments[0].ta)); + select(&mut s, &[0, 1]); + ex(&mut s, "align.left", json!({})); + let after = net(&s, id); + let moved: Vec = (0..2).filter(|i| !near(page(&s, id)[*i], page_before[*i])).collect(); + assert!(!moved.is_empty(), "something moved"); + let p = page(&s, id); + assert!(near(p[0], pt(0.0, 0.0)) && near(p[1], pt(0.0, 100.0)), "{p:?}"); + assert!(near(p[2], page_before[2]), "vertex 2 stays"); + // Handles: vertex 1's incoming one (vertex + segment 0's `tb`) moves with it by (-100, 0). + let a0 = &after.segments[0]; + assert!(near(h1_before, pt(50.0, 100.0)) && near(handle(&s, &after, 1, a0.tb), pt(-50.0, 100.0)), "vertex 1's handle moved by (-100, 0)"); + assert!(near(h0_before, handle(&s, &after, 0, a0.ta)), "vertex 0's handle stays"); + assert_eq!(before.segments.len(), after.segments.len()); + for (a, b) in before.segments.iter().zip(&after.segments) { + assert_eq!((a.ta, a.tb), (b.ta, b.tb), "handle offsets travel with their vertex"); + } +} + +#[test] +fn one_undo_restores_the_points() { + let mut s = Session::new(); + let id = path(&mut s); + let before = page(&s, id); + select(&mut s, &[0, 1, 2, 3]); + ex(&mut s, "align.right", json!({})); + assert_ne!(page(&s, id), before); + s.undo().unwrap(); + let after = page(&s, id); + assert!(before.iter().zip(&after).all(|(a, b)| near(*a, *b)), "{after:?}"); +} + +#[test] +fn ids_in_edit_mode_still_align_layers() { + let mut s = Session::new(); + let mut square = |x: f64| crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": x, "y": 0, "width": 50, "height": 50}))["id"]).unwrap(); + let (a, b) = (square(0.0), square(200.0)); + ex(&mut s, "vector.edit.begin", json!({"id": a})); + select(&mut s, &[0, 1]); + let local = net(&s, a).vertices; + ex(&mut s, "align.left", json!({"ids": [a, b]})); + let x = |id| s.doc().unwrap().world_bounds(id).unwrap().x0; + assert!((x(a) - x(b)).abs() < 1e-6, "layers aligned"); + assert_eq!(net(&s, a).vertices, local, "the selected points kept their local positions"); +} + +#[test] +fn a_segment_selected_in_another_edited_layer_counts_both_its_ends() { + // `a`'s segment (two ends) and `b`'s first point: three points, so the panel offers + // Distribute and the command spaces all three. + let mut s = Session::new(); + let mut line = |p: serde_json::Value| crate::params::id_of(&ex(&mut s, "vector.create", json!({"points": p, "closed": false}))["id"]).unwrap(); + let (a, b) = (line(json!([[0, 0], [100, 50]])), line(json!([[300, 200], [400, 260]]))); + ex(&mut s, "vector.edit.begin", json!({"ids": [a, b]})); + ex(&mut s, "vector.edit.select", json!({"id": a, "segments": [0]})); + ex(&mut s, "vector.edit.select", json!({"id": b, "vertices": [0], "add": true})); + assert_eq!(transform::edit_point_count(s.doc().unwrap(), &ve(&s)), 3); + ex(&mut s, "distribute.horizontal", json!({})); + let xs: Vec = page(&s, a).iter().chain(page(&s, b).first()).map(|p| p.x).collect(); + assert!(xs.iter().zip([0.0, 150.0, 300.0]).all(|(x, w)| (x - w).abs() < 1e-6), "{xs:?}"); +} diff --git a/crates/engine/src/canvas/vectoredit/transform.rs b/crates/engine/src/canvas/vectoredit/transform.rs index 0f87a0bd5..0eaacb185 100644 --- a/crates/engine/src/canvas/vectoredit/transform.rs +++ b/crates/engine/src/canvas/vectoredit/transform.rs @@ -172,6 +172,126 @@ pub fn transform_in_edit_mode(s: &mut Session, p: &Value, f: impl FnOnce(&PointB Some(s.doc_mut().and_then(|doc| transform_points(doc, ve.id, &b.points, m)).map(|()| json!({"ok": true}))) } +/// Which edge or centre line of the selected points' box each point goes to. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PointAlign { + Left, + HCenter, + Right, + Top, + VCenter, + Bottom, +} + +/// Every selected point of `b` in every layer as (layer, vertex, page position). +fn page_points(doc: &Document, b: &PointBox, id: NodeId) -> Vec<(NodeId, usize, Point)> { + let layers = std::iter::once((id, &b.points)).chain(b.others.iter().map(|(o, v)| (*o, v))); + layers + .flat_map(|(l, verts)| { + let w = doc.world_transform(l); + let net = network(doc, l); + verts.iter().filter_map(move |v| net.and_then(|n| n.vertices.get(*v)).map(|vx| (l, *v, w * vx.point()))).collect::>() + }) + .collect() +} + +/// The box to align or distribute in: all edited layers' points when several are selected. +fn edit_box(doc: &Document, ve: &VectorEdit) -> Option { + let b = if ve.others_selected() { layers_box(doc, ve) } else { point_box(doc, ve) }; + b.filter(|b| b.point_count() > 0) +} + +/// How many points align and distribute act on: the selected points and selected segments' ends +/// of every edited layer. +pub fn edit_point_count(doc: &Document, ve: &VectorEdit) -> usize { + edit_box(doc, ve).map_or(0, |b| b.point_count()) +} + +/// Move each point by its own page delta, one vertex at a time (handles go with their vertex). +fn move_each(doc: &mut Document, moves: &[(NodeId, usize, Point)]) -> Result<()> { + for (l, v, d) in moves { + if d.x.is_finite() && d.y.is_finite() && (d.x != 0.0 || d.y != 0.0) { + transform_points(doc, *l, &[*v], Affine::translate((d.x, d.y)))?; + } + } + Ok(()) +} + +/// The page delta of moving by `(dx, dy)` along the box's axes. +fn along(frame: Affine, dx: f64, dy: f64) -> Point { + let [a, b, c, d, _, _] = frame.as_coeffs(); + Point::new(a * dx + c * dy, b * dx + d * dy) +} + +/// Align the selected points to their box's edge or centre line (`None` when edit mode is off or +/// the command names layers; with no points selected in edit mode nothing moves, and the edited +/// layer is not aligned to its parent). Each point moves along one axis of the box only; fewer than +/// two points stay put. +pub fn align_points_in_edit_mode(s: &mut Session, p: &Value, how: PointAlign) -> Option> { + if get(p, "ids").is_some() || get(p, "id").is_some() { + return None; + } + let ve = editing(s).ok()?; + let Some(b) = edit_box(s.doc().ok()?, &ve) else { + return Some(Ok(json!({"ok": true}))); + }; + let pts = page_points(s.doc().ok()?, &b, ve.id); + let inv = b.frame.inverse(); + let moves: Vec<(NodeId, usize, Point)> = if b.point_count() < 2 { + vec![] + } else { + pts.iter() + .map(|(l, v, pg)| { + let q = inv * *pg; + let (dx, dy) = match how { + PointAlign::Left => (-q.x, 0.0), + PointAlign::HCenter => (b.width / 2.0 - q.x, 0.0), + PointAlign::Right => (b.width - q.x, 0.0), + PointAlign::Top => (0.0, -q.y), + PointAlign::VCenter => (0.0, b.height / 2.0 - q.y), + PointAlign::Bottom => (0.0, b.height - q.y), + }; + (*l, *v, along(b.frame, dx, dy)) + }) + .collect() + }; + Some(s.doc_mut().and_then(|doc| move_each(doc, &moves)).map(|()| json!({"ok": true}))) +} + +/// Space the selected points evenly along the box's x (or y) axis between the outermost two, in +/// order along it (`None` when edit mode is off or the command names layers; with no points +/// selected in edit mode nothing moves). Fewer than three points stay put. +pub fn distribute_points_in_edit_mode(s: &mut Session, p: &Value, horizontal: bool) -> Option> { + if get(p, "ids").is_some() || get(p, "id").is_some() { + return None; + } + let ve = editing(s).ok()?; + let Some(b) = edit_box(s.doc().ok()?, &ve) else { + return Some(Ok(json!({"ok": true}))); + }; + let pts = page_points(s.doc().ok()?, &b, ve.id); + let inv = b.frame.inverse(); + let mut items: Vec<(NodeId, usize, Point)> = pts.iter().map(|(l, v, pg)| (*l, *v, inv * *pg)).collect(); + let axis = |q: &Point| if horizontal { q.x } else { q.y }; + items.sort_by(|a, c| axis(&a.2).total_cmp(&axis(&c.2))); + let n = items.len(); + let moves: Vec<(NodeId, usize, Point)> = if n < 3 { + vec![] + } else { + let (lo, hi) = (0.0, if horizontal { b.width } else { b.height }); + items + .iter() + .enumerate() + .map(|(k, (l, v, q))| { + let target = lo + (hi - lo) * k as f64 / (n - 1) as f64; + let d = target - axis(q); + (*l, *v, if horizontal { along(b.frame, d, 0.0) } else { along(b.frame, 0.0, d) }) + }) + .collect() + }; + Some(s.doc_mut().and_then(|doc| move_each(doc, &moves)).map(|()| json!({"ok": true}))) +} + /// The selected points' box, or an error naming `cmd`. fn selected_box(s: &Session, cmd: &str) -> Result<(VectorEdit, PointBox)> { let ve = editing(s)?; diff --git a/crates/engine/src/canvas/vectoredit/transform_tests.rs b/crates/engine/src/canvas/vectoredit/transform_tests.rs index eb2f96f5e..7d6206ea7 100644 --- a/crates/engine/src/canvas/vectoredit/transform_tests.rs +++ b/crates/engine/src/canvas/vectoredit/transform_tests.rs @@ -315,9 +315,23 @@ fn edit_mode_transform_commands_survive_junk() { json!({"width": -1e308, "height": "x", "center": "maybe", "angle": 1e308, "cx": "NaN", "matrix": [1, 2, 3, "a", 5, 6]}), json!({"matrix": [0, 0, 0, 0, 0, 0], "vertices": [1e12, -1], "width": 1e308, "height": 0}), ]; - for c in - ["object.flipH", "object.flipV", "object.rotate180", "object.rotateLeft", "object.rotateRight", "vector.edit.resize", "vector.edit.rotate"] - { + for c in [ + "object.flipH", + "object.flipV", + "object.rotate180", + "object.rotateLeft", + "object.rotateRight", + "vector.edit.resize", + "vector.edit.rotate", + "align.left", + "align.hcenter", + "align.right", + "align.top", + "align.vcenter", + "align.bottom", + "distribute.horizontal", + "distribute.vertical", + ] { for j in &junk { let mut s = Session::new(); let id = rect(&mut s); diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index d32064271..ea7a8830e 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -11,14 +11,62 @@ use crate::{Result, Session, bad, spec}; pub fn specs() -> Vec { vec![ - spec!("align.left", "Align left", "{ids?}", true, |s, p| align(s, p, Al::Left)), - spec!("align.hcenter", "Align horizontal centers", "{ids?}", true, |s, p| align(s, p, Al::HCenter)), - spec!("align.right", "Align right", "{ids?}", true, |s, p| align(s, p, Al::Right)), - spec!("align.top", "Align top", "{ids?}", true, |s, p| align(s, p, Al::Top)), - spec!("align.vcenter", "Align vertical centers", "{ids?}", true, |s, p| align(s, p, Al::VCenter)), - spec!("align.bottom", "Align bottom", "{ids?}", true, |s, p| align(s, p, Al::Bottom)), - spec!("distribute.horizontal", "Distribute horizontal spacing", "{ids?, spacing?}", true, |s, p| distribute(s, p, true)), - spec!("distribute.vertical", "Distribute vertical spacing", "{ids?, spacing?}", true, |s, p| distribute(s, p, false)), + spec!( + "align.left", + "Align left", + "{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)", + true, + |s, p| align(s, p, Al::Left) + ), + spec!( + "align.hcenter", + "Align horizontal centers", + "{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)", + true, + |s, p| align(s, p, Al::HCenter) + ), + spec!( + "align.right", + "Align right", + "{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)", + true, + |s, p| align(s, p, Al::Right) + ), + spec!( + "align.top", + "Align top", + "{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)", + true, + |s, p| align(s, p, Al::Top) + ), + spec!( + "align.vcenter", + "Align vertical centers", + "{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)", + true, + |s, p| align(s, p, Al::VCenter) + ), + spec!( + "align.bottom", + "Align bottom", + "{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)", + true, + |s, p| align(s, p, Al::Bottom) + ), + spec!( + "distribute.horizontal", + "Distribute horizontal spacing", + "{ids?, spacing?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)", + true, + |s, p| distribute(s, p, true) + ), + spec!( + "distribute.vertical", + "Distribute vertical spacing", + "{ids?, spacing?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)", + true, + |s, p| distribute(s, p, false) + ), spec!( "arrange.spacing", "Spacing", @@ -192,6 +240,18 @@ fn align_target(doc: &Document, roots: &[NodeId]) -> Option { } fn align(s: &mut Session, p: &Value, a: Al) -> Result { + use crate::vectoredit::transform::PointAlign; + let how = match a { + Al::Left => PointAlign::Left, + Al::HCenter => PointAlign::HCenter, + Al::Right => PointAlign::Right, + Al::Top => PointAlign::Top, + Al::VCenter => PointAlign::VCenter, + Al::Bottom => PointAlign::Bottom, + }; + if let Some(r) = crate::vectoredit::transform::align_points_in_edit_mode(s, p, how) { + return r; + } let ids = req_targets("align", s, p)?; let doc = s.doc_mut()?; let ids = roots(doc, &ids); @@ -212,6 +272,9 @@ fn align(s: &mut Session, p: &Value, a: Al) -> Result { } fn distribute(s: &mut Session, p: &Value, horizontal: bool) -> Result { + if let Some(r) = crate::vectoredit::transform::distribute_points_in_edit_mode(s, p, horizontal) { + return r; + } let ids = req_targets("distribute", s, p)?; let doc = s.doc_mut()?; let ids = roots(doc, &ids); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 692b55ff0..80cc05bbc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -300,6 +300,8 @@ mod variables_window_resize_tests; #[cfg(test)] mod variants_discovery_tests; #[cfg(test)] +mod vector_align_tests; +#[cfg(test)] mod vector_keys_tests; #[cfg(test)] mod vector_panel_tests; diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 9446279fe..9243ab3a3 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -671,7 +671,7 @@ pub(crate) fn tidy_available(ctx: &egui::Context, doc: &Arc, sel: &[No fn position_fields(app: &mut FigApp, ui: &mut Ui, doc: &Arc, sel: &[NodeId]) { let pv = position_values(ui.ctx(), doc, sel); let col = widgets::col_width(ui.available_width()); - align_row(app, ui, sel, pv.can_align, pv.align_blocked, col); + align_row(app, ui, AlignTarget::Layers(sel), pv.can_align, pv.align_blocked, col); position_row(app, ui, doc, sel, &pv, col); rotation_row(app, ui, doc, sel, pv.rot, col); if pv.in_frame { @@ -679,9 +679,24 @@ fn position_fields(app: &mut FigApp, ui: &mut Ui, doc: &Arc, sel: &[No } } -/// Alignment, and distribution and tidy up for three or more layers. -fn align_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], can_align: bool, blocked: bool, col: f32) { - let ids = sel.to_vec(); +/// What the alignment row acts on. +#[derive(Clone, Copy)] +pub enum AlignTarget<'a> { + /// These layers (distribution and tidy up from three). + Layers(&'a [NodeId]), + /// The selected points in vector edit mode, this many of them (distribution from three, no + /// tidy up). + Points(usize), +} + +/// Alignment, and distribution and tidy up for three or more layers (or the selected points). +pub fn align_row(app: &mut FigApp, ui: &mut Ui, target: AlignTarget, can_align: bool, blocked: bool, col: f32) { + let (ids, count, points) = match target { + AlignTarget::Layers(sel) => (sel.to_vec(), sel.len(), false), + AlignTarget::Points(n) => (vec![], n, true), + }; + // Points take the commands with no ids: they act on the selected points. + let params = || if points { json!({}) } else { json!({"ids": ids}) }; widgets::sublabels(ui, tr("Alignment"), None); row(ui, 32.0, |ui| { let cmds = ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom"]; @@ -707,24 +722,26 @@ fn align_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], can_align: bool, blo }; picked.response.on_disabled_hover_text(why); if let Some(i) = picked.inner { - app.run(cmds[i], json!({"ids": ids})); + app.run(cmds[i], params()); } - if sel.len() > 2 { + if count > 2 { let more = icons::button(ui, Icon::DistributeH, 24.0, false, tr("Distribute and tidy")); menu_popup(&more).show(|ui| { - let can_tidy = app.session.ds().is_ok_and(|ds| tidy_available(ui.ctx(), &ds.doc, &ids)); - for (l, c, on) in [ + let can_tidy = !points && app.session.ds().is_ok_and(|ds| tidy_available(ui.ctx(), &ds.doc, &ids)); + let tidy = (tr("Tidy up"), "arrange.tidy", can_tidy); + let entries = [ (tr("Distribute horizontal spacing"), "distribute.horizontal", true), (tr("Distribute vertical spacing"), "distribute.vertical", true), - (tr("Tidy up"), "arrange.tidy", can_tidy), - ] { + ]; + // Points have no tidy up. + for (l, c, on) in entries.into_iter().chain((!points).then_some(tidy)) { let item = ui.add_enabled_ui(on, |ui| menu_item(ui, l, crate::shortcuts::shortcut(c).unwrap_or(""))); if !on { item.response .on_disabled_hover_text(tr("Select a row, a column or a full grid of three or more layers, outside an auto layout flow")); } if item.inner { - app.run(c, json!({"ids": ids})); + app.run(c, params()); ui.close(); } } diff --git a/crates/ui-egui/src/panels/vector_panel.rs b/crates/ui-egui/src/panels/vector_panel.rs index 3b91c9ffc..bde550ee1 100644 --- a/crates/ui-egui/src/panels/vector_panel.rs +++ b/crates/ui-egui/src/panels/vector_panel.rs @@ -99,12 +99,19 @@ pub fn points(app: &mut FigApp, ui: &mut Ui, doc: &Document, ve: &VectorEdit) { let Some(net) = vectoredit::network(doc, ve.id) else { return }; let pts = vectoredit::selected_points(net, ve); widgets::section_header(ui, if pts.len() > 1 { tr("Points") } else { tr("Point") }, &[], false); + let col = widgets::col_width(ui.available_width()); + // Figma puts alignment first; one point is a no-op there too. The count is the engine's, so + // selected segments' ends in any edited layer count as the commands do: the row shows even + // when only another edited layer has points selected. + let count = vectoredit::transform::edit_point_count(doc, ve); + if count > 0 { + crate::right::align_row(app, ui, crate::right::AlignTarget::Points(count), true, false, col); + } if pts.is_empty() { let t = crate::theme::Tokens::get(ui.ctx()); widgets::note(ui, tr("Select points to edit their position, radius and mirroring"), t.text_secondary); return; } - let col = widgets::col_width(ui.available_width()); let round = |v: f64| (v * 100.0).round() / 100.0; let parent_pts = vectoredit::selected_parent_points(doc, ve); // The value the selected points share (within 1e-6), or none: Mixed. diff --git a/crates/ui-egui/src/vector_align_tests.rs b/crates/ui-egui/src/vector_align_tests.rs new file mode 100644 index 000000000..e6ce444c1 --- /dev/null +++ b/crates/ui-egui/src/vector_align_tests.rs @@ -0,0 +1,99 @@ +//! Align and distribute the selected points in vector edit mode: the Design panel's alignment row +//! and the Alt+letter keys act on the points. + +use egui::accesskit::Node; +use egui::{Event, Key, Modifiers, Pos2}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; + +/// A four-point open path in edit mode, the first two points selected. +fn two_selected() -> (Ui, NodeId) { + let mut s = Session::new(); + let r = s.execute("vector.create", &json!({"points": [[330, 480], [480, 430], [560, 560], [380, 620]], "closed": false})).unwrap(); + let path = NodeId(r["id"].as_u64().unwrap()); + s.execute("vector.edit.begin", &json!({"id": path})).unwrap(); + s.execute("vector.edit.select", &json!({"vertices": [0, 1]})).unwrap(); + let mut u = Ui::new(s); + u.frame(vec![]); + (u, path) +} + +/// Page x of every point of `path`. +fn xs(u: &Ui, path: NodeId) -> Vec { + let doc = u.app.session.doc().unwrap(); + let w = doc.world_transform(path); + figcraft_engine::vectoredit::network(doc, path).unwrap().vertices.iter().map(|v| (w * v.point()).x).collect() +} + +fn tree(u: &mut Ui) -> Vec { + u.ctx.enable_accesskit(); + u.frame(vec![]); + let out = u.frame_output(vec![]); + out.platform_output.accesskit_update.expect("an AccessKit update").nodes.into_iter().map(|(_, n)| n).collect() +} + +fn button<'a>(nodes: &'a [Node], label: &str) -> Option<&'a Node> { + nodes.iter().find(|n| n.label().is_some_and(|l| l.starts_with(label))) +} + +#[test] +fn the_alignment_row_shows_for_points_and_align_left_moves_them() { + let (mut u, path) = two_selected(); + let nodes = tree(&mut u); + let left = button(&nodes, "Align left").expect("the alignment row shows in edit mode with points selected"); + assert!(!left.is_disabled(), "enabled whenever points are selected"); + assert!(button(&nodes, "Distribute and tidy").is_none(), "two points have nothing to distribute"); + let b = left.bounds().expect("bounds"); + let p = Pos2::new(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + u.button(p, true); + u.button(p, false); + u.frame(vec![]); + let x = xs(&u, path); + assert!((x[0] - 330.0).abs() < 1e-6 && (x[1] - 330.0).abs() < 1e-6, "{x:?}"); + assert!((x[2] - 560.0).abs() < 1e-6, "unselected points stay: {x:?}"); +} + +#[test] +fn the_distribute_menu_shows_from_three_points() { + let (mut u, _) = two_selected(); + u.app.session.execute("vector.edit.select", &json!({"vertices": [0, 1, 2]})).unwrap(); + let nodes = tree(&mut u); + assert!(button(&nodes, "Distribute and tidy").is_some()); +} + +/// Two layers edited at once, points selected only in the one that isn't active: the row still +/// shows, since the commands act on every edited layer's selected points. +#[test] +fn the_alignment_row_shows_when_only_another_edited_layer_has_points_selected() { + let mut s = Session::new(); + let mut make = + |pts: serde_json::Value| NodeId(s.execute("vector.create", &json!({"points": pts, "closed": false})).unwrap()["id"].as_u64().unwrap()); + let a = make(json!([[330, 480], [480, 430], [560, 560]])); + let b = make(json!([[700, 480], [800, 430], [900, 560]])); + s.execute("vector.edit.begin", &json!({"ids": [a, b]})).unwrap(); + s.execute("vector.edit.select", &json!({"id": a, "vertices": [0, 1, 2]})).unwrap(); + s.execute("vector.edit.select", &json!({"id": b, "vertices": [], "add": true})).unwrap(); + let mut u = Ui::new(s); + u.frame(vec![]); + let nodes = tree(&mut u); + assert!(button(&nodes, "Align left").is_some(), "the row shows for the other layer's points"); + assert!(button(&nodes, "Distribute and tidy").is_some(), "three points there: distribute too"); +} + +#[test] +fn alt_d_in_edit_mode_aligns_the_points_right() { + let (mut u, path) = two_selected(); + let m = Modifiers::ALT; + u.frame_with( + vec![ + Event::Key { key: Key::D, physical_key: Some(Key::D), pressed: true, repeat: false, modifiers: m }, + Event::Key { key: Key::D, physical_key: Some(Key::D), pressed: false, repeat: false, modifiers: m }, + ], + m, + ); + let x = xs(&u, path); + assert!((x[0] - 480.0).abs() < 1e-6 && (x[1] - 480.0).abs() < 1e-6, "{x:?}"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8fb0abec1..99106ec27 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -255,7 +255,7 @@ Hours in this narrative are the builders' estimates; the tables above supersede smooth interpolation per subpath, dashes, caps and joins, canvas/PNG/SVG/PDF and outline stroke), a transform box around several selected points (corners and edges scale them, Shift keeps proportions, Alt from the centre; just outside a corner rotates, Shift in 15° steps; drag inside - to move; the Design panel's X/Y/W/H and flip/rotate act on the points), point snapping while + to move; the Design panel's X/Y/W/H, align, distribute and flip/rotate act on the points), point snapping while dragging points or handles and with both pens (to the points and segment midpoints of this and other vectors, the usual layer targets and the pixel grid, with guides and a marker on the point landed on; Ctrl/Cmd turns it off), arc handles on the canvas (sweep, start and ratio with a @@ -652,6 +652,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | +| 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when no `ids` are given, as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | | 2026-11-15 | minor | M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured | | 2026-11-10 | minor | M4, #2222: a boolean group's corner radius rounds every sharp corner of its result (row 4). Numbers unchanged | | 2026-11-08 | minor | M8: measured in Figma on 2026-11-08, vector edit mode's Point section: X and Y show the value the selected points share, or Mixed when they differ, and a typed value sets every selected point's own coordinate in the layer being edited, points of other edited layers left as they are (it moved the group's top-left before); a relative edit (`+10`, `*2`, `/2`) typed into a Mixed field applies to each point's own value (`vector.edit.position` takes a number or `{add}`, `{mul}`, `{div}` per axis); the W and H row and other edited layers' points are unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3d976c68b..2ec810638 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-17 · **Change:** minor (going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -94,6 +94,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Rectangle, ellipse (arc handles and Design panel arc fields), polygon, star, line, arrow; Shift/Alt | done | Alt draws lines from the centre too (`shapes_behaviour_tests`) | | Corner radius handles (inside each corner of a rectangle or frame, a polygon's or star's top point; Alt: one corner), star ratio handle; Count and Ratio fields | done | handles hide under 48 px on screen; a Count handle sits on a polygon's first vertex or a star's first outer point clockwise from the top, and the count follows the pointer's angle about the centre, `round(360 / angle)` clockwise from the top point, clamped to 3 to 60, in one undo step (measured in Figma's web app, 2026-11-12; a polygon's maximum wasn't read and is clamped at 60 like the star's, the help center's range); corner smoothing rounds rectangles and frames only | | Pen: vector networks, branch, close, bend; pencil | done | pen pressure on Windows and from browser styluses only; outside edit mode the Pen closes on its first point, connects to its other points and continues a selected open path from an end point (`vector_multi_behaviour_tests`); Escape ends the path and keeps its layer in edit mode with the pen, so the next path joins the same vector and another Escape leaves edit mode (#760, `pen_end_tests`); Enter or a double-click ends the path (at the double-click's point, added once) and edits the vector with the Move tool, a double-click with the idle pen edits the layer under it, and in edit mode the pen's Enter or double-click takes the Move tool (#1430, `pen_vector_edit_tests`); switching from Design to Prototype or Inspect ends the path and returns to Move (#308) | +| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring, align and distribute points | done | a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn; Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | | Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn, an arc reaching along the whole of a segment whose other end is sharp and half of one whose other end is rounded too, so one rounded corner of a 100 × 100 square with radius 100 runs from one neighbour to the other, while the radius field keeps what was typed (#2334, `vector_radius_tests`, `vector_point_radius_tests`); Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | | Shape builder (Shift+M) on fills, strokes and open paths; variable width (Shift+W), one side with Alt | done | | | Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003); a boolean group takes a corner radius from the Design panel and from `node.set cornerRadius`: every sharp corner of its result rounds, convex and concave, layers inside keep their own radius and do not stack with it, a radius larger than the edges allow shrinks to fit while the field keeps the value typed, Flatten bakes the arcs and a mixed selection reads Mixed; measured in Figma's web app on 2026-11-10 (#2222; `crates/pathops/src/round_tests.rs`, `crates/render/src/boolean_radius_tests.rs`, `crates/engine/src/boolean_radius_tests.rs`, the boolean group test in `crates/ui-egui/src/field_tests.rs`). Pinned and not yet compared with Figma: corner smoothing on a boolean group draws the polygon profile between straight edges, a corner beside a curve stays within the curve piece next to it, and there is no radius handle on the canvas | @@ -207,6 +208,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when neither `ids` nor `id` is given (either one targets layers), as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | | 2026-11-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | | 2026-11-17 | patch | M8: each page keeps its view in a session: going back to a page (the Pages list, `page.select`, Previous/Next page) shows it where it was left instead of fitting it again; a new page is still fitted, and going to the page shown moves nothing (`page_view_tests`) | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): UI3 layout, Light and dark themes, Rotate just outside a corner, Selection colors, Keyboard box selection, Boolean groups, Text: point, auto height, fixed, Text: wrap style, Bound as documented, Pan/zoom. | From d6bfe68936f176213737b780143f5cea52569925 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 16:51:10 -0500 Subject: [PATCH 091/129] M1: Paste with a layer in a frame selected puts the copy next to it (#2355) Cmd/Ctrl+V with one layer inside a frame selected pasted onto the page on top of the frame. It now pastes into the layer's parent just above it, in an auto layout frame the item after it. Page-level layers, several layers, instance children, board atoms, component sets and copied components keep today's behaviour. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/edit/clipboard.rs | 44 ++++++-- crates/engine/src/lib.rs | 2 + crates/engine/src/paste_sibling_tests.rs | 122 +++++++++++++++++++++++ docs/ui-parity.md | 5 +- 4 files changed, 164 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/paste_sibling_tests.rs diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index dbf4ec180..09c79190b 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -295,6 +295,9 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result { }) .filter(|i| !copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, *i))) }); + // One layer selected that isn't a frame target: the copy joins its parent, just above it (#2355). + let sibling_of = if target.is_none() && id(p, "parent").is_none() { sibling_anchor(s, &sel, copy_local) } else { None }; + let target = target.or_else(|| sibling_of.and_then(|i| doc.node(i).and_then(|n| n.parent))); let parent = target.unwrap_or(page); let at = match (num(p, "x"), num(p, "y")) { (Some(x), Some(y)) => Some((x, y)), @@ -321,10 +324,42 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result { } }; let ids = paste_into(s, parent, at)?; + if let Some(sel) = sibling_of { + let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1); + move_above(s, &ids, parent, above)?; + } s.set_selection(ids.clone()); Ok(json!({"ids": ids})) } +/// The one selected layer a plain paste goes next to: not a page-level layer, not inside an instance +/// (its children are fixed), not a board atom, a component set (a variant's parent) or inside a copied +/// component. Else the page, as before. +fn sibling_anchor(s: &Session, sel: &[NodeId], copy_local: bool) -> Option { + let [only] = sel else { return None }; + let doc = s.doc().ok()?; + let parent = doc.node(*only)?.parent?; + let pn = doc.node(parent)?; + let ok = !pn.is_page() + && pn.kind.is_frame_like() + && !pn.is_board_atom() + && !crate::components::inside_instance(doc, *only) + && !matches!(pn.kind, NodeKind::Instance { .. } | NodeKind::ComponentSet { .. }) + && (!copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, parent))); + ok.then_some(*only) +} + +/// Move the pasted copies that landed in `parent` to `above` and after, in the copied order. +fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option) -> Result<()> { + let Some(above) = above else { return Ok(()) }; + 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)?; + } + Ok(()) +} + pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { let sel = s.selection(); let page = s.page()?; @@ -337,14 +372,7 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { 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)?; - } - } + move_above(s, &ids, parent, above)?; s.set_selection(ids.clone()); Ok(json!({"ids": ids})) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3c81b9147..91de56d61 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -474,6 +474,8 @@ mod panels_behaviour_tests; #[cfg(test)] mod paste_missing_image_tests; #[cfg(test)] +mod paste_sibling_tests; +#[cfg(test)] mod path_read_caps_tests; #[cfg(test)] mod pdf_print_tests; diff --git a/crates/engine/src/paste_sibling_tests.rs b/crates/engine/src/paste_sibling_tests.rs new file mode 100644 index 000000000..70174fff6 --- /dev/null +++ b/crates/engine/src/paste_sibling_tests.rs @@ -0,0 +1,122 @@ +//! Cmd/Ctrl+V with one layer inside a frame selected pastes next to it, in its parent (#2355). + +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; +use figcraft_doc::NodeId; + +fn id(v: &Value) -> NodeId { + id_of(&v["id"]).unwrap() +} + +fn sess() -> Session { + Session::new() +} + +fn rect(s: &mut Session, parent: Option, x: f64, y: f64) -> NodeId { + let mut p = json!({"x": x, "y": y, "width": 40, "height": 20}); + if let Some(parent) = parent { + p["parent"] = json!(parent); + } + id(&s.execute("shape.rectangle", &p).unwrap()) +} + +fn kids(s: &Session, parent: NodeId) -> Vec { + s.doc().unwrap().node(parent).unwrap().children.clone() +} + +fn parent_of(s: &Session, n: NodeId) -> Option { + s.doc().unwrap().node(n).unwrap().parent +} + +fn paste(s: &mut Session) -> Vec { + s.execute("edit.paste", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(id_of).collect() +} + +#[test] +fn paste_with_a_layer_in_an_auto_layout_frame_selected_goes_right_after_it() { + let mut s = sess(); + let a = rect(&mut s, None, 0.0, 0.0); + let b = rect(&mut s, None, 0.0, 30.0); + let r = s.execute("layout.add", &json!({"ids": [a, b], "direction": "vertical"})).unwrap(); + let frame = id_of(&r["ids"][0]).unwrap(); + s.execute("node.set", &json!({"id": frame, "props": {"gap": 10}})).unwrap(); + let h0 = s.doc().unwrap().node(frame).unwrap().height; + assert_eq!(h0, 50.0); + assert_eq!(kids(&s, frame), vec![a, b]); + s.set_selection(vec![b]); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = paste(&mut s); + assert_eq!(pasted.len(), 1); + assert_eq!(parent_of(&s, pasted[0]), Some(frame), "the copy joins the selected layer's frame"); + assert_eq!(kids(&s, frame), vec![a, b, pasted[0]], "right after the selected layer in the flow"); + assert_eq!(s.doc().unwrap().node(frame).unwrap().height, h0 + 20.0 + 10.0, "the frame grew by the copy's height plus the gap"); + assert_eq!(s.selection(), pasted); +} + +#[test] +fn paste_with_a_layer_in_a_plain_frame_selected_stays_in_the_frame_in_place() { + let mut s = sess(); + let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()); + let a = rect(&mut s, Some(frame), 10.0, 10.0); + let b = rect(&mut s, Some(frame), 100.0, 100.0); + s.set_selection(vec![a]); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = paste(&mut s); + assert_eq!(pasted.len(), 1); + assert_eq!(parent_of(&s, pasted[0]), Some(frame)); + assert_eq!(kids(&s, frame), vec![a, pasted[0], b], "just above the selected layer"); + let wb = s.doc().unwrap().world_bounds(pasted[0]).unwrap(); + assert_eq!((wb.x0, wb.y0), (10.0, 10.0), "at the selected layer's position"); + assert_eq!(s.selection(), pasted); +} + +#[test] +fn paste_with_a_top_level_layer_selected_is_unchanged() { + let mut s = sess(); + let a = rect(&mut s, None, 10.0, 10.0); + let page = parent_of(&s, a).unwrap(); + let before = kids(&s, page); + s.set_selection(vec![a]); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = paste(&mut s); + assert_eq!(parent_of(&s, pasted[0]), Some(page)); + let mut want = before; + want.push(pasted[0]); + assert_eq!(kids(&s, page), want, "on the page, on top, as before"); +} + +#[test] +fn paste_with_two_layers_selected_is_unchanged() { + let mut s = sess(); + let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()); + let a = rect(&mut s, Some(frame), 10.0, 10.0); + let b = rect(&mut s, Some(frame), 100.0, 100.0); + let page = parent_of(&s, frame).unwrap(); + s.set_selection(vec![a, b]); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = paste(&mut s); + assert_eq!(pasted.len(), 2); + assert!(pasted.iter().all(|p| parent_of(&s, *p) == Some(page)), "on the page, as before"); + assert_eq!(kids(&s, frame), vec![a, b]); +} + +#[test] +fn paste_with_a_layer_inside_an_instance_selected_is_unchanged() { + let mut s = sess(); + let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 50, "name": "Button"})).unwrap()); + s.execute("text.create", &json!({"text": "OK", "x": 10, "y": 10, "parent": f})).unwrap(); + let c = id(&s.execute("component.create", &json!({"ids": [f]})).unwrap()); + let inst = id(&s.execute("instance.create", &json!({"component": c, "x": 200, "y": 0})).unwrap()); + let page = parent_of(&s, inst).unwrap(); + let inner = kids(&s, inst)[0]; + let inner_kids = kids(&s, inst); + let other = rect(&mut s, None, 500.0, 500.0); + s.set_selection(vec![other]); + s.execute("edit.copy", &json!({})).unwrap(); + s.set_selection(vec![inner]); + let pasted = paste(&mut s); + assert_eq!(parent_of(&s, pasted[0]), Some(page), "an instance's children are fixed: the copy goes to the page"); + assert_eq!(kids(&s, inst), inner_kids); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2ec810638..fcd4212c6 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -159,7 +159,9 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look presenting. The paint bucket's tooltip shows Shift+B (B still works). - **Fixed (2026-10-17):** Shift+Cmd/Ctrl+V (Paste over selection) and Alt+Cmd/Ctrl+V (Paste properties) work on the desktop (they were bound but didn't act there, #716); Cmd/Ctrl+V pastes an - image copied in another app (#663). Counts above unchanged (the suite checks bindings). + image copied in another app (#663). With one layer inside a frame selected, Cmd/Ctrl+V pastes + into its parent just above it (in an auto layout frame, the item after it), #2355. Counts above + unchanged (the suite checks bindings). - **Where the documentation disagrees with itself** (noted per row): pixel grid (Shift+' or Cmd+'), letter spacing (Alt or Cmd with < >; Cmd would be the font size keys, Alt bound), Windows remove fill (Alt+/ or Alt+,; Alt+, is letter spacing), the Layers panel on Windows (Alt+1 @@ -208,6 +210,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when neither `ids` nor `id` is given (either one targets layers), as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | | 2026-11-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | | 2026-11-17 | patch | M8: each page keeps its view in a session: going back to a page (the Pages list, `page.select`, Previous/Next page) shows it where it was left instead of fitting it again; a new page is still fitted, and going to the page shown moves nothing (`page_view_tests`) | From 3ae4971b5fea17627d82dc6cb6112d2063781dfe Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 16:51:49 -0500 Subject: [PATCH 092/129] docs: the #2355 paste note gets its own dated bullet Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index fcd4212c6..dac2960bd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -159,9 +159,9 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look presenting. The paint bucket's tooltip shows Shift+B (B still works). - **Fixed (2026-10-17):** Shift+Cmd/Ctrl+V (Paste over selection) and Alt+Cmd/Ctrl+V (Paste properties) work on the desktop (they were bound but didn't act there, #716); Cmd/Ctrl+V pastes an - image copied in another app (#663). With one layer inside a frame selected, Cmd/Ctrl+V pastes - into its parent just above it (in an auto layout frame, the item after it), #2355. Counts above - unchanged (the suite checks bindings). + image copied in another app (#663). Counts above unchanged (the suite checks bindings). +- **Fixed (2026-11-13):** with one layer inside a frame selected, Cmd/Ctrl+V pastes into its parent + just above it (in an auto layout frame, the item after it), #2355. - **Where the documentation disagrees with itself** (noted per row): pixel grid (Shift+' or Cmd+'), letter spacing (Alt or Cmd with < >; Cmd would be the font size keys, Alt bound), Windows remove fill (Alt+/ or Alt+,; Alt+, is letter spacing), the Layers panel on Windows (Alt+1 From d21aebab4b586b3e0584a0392b5241cad5511028 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 14:16:20 +0700 Subject: [PATCH 093/129] M3: combining components gives every variant the properties any of them had A property added to a set goes to all its variants (component.addProperty), but Combine as variants kept each component's own definitions, so a property made on one component before combining was missing from the others: their layers couldn't be bound to it ("the component has no property") and an instance switched to one of them dropped its value. make_variant_set now gives every variant the properties any of them has (share_props, through the give_prop step addProperty uses too); a variant with a property of that name keeps its own. Tests: variant_shared_props_tests. --- crates/engine/src/cmd/component/props.rs | 58 ++++++++++++++----- crates/engine/src/cmd/component/variants.rs | 4 +- crates/engine/src/lib.rs | 2 + .../engine/src/variant_shared_props_tests.rs | 58 +++++++++++++++++++ docs/components-parity.md | 5 +- 5 files changed, 110 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/variant_shared_props_tests.rs diff --git a/crates/engine/src/cmd/component/props.rs b/crates/engine/src/cmd/component/props.rs index 97bef3ce2..8ef066d37 100644 --- a/crates/engine/src/cmd/component/props.rs +++ b/crates/engine/src/cmd/component/props.rs @@ -218,6 +218,49 @@ fn set_prop_defs(doc: &mut Document, c: NodeId, rename: Option<(&str, &str)>, f: Ok(()) } +/// Give each of components `comps` that lacks it property `name` (`def`), and their existing +/// instances its default. +fn give_prop(doc: &mut Document, comps: &[NodeId], name: &str, def: &PropDef) -> Result<()> { + for c in comps { + if prop_defs(doc, *c).contains_key(name) { + continue; + } + set_prop_defs(doc, *c, None, |m| { + m.insert(name.to_string(), def.clone()); + })?; + if !takes_value(def) { + continue; + } + for inst in instances_of(doc, *c) { + if let NodeKind::Instance { props, .. } = &mut doc.get_mut(inst)?.kind { + props.entry(name.to_string()).or_insert_with(|| prop_default_value(def)); + } + } + } + Ok(()) +} + +/// Give every one of components `comps` (the variants of a set) the properties any of them has: +/// a set's properties belong to all its variants, as `component.addProperty` gives them, so one +/// made on a component before it was combined stays on an instance switched to another variant. +/// A variant that has a property of that name keeps its own. +pub(super) fn share_props(doc: &mut Document, comps: &[NodeId]) -> Result<()> { + let mut all: Vec<(String, PropDef)> = Vec::new(); + for c in comps { + if let Some(NodeKind::Component { props, prop_order, .. }) = doc.node(*c).map(|n| &n.kind) { + for (k, d) in ordered_props(props, prop_order) { + if !all.iter().any(|(n, _)| n == k) { + all.push((k.clone(), d.clone())); + } + } + } + } + for (name, def) in &all { + give_prop(doc, comps, name, def)?; + } + Ok(()) +} + fn valid_prop_name(cmd: &str, name: &str) -> Result { let name = name.trim(); if name.is_empty() || name.contains([',', '=']) || name.chars().count() > 200 { @@ -295,20 +338,7 @@ pub(super) fn add_prop_for(cmd: &str, s: &mut Session, p: &Value) -> Result return Err(bad(cmd, "type: boolean|text|instanceSwap|variant|slot")), }; - for c in &comps { - set_prop_defs(doc, *c, None, |m| { - m.insert(name.clone(), def.clone()); - })?; - // Existing instances get the default. - if !takes_value(&def) { - continue; - } - for inst in instances_of(doc, *c) { - if let NodeKind::Instance { props, .. } = &mut doc.get_mut(inst)?.kind { - props.entry(name.clone()).or_insert_with(|| prop_default_value(&def)); - } - } - } + give_prop(doc, &comps, &name, &def)?; if let Some(l) = layer { bind(cmd, doc, l, Some(&name), None)?; } diff --git a/crates/engine/src/cmd/component/variants.rs b/crates/engine/src/cmd/component/variants.rs index 96de6ba3a..be43bced0 100644 --- a/crates/engine/src/cmd/component/variants.rs +++ b/crates/engine/src/cmd/component/variants.rs @@ -68,7 +68,8 @@ pub fn can_add_variant(doc: &Document, id: NodeId) -> bool { } /// Wrap `ids` (z-sorted main components) in a new component set, naming them "Property 1=Default", -/// "Property 1=VariantN" unless already in prop=value form. Returns the set. +/// "Property 1=VariantN" unless already in prop=value form, each with the component properties +/// any of them has. Returns the set. fn make_variant_set(cmd: &str, doc: &mut Document, ids: &[NodeId]) -> Result { let set = wrap_in_set(cmd, doc, ids)?; for (k, i) in ids.iter().enumerate() { @@ -77,6 +78,7 @@ fn make_variant_set(cmd: &str, doc: &mut Document, ids: &[NodeId]) -> Result (NodeId, NodeId) { + let f = idv(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 120, "height": 40, "name": name}))); + let t = idv(&ex(s, "text.create", json!({"text": "Button", "x": 8, "y": 8, "parent": f}))); + (idv(&ex(s, "component.create", json!({"ids": [f]}))), t) +} + +/// `id`'s component property `name` as `component.properties` lists it. +fn property(s: &mut Session, id: NodeId, name: &str) -> Option { + let all = ex(s, "component.properties", json!({"id": id})); + all["properties"].as_array().and_then(|l| l.iter().find(|p| p["name"] == name).cloned()) +} + +#[test] +fn a_property_made_before_combining_goes_to_every_variant() { + let mut s = Session::new(); + let (a, label) = component(&mut s, "State=Default", 0.0); + let (b, b_label) = component(&mut s, "State=Hover", 200.0); + ex(&mut s, "component.addProperty", json!({"id": a, "name": "Text", "type": "text", "layer": label})); + let of_b = idv(&ex(&mut s, "instance.create", json!({"component": b, "x": 0, "y": 300}))); + ex(&mut s, "component.combineVariants", json!({"ids": [a, b]})); + healthy(&s); + let shared = property(&mut s, b, "Text").expect("the other variant has the property"); + assert_eq!((shared["type"].clone(), shared["default"].clone()), (json!("text"), json!("Button"))); + // The other variant's text can be bound to it, and its instance then shows the default. + ex(&mut s, "component.bindProperty", json!({"layer": b_label, "property": "Text"})); + assert_eq!(property(&mut s, of_b, "Text").map(|p| p["value"].clone()), Some(json!("Button"))); + // An instance switched to the other variant keeps the value it was given. + let of_a = idv(&ex(&mut s, "instance.create", json!({"component": a, "x": 200, "y": 300}))); + ex(&mut s, "instance.setProperties", json!({"ids": [of_a], "properties": {"Text": "Buy"}})); + ex(&mut s, "instance.setProperties", json!({"ids": [of_a], "properties": {"State": "Hover"}})); + assert_eq!(property(&mut s, of_a, "Text").map(|p| p["value"].clone()), Some(json!("Buy"))); + healthy(&s); +} + +#[test] +fn a_variant_keeps_its_own_property_of_the_same_name() { + let mut s = Session::new(); + let (a, _) = component(&mut s, "State=Default", 0.0); + let (b, _) = component(&mut s, "State=Hover", 200.0); + ex(&mut s, "component.addProperty", json!({"id": a, "name": "Icon", "type": "text", "default": "Star"})); + ex(&mut s, "component.addProperty", json!({"id": b, "name": "Icon", "type": "boolean", "default": false})); + ex(&mut s, "component.combineVariants", json!({"ids": [a, b]})); + healthy(&s); + assert_eq!(property(&mut s, a, "Icon").map(|p| p["type"].clone()), Some(json!("text"))); + assert_eq!(property(&mut s, b, "Icon").map(|p| p["type"].clone()), Some(json!("boolean"))); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 3776a4f96..73d1d8ced 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** minor (renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -17,7 +17,7 @@ accounts). | Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances | | What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it; an instance's own resizing (hug or fixed) follows its main's unless its size is overridden, measured: a plain instance turns Fixed when its main does (a child set to Fill along the hugging axis) and back to Hug with it, one whose width was typed keeps it, and Fill in its own auto layout parent is its own | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | | What it doesn't: position, rotation, constraints and absolute or grid placement of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out (Delete on a layer inside an instance hides it instead of removing it, as the help center says it does); the instance itself resizes and its layers follow the main's constraints | -| Component sets / variants, add variant, switch | done | Combine as variants is in the Object menu, and the canvas and layers context menu and the Design panel offer it when two or more main components are selected; Add variant on a main component not in a set yet makes it a set of itself and the new variant, one undo step (#903); components that are variants already aren't combined again (it used to put a set inside a set) | +| Component sets / variants, add variant, switch | done | Combine as variants is in the Object menu, and the canvas and layers context menu and the Design panel offer it when two or more main components are selected; Add variant on a main component not in a set yet makes it a set of itself and the new variant, one undo step (#903); components that are variants already aren't combined again (it used to put a set inside a set); combining gives every variant the component properties any of them had, so another variant's layers can be bound to one made before combining | | A main's copy within its file is an instance of it: Duplicate, Alt-drag, Copy then Paste | done | a variant duplicated in its set stays a new variant and a whole set copies as a new set; only the copied roots become instances (a main inside a copied frame is copied as a main); Cut then Paste and pastes into other files keep the component (#892) | | A component can't contain its own instance, directly or through other components | done | refused with the loop named (creating, placing, swapping, switching variants, moving, pasting, an instance-swap value); each variant counts as its own component, so a variant may hold a sibling variant's instance unless that one leads back to it; a dropped instance lands on the page; a file holding a loop opens with one instance detached and a note, any other file unchanged; a loop merged in a live session stops expanding where an instance would show itself again (#1084) | | Switching variants keeps overrides where names match and both variants had the same value; text layers keep theirs | done | | @@ -80,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | patch | M3: Combine as variants gives every variant the component properties any of the components had (as a property added to a set goes to all its variants); a property made on one component before combining was missing from the others, so their layers couldn't be bound to it and an instance switched to them dropped its value. A variant with a property of the same name keeps its own. Tests: `variant_shared_props_tests`. | | 2026-11-18 | patch | M3, #2368: a text field that isn't being edited ends a value too long for it with an ellipsis and shows the whole value on hover (a secret field shows none), so the variant value "Down left" no longer reads "Down lef"; screen readers and editing keep the whole value (`field_ellipsis_tests`). Grade unchanged. | | 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. | | 2026-11-07 | patch | M3, #2090: an instance's own resizing follows its main's unless its size is overridden. Measured in Figma: a plain instance turns Fixed when its main's width does (a child set to Fill along it) and back to Hug with it; an instance whose width was typed keeps it; Fill in its own auto layout parent is kept. Tests: `components_behaviour_tests::a_plain_instances_resizing_follows_the_mains_root_both_ways` and the instance resizing tests beside it. | From e4bc5678552bd6ba9a0ac86d38ede2c2b912c9d1 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 31 Oct 2026 08:15:52 +0700 Subject: [PATCH 094/129] M3: library analytics count insertions and detachments of styles and variables Applying a style or variable, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and library.usage give them over the chosen period. --- ROADMAP.md | 3 +- apps/figcraft-server/src/disk.rs | 1 + .../src/library_assets_tests.rs | 39 +++++- apps/figcraft-server/src/store.rs | 12 +- apps/figcraft-server/src/store/backend.rs | 2 + apps/figcraft-server/src/store/library.rs | 95 ++++++++++----- crates/collab-net/src/link.rs | 5 +- crates/collab/src/message.rs | 20 ++- crates/doc/src/library.rs | 31 +++++ crates/engine/src/assets/library.rs | 57 ++++++++- crates/engine/src/assets/library_server.rs | 12 +- crates/engine/src/cmd/library.rs | 44 ++++++- crates/engine/src/cmd/styles.rs | 12 ++ crates/engine/src/lib.rs | 2 + .../engine/src/library_asset_counts_tests.rs | 115 ++++++++++++++++++ crates/engine/src/sharing/background/tests.rs | 5 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/assets_panel.rs | 39 ++++-- crates/ui-egui/src/usage_summary_tests.rs | 30 +++++ docs/collab-protocol.md | 8 +- docs/components-parity.md | 5 +- docs/gaps.md | 12 +- docs/mcp.md | 2 +- docs/roadmap.md | 3 +- docs/server.md | 5 +- 25 files changed, 484 insertions(+), 77 deletions(-) create mode 100644 crates/engine/src/library_asset_counts_tests.rs create mode 100644 crates/ui-egui/src/usage_summary_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index ad2ae9f69..107a11f96 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. | diff --git a/apps/figcraft-server/src/disk.rs b/apps/figcraft-server/src/disk.rs index 219bce324..19cbfc8d3 100644 --- a/apps/figcraft-server/src/disk.rs +++ b/apps/figcraft-server/src/disk.rs @@ -28,6 +28,7 @@ pub const LINKS: &str = "links.json"; pub const LIBRARY: &str = "library.bin"; pub const USAGE: &str = "usage.json"; pub const ACTIONS: &str = "actions.json"; +pub const ASSET_ACTIONS: &str = "asset-actions.json"; const SNAP_MAGIC: &[u8; 4] = b"FCSN"; const LOG_MAGIC: &[u8; 4] = b"FCLG"; diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index 4c9b8aaef..4da1aba8d 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -79,7 +79,7 @@ fn styles_and_variables_are_counted_per_layer_and_file() { // Bo takes the style off one layer and the variable off its only one. ex(&mut b, "style.detach", json!({"ids": [two], "which": "fill"})); ex(&mut b, "variable.bind", json!({"ids": [three], "field": "fill"})); - let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"].as_array().is_some_and(Vec::is_empty)); + let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"][0]["layers"] == 0); assert_eq!(u["styles"].as_array().unwrap().len(), 1, "{u}"); server.stop(); } @@ -143,3 +143,40 @@ fn answer(raw: &mut Raw) -> LibraryReply { other => panic!("not a library answer: {other:?}"), } } + +#[test] +fn inserts_and_detaches_count_per_style_and_variable_in_the_period() { + let dir = TempDir::new("library-asset-actions"); + let cfg = config(dir.path()); + let mut server = crate::start(&cfg).unwrap(); + let addr = server.addr(); + let mut a = session("Ada"); + let r = rect(&mut a, 0); + ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0})); + let collection = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"})); + ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": collection["id"], "value": "#0D99FF"})); + let p = publish(&mut a, dir.path(), addr); + ex(&mut a, "library.publishToServer", json!({})); + + let mut b = session("Bo"); + let lid = ex(&mut b, "library.add", json!({"path": p.view}))["id"].as_str().unwrap().to_string(); + let (one, two) = (rect(&mut b, 0), rect(&mut b, 100)); + ex(&mut b, "library.applyStyle", json!({"library": lid, "style": "Brand", "ids": [one.0, two.0]})); + ex(&mut b, "style.detach", json!({"ids": [two.0], "which": "fill"})); + ex(&mut b, "library.bindVariable", json!({"library": lid, "variable": "Accent", "ids": [two.0], "field": "fill"})); + + let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["insertions"] == 2 && u["variables"][0]["insertions"] == 1); + assert_eq!(u["assetActionsKnown"], true, "{u}"); + assert_eq!(u["styles"][0]["detachments"], 1, "{u}"); + assert_eq!(u["variables"][0]["detachments"], 0, "{u}"); + assert_eq!(u["insertions"], 0, "components count on their own: {u}"); + + // An undo and a redo count once, and a style no layer uses any more stays listed. + ex(&mut b, "edit.undo", json!({})); + ex(&mut b, "edit.redo", json!({})); + ex(&mut b, "style.detach", json!({"ids": [one.0], "which": "fill"})); + let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2); + assert_eq!((u["styles"][0]["insertions"].clone(), u["styles"][0]["layers"].clone()), (json!(2), json!(0)), "{u}"); + assert_eq!(u["variables"][0]["insertions"], 1, "{u}"); + server.stop(); +} diff --git a/apps/figcraft-server/src/store.rs b/apps/figcraft-server/src/store.rs index 2e713deb2..fbf4bc2db 100644 --- a/apps/figcraft-server/src/store.rs +++ b/apps/figcraft-server/src/store.rs @@ -40,8 +40,8 @@ use std::path::{Path, PathBuf}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use figcraft_collab::message::{ - Access, Admin, AdminReply, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, LibraryReq, - LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions, + Access, Admin, AdminReply, AssetActions, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, + LibraryReq, LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions, }; use figcraft_collab::{Change, NodeId, Replica, Server, same_secret}; use figcraft_collab_net::hub::{Admission, Backend, Closing, Handled, OpenFile, ip_blocks, ip_key}; @@ -52,7 +52,7 @@ use sha2::{Digest, Sha256}; use crate::abuse::{Abuse, AbuseConfig, Action}; use crate::codes::{self, Sealed}; use crate::directory::{Directory, DirectoryConfig}; -use crate::disk::{self, ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE}; +use crate::disk::{self, ACTIONS, ASSET_ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE}; mod backend; mod files; @@ -298,6 +298,8 @@ struct UsageCache { list: Vec, /// Insertions and detachments week by week, over every file (kept in `actions.json`). weeks: Vec, + /// The same for styles and variables (kept in `asset-actions.json`). + asset_weeks: Vec>, dirty: bool, written: u64, } @@ -321,6 +323,8 @@ struct UsageEntry { styles: Vec<(String, u32)>, #[serde(default, skip_serializing_if = "Vec::is_empty")] variables: Vec<(String, u32)>, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + asset_peaks: Vec<(String, u32, u32)>, } fn is_zero(n: &u64) -> bool { @@ -560,7 +564,7 @@ impl Store { /// A file folder's description and links, after checking its snapshot and log. Leftover /// temporary files (writes cut short) are removed. fn check(&self, path: &Path) -> Result { - for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS] { + for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS, ASSET_ACTIONS] { let tmp = disk::temp_of(&path.join(name)); if tmp.exists() { let _ = fs::remove_file(&tmp); diff --git a/apps/figcraft-server/src/store/backend.rs b/apps/figcraft-server/src/store/backend.rs index 5d4a3bfe9..42900e6b8 100644 --- a/apps/figcraft-server/src/store/backend.rs +++ b/apps/figcraft-server/src/store/backend.rs @@ -278,6 +278,8 @@ impl Backend for Store { LibraryReq::Actions => self.library_actions(file).map_or_else(failed, LibraryReply::Actions), LibraryReq::ReportAssets(a) => self.report_assets(file, a).map_or_else(failed, |()| LibraryReply::Noted), LibraryReq::Assets => self.library_assets(file).map_or_else(failed, LibraryReply::Assets), + LibraryReq::ReportAssetActions(a) => self.report_asset_actions(file, a).map_or_else(failed, |()| LibraryReply::Noted), + LibraryReq::AssetActions => self.library_asset_actions(file).map_or_else(failed, LibraryReply::AssetActions), } } diff --git a/apps/figcraft-server/src/store/library.rs b/apps/figcraft-server/src/store/library.rs index 322c906e8..10337a451 100644 --- a/apps/figcraft-server/src/store/library.rs +++ b/apps/figcraft-server/src/store/library.rs @@ -1,9 +1,9 @@ use figcraft_collab::message::MAX_ASSET_USAGE; use super::{ - ACTIONS, Action, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY, LibraryMeta, LibraryReply, - MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY, NodeId, Path, PathBuf, - Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json, + ACTIONS, ASSET_ACTIONS, Action, AssetActions, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY, + LibraryMeta, LibraryReply, MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY, + NodeId, Path, PathBuf, Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json, }; /// Which of a file's totals a report brings. @@ -46,49 +46,55 @@ fn read_kept(path: &Path) -> Vec { disk::read_capped(path, MAX_USAGE_FILE).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() } +/// Raise the highest `kind` totals in `peaks` to `counts`, each from what `last` says was reported +/// before them; what grew past them, by how much. +fn grow(peaks: &mut Vec<(K, u32, u32)>, counts: &[(K, u32)], kind: Count, last: impl Fn(&K) -> u32) -> Vec<(K, u32)> { + let mut grown = Vec::new(); + for (c, n) in counts { + let at = match peaks.iter().position(|p| p.0 == *c) { + Some(at) => at, + None if peaks.len() < MAX_REPORTED => { + peaks.push((c.clone(), 0, 0)); + peaks.len() - 1 + } + None => continue, + }; + let Some(p) = peaks.get_mut(at) else { continue }; + let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 }; + let base = (*peak).max(last(c)); + if *n > base { + grown.push((c.clone(), *n - base)); + } + *peak = base.max(*n); + } + grown +} + impl UsageEntry { /// Raise this file's highest `kind` totals to `counts`; what grew past them, by how much. /// A detach total reported before peaks were kept starts from that report. fn grow_peaks(&mut self, counts: &[(NodeId, u32)], kind: Count) -> Vec<(NodeId, u32)> { - let mut grown = Vec::new(); - for &(c, n) in counts { - let last = if kind == Count::Detached { self.detached.iter().find(|d| d.0 == c).map_or(0, |d| d.1) } else { 0 }; - let at = match self.peaks.iter().position(|p| p.0 == c) { - Some(at) => at, - None if self.peaks.len() < MAX_REPORTED => { - self.peaks.push((c, 0, 0)); - self.peaks.len() - 1 - } - None => continue, - }; - let Some(p) = self.peaks.get_mut(at) else { continue }; - let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 }; - let base = (*peak).max(last); - if n > base { - grown.push((c, n - base)); - } - *peak = base.max(n); - } - grown + let detached = &self.detached; + grow(&mut self.peaks, counts, kind, |c| if kind == Count::Detached { detached.iter().find(|d| d.0 == *c).map_or(0, |d| d.1) } else { 0 }) } } /// Add `grown` to this week's `kind` counts in `weeks`, dropping weeks older than [`MAX_WEEKS`] /// and, past [`MAX_WEEK_ROWS`], the oldest rows. -fn add_to_week(weeks: &mut Vec, grown: &[(NodeId, u32)], kind: Count, t: u64) { +fn add_to_week(weeks: &mut Vec>, grown: &[(K, u32)], kind: Count, t: u64) { let week = week_of(t); weeks.retain(|w| w.week.saturating_add(MAX_WEEKS * WEEK) > week); - for &(component, n) in grown { - let at = match weeks.iter().position(|w| w.week == week && w.component == component) { + for (component, n) in grown { + let at = match weeks.iter().position(|w| w.week == week && w.component == *component) { Some(at) => at, None => { - weeks.push(WeekActions { week, component, insertions: 0, detachments: 0 }); + weeks.push(WeekActions { week, component: component.clone(), insertions: 0, detachments: 0 }); weeks.len() - 1 } }; if let Some(w) = weeks.get_mut(at) { let slot = if kind == Count::Inserted { &mut w.insertions } else { &mut w.detachments }; - *slot = slot.saturating_add(n); + *slot = slot.saturating_add(*n); } } if weeks.len() > MAX_WEEK_ROWS { @@ -184,8 +190,9 @@ impl Store { } if !self.usage.contains_key(file) { let path = self.dir(file).join(USAGE); - let (list, weeks) = (read_kept(&path), read_kept(&self.dir(file).join(ACTIONS))); - self.usage.insert(file.to_string(), UsageCache { list, weeks, dirty: false, written: now() }); + let dir = self.dir(file); + let (list, weeks, asset_weeks) = (read_kept(&path), read_kept(&dir.join(ACTIONS)), read_kept(&dir.join(ASSET_ACTIONS))); + self.usage.insert(file.to_string(), UsageCache { list, weeks, asset_weeks, dirty: false, written: now() }); } Ok(self.usage.get_mut(file)) } @@ -234,6 +241,31 @@ impl Store { }) } + /// A file's library's styles' and variables' insertions and detachments week by week, over + /// the last [`MAX_WEEKS`] weeks (none when it has no library). + pub fn library_asset_actions(&mut self, file: &str) -> Result>, String> { + let since = week_of(now()).saturating_sub((MAX_WEEKS - 1) * WEEK); + let weeks = self.usage_of(file)?.map(|u| u.asset_weeks.as_slice()).unwrap_or_default(); + Ok(weeks.iter().filter(|w| w.week >= since).cloned().collect()) + } + + /// Note how many times one file has inserted and detached a file's library's styles and + /// variables: what its totals grew past their highest counts in this week. + pub fn report_asset_actions(&mut self, file: &str, actions: AssetActions) -> Result<(), String> { + for (counts, kind) in [(actions.inserted, Count::Inserted), (actions.detached, Count::Detached)] { + let mut grown = Vec::new(); + self.report(file, &actions.file, known_assets(counts), |e, counts| { + grown = grow(&mut e.asset_peaks, &counts, kind, |_| 0); + !grown.is_empty() + })?; + if let (false, Some(u)) = (grown.is_empty(), self.usage.get_mut(file)) { + add_to_week(&mut u.asset_weeks, &grown, kind, now()); + u.dirty = true; + } + } + Ok(()) + } + /// Keep how many layers of one file use a file's library's styles and variables (as /// [`Self::report_usage`] keeps its usage, beside it). pub fn report_assets(&mut self, file: &str, assets: AssetUsage) -> Result<(), String> { @@ -325,7 +357,8 @@ impl Store { if let Err(e) = write_json(&root.join(file).join(USAGE), &u.list) { log::warn!("file {file}: library usage couldn't be kept: {e}"); } - if let Err(e) = write_json(&root.join(file).join(ACTIONS), &u.weeks) { + let actions = write_json(&root.join(file).join(ACTIONS), &u.weeks); + if let Err(e) = actions.and_then(|()| write_json(&root.join(file).join(ASSET_ACTIONS), &u.asset_weeks)) { log::warn!("file {file}: library analytics couldn't be kept: {e}"); } (u.dirty, u.written) = (false, t); diff --git a/crates/collab-net/src/link.rs b/crates/collab-net/src/link.rs index 30bc587c3..198022a09 100644 --- a/crates/collab-net/src/link.rs +++ b/crates/collab-net/src/link.rs @@ -277,7 +277,10 @@ impl LiveLink for NetLink { let spawned = std::thread::Builder::new().name("library-fetch".into()).spawn(move || { for (link, req) in jobs { // A report's answer says nothing about the library (and an older server refuses it). - let report = matches!(req, LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_)); + let report = matches!( + req, + LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_) + ); let reply = manage::library(&link, req, &limits, CONNECT); if !report { inbox.push(Event::Library { link, reply }); diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index 07adbb2af..1ba0896aa 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -629,6 +629,15 @@ pub struct AssetUsage { pub variables: Vec<(String, u32)>, } +/// How many times one file has inserted and detached a library's styles and variables, as its app +/// reports them: its name and its totals of each (by their ids in the library). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct AssetActions { + pub file: String, + pub inserted: Vec<(String, u32)>, + pub detached: Vec<(String, u32)>, +} + /// A file's last usage report, with when it came (seconds since 1970, UTC). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct FileUsage { @@ -655,9 +664,9 @@ pub struct FileDetached { /// 1970 UTC, a Monday at 00:00), over every file that reported it: instances inserted (placed, /// pasted or duplicated) and detached, counted when the server first heard of them. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct WeekActions { +pub struct WeekActions { pub week: u64, - pub component: NodeId, + pub component: K, pub insertions: u32, pub detachments: u32, } @@ -692,6 +701,12 @@ pub enum LibraryReq { ReportAssets(AssetUsage), /// The style and variable reports of the files that use the library. Assets, + /// How many times the asking file has inserted and detached the library's styles and variables + /// (answered with [`LibraryReply::Noted`]). + ReportAssetActions(AssetActions), + /// The library's styles' and variables' insertions and detachments week by week (answered with + /// [`LibraryReply::AssetActions`]). + AssetActions, } /// The answer to a [`LibraryReq`] (the first one on a connection answers [`OpenLibrary`]). @@ -727,6 +742,7 @@ pub enum LibraryReply { Detached(Vec), Actions(Vec), Assets(Vec), + AssetActions(Vec>), } /// Opens a connection to a server's plugin directory (instead of [`Hello`]). Anyone who can reach diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index 35279aae4..828e1605b 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -217,6 +217,10 @@ pub struct Libraries { /// or duplicated; reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] components. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub inserted: Vec, + /// How often this document has inserted and detached each library style and variable + /// (reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] of them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub asset_counts: Vec, } /// Most library components a document counts detaches for. @@ -233,6 +237,17 @@ pub struct DetachCount { pub count: u32, } +/// Inserts and detaches of one library style or variable in a document. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AssetCount { + /// The library's id. + pub library: String, + /// Its id in the library. + pub key: String, + pub inserted: u32, + pub detached: u32, +} + /// Count one more instance of component `key` of library `library` in `list` (a component not /// counted yet is left out once [`MAX_DETACH_COUNTS`] are). fn count(list: &mut Vec, library: &str, key: NodeId) { @@ -256,6 +271,21 @@ impl Libraries { count(&mut self.inserted, library, key); } + /// Count `n` more inserts (or, with `detach`, detaches) of style or variable `key` of library + /// `library` (one not counted yet is left out once [`MAX_DETACH_COUNTS`] are). + pub fn count_asset(&mut self, library: &str, key: &str, detach: bool, n: u32) { + let at = self.asset_counts.iter().position(|c| c.library == library && c.key == key); + let at = at.or_else(|| { + let room = self.asset_counts.len() < MAX_DETACH_COUNTS; + room.then(|| self.asset_counts.push(AssetCount { library: library.to_string(), key: key.to_string(), inserted: 0, detached: 0 }))?; + Some(self.asset_counts.len() - 1) + }); + if let Some(c) = at.and_then(|at| self.asset_counts.get_mut(at)) { + let total = if detach { &mut c.detached } else { &mut c.inserted }; + *total = total.saturating_add(n); + } + } + /// Whether nothing is enabled, kept or counted. pub fn is_empty(&self) -> bool { self.enabled.is_empty() @@ -266,6 +296,7 @@ impl Libraries { && self.variables.is_empty() && self.detached.is_empty() && self.inserted.is_empty() + && self.asset_counts.is_empty() } /// Serde helper: leave the field out of files that use no libraries. diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 785e6c748..5c8baa1f1 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -83,14 +83,57 @@ pub fn asset_root(doc: &Document, id: NodeId) -> Option { chain.into_iter().rfind(|c| doc.node(*c).is_some_and(is_asset)) } +/// The styles and variables layer `n` links to, each once. +fn asset_links(n: &Node) -> BTreeSet<&str> { + style_links(n).map(String::as_str).chain(n.bound.values().map(String::as_str)).collect() +} + +/// The library and the id there of a local copy of a library style or variable. +fn asset_record<'a>(doc: &'a Document, local: &str) -> Option<&'a ImportedRecord> { + doc.libraries.styles.iter().chain(&doc.libraries.variables).find(|r| r.local == local) +} + +/// How many layers link to each local copy of a library style or variable. +fn library_links(doc: &Document) -> BTreeMap { + let mut links = BTreeMap::new(); + if doc.libraries.styles.is_empty() && doc.libraries.variables.is_empty() { + return links; + } + for local in doc.nodes().flat_map(asset_links).filter(|l| asset_record(doc, l).is_some()) { + *links.entry(local.to_string()).or_default() += 1; + } + links +} + +/// Run `edit`, a user's applying (or, with `detach`, detaching) of styles or variables, and count +/// the layers it links to library copies (or unlinks from them) for the libraries' analytics. A +/// style replaced by another isn't a detach: only what the action names counts. +pub(crate) fn counting_links(s: &mut crate::Session, detach: bool, edit: impl FnOnce(&mut crate::Session) -> Result) -> Result { + let before = library_links(s.doc()?); + let out = edit(s)?; + let after = library_links(s.doc()?); + let (from, to) = if detach { (&after, &before) } else { (&before, &after) }; + let grown: Vec<_> = to.iter().map(|(l, n)| (l, n.saturating_sub(from.get(l).copied().unwrap_or(0)))).filter(|g| g.1 > 0).collect(); + for (local, n) in grown { + let doc = s.doc_mut()?; + if let Some(r) = asset_record(doc, local).cloned() { + doc.libraries_mut().count_asset(&r.library, &r.key, detach, n); + } + } + Ok(out) +} + /// Count the instances of library components among `roots` (new layers: placed, pasted or -/// duplicated) and in what they hold as inserted, for the libraries' analytics. An instance inside -/// another instance is part of it and isn't counted on its own. +/// duplicated) and in what they hold as inserted, and the library styles and variables of the +/// rest, for the libraries' analytics. An instance inside another instance is part of it and isn't +/// counted on its own, and what an instance uses is counted as the instance alone. pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) { - if doc.libraries.components.is_empty() { + let l = &doc.libraries; + if l.components.is_empty() && l.styles.is_empty() && l.variables.is_empty() { return; } let mut found = Vec::new(); + let mut assets = Vec::new(); let mut stack = roots.to_vec(); while let Some(id) = stack.pop() { let Some(n) = doc.node(id) else { continue }; @@ -99,12 +142,18 @@ pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) { let root = asset_root(doc, component); found.extend(doc.libraries.components.iter().find(|r| Some(r.root) == root).map(|r| (r.library.clone(), r.key))); } - _ => stack.extend(n.children.iter().copied()), + _ => { + stack.extend(n.children.iter().copied()); + assets.extend(asset_links(n).into_iter().filter_map(|l| asset_record(doc, l)).cloned()); + } } } for (library, key) in found { doc.libraries_mut().count_insert(&library, key); } + for r in assets { + doc.libraries_mut().count_asset(&r.library, &r.key, false, 1); + } } /// Components the layers of `root` use: mains of instances, instance swap defaults and values. diff --git a/crates/engine/src/assets/library_server.rs b/crates/engine/src/assets/library_server.rs index 81889be5d..3d42e7c98 100644 --- a/crates/engine/src/assets/library_server.rs +++ b/crates/engine/src/assets/library_server.rs @@ -15,7 +15,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::io::Cursor; use std::sync::Arc; -use figcraft_collab::message::{AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage}; +use figcraft_collab::message::{AssetActions, AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage}; use figcraft_doc::{DetachCount, Document, ImportedRecord, NodeId, NodeKind, PublishedLibrary}; use crate::live::{NetReply, NetRequest}; @@ -123,6 +123,15 @@ pub fn asset_usage(doc: &Document, library: &str) -> Option { Some(AssetUsage { file: doc.name.clone(), styles: most_used(styles), variables: most_used(variables) }) } +/// How many times `doc` has inserted and detached `library`'s styles and variables, its totals; +/// `None` when it has done neither. +pub fn asset_actions(doc: &Document, library: &str) -> Option { + let counts: Vec<_> = doc.libraries.asset_counts.iter().filter(|c| c.library == library).collect(); + let totals = + |n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).take(MAX_ASSET_USAGE).collect(); + (!counts.is_empty()).then(|| AssetActions { file: doc.name.clone(), inserted: totals(|c| c.inserted), detached: totals(|c| c.detached) }) +} + /// `counts`, the most used first, at most [`MAX_ASSET_USAGE`]. fn most_used(counts: BTreeMap<&str, u32>) -> Vec<(String, u32)> { let mut list: Vec<(String, u32)> = counts.into_iter().map(|(k, n)| (k.to_string(), n)).collect(); @@ -270,6 +279,7 @@ impl Session { detached(doc, &l.id).map(LibraryReq::ReportDetached), inserted(doc, &l.id).map(LibraryReq::ReportInserted), asset_usage(doc, &l.id).map(LibraryReq::ReportAssets), + asset_actions(doc, &l.id).map(LibraryReq::ReportAssetActions), ]; let fetch = LibraryReq::Fetch { have, usage: Some(usage(doc, &l.id)) }; std::iter::once(fetch).chain(reports.into_iter().flatten()).map(|req| (l.path.clone(), req)) diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index d8e2e6893..e562b142b 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -436,6 +436,8 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result { Err(EngineError::Waiting) => return Err(EngineError::Waiting), _ => None, }; + let asset_weeks = asset_week_rows(s, &link, since)?; + let asset_actions = asset_period(asset_weeks.as_deref().unwrap_or_default()); let m = &lib.manifest; // Component → (instances, files using it, instances detached). let mut per: std::collections::BTreeMap = std::collections::BTreeMap::new(); @@ -481,30 +483,62 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result { "files": rows, "components": components, "assetsKnown": assets.is_some(), - "styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), |id| { + "assetActionsKnown": asset_weeks.is_some(), + "styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), &asset_actions, |id| { m.style(id).map(|x| json!({"name": x.name, "type": x.kind})) }), - "variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), |id| { + "variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), &asset_actions, |id| { let v = m.variable(id)?; Some(json!({"name": v.name, "collection": m.collection(&v.collection).map(|c| c.name.clone())})) }), })) } -/// The style or variable reports' totals, the most used first: each one's `id`, `layers` and -/// `files`, with what `describe` says of it (nothing for one no longer published). -fn asset_rows<'a>(reports: impl Iterator>, describe: impl Fn(&str) -> Option) -> Vec { +/// The styles' and variables' weeks overlapping a period from `since`; `None` from a server from +/// before them. +fn asset_week_rows(s: &mut Session, link: &str, since: u64) -> Result>>> { + match s.library_request(link, LibraryReq::AssetActions) { + Ok(LibraryReply::AssetActions(w)) => Ok(Some(w.into_iter().filter(|w| w.week.saturating_add(7 * 86_400) > since).collect())), + Err(EngineError::Waiting) => Err(EngineError::Waiting), + _ => Ok(None), + } +} + +/// Each style's or variable's insertions and detachments in `weeks`. +fn asset_period(weeks: &[WeekActions]) -> std::collections::BTreeMap<&str, (u64, u64)> { + let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new(); + for w in weeks { + let e = per.entry(&w.component).or_default(); + e.0 += u64::from(w.insertions); + e.1 += u64::from(w.detachments); + } + per +} + +/// The style or variable reports' totals, the most used first: each one's `id`, `layers`, `files`, +/// `insertions` and `detachments` in the period, with what `describe` says of it (nothing for one +/// no longer published). One only inserted or detached is listed too, when it's of this kind. +fn asset_rows<'a>( + reports: impl Iterator>, + actions: &std::collections::BTreeMap<&str, (u64, u64)>, + describe: impl Fn(&str) -> Option, +) -> Vec { let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new(); for (id, n) in reports.flatten() { let e = per.entry(id).or_default(); e.0 += u64::from(*n); e.1 += 1; } + for id in actions.keys().filter(|id| describe(id).is_some()) { + per.entry(id).or_default(); + } let mut rows: Vec<_> = per.into_iter().collect(); rows.sort_by_key(|r| std::cmp::Reverse(r.1.0)); let row = |(id, (layers, files)): (&str, (u64, u64))| { let mut r = describe(id).unwrap_or_else(|| json!({})); + let (insertions, detachments) = actions.get(id).copied().unwrap_or_default(); (r["id"], r["layers"], r["files"]) = (json!(id), json!(layers), json!(files)); + (r["insertions"], r["detachments"]) = (json!(insertions), json!(detachments)); r }; rows.into_iter().map(row).collect() diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 710eec76e..f5a0dd6a0 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -302,6 +302,10 @@ fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option Result { + crate::library::counting_links(s, true, |s| detach_style(s, p)) +} + +fn detach_style(s: &mut Session, p: &Value) -> Result { let cmd = "style.detach"; let which = req_string(cmd, p, "which")?; if which == "text" { @@ -458,6 +462,10 @@ pub fn apply_style_ref(doc: &mut Document, id: NodeId, field: &str, sid: Option< } pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { + crate::library::counting_links(s, false, |s| apply_style(s, p)) +} + +fn apply_style(s: &mut Session, p: &Value) -> Result { let cmd = "style.apply"; let st = req_string(cmd, p, "style")?; let style = s.doc()?.style(&st).cloned().ok_or_else(|| bad(cmd, format!("no style `{st}`")))?; @@ -846,6 +854,10 @@ pub fn sync_list_styles(doc: &mut Document, before: &Document, ids: &[NodeId]) { /// `variable.bind`: bind (or with no variable, unbind) `field` of the targets. pub fn bind(s: &mut Session, p: &Value) -> Result { + crate::library::counting_links(s, string(p, "variable").is_none(), |s| bind_field(s, p)) +} + +fn bind_field(s: &mut Session, p: &Value) -> Result { let cmd = "variable.bind"; let field = req_string(cmd, p, "field")?; let var = string(p, "variable"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a74219fb6..3e4af48c3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -404,6 +404,8 @@ mod keymap_tests; #[cfg(test)] mod layout_suggest_tests; #[cfg(test)] +mod library_asset_counts_tests; +#[cfg(test)] mod library_beacon_tests; #[cfg(test)] mod library_path_tests; diff --git a/crates/engine/src/library_asset_counts_tests.rs b/crates/engine/src/library_asset_counts_tests.rs new file mode 100644 index 000000000..faacb880c --- /dev/null +++ b/crates/engine/src/library_asset_counts_tests.rs @@ -0,0 +1,115 @@ +//! What a file counts as inserting and detaching a library's styles and variables, as the help +//! center's library analytics page says: applying one, or copying or duplicating content that uses +//! it, inserts it; the Detach button detaches it. Content that is an instance counts as the +//! instance alone, and local styles and variables count nothing. An undo takes its count back. + +use serde_json::{Value, json}; + +use crate::Session; +use crate::components::tests::{ex, idv}; +use crate::library_server::asset_actions; +use figcraft_doc::{AssetCount, NodeId, PublishedLibrary}; + +/// A file with a published library holding a paint style, a colour variable and a Card, and a +/// second file that uses it: the second session, the library's id and its keys. +fn user() -> (Session, String, Value) { + let mut a = Session::new(); + let r = idv(&ex(&mut a, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))); + let style = ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0})); + let coll = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"})); + ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": coll["id"], "value": "#0D99FF"})); + let card = idv(&ex(&mut a, "frame.create", json!({"x": 0, "y": 100, "width": 100, "height": 40, "name": "Card"}))); + ex(&mut a, "style.apply", json!({"ids": [card.0], "style": style["id"]})); + ex(&mut a, "component.create", json!({"ids": [card.0]})); + ex(&mut a, "library.publish", json!({})); + let lib: PublishedLibrary = a.doc().unwrap().published.as_deref().unwrap().clone(); + let path = std::env::temp_dir().join(format!("figcraft-asset-counts-{}-{:?}.figcraft", std::process::id(), std::thread::current().id())); + ex(&mut a, "file.save", json!({"path": path.to_string_lossy()})); + let mut b = Session::new(); + let id = ex(&mut b, "library.add", json!({"path": path.to_string_lossy()}))["id"].as_str().unwrap().to_string(); + assert_eq!(lib.manifest.id, id); + (b, id, json!({"style": "Brand", "variable": "Accent"})) +} + +fn rect(s: &mut Session, x: i32) -> NodeId { + idv(&ex(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 40, "height": 40}))) +} + +/// (inserted, detached) of the style and of the variable, as `doc` keeps them. +fn counts(s: &Session) -> ((u32, u32), (u32, u32)) { + let of = |key: &str| { + s.doc().unwrap().libraries.asset_counts.iter().find(|c: &&AssetCount| c.key.starts_with(key)).map_or((0, 0), |c| (c.inserted, c.detached)) + }; + (of("S:"), of("VariableID:")) +} + +#[test] +fn applying_counts_once_per_layer_that_takes_it() { + let (mut s, lib, _) = user(); + let (one, two) = (rect(&mut s, 0), rect(&mut s, 100)); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]})); + assert_eq!(counts(&s).0, (2, 0)); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]})); + assert_eq!(counts(&s).0, (2, 0), "a layer that has it already adds nothing"); + let three = rect(&mut s, 200); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [three.0], "field": "fill"})); + assert_eq!(counts(&s).1, (1, 0)); +} + +#[test] +fn duplicating_and_pasting_content_counts_what_it_uses() { + let (mut s, lib, _) = user(); + let one = rect(&mut s, 0); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]})); + ex(&mut s, "select.set", json!({"ids": [one.0]})); + ex(&mut s, "edit.duplicate", json!({})); + assert_eq!(counts(&s).0, (2, 0), "the copy inserts it too"); + ex(&mut s, "select.set", json!({"ids": [one.0]})); + ex(&mut s, "edit.copy", json!({})); + ex(&mut s, "edit.paste", json!({})); + assert_eq!(counts(&s).0, (3, 0)); +} + +#[test] +fn an_instance_counts_as_its_component_alone() { + let (mut s, lib, _) = user(); + let i = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0}))); + assert_eq!(counts(&s).0, (0, 0), "placing it"); + ex(&mut s, "select.set", json!({"ids": [i.0]})); + ex(&mut s, "edit.duplicate", json!({})); + assert_eq!(counts(&s).0, (0, 0), "duplicating it"); + assert_eq!(s.doc().unwrap().libraries.inserted[0].count, 2); +} + +#[test] +fn only_the_detach_buttons_detach() { + let (mut s, lib, _) = user(); + let (one, two) = (rect(&mut s, 0), rect(&mut s, 100)); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]})); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [two.0], "field": "stroke"})); + ex(&mut s, "style.detach", json!({"ids": [one.0, two.0], "which": "fill"})); + assert_eq!(counts(&s).0, (2, 2)); + ex(&mut s, "variable.bind", json!({"ids": [two.0], "field": "stroke"})); + assert_eq!(counts(&s).1, (1, 1)); + // Another style in its place isn't a detach of the first. + let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0})); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]})); + ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]})); + assert_eq!(counts(&s).0, (3, 2)); +} + +#[test] +fn local_styles_count_nothing_and_undo_takes_a_count_back() { + let (mut s, lib, _) = user(); + let one = rect(&mut s, 0); + let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0})); + ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]})); + ex(&mut s, "style.detach", json!({"ids": [one.0], "which": "fill"})); + assert!(s.doc().unwrap().libraries.asset_counts.is_empty()); + assert!(asset_actions(s.doc().unwrap(), &lib).is_none()); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]})); + let report = asset_actions(s.doc().unwrap(), &lib).unwrap(); + assert_eq!((report.inserted.len(), report.detached.len()), (1, 0)); + ex(&mut s, "edit.undo", json!({})); + assert_eq!(counts(&s).0, (0, 0)); +} diff --git a/crates/engine/src/sharing/background/tests.rs b/crates/engine/src/sharing/background/tests.rs index 6f98841df..cd9bc951c 100644 --- a/crates/engine/src/sharing/background/tests.rs +++ b/crates/engine/src/sharing/background/tests.rs @@ -98,10 +98,13 @@ fn library(w: &mut Wire, req: LibraryReq) -> LibraryReply { LibraryReply::Published { version: 1 } } (LibraryReq::Usage, _) => LibraryReply::Usage(Vec::new()), - (LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_), _) => LibraryReply::Noted, + (LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_), _) => { + LibraryReply::Noted + } (LibraryReq::Detached, _) => LibraryReply::Detached(Vec::new()), (LibraryReq::Actions, _) => LibraryReply::Actions(Vec::new()), (LibraryReq::Assets, _) => LibraryReply::Assets(Vec::new()), + (LibraryReq::AssetActions, _) => LibraryReply::AssetActions(Vec::new()), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fcabb5d8f..fecdc3882 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -290,6 +290,8 @@ mod ui_params_tests; #[cfg(test)] mod ui_scale_tests; #[cfg(test)] +mod usage_summary_tests; +#[cfg(test)] mod variable_picker_tests; #[cfg(test)] mod variables_export_ui_tests; diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index 41f7762ff..4d516d50d 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -1028,22 +1028,32 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { } let actions = v["actionsKnown"].as_bool().unwrap_or(false); let inserted_n = |n: u64| trn("{n} inserted", n as usize, &[]); - if actions { + let Some(kind) = usage_kind(ui, w, usage_id, &v) else { + ui.add_space(8.0); + return; + }; + if let Some((i, d)) = period_totals(&v, kind) { let label = USAGE_PERIODS.iter().find(|p| p.0 == days).map_or(USAGE_PERIODS[0].2, |p| p.2); - let (i, d) = (v["insertions"].as_u64().unwrap_or(0), v["detachments"].as_u64().unwrap_or(0)); let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &trn("{n} detached", d as usize, &[]))]); hint(ui, &trf("{period}: {counts}", &[("period", &tr(label)), ("counts", &counts)])); } else { hint(ui, tr("This server doesn't count insertions")); } - let Some(kind) = usage_kind(ui, w, usage_id, &v) else { - ui.add_space(8.0); - return; - }; + if v["assetsKnown"].as_bool() == Some(true) && v[kind].as_array().is_none_or(Vec::is_empty) { + hint(ui, tr("Nothing counted yet")); + } if kind != "components" { for a in v[kind].as_array().into_iter().flatten().take(USAGE_ROWS) { let (n, f) = (a["layers"].as_u64().unwrap_or(0), a["files"].as_u64().unwrap_or(0)); let counts = trf("{instances} in {files}", &[("instances", &trn("{n} layers", n as usize, &[])), ("files", &files_n(f))]); + // Inserted and detached in the period, after what it counts in all. + let (added, gone) = (a["insertions"].as_u64().unwrap_or(0), a["detachments"].as_u64().unwrap_or(0)); + let counts = if added > 0 { trf("{used} · {inserted}", &[("used", &counts), ("inserted", &inserted_n(added))]) } else { counts }; + let counts = if gone > 0 { + trf("{used} · {detached}", &[("used", &counts), ("detached", &trn("{n} detached", gone as usize, &[]))]) + } else { + counts + }; usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts); } ui.add_space(8.0); @@ -1067,6 +1077,17 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { ui.add_space(8.0); } +/// What the `kind` list of a Show usage answer adds up to in its period: insertions and +/// detachments, `None` from a server that doesn't count them for that kind. +pub(crate) fn period_totals(v: &Value, kind: &str) -> Option<(u64, u64)> { + let known = if kind == "components" { "actionsKnown" } else { "assetActionsKnown" }; + (v[known].as_bool() == Some(true)).then(|| { + let rows = v[kind].as_array().map_or(&[][..], Vec::as_slice); + let sum = |key: &str| rows.iter().filter_map(|r| r[key].as_u64()).sum(); + (sum("insertions"), sum("detachments")) + }) +} + /// Which list Show usage shows: `components`, `styles` or `variables` (a choice kept with the /// answer's `id`), `None` for nothing to list. A server from before style and variable reports /// shows just components, and says so. @@ -1092,11 +1113,7 @@ fn usage_kind(ui: &mut Ui, w: f32, id: Id, v: &Value) -> Option<&'static str> { }); }); ui.data_mut(|d| d.insert_temp(id, at)); - let kind = KINDS.get(at)?.0; - if v[kind].as_array().is_none_or(Vec::is_empty) { - hint(ui, tr("Nothing counted yet")); - } - Some(kind) + Some(KINDS.get(at)?.0) } /// A Show usage row: two lines, as the counts don't leave a name room on one. diff --git a/crates/ui-egui/src/usage_summary_tests.rs b/crates/ui-egui/src/usage_summary_tests.rs new file mode 100644 index 000000000..4a512cc85 --- /dev/null +++ b/crates/ui-egui/src/usage_summary_tests.rs @@ -0,0 +1,30 @@ +//! Show usage's period line sums the list the Type choice shows, so it never reads 0 above a list +//! with counts, and a server that doesn't count a kind says so for that kind alone. + +use serde_json::json; + +use crate::panels::assets_panel::period_totals; + +#[test] +fn the_period_line_sums_the_list_shown() { + let v = json!({ + "actionsKnown": true, + "assetActionsKnown": true, + "insertions": 0, + "detachments": 0, + "components": [], + "styles": [{"insertions": 3, "detachments": 1}, {"insertions": 2, "detachments": 0}], + "variables": [{"insertions": 1, "detachments": 4}], + }); + assert_eq!(period_totals(&v, "components"), Some((0, 0))); + assert_eq!(period_totals(&v, "styles"), Some((5, 1))); + assert_eq!(period_totals(&v, "variables"), Some((1, 4))); +} + +#[test] +fn a_server_that_doesnt_count_a_kind_has_no_totals_for_it() { + let v = json!({"actionsKnown": true, "components": [{"insertions": 2, "detachments": 1}], "styles": [{"layers": 3}]}); + assert_eq!(period_totals(&v, "components"), Some((2, 1))); + assert_eq!(period_totals(&v, "styles"), None, "a server from before them"); + assert_eq!(period_totals(&json!({}), "components"), None); +} diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 41c73190d..a3e9ccae5 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -257,7 +257,7 @@ Client → server: | `Manage {protocol, key, client_version}` | Instead of `Hello`: manage a server's files with its key. | | `Admin {publish {name, snapshot} \| files \| links {file} \| createLink {file, access, label} \| revoke {file, link} \| remove {file}}` | A request on a managing connection; each gets one `Admin` reply, in order. | | `OpenLibrary {protocol, file, token, client_version}` | Instead of `Hello`: use a file's team library with one of the file's share links. | -| `Library {fetch {have?, usage?} \| publish {archive} \| usage \| reportDetached {file, components} \| detached \| reportInserted {file, components} \| actions \| reportAssets {file, styles, variables} \| assets}` | A request on a library connection; each gets one `Library` reply, in order. `usage` is `{file, components: [(id, instances)]}`; `reportDetached` gives the asking file's detached instances per component the same way (answered `noted`), `detached` asks for every file's. The last two are newer: a server from before them can't read them and refuses the request. | +| `Library {fetch {have?, usage?} \| publish {archive} \| usage \| reportDetached {file, components} \| detached \| reportInserted {file, components} \| actions \| reportAssets {file, styles, variables} \| assets \| reportAssetActions {file, inserted, detached} \| assetActions}` | A request on a library connection; each gets one `Library` reply, in order. `usage` is `{file, components: [(id, instances)]}`; `reportDetached` gives the asking file's detached instances per component the same way (answered `noted`), `detached` asks for every file's. The last two are newer: a server from before them can't read them and refuses the request. | | `Signal {kind, text}` | Ephemeral presence, only after the server's `ready`: `chat` (the cursor chat message; empty: closed), `spotlight` (`"on"`, or empty: stopped) or `name` (your new name: the server keeps it, cleaned like a hello's, and sends everyone, you too, your `PeerJoined`; never passed on as a signal). | | `OpenPlugins {protocol, key, client_version}` | Instead of `Hello`: use the server's plugin directory; `key` empty to browse, the server key to publish too. | | `OpenHosting {protocol, client_version, file, owner}` | Instead of `Hello`: ask about the server's hosting; publish without the key (`Admin publish`) when it is open to the public; with a file's id and owner token, manage that file (`Admin links \| createLink \| revoke \| rename \| remove` of it). Answered with `Hosting` or `Refused`. | @@ -279,7 +279,7 @@ Server → client: | `Refused {reason}` | The connection is refused (protocol version, token, session full, a message out of place). | | `Pong` | Keep-alive. | | `Admin {ready \| published {file, edit, view} \| files \| links \| link \| done \| failed {reason}}` | A managing connection's answer: the key is right, a published file with its first two links (tokens shown once), listings, a new link, done, or why not. | -| `Library {ready {access} \| library {version, archive} \| unchanged {version} \| empty \| published {version} \| usage [{usage, updated}] \| failed {reason} \| noted \| detached [{detached, updated}] \| actions [{week, component, insertions, detachments}] \| assets [{file, styles, variables}]}` | A library connection's answer: the link is right (with its access), the library (a `.figcraft` archive holding it), no newer version, no library yet, kept, the usage reports, or why not; then (newer) a detach report kept, and the detach reports. | +| `Library {ready {access} \| library {version, archive} \| unchanged {version} \| empty \| published {version} \| usage [{usage, updated}] \| failed {reason} \| noted \| detached [{detached, updated}] \| actions [{week, component, insertions, detachments}] \| assets [{file, styles, variables}] \| assetActions [{week, component, insertions, detachments}]}` | A library connection's answer: the link is right (with its access), the library (a `.figcraft` archive holding it), no newer version, no library yet, kept, the usage reports, or why not; then (newer) a detach report kept, and the detach reports. | | `Signal {client_id, signal: {kind, text}}` | Someone's cursor chat or spotlight, cleaned by the server; `ready` (about the client itself, after its welcome): signals may be sent. Only to clients whose hello announced `signals`. | | `Hosting {open, operator, terms, idle_secs, max_file_mb, expires?}` | The answer to `OpenHosting`, and after a welcome to clients whose hello announced `hosting`: anyone may publish, how to reach the operator, the terms (a URL), how long files published without the key are kept unopened, the largest file, and this file's expiry (seconds since 1970). | | `Admin {hosted {file, edit, view, owner, expires?} \| listing [row] \| reports [report] \| blocked [ip]}` | A file published without the key with its links and owner token (shown once), and the answers to the later managing requests. | @@ -848,7 +848,9 @@ resuming with its offline edits, and leaving the session going back to snapshot styles or variables sends `reportAssets` with how many of its layers use each (at most 250 of each kind, the most used first; none is a report too, so a file that stops using them stops counting); the server keeps the latest in the same `usage.json` entry and answers `assets` with - them. The variants are appended to the enums, so the older messages keep their bytes; an older server refuses the new + them. It sends `reportAssetActions` with its totals of inserted and detached styles and variables, + counted over the weeks as for components (`asset-actions.json`), and `assetActions` answers with + those weeks (`component` is the style's or variable's id). The variants are appended to the enums, so the older messages keep their bytes; an older server refuses the new requests, and the app ignores that. *Built* (the plugin directory; operating it: [`server.md`](server.md#plugin-directory), publishing and diff --git a/docs/components-parity.md b/docs/components-parity.md index 73d1d8ced..bb2a3e2ab 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -54,7 +54,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Go to main component from an instance of a library component | done | opens the library file in a tab, or brings it to the front, on the page holding the main, selected and zoomed to; a variant goes to that variant. Team libraries on a server are refused with a note; no Return to instance yet | | Library updates available; overrides kept | done | a library file saved again within two seconds of being read, at the same length, is read again (its time stamp can't prove it unchanged; #652) | | Team libraries: publish to a `figcraft-server` under the file, enable by a share link (a view link reads it), background update checks | done | [server.md](server.md#team-libraries); no team-wide library list or accounts ([gaps](gaps.md) #10) | -| Library analytics | partial | instances per component and the files using them, and the instances each file detached (per component and per file), as apps report them; insertions and detachments week by week for a year (Show usage: the past 30 days, 90 days or year), for components; the layers and files using each style and variable, without insertions, detachments or modes; no chart | +| Library analytics | partial | instances per component and the files using them, and the instances each file detached (per component and per file), as apps report them; insertions and detachments week by week for a year (Show usage: the past 30 days, 90 days or year), for components; the layers and files using each style and variable, with their insertions and detachments over the same periods, no modes; no chart | | Swap library (instances, styles and variables to another library's of the same names, overrides kept) | done | what has no match stays and is listed; one undo step | ## Styles and variables @@ -80,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | patch | M3: Combine as variants gives every variant the component properties any of the components had (as a property added to a set goes to all its variants); a property made on one component before combining was missing from the others, so their layers couldn't be bound to it and an instance switched to them dropped its value. A variant with a property of the same name keeps its own. Tests: `variant_shared_props_tests`. | | 2026-11-18 | patch | M3, #2368: a text field that isn't being edited ends a value too long for it with an ellipsis and shows the whole value on hover (a secret field shows none), so the variant value "Down left" no longer reads "Down lef"; screen readers and editing keep the whole value (`field_ellipsis_tests`). Grade unchanged. | | 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. | diff --git a/docs/gaps.md b/docs/gaps.md index 8e1d60686..bb3ede386 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -23,7 +23,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | 7 | CPU canvas where Figma uses the GPU | Hardware/performance | 30–60 | [hardware-parity](hardware-parity.md) | | 8 | Platform QA: Linux and the browser left (Windows pass done 2026-10-11) | Stability/platforms | 10–20 | [hardware-parity](hardware-parity.md) | | 9 | Figma Draw: pen pressure on macOS/Linux tablets (multi-edit, brushes, pressure, text on a path and pattern fills landed) | Feature | 1–3 | [target-app-parity](target-app-parity.md) | -| 10 | Team libraries: no team-wide lists or accounts; analytics count insertions for components only | Feature | 4–8 | [components-parity](components-parity.md) | +| 10 | Team libraries: no team-wide lists or accounts; analytics don't count modes | Feature | 4–8 | [components-parity](components-parity.md) | | 11 | Spell check | Feature | 4–8 | [target-app-parity](target-app-parity.md) | | 12 | Video fills; HEIC images | File format | 5–10 | [file-format-parity](file-format-parity.md) | | 13 | Vector tail: none left (boolean hit testing on the result landed 2026-10-11) | Feature | — | [target-app-parity](target-app-parity.md) | @@ -378,11 +378,10 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Impact:** illustration-flavoured work moved into Figma Draw in 2025. - **Estimate:** 1–3 h once winit (or a platform tablet API behind it) reports pressure there. -### 10. Team libraries: no team-wide lists or accounts; analytics count insertions for components only +### 10. Team libraries: no team-wide lists or accounts; analytics don't count modes - **Missing:** libraries listed for a whole team or organization (each file enables a library by - its link), accounts and per-person library permissions, insertions, detachments and mode counts for - styles and variables (they count layers and files using them; a component's instances, - insertions and detachments are counted, the last two week by week), + its link), accounts and per-person library permissions, mode counts (a component's instances and a style's + or variable's layers are counted, with their insertions and detachments week by week), update notices pushed by the server (apps ask every 30 seconds while the Assets panel shows). - **Evidence:** a file's library is published to `figcraft-server` under the file and enabled in other files by a share link, with per-asset versions, updates with overrides kept, usage counts @@ -618,6 +617,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Gap 10: library analytics count insertions and detachments of styles and variables; modes stay on the missing list. | | 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. | | 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` | | 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` | diff --git a/docs/mcp.md b/docs/mcp.md index 0a557c6b2..8940fa184 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1028,7 +1028,7 @@ most when it can't be reached). `library.acceptUpdates` takes it, overrides kept. The app's own background checks ask only about team libraries added (`library.add`) or checked (`library.check {library?}`) on this computer, so opening a file that names another one contacts nothing (#1097). -- `library.usage {library?, days?}` → `{id, name, assetsKnown, styles [{id, name, type, layers, files}], variables [{id, name, collection, layers, files}], instances, detached, detachesKnown, days, +- `library.usage {library?, days?}` → `{id, name, assetsKnown, assetActionsKnown, styles [{id, name, type, layers, files, insertions, detachments}], variables [{id, name, collection, layers, files, insertions, detachments}], instances, detached, detachesKnown, days, insertions, detachments, actionsKnown, weeks: [{week, insertions, detachments}], files: [{name, updated, instances, detached}], components: [{id, name, instances, files, detached, insertions, detachments}]}`: what the files using it reported (each fetch reports the asking document's name diff --git a/docs/roadmap.md b/docs/roadmap.md index 78f4d4df3..b797063a6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -76,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | diff --git a/docs/server.md b/docs/server.md index 37f0182d9..c7cbe3093 100644 --- a/docs/server.md +++ b/docs/server.md @@ -254,8 +254,9 @@ which other files use without anyone copying the library file around. layers use each of the library's styles and variables. **Show usage** in the library file (`library.usage`) lists the files and the instances and detaches of each component, the insertions and detachments of the past 30 days, 90 days or year, and, by its Type choice, the - layers and files using each style and variable. Layers inside instances count for their - component. Files are + layers and files using each style and variable with their insertions and detachments. Applying + a style or variable, or copying or duplicating content that uses it, inserts it, and the Detach + button detaches it. Layers inside instances count for their component. Files are told apart by their names; a file's report changes only when its usage does. The server counts what a file's totals grow past their highest in the week it hears of it, keeps a year of weeks, and counts an undo and a redo once. A server from before these counts refuses the reports From 64b662b86983fb302644ba450be53222c2615e22 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 31 Oct 2026 10:04:21 +0700 Subject: [PATCH 095/129] M3: Show usage's rows are drawn by small helpers --- crates/ui-egui/src/panels/assets_panel.rs | 85 ++++++++++++++--------- 1 file changed, 52 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index 4d516d50d..9d58a81c5 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -1014,27 +1014,19 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { }; let files = v["files"].as_array().map_or(0, Vec::len); let instances = v["instances"].as_u64().unwrap_or(0); - let files_n = |n: u64| trn("{n} files", n as usize, &[]); - let instances_n = |n: u64| trn("{n} instances", n as usize, &[]); - // Detached instances, beside what they are counted with (a server from before them keeps none). let known = v["detachesKnown"].as_bool().unwrap_or(false); - let with_detached = |used: String, n: u64| { - if known && n > 0 { trf("{used} · {detached}", &[("used", &used), ("detached", &trn("{n} detached", n as usize, &[]))]) } else { used } - }; let used = trf("Used in {files} · {instances}", &[("files", &files_n(files as u64)), ("instances", &instances_n(instances))]); - hint(ui, &with_detached(used, v["detached"].as_u64().unwrap_or(0))); + hint(ui, &with_detached(known, used, v["detached"].as_u64().unwrap_or(0))); if !known { hint(ui, tr("This server doesn't count detached instances")); } - let actions = v["actionsKnown"].as_bool().unwrap_or(false); - let inserted_n = |n: u64| trn("{n} inserted", n as usize, &[]); let Some(kind) = usage_kind(ui, w, usage_id, &v) else { ui.add_space(8.0); return; }; if let Some((i, d)) = period_totals(&v, kind) { let label = USAGE_PERIODS.iter().find(|p| p.0 == days).map_or(USAGE_PERIODS[0].2, |p| p.2); - let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &trn("{n} detached", d as usize, &[]))]); + let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &detached_n(d))]); hint(ui, &trf("{period}: {counts}", &[("period", &tr(label)), ("counts", &counts)])); } else { hint(ui, tr("This server doesn't count insertions")); @@ -1042,39 +1034,66 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { if v["assetsKnown"].as_bool() == Some(true) && v[kind].as_array().is_none_or(Vec::is_empty) { hint(ui, tr("Nothing counted yet")); } - if kind != "components" { - for a in v[kind].as_array().into_iter().flatten().take(USAGE_ROWS) { - let (n, f) = (a["layers"].as_u64().unwrap_or(0), a["files"].as_u64().unwrap_or(0)); - let counts = trf("{instances} in {files}", &[("instances", &trn("{n} layers", n as usize, &[])), ("files", &files_n(f))]); - // Inserted and detached in the period, after what it counts in all. - let (added, gone) = (a["insertions"].as_u64().unwrap_or(0), a["detachments"].as_u64().unwrap_or(0)); - let counts = if added > 0 { trf("{used} · {inserted}", &[("used", &counts), ("inserted", &inserted_n(added))]) } else { counts }; - let counts = if gone > 0 { - trf("{used} · {detached}", &[("used", &counts), ("detached", &trn("{n} detached", gone as usize, &[]))]) - } else { - counts - }; - usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts); - } - ui.add_space(8.0); - return; + if kind == "components" { + component_rows(ui, w, &v, known); + } else { + asset_rows(ui, w, &v, kind); } + ui.add_space(8.0); +} + +fn files_n(n: u64) -> String { + trn("{n} files", n as usize, &[]) +} + +fn instances_n(n: u64) -> String { + trn("{n} instances", n as usize, &[]) +} + +fn inserted_n(n: u64) -> String { + trn("{n} inserted", n as usize, &[]) +} + +fn detached_n(n: u64) -> String { + trn("{n} detached", n as usize, &[]) +} + +/// `used`, with the detached instances beside it (a server from before them keeps none: `known`). +fn with_detached(known: bool, used: String, n: u64) -> String { + if known && n > 0 { trf("{used} · {detached}", &[("used", &used), ("detached", &detached_n(n))]) } else { used } +} + +/// `used`, with the insertions counted in the period after it. +fn with_inserted(used: String, n: u64) -> String { + if n > 0 { trf("{used} · {inserted}", &[("used", &used), ("inserted", &inserted_n(n))]) } else { used } +} + +/// Show usage's rows for a style or variable list. +fn asset_rows(ui: &mut Ui, w: f32, v: &Value, kind: &str) { + for a in v[kind].as_array().into_iter().flatten().take(USAGE_ROWS) { + let (n, f) = (a["layers"].as_u64().unwrap_or(0), a["files"].as_u64().unwrap_or(0)); + let counts = trf("{instances} in {files}", &[("instances", &trn("{n} layers", n as usize, &[])), ("files", &files_n(f))]); + let counts = with_detached(true, with_inserted(counts, a["insertions"].as_u64().unwrap_or(0)), a["detachments"].as_u64().unwrap_or(0)); + usage_row(ui, w, a["name"].as_str().unwrap_or(tr("(no longer published)")), &counts); + } +} + +/// Show usage's rows for the components; `known`: the server counts detached instances. +fn component_rows(ui: &mut Ui, w: f32, v: &Value, known: bool) { + let actions = v["actionsKnown"].as_bool().unwrap_or(false); for c in v["components"].as_array().into_iter().flatten().take(USAGE_ROWS) { let name = c["name"].as_str().unwrap_or(tr("(no longer published)")); let (n, f) = (c["instances"].as_u64().unwrap_or(0), c["files"].as_u64().unwrap_or(0)); let gone = c["detached"].as_u64().unwrap_or(0); // A component only detached (no instances left anywhere) says just that. let right = if n == 0 && known && gone > 0 { - trn("{n} detached", gone as usize, &[]) + detached_n(gone) } else { - with_detached(trf("{instances} in {files}", &[("instances", &instances_n(n)), ("files", &files_n(f))]), gone) + with_detached(known, trf("{instances} in {files}", &[("instances", &instances_n(n)), ("files", &files_n(f))]), gone) }; - // Inserted in the period, after what the component counts in all. - let added = c["insertions"].as_u64().unwrap_or(0); - let right = if actions && added > 0 { trf("{used} · {inserted}", &[("used", &right), ("inserted", &inserted_n(added))]) } else { right }; - usage_row(ui, w, name, &right); + let added = if actions { c["insertions"].as_u64().unwrap_or(0) } else { 0 }; + usage_row(ui, w, name, &with_inserted(right, added)); } - ui.add_space(8.0); } /// What the `kind` list of a Show usage answer adds up to in its period: insertions and From b63368e39cbd3a2a3df630b2021027c7763fb44a Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 14:08:11 +0700 Subject: [PATCH 096/129] M3: a style or variable applied or detached inside an instance counts nothing counting_links compared library_links, which walked every node, so applying or detaching a library style or variable on an instance or a layer in it counted, while duplicating that instance counts only its component. library_links now walks the pages and skips instances with what they hold, as count_inserted does. Test: library_asset_counts_tests::applying_and_detaching_inside_an_instance_counts_nothing (an instance, its layer, a nested instance and its layer). The server test waits for the detachments too, not only the insertions. --- .../src/library_assets_tests.rs | 7 +++- crates/engine/src/assets/library.rs | 15 +++++-- .../engine/src/library_asset_counts_tests.rs | 41 ++++++++++++++++++- 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index 4da1aba8d..5941e4980 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -165,7 +165,12 @@ fn inserts_and_detaches_count_per_style_and_variable_in_the_period() { ex(&mut b, "style.detach", json!({"ids": [two.0], "which": "fill"})); ex(&mut b, "library.bindVariable", json!({"library": lid, "variable": "Accent", "ids": [two.0], "field": "fill"})); - let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["insertions"] == 2 && u["variables"][0]["insertions"] == 1); + let u = usage_when(&mut a, &mut b, |u| { + u["assetActionsKnown"] == true + && u["styles"][0]["insertions"] == 2 + && u["styles"][0]["detachments"] == 1 + && u["variables"][0]["insertions"] == 1 + }); assert_eq!(u["assetActionsKnown"], true, "{u}"); assert_eq!(u["styles"][0]["detachments"], 1, "{u}"); assert_eq!(u["variables"][0]["detachments"], 0, "{u}"); diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 5c8baa1f1..054710464 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -93,14 +93,23 @@ fn asset_record<'a>(doc: &'a Document, local: &str) -> Option<&'a ImportedRecord doc.libraries.styles.iter().chain(&doc.libraries.variables).find(|r| r.local == local) } -/// How many layers link to each local copy of a library style or variable. +/// How many layers link to each local copy of a library style or variable. An instance and the +/// layers in it don't count: an instance counts as its component alone, as in [`count_inserted`]. fn library_links(doc: &Document) -> BTreeMap { let mut links = BTreeMap::new(); if doc.libraries.styles.is_empty() && doc.libraries.variables.is_empty() { return links; } - for local in doc.nodes().flat_map(asset_links).filter(|l| asset_record(doc, l).is_some()) { - *links.entry(local.to_string()).or_default() += 1; + let mut stack = doc.pages.clone(); + while let Some(id) = stack.pop() { + let Some(n) = doc.node(id) else { continue }; + if matches!(n.kind, NodeKind::Instance { .. }) { + continue; + } + stack.extend(n.children.iter().copied()); + for local in asset_links(n).into_iter().filter(|l| asset_record(doc, l).is_some()) { + *links.entry(local.to_string()).or_default() += 1; + } } links } diff --git a/crates/engine/src/library_asset_counts_tests.rs b/crates/engine/src/library_asset_counts_tests.rs index faacb880c..e0f4fe456 100644 --- a/crates/engine/src/library_asset_counts_tests.rs +++ b/crates/engine/src/library_asset_counts_tests.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use crate::Session; use crate::components::tests::{ex, idv}; use crate::library_server::asset_actions; -use figcraft_doc::{AssetCount, NodeId, PublishedLibrary}; +use figcraft_doc::{AssetCount, NodeId, NodeKind, PublishedLibrary}; /// A file with a published library holding a paint style, a colour variable and a Card, and a /// second file that uses it: the second session, the library's id and its keys. @@ -81,6 +81,45 @@ fn an_instance_counts_as_its_component_alone() { assert_eq!(s.doc().unwrap().libraries.inserted[0].count, 2); } +/// Applying and detaching a library style or variable on an instance, on a layer in it, or on a +/// layer of an instance nested in it counts nothing either: what an instance uses counts as it. +#[test] +fn applying_and_detaching_inside_an_instance_counts_nothing() { + let (mut s, lib, _) = user(); + let placed = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0}))); + // A Button holding a rectangle and an Icon instance (the Icon holds a dot), and a Button instance. + let icon = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 24, "height": 24, "name": "Icon"}))); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 8, "height": 8, "parent": icon.0})); + let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon.0]}))); + let button = idv(&ex(&mut s, "frame.create", json!({"x": 100, "y": 200, "width": 80, "height": 40, "name": "Button"}))); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 80, "height": 40, "parent": button.0})); + ex(&mut s, "instance.create", json!({"component": icon.0, "parent": button.0, "x": 4, "y": 4})); + let button = idv(&ex(&mut s, "component.create", json!({"ids": [button.0]}))); + let i = idv(&ex(&mut s, "instance.create", json!({"component": button.0, "x": 300, "y": 200}))); + let (layer, nested, deep) = { + let d = s.doc().unwrap(); + let kids = |id: NodeId| d.node(id).unwrap().children.clone(); + let nested = kids(i).into_iter().find(|k| matches!(d.node(*k).unwrap().kind, NodeKind::Instance { .. })).unwrap(); + let layer = kids(i).into_iter().find(|k| *k != nested).unwrap(); + (layer, nested, kids(nested)[0]) + }; + let targets = [placed.0, i.0, layer.0, nested.0, deep.0]; + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": targets})); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": targets, "field": "stroke"})); + let d = s.doc().unwrap(); + assert!(d.node(deep).unwrap().styles.fill.is_some() && !d.node(deep).unwrap().bound.is_empty(), "the nested layer took both"); + ex(&mut s, "style.detach", json!({"ids": targets, "which": "fill"})); + ex(&mut s, "variable.bind", json!({"ids": targets, "field": "stroke"})); + assert_eq!(counts(&s), ((0, 0), (0, 0))); + // The same on a plain layer counts. + let plain = rect(&mut s, 600); + ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [plain.0]})); + ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [plain.0], "field": "stroke"})); + ex(&mut s, "style.detach", json!({"ids": [plain.0], "which": "fill"})); + ex(&mut s, "variable.bind", json!({"ids": [plain.0], "field": "stroke"})); + assert_eq!(counts(&s), ((1, 1), (1, 1))); +} + #[test] fn only_the_detach_buttons_detach() { let (mut s, lib, _) = user(); From 2b175686ba290bcb64b158945f7e353b92e74168 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 19:16:42 +0700 Subject: [PATCH 097/129] M3: Show usage's answer is drawn by its own function, tested --- crates/ui-egui/src/panels/assets_panel.rs | 22 +++++--- crates/ui-egui/src/usage_summary_tests.rs | 63 ++++++++++++++++++++++- 2 files changed, 75 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index 9d58a81c5..9ee6c0dfe 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -1008,10 +1008,16 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { }); app.run_background(&ui.ctx().clone(), USAGE, json!({"days": period.unwrap_or(days)}), done); } - let Some(v) = shown else { - ui.add_space(8.0); - return; - }; + match shown { + Some(v) => usage_answer(ui, w, usage_id, &v), + None => ui.add_space(8.0), + } +} + +/// Show usage's answer `v`: what uses the library, the period's insertions and detachments and +/// the rows of the list chosen (the choice kept with `id`). +pub(crate) fn usage_answer(ui: &mut Ui, w: f32, id: Id, v: &Value) { + let days = v["days"].as_u64().unwrap_or(USAGE_PERIODS[0].0); let files = v["files"].as_array().map_or(0, Vec::len); let instances = v["instances"].as_u64().unwrap_or(0); let known = v["detachesKnown"].as_bool().unwrap_or(false); @@ -1020,11 +1026,11 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { if !known { hint(ui, tr("This server doesn't count detached instances")); } - let Some(kind) = usage_kind(ui, w, usage_id, &v) else { + let Some(kind) = usage_kind(ui, w, id, v) else { ui.add_space(8.0); return; }; - if let Some((i, d)) = period_totals(&v, kind) { + if let Some((i, d)) = period_totals(v, kind) { let label = USAGE_PERIODS.iter().find(|p| p.0 == days).map_or(USAGE_PERIODS[0].2, |p| p.2); let counts = trf("{insertions} · {detachments}", &[("insertions", &inserted_n(i)), ("detachments", &detached_n(d))]); hint(ui, &trf("{period}: {counts}", &[("period", &tr(label)), ("counts", &counts)])); @@ -1035,9 +1041,9 @@ fn usage(app: &mut FigApp, ui: &mut Ui, w: f32, link: &str) { hint(ui, tr("Nothing counted yet")); } if kind == "components" { - component_rows(ui, w, &v, known); + component_rows(ui, w, v, known); } else { - asset_rows(ui, w, &v, kind); + asset_rows(ui, w, v, kind); } ui.add_space(8.0); } diff --git a/crates/ui-egui/src/usage_summary_tests.rs b/crates/ui-egui/src/usage_summary_tests.rs index 4a512cc85..e9ce53fb9 100644 --- a/crates/ui-egui/src/usage_summary_tests.rs +++ b/crates/ui-egui/src/usage_summary_tests.rs @@ -1,9 +1,11 @@ //! Show usage's period line sums the list the Type choice shows, so it never reads 0 above a list -//! with counts, and a server that doesn't count a kind says so for that kind alone. +//! with counts, and a server that doesn't count a kind says so for that kind alone. The answer draws +//! its totals, its period and the rows of the list chosen. use serde_json::json; -use crate::panels::assets_panel::period_totals; +use crate::live_tests::{flat, has_text}; +use crate::panels::assets_panel::{period_totals, usage_answer}; #[test] fn the_period_line_sums_the_list_shown() { @@ -28,3 +30,60 @@ fn a_server_that_doesnt_count_a_kind_has_no_totals_for_it() { assert_eq!(period_totals(&v, "styles"), None, "a server from before them"); assert_eq!(period_totals(&json!({}), "components"), None); } + +/// The texts Show usage draws for the answer `v` with the Type choice at `kind` (0 components, +/// 1 styles, 2 variables). +fn drawn(v: &serde_json::Value, kind: usize) -> Vec { + let ctx = egui::Context::default(); + let id = egui::Id::new("usage"); + ctx.data_mut(|d| d.insert_temp(id.with("kind"), kind)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| usage_answer(ui, 600.0, id, v)); + out.textures_delta.clear(); + flat(&out.shapes) +} + +#[test] +fn show_usage_draws_the_totals_the_period_and_the_list_chosen() { + let v = json!({ + "days": 90, + "files": [{}, {}], + "instances": 5, + "detachesKnown": true, + "detached": 3, + "actionsKnown": true, + "assetActionsKnown": true, + "assetsKnown": true, + "components": [ + {"name": "Button", "instances": 4, "files": 2, "detached": 2, "insertions": 6, "detachments": 2}, + {"name": "Gone", "instances": 0, "files": 0, "detached": 3}, + ], + "styles": [{"name": "Brand", "layers": 7, "files": 3, "insertions": 2, "detachments": 0}], + "variables": [], + }); + let components = drawn(&v, 0); + for text in [ + "Used in 2 files · 5 instances · 3 detached", + "Past 90 days: 6 inserted · 2 detached", + "4 instances in 2 files · 2 detached · 6 inserted", + "3 detached", + ] { + assert!(has_text(&components, text), "{text}"); + } + let styles = drawn(&v, 1); + assert!(has_text(&styles, "Past 90 days: 2 inserted · 0 detached")); + assert!(has_text(&styles, "7 layers in 3 files · 2 inserted")); + assert!(has_text(&drawn(&v, 2), "Nothing counted yet"), "an empty list says so"); +} + +#[test] +fn show_usage_from_an_older_server_says_what_it_doesnt_count() { + let shapes = drawn(&json!({"files": [{}, {}], "instances": 5, "components": []}), 0); + for text in [ + "Used in 2 files · 5 instances", + "This server doesn't count detached instances", + "This server doesn't count styles and variables", + "This server doesn't count insertions", + ] { + assert!(has_text(&shapes, text), "{text}"); + } +} From 9e45db68859a0709b64cf93fb43994f7fcab1503 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:06:35 +0700 Subject: [PATCH 098/129] Keep asset-action peaks when usage rows evict, and report every count CodeRabbit's majors on #1735: evicting a file from the capped usage list dropped asset_peaks, so a later identical report was counted twice. Retention now includes asset_updated, and the file just heard from is kept even when timestamps tie. The document keeps up to 1000 asset counts, but each wire message is still capped at 250, so reports are sent in batches an older server will accept. Tests: evicting_capped_usage_rows_keeps_asset_peaks_so_a_repeat_report_is_not_counted_twice and asset_action_reports_cover_every_count_past_the_message_cap. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- .../src/library_assets_tests.rs | 36 +++++++++++++++++- apps/figcraft-server/src/store.rs | 5 ++- apps/figcraft-server/src/store/library.rs | 18 +++++++-- crates/engine/src/assets/library_server.rs | 38 ++++++++++++++++--- .../engine/src/library_asset_counts_tests.rs | 33 +++++++++++++++- 5 files changed, 118 insertions(+), 12 deletions(-) diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index 5941e4980..d5d6744e9 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -5,12 +5,15 @@ use std::time::{Duration, Instant}; -use figcraft_collab::message::{Access, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg}; +use figcraft_collab::message::{ + Access, AssetActions, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg, Usage, +}; use figcraft_collab_net::Invite; use figcraft_doc::NodeId; use figcraft_engine::Session; use serde_json::{Value, json}; +use crate::store::{MAX_USERS, Store}; use crate::test_util::{Raw, TempDir, config, publish, session}; fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { @@ -185,3 +188,34 @@ fn inserts_and_detaches_count_per_style_and_variable_in_the_period() { assert_eq!(u["variables"][0]["insertions"], 1, "{u}"); server.stop(); } + +#[test] +fn evicting_capped_usage_rows_keeps_asset_peaks_so_a_repeat_report_is_not_counted_twice() { + let dir = TempDir::new("library-asset-peaks-evict"); + let cfg = config(dir.path()); + let mut server = crate::start(&cfg).unwrap(); + let addr = server.addr(); + let mut a = session("Ada"); + let r = rect(&mut a, 0); + ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0})); + let p = publish(&mut a, dir.path(), addr); + ex(&mut a, "library.publishToServer", json!({})); + let file = Invite::parse(&p.edit).unwrap().file; + server.stop(); + drop(server); + + let mut store = Store::open(dir.path(), cfg.store()).unwrap(); + for i in 0..MAX_USERS { + store.report_usage(&file, Usage { file: format!("Old{i}"), components: Vec::new() }).unwrap(); + } + let actions = AssetActions { file: "Kept".into(), inserted: vec![("Brand".into(), 2)], detached: Vec::new() }; + store.report_asset_actions(&file, actions.clone()).unwrap(); + // One more usage-only file would evict "Kept" if asset activity did not count for retention. + store.report_usage(&file, Usage { file: "Extra".into(), components: Vec::new() }).unwrap(); + store.report_asset_actions(&file, actions).unwrap(); + let weeks = store.library_asset_actions(&file).unwrap(); + let brand: Vec<_> = weeks.iter().filter(|w| w.component == "Brand").collect(); + assert_eq!(brand.len(), 1, "{weeks:?}"); + assert_eq!(brand[0].insertions, 2, "lost peaks would grow the same totals again: {weeks:?}"); + assert_eq!(brand[0].detachments, 0, "{weeks:?}"); +} diff --git a/apps/figcraft-server/src/store.rs b/apps/figcraft-server/src/store.rs index fbf4bc2db..d75a24f1b 100644 --- a/apps/figcraft-server/src/store.rs +++ b/apps/figcraft-server/src/store.rs @@ -103,7 +103,7 @@ pub const NO_PUBLIC_LIBRARY: &str = "on this public server only files published /// Most files whose usage of one library is kept (the least recently changed go first), and most /// components one file's report keeps. -const MAX_USERS: usize = 200; +pub(crate) const MAX_USERS: usize = 200; const MAX_REPORTED: usize = 1_000; /// Largest `usage.json` (and `actions.json`) read. const MAX_USAGE_FILE: u64 = 16 << 20; @@ -325,6 +325,9 @@ struct UsageEntry { variables: Vec<(String, u32)>, #[serde(default, skip_serializing_if = "Vec::is_empty")] asset_peaks: Vec<(String, u32, u32)>, + /// When this file last reported style or variable insertions or detachments (seconds since 1970, UTC). + #[serde(default, skip_serializing_if = "is_zero")] + asset_updated: u64, } fn is_zero(n: &u64) -> bool { diff --git a/apps/figcraft-server/src/store/library.rs b/apps/figcraft-server/src/store/library.rs index 10337a451..4cb32f4e6 100644 --- a/apps/figcraft-server/src/store/library.rs +++ b/apps/figcraft-server/src/store/library.rs @@ -256,7 +256,13 @@ impl Store { let mut grown = Vec::new(); self.report(file, &actions.file, known_assets(counts), |e, counts| { grown = grow(&mut e.asset_peaks, &counts, kind, |_| 0); - !grown.is_empty() + if grown.is_empty() { + return false; + } + // Heard from for retention: evicting the row would drop asset_peaks, the + // baseline grow uses so a later identical report is not counted twice. + e.asset_updated = now(); + true })?; if let (false, Some(u)) = (grown.is_empty(), self.usage.get_mut(file)) { add_to_week(&mut u.asset_weeks, &grown, kind, now()); @@ -329,7 +335,7 @@ impl Store { let at = match u.list.iter().position(|e| e.usage.file == name) { Some(at) => at, None => { - u.list.push(UsageEntry { usage: Usage { file: name, components: Vec::new() }, ..UsageEntry::default() }); + u.list.push(UsageEntry { usage: Usage { file: name.clone(), components: Vec::new() }, ..UsageEntry::default() }); u.list.len() - 1 } }; @@ -338,7 +344,13 @@ impl Store { return Ok(()); } if u.list.len() > MAX_USERS { - u.list.sort_by_key(|e| std::cmp::Reverse(e.updated.max(e.detached_updated))); + // The file just heard from stays, even when several share a timestamp (now() is + // seconds). Asset-action reports use asset_updated so their peaks are not dropped + // in favour of a usage-only row from the same second. + u.list.sort_by_key(|e| { + let recent = e.usage.file == name; + std::cmp::Reverse((e.updated.max(e.detached_updated).max(e.asset_updated), recent)) + }); u.list.truncate(MAX_USERS); } u.dirty = true; diff --git a/crates/engine/src/assets/library_server.rs b/crates/engine/src/assets/library_server.rs index 3d42e7c98..f8ddf0e50 100644 --- a/crates/engine/src/assets/library_server.rs +++ b/crates/engine/src/assets/library_server.rs @@ -124,14 +124,42 @@ pub fn asset_usage(doc: &Document, library: &str) -> Option { } /// How many times `doc` has inserted and detached `library`'s styles and variables, its totals; -/// `None` when it has done neither. +/// `None` when it has done neither. Every count the document keeps is included (up to +/// [`figcraft_doc::MAX_DETACH_COUNTS`]); the wire message is capped at [`MAX_ASSET_USAGE`], so +/// [`asset_action_reports`] splits them into batches an older server still accepts. pub fn asset_actions(doc: &Document, library: &str) -> Option { let counts: Vec<_> = doc.libraries.asset_counts.iter().filter(|c| c.library == library).collect(); - let totals = - |n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).take(MAX_ASSET_USAGE).collect(); + let totals = |n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).collect(); (!counts.is_empty()).then(|| AssetActions { file: doc.name.clone(), inserted: totals(|c| c.inserted), detached: totals(|c| c.detached) }) } +/// Reports for the server, each with at most [`MAX_ASSET_USAGE`] inserted and detached counts. +pub fn asset_action_reports(doc: &Document, library: &str) -> Vec { + let Some(full) = asset_actions(doc, library) else { return Vec::new() }; + chunk_asset_actions(full) +} + +fn chunk_asset_actions(actions: AssetActions) -> Vec { + let AssetActions { file, inserted, detached } = actions; + if inserted.is_empty() && detached.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + let mut i = 0; + let mut d = 0; + loop { + let ins: Vec<_> = inserted.get(i..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect(); + let det: Vec<_> = detached.get(d..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect(); + if ins.is_empty() && det.is_empty() { + break; + } + i += ins.len(); + d += det.len(); + out.push(AssetActions { file: file.clone(), inserted: ins, detached: det }); + } + out +} + /// `counts`, the most used first, at most [`MAX_ASSET_USAGE`]. fn most_used(counts: BTreeMap<&str, u32>) -> Vec<(String, u32)> { let mut list: Vec<(String, u32)> = counts.into_iter().map(|(k, n)| (k.to_string(), n)).collect(); @@ -279,10 +307,10 @@ impl Session { detached(doc, &l.id).map(LibraryReq::ReportDetached), inserted(doc, &l.id).map(LibraryReq::ReportInserted), asset_usage(doc, &l.id).map(LibraryReq::ReportAssets), - asset_actions(doc, &l.id).map(LibraryReq::ReportAssetActions), ]; + let asset_reports = asset_action_reports(doc, &l.id).into_iter().map(LibraryReq::ReportAssetActions); let fetch = LibraryReq::Fetch { have, usage: Some(usage(doc, &l.id)) }; - std::iter::once(fetch).chain(reports.into_iter().flatten()).map(|req| (l.path.clone(), req)) + std::iter::once(fetch).chain(reports.into_iter().flatten()).chain(asset_reports).map(|req| (l.path.clone(), req)) }) .collect(); // Confined to automation roots, nothing reaches a server (#1095). diff --git a/crates/engine/src/library_asset_counts_tests.rs b/crates/engine/src/library_asset_counts_tests.rs index e0f4fe456..1eb3a1403 100644 --- a/crates/engine/src/library_asset_counts_tests.rs +++ b/crates/engine/src/library_asset_counts_tests.rs @@ -7,8 +7,9 @@ use serde_json::{Value, json}; use crate::Session; use crate::components::tests::{ex, idv}; -use crate::library_server::asset_actions; -use figcraft_doc::{AssetCount, NodeId, NodeKind, PublishedLibrary}; +use crate::library_server::{asset_action_reports, asset_actions}; +use figcraft_collab::message::MAX_ASSET_USAGE; +use figcraft_doc::{AssetCount, Document, NodeId, NodeKind, PublishedLibrary}; /// A file with a published library holding a paint style, a colour variable and a Card, and a /// second file that uses it: the second session, the library's id and its keys. @@ -152,3 +153,31 @@ fn local_styles_count_nothing_and_undo_takes_a_count_back() { ex(&mut s, "edit.undo", json!({})); assert_eq!(counts(&s).0, (0, 0)); } + +#[test] +fn asset_action_reports_cover_every_count_past_the_message_cap() { + let mut doc = Document::new("File"); + let n = MAX_ASSET_USAGE + 1; + let libraries = std::sync::Arc::make_mut(&mut doc.libraries); + for i in 0..n { + let key = format!("s{i}"); + libraries.count_asset("Lib", &key, false, 1); + libraries.count_asset("Lib", &key, true, 2); + } + // Another library's counts do not belong in these reports. + libraries.count_asset("Other", "x", false, 9); + libraries.count_asset("Other", "x", true, 9); + + let full = asset_actions(&doc, "Lib").unwrap(); + assert_eq!(full.inserted.len(), n, "the document's counts are not truncated"); + assert_eq!(full.detached.len(), n); + + let reports = asset_action_reports(&doc, "Lib"); + assert!(reports.len() >= 2, "one message cannot carry {n} counts"); + assert!(reports.iter().all(|r| r.file == "File" && r.inserted.len() <= MAX_ASSET_USAGE && r.detached.len() <= MAX_ASSET_USAGE)); + let inserted: Vec<_> = reports.iter().flat_map(|r| r.inserted.iter().cloned()).collect(); + let detached: Vec<_> = reports.iter().flat_map(|r| r.detached.iter().cloned()).collect(); + assert_eq!(inserted, full.inserted); + assert_eq!(detached, full.detached); + assert!(asset_action_reports(&doc, "Missing").is_empty()); +} From 23e5877e6bd4a9c451e227dbcc16a322c427c07f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:04:11 +0700 Subject: [PATCH 099/129] Wait for style layers to clear, and cover a full asset-peak cap inserts_and_detaches_count_per_style_and_variable_in_the_period returned as soon as detachments reached 2, then asserted layers == 0. Asset-action reports can arrive before the usage snapshot, so CI saw layers still at 1. The wait now requires both. Sonar on the same-repo vehicle (#2451) evaluated the coverage gate at 79.74% of 232 new lines (one line under 80%). A unit test covers grow's branch that drops a new key once peaks are already at MAX_REPORTED. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- apps/figcraft-server/src/library_assets_tests.rs | 2 +- apps/figcraft-server/src/store/library.rs | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index d5d6744e9..9cbf24e1d 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -183,7 +183,7 @@ fn inserts_and_detaches_count_per_style_and_variable_in_the_period() { ex(&mut b, "edit.undo", json!({})); ex(&mut b, "edit.redo", json!({})); ex(&mut b, "style.detach", json!({"ids": [one.0], "which": "fill"})); - let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2); + let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2 && u["styles"][0]["layers"] == 0); assert_eq!((u["styles"][0]["insertions"].clone(), u["styles"][0]["layers"].clone()), (json!(2), json!(0)), "{u}"); assert_eq!(u["variables"][0]["insertions"], 1, "{u}"); server.stop(); diff --git a/apps/figcraft-server/src/store/library.rs b/apps/figcraft-server/src/store/library.rs index 4cb32f4e6..42d284b04 100644 --- a/apps/figcraft-server/src/store/library.rs +++ b/apps/figcraft-server/src/store/library.rs @@ -390,3 +390,17 @@ fn library_file(dir: &Path, version: u64) -> PathBuf { let path = dir.join(library_name(version)); if path.exists() { path } else { dir.join(LIBRARY) } } + +#[cfg(test)] +mod grow_tests { + use super::*; + + #[test] + fn a_new_key_is_dropped_once_peaks_are_full() { + let mut peaks: Vec<(u32, u32, u32)> = (0..MAX_REPORTED as u32).map(|i| (i, 1, 0)).collect(); + let grown = grow(&mut peaks, &[(MAX_REPORTED as u32, 3)], Count::Inserted, |_| 0); + assert!(grown.is_empty(), "a key past the cap must not start a peak or count as growth"); + assert_eq!(peaks.len(), MAX_REPORTED); + assert!(peaks.iter().all(|p| p.0 < MAX_REPORTED as u32)); + } +} From 6c63071241a78c807d71b23e4a155123cb9ed22b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 19:27:59 +0700 Subject: [PATCH 100/129] M3: the Show usage test keys its choice with Id::unique --- crates/ui-egui/src/usage_summary_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/usage_summary_tests.rs b/crates/ui-egui/src/usage_summary_tests.rs index e9ce53fb9..72941743f 100644 --- a/crates/ui-egui/src/usage_summary_tests.rs +++ b/crates/ui-egui/src/usage_summary_tests.rs @@ -35,7 +35,7 @@ fn a_server_that_doesnt_count_a_kind_has_no_totals_for_it() { /// 1 styles, 2 variables). fn drawn(v: &serde_json::Value, kind: usize) -> Vec { let ctx = egui::Context::default(); - let id = egui::Id::new("usage"); + let id = egui::Id::unique("usage_summary_tests"); ctx.data_mut(|d| d.insert_temp(id.with("kind"), kind)); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| usage_answer(ui, 600.0, id, v)); out.textures_delta.clear(); From e94ecfca7a2ebc6c427a0ed58ed5f9e082298906 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 20:44:01 -0500 Subject: [PATCH 101/129] M5: the arrow keys move a layer along the canvas axes inside a rotated parent (#2372) transform.nudge applied the step in the parent's local space, so Down inside a frame rotated 90 degrees moved the layer sideways. The step is now turned into the parent's space first (falling back to the plain step if the parent's transform is not invertible). Auto layout children are unchanged. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/edit.rs | 2 + .../cmd/edit/nudge_rotated_parent_tests.rs | 92 +++++++++++++++++++ crates/engine/src/cmd/edit/select.rs | 13 ++- docs/ui-parity.md | 3 +- 4 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00a237c21..cc2391ef5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -20,6 +20,8 @@ mod select; mod vector_clipboard; pub use vector_clipboard::clipboard_svg; #[cfg(test)] +mod nudge_rotated_parent_tests; +#[cfg(test)] mod vector_clipboard_tests; pub(crate) use clipboard::apply_copied_props; diff --git a/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs b/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs new file mode 100644 index 000000000..f1ab3ba48 --- /dev/null +++ b/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs @@ -0,0 +1,92 @@ +//! The arrow keys move a layer along the canvas axes whatever its parent's rotation (#2372). + +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; +use figcraft_doc::NodeId; + +fn frame(s: &mut Session, parent: Option, w: f64, h: f64, rotation: f64) -> NodeId { + let mut p = json!({"x": 10, "y": 20, "width": w, "height": h}); + if let (Some(par), Some(o)) = (parent, p.as_object_mut()) { + o.insert("parent".into(), json!(par)); + } + let r = s.execute("frame.create", &p).unwrap(); + let id = id_of(&r["id"]).unwrap(); + if rotation != 0.0 { + s.execute("node.set", &json!({"id": id, "props": {"rotation": rotation}})).unwrap(); + } + id +} + +fn world(s: &Session, id: NodeId) -> (f64, f64) { + let c = s.doc().unwrap().world_transform(id).as_coeffs(); + (c[4], c[5]) +} + +fn nudge(s: &mut Session, id: NodeId, params: Value) { + let mut p = params; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([id])); + } + s.execute("transform.nudge", &p).unwrap(); +} + +fn moved_by(s: &mut Session, id: NodeId, params: Value) -> (f64, f64) { + let before = world(s, id); + nudge(s, id, params); + let after = world(s, id); + (after.0 - before.0, after.1 - before.1) +} + +fn near(got: (f64, f64), want: (f64, f64)) { + assert!((got.0 - want.0).abs() < 1e-6 && (got.1 - want.1).abs() < 1e-6, "moved by {got:?}, wanted {want:?}"); +} + +fn in_rotated(rotation: f64) -> (Session, NodeId) { + let mut s = Session::new(); + let outer = frame(&mut s, None, 400.0, 300.0, rotation); + let child = frame(&mut s, Some(outer), 100.0, 80.0, 0.0); + (s, child) +} + +#[test] +fn down_moves_a_child_of_a_frame_rotated_90_down_the_canvas() { + let (mut s, child) = in_rotated(90.0); + let k = s.prefs.nudge_small; + near(moved_by(&mut s, child, json!({"dx": 0, "dy": 1})), (0.0, k)); +} + +#[test] +fn right_moves_it_right_on_the_canvas() { + let (mut s, child) = in_rotated(90.0); + let k = s.prefs.nudge_small; + near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0})), (k, 0.0)); +} + +#[test] +fn a_big_nudge_in_a_rotated_parent_follows_the_canvas_too() { + let (mut s, child) = in_rotated(90.0); + let k = s.prefs.nudge_big; + near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0, "big": true})), (k, 0.0)); +} + +#[test] +fn a_child_of_an_unrotated_frame_moves_as_before() { + let (mut s, child) = in_rotated(0.0); + let k = s.prefs.nudge_small; + let local_before = s.doc().unwrap().node(child).unwrap().transform.as_coeffs(); + near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0})), (k, 0.0)); + let local_after = s.doc().unwrap().node(child).unwrap().transform.as_coeffs(); + assert!((local_after[4] - local_before[4] - k).abs() < 1e-6 && (local_after[5] - local_before[5]).abs() < 1e-6); +} + +#[test] +fn a_layer_two_rotated_frames_deep_moves_along_the_canvas() { + let mut s = Session::new(); + let outer = frame(&mut s, None, 500.0, 400.0, 45.0); + let inner = frame(&mut s, Some(outer), 300.0, 200.0, 30.0); + let child = frame(&mut s, Some(inner), 100.0, 80.0, 0.0); + let k = s.prefs.nudge_small; + near(moved_by(&mut s, child, json!({"dx": 0, "dy": 1})), (0.0, k)); +} diff --git a/crates/engine/src/cmd/edit/select.rs b/crates/engine/src/cmd/edit/select.rs index 17f80af6b..9d8fa822e 100644 --- a/crates/engine/src/cmd/edit/select.rs +++ b/crates/engine/src/cmd/edit/select.rs @@ -184,8 +184,19 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { // Children in an auto layout flow move one place instead (see `al_keys`). for i in &ids { if crate::al_keys::flowing_parent(doc, *i).is_none() && (dx, dy) != (0.0, 0.0) { + // The step is along the canvas axes; the layer's transform is in its parent's space. + let (lx, ly) = match doc.node(*i).and_then(|n| n.parent) { + Some(par) => { + let inv = doc.world_transform(par).inverse(); + let o = inv * figcraft_geom::Point::new(0.0, 0.0); + let q = inv * figcraft_geom::Point::new(dx, dy); + let (lx, ly) = (q.x - o.x, q.y - o.y); + if lx.is_finite() && ly.is_finite() { (lx, ly) } else { (dx, dy) } + } + None => (dx, dy), + }; let n = doc.get_mut(*i)?; - n.transform = Affine::translate((dx, dy)) * n.transform; + n.transform = Affine::translate((lx, ly)) * n.transform; changed = true; } } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index dac2960bd..f05c3e244 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -71,7 +71,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's move and rotation (the move of its centre in the page frame, then the turn about the copy's own centre, or the selection's centre for several layers; not its size), also after a Duplicate whose copy was moved, as long as the copies stay selected and the selection hasn't changed (measured in Figma's web app, 2026-11-12); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | Scale tool (K): handles about the opposite handle, live factor, panel | done | Dragging a handle ignores the origin grid and pivots on the opposite handle's point (the opposite corner, or the opposite edge's middle for an edge, which scales both ways), with Alt on the centre; the origin grid (`tool.scaleAnchor`) starts at the centre and sets only what the Scale field and the W and H fields keep fixed (W and H with a non-centre origin are unmeasured). Measured in Figma's web app, 2026-11-09. Tests: `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`. Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin, which starts at the centre, as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | -| Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | +| Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children; the arrow keys move along the canvas axes inside a rotated parent, as in Figma, #2372 | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | | Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) | @@ -210,6 +210,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | | 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when neither `ids` nor `id` is given (either one targets layers), as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | | 2026-11-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | From 4806b95e8e529b7a77a26a04364dffcc35971645 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 14 Nov 2026 22:52:12 -0500 Subject: [PATCH 102/129] M5: a drag from a child of a selected frame moves the frame (#2360) A press on a layer inside a selected one now drags the selection, and a click without a drag selects that layer (also in Dev Mode and for a single selection), as in Figma. Cmd/Ctrl, Shift and layers outside the selection are unchanged. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/canvas/tools.rs | 4 +- crates/engine/src/canvas/tools/drag.rs | 18 +++-- crates/engine/src/canvas/tools/draw.rs | 5 +- .../engine/src/selection_behaviour_tests.rs | 68 +++++++++++++++++++ docs/ui-parity.md | 3 +- 5 files changed, 89 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index 86418b814..c60483fcf 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -444,8 +444,8 @@ pub(crate) enum Gesture { /// A Shift-press on this selected layer: it leaves the selection on release, unless the /// press became a drag. deselect: Option, - /// A press on one layer of a multi-selection that keeps the selection to drag it all: a - /// release without a drag selects just this layer. + /// A press on one layer of a multi-selection, or on a layer inside a selected one, that + /// keeps the selection to drag it all: a release without a drag selects just this layer. keep: Option, }, Resize { diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index b41613f97..9e19c57f2 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -92,8 +92,14 @@ impl Session { // inside, the frame or canvas behind it, or a layer stacked below the selected layer the // press is in) drags the selection. In a gap between selected layers, what's there is hit. let in_own_box = |s: NodeId| selection_box(&doc, &[s]).is_some_and(|q| in_quad(&q, ev.p())); + // A press on a layer inside a selected one (a child of a selected frame) drags the + // selection too, and a click selects that layer; Cmd/Ctrl keeps the deep pick. + let in_selected = |t: NodeId| sel.iter().any(|s| *s != t && doc.is_ancestor(*s, t)); let behind_sel = |t: Option| { - t.is_none_or(|t| sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s))))) + t.is_none_or(|t| { + (!ev.cmd && in_selected(t)) + || sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s)))) + }) }; // What the press hit (a label or a painted layer): a click that doesn't become a drag // selects just it. A press that reaches nothing above the selection uses the selection as @@ -116,8 +122,12 @@ impl Session { let without_target = || sel.iter().copied().filter(|x| *x != target).collect::>(); // A release without a drag narrows the selection to the layer the press hit. A // selected frame's name label sits outside the selection bounds, so it counts too. - let keep = clicked - .filter(|c| (label.is_some() || in_sel_box) && !ev.cmd && (sel.contains(c) || sel.iter().any(|s| doc.is_ancestor(*s, *c)))); + // A layer inside a selected one counts as well: the press drags the selection, and + // a click selects that layer. + let keep = clicked.filter(|c| { + !ev.cmd + && (((label.is_some() || in_sel_box) && (sel.contains(c) || sel.iter().any(|s| doc.is_ancestor(*s, *c)))) || in_selected(*c)) + }); let new_sel = if keep.is_some() { sel.clone() } else if ev.shift && deselect.is_none() { @@ -135,7 +145,7 @@ impl Session { if !edits { if deselect.is_some() { self.set_selection(without_target()); - } else if let Some(k) = keep.filter(|_| sel.len() > 1) { + } else if let Some(k) = keep.filter(|k| sel.as_slice() != [*k]) { self.set_selection(vec![k]); } return Ok(()); diff --git a/crates/engine/src/canvas/tools/draw.rs b/crates/engine/src/canvas/tools/draw.rs index 43110681c..dea4aab47 100644 --- a/crates/engine/src/canvas/tools/draw.rs +++ b/crates/engine/src/canvas/tools/draw.rs @@ -176,10 +176,11 @@ impl Session { let sel = self.selection().into_iter().filter(|x| *x != d).collect(); self.set_selection(sel); } else if let Some(k) = keep { - // A click (not a drag) on one layer of a multi-selection selects just it. + // A click (not a drag) on one layer of a multi-selection, or on a layer + // inside a selected one, selects just it. let doc = self.doc()?.clone(); let sel = self.selection(); - if sel.len() > 1 && (sel.contains(&k) || sel.iter().any(|s| doc.is_ancestor(*s, k))) { + if sel.as_slice() != [k] && (sel.contains(&k) || sel.iter().any(|s| doc.is_ancestor(*s, k))) { self.set_selection(vec![k]); } } diff --git a/crates/engine/src/selection_behaviour_tests.rs b/crates/engine/src/selection_behaviour_tests.rs index 0499996ff..b2aed52cf 100644 --- a/crates/engine/src/selection_behaviour_tests.rs +++ b/crates/engine/src/selection_behaviour_tests.rs @@ -562,3 +562,71 @@ fn shift_click_takes_a_layer_out_where_nothing_can_move() { s.pointer(&ev(PointerKind::Up, 520.0, 20.0, SHIFT)).unwrap(); assert_eq!(s.selection(), vec![k.empty], "Shift-click still takes the layer out"); } + +/// A top-level 300 x 300 frame with a filled 100 x 100 rectangle at (50, 50) and a nested frame +/// at (200, 200 80x80) holding a rectangle at (210, 210 40x40). +fn frame_with_child(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let f = id(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 300}))); + let c = id(&ex(s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100, "parent": f}))); + let n = id(&ex(s, "frame.create", json!({"x": 180, "y": 180, "width": 100, "height": 100, "parent": f}))); + let gc = id(&ex(s, "shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 40, "parent": n}))); + (f, c, n, gc) +} + +#[test] +fn a_drag_from_a_child_of_a_selected_frame_moves_the_frame() { + let mut s = Session::new(); + let (f, c, _n, gc) = frame_with_child(&mut s); + let sib = id(&ex(&mut s, "shape.rectangle", json!({"x": 90, "y": 90, "width": 30, "height": 30}))); + let at = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap().origin(); + let local = |s: &Session, i: NodeId| { + let d = s.doc().unwrap(); + let n = d.node(i).unwrap(); + let c = n.transform.as_coeffs(); + (c[4], c[5]) + }; + let c_local = local(&s, c); + // (selection before, press point, modifiers, selection after, the layers that move by (10, 10), derivation) + let rows: Vec<(Vec, (f64, f64), Mods, Vec, Vec, &str)> = vec![ + (vec![f], (60.0, 60.0), NONE, vec![f], vec![f, c, gc], "a drag from a child of the selected frame moves the frame"), + (vec![f], (220.0, 220.0), NONE, vec![f], vec![f, c, gc], "a drag from a grandchild moves the top-level frame"), + (vec![], (60.0, 60.0), NONE, vec![c], vec![c], "with nothing selected the child is picked and moved"), + (vec![f], (60.0, 60.0), CMD, vec![c], vec![c], "Cmd picks the deepest layer and moves it"), + (vec![f], (100.0, 100.0), NONE, vec![sib], vec![sib], "a sibling painted above the frame takes the press"), + ]; + for (before, from, m, after, moved, why) in rows { + let all = [f, c, gc, sib]; + let home: Vec = all.iter().map(|i| at(&s, *i)).collect(); + ex(&mut s, "select.set", json!({"ids": before})); + drag(&mut s, from, (from.0 + 10.0, from.1 + 10.0), m); + assert_eq!(sorted(s.selection()), sorted(after), "{why}"); + for (i, h) in all.iter().zip(&home) { + // The frame carries its children: they move in the world, not in their local space. + let d = if moved.contains(i) { 10.0 } else { 0.0 }; + assert_eq!(at(&s, *i), Point::new(h.x + d, h.y + d), "{why}"); + } + assert_eq!(local(&s, c), if moved == [c] { (c_local.0 + 10.0, c_local.1 + 10.0) } else { c_local }, "{why}: the child's local position"); + assert!(s.undo().unwrap(), "{why}: one undo step"); + for (i, h) in all.iter().zip(&home) { + assert_eq!(at(&s, *i), *h, "{why}: undo restores"); + } + } +} + +#[test] +fn a_click_on_a_child_of_a_selected_frame_selects_the_child() { + let mut s = Session::new(); + let (f, c, n, gc) = frame_with_child(&mut s); + let home = s.doc().unwrap().world_bounds(c).unwrap().origin(); + for (p, want) in [((60.0, 60.0), c), ((190.0, 190.0), n)] { + ex(&mut s, "select.set", json!({"ids": [f]})); + click(&mut s, p.0, p.1, NONE); + assert_eq!(s.selection(), vec![want], "a click selects the layer inside the selected frame"); + } + assert_eq!(s.doc().unwrap().world_bounds(c).unwrap().origin(), home, "nothing moved"); + let _ = gc; + s.tool.dev_mode = true; + ex(&mut s, "select.set", json!({"ids": [f]})); + click(&mut s, 60.0, 60.0, NONE); + assert_eq!(s.selection(), vec![c], "in Dev Mode too"); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f05c3e244..94ad714ae 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -57,7 +57,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Item | Status | Notes | |---|---|---| -| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to the dominant axis with no 45° snap (#498; `shift_drag_moves_the_selection`; measured in Figma's web app, 2026-11-08); a marquee selects the top-level layers it touches, by the box and a rotated shape by its outline (rectangle and ellipse measured, the other shapes by the same code); a partly covered top-level frame or section gives the layers in it the marquee touches, an enclosed one is selected itself, an empty frame on touch; a drag from a frame's background selects that frame only when the marquee also takes another top-level frame (then whole), and also takes what it touches outside it; selecting a frame whole keeps the marquee at the top level (a partly covered frame then comes whole too); locked and hidden layers are skipped (`marquee_behaviour_tests`, `selection_behaviour_tests`; measured in Figma's web app, 2026-11-11; Shift and Cmd/Ctrl marquees not measured) (a locked layer selected from the panel ignores the arrow keys and the nudge commands; its properties still edit; measured in Figma's web app, 2026-11-10) | +| Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to the dominant axis with no 45° snap (#498; `shift_drag_moves_the_selection`; measured in Figma's web app, 2026-11-08); with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child, as in Figma (#2360; `a_drag_from_a_child_of_a_selected_frame_moves_the_frame`, `a_click_on_a_child_of_a_selected_frame_selects_the_child`); a marquee selects the top-level layers it touches, by the box and a rotated shape by its outline (rectangle and ellipse measured, the other shapes by the same code); a partly covered top-level frame or section gives the layers in it the marquee touches, an enclosed one is selected itself, an empty frame on touch; a drag from a frame's background selects that frame only when the marquee also takes another top-level frame (then whole), and also takes what it touches outside it; selecting a frame whole keeps the marquee at the top level (a partly covered frame then comes whole too); locked and hidden layers are skipped (`marquee_behaviour_tests`, `selection_behaviour_tests`; measured in Figma's web app, 2026-11-11; Shift and Cmd/Ctrl marquees not measured) (a locked layer selected from the panel ignores the arrow keys and the nudge commands; its properties still edit; measured in Figma's web app, 2026-11-10) | | Deep select (Cmd/Ctrl-click, Cmd/Ctrl-marquee) | done | | | Select layer menu (every layer under the click) | done | shown only with more than one layer under the pointer; locked layers are listed with a padlock in the leading column and are selectable there, as Lock and unlock layers' note says (measured in Figma's web app, 2026-11-10; the "more than one layer" gate was measured on a single locked layer only) (`select_layer_marks_locked_layers_with_a_padlock_and_picks_them`, `select_layer_needs_more_than_one_layer_under_the_pointer`) | | Escape with layers selected | done | clears the selection at once, whatever the nesting; it never selects the parent. Measured in the Figma web app (2026-11-08) with a rectangle in a group in a frame, selected from the canvas (a double-click into the group), from the Layers panel, and after Tab moved the selection to its sibling: one Escape selects nothing, a second leaves nothing selected. Escape still leaves text and vector editing, ends gestures and the pen first, and ends the focus view once nothing or the focused frame is selected (`selection_behaviour_tests`, `devfocus_tests`) | @@ -210,6 +210,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-19 | patch | M5, #2360: with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child (a press on a layer inside a selected one drags the selection), as in Figma; Cmd/Ctrl, Shift and layers outside the frame are unchanged. | | 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | | 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when neither `ids` nor `id` is given (either one targets layers), as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | From 944fe8616cdd7c79f99e014d1bbaaac58869941d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 00:35:17 -0500 Subject: [PATCH 103/129] M5: the frame_with_child doc comment gives the layers' real positions (#2377 review) The nested frame is 100 x 100 at (180, 180) and its rectangle is 40 x 40 at (200, 200), as the code creates them. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- crates/engine/src/selection_behaviour_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/selection_behaviour_tests.rs b/crates/engine/src/selection_behaviour_tests.rs index b2aed52cf..62583e695 100644 --- a/crates/engine/src/selection_behaviour_tests.rs +++ b/crates/engine/src/selection_behaviour_tests.rs @@ -563,8 +563,8 @@ fn shift_click_takes_a_layer_out_where_nothing_can_move() { assert_eq!(s.selection(), vec![k.empty], "Shift-click still takes the layer out"); } -/// A top-level 300 x 300 frame with a filled 100 x 100 rectangle at (50, 50) and a nested frame -/// at (200, 200 80x80) holding a rectangle at (210, 210 40x40). +/// A top-level 300 x 300 frame with a filled 100 x 100 rectangle at (50, 50) and a nested 100 x 100 +/// frame at (180, 180) holding a 40 x 40 rectangle at (200, 200). fn frame_with_child(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { let f = id(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 300}))); let c = id(&ex(s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100, "parent": f}))); From b5d43a7de2a2af6b79f9bf5077180721bc476b85 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 00:47:42 +0700 Subject: [PATCH 104/129] M8: a Shift-click range in the Layers panel keeps a frame, not its covered children, as in Figma (#2330) The change from #2330 by @TrevorBrown-dev, as one commit. --- crates/ui-egui/src/layers_behaviour_tests.rs | 58 ++++++++++++++++++++ crates/ui-egui/src/layers_keys_tests.rs | 36 ++++++++++++ crates/ui-egui/src/panels/layers.rs | 18 +++++- docs/ui-parity.md | 5 +- 4 files changed, 113 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/layers_behaviour_tests.rs b/crates/ui-egui/src/layers_behaviour_tests.rs index d5dff9bd0..2bd7aabe8 100644 --- a/crates/ui-egui/src/layers_behaviour_tests.rs +++ b/crates/ui-egui/src/layers_behaviour_tests.rs @@ -951,6 +951,64 @@ fn search_fields_keep_their_text_in_the_middle() { assert!(off < 1.0, "Search assets is {off} points off the middle"); } +#[test] +fn a_shift_range_across_frames_keeps_a_frame_and_not_its_covered_children() { + let mut s = Session::new(); + let frame1 = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "name": "Frame 1"})).unwrap()); + let rect2 = rect(&mut s, "Rect 2", 0.0, Some(frame1)); + let rect3 = rect(&mut s, "Rect 3", 30.0, Some(frame1)); + let frame2 = id(s.execute("frame.create", &json!({"x": 200, "y": 0, "width": 100, "height": 100, "name": "Frame 2"})).unwrap()); + let rect4 = rect(&mut s, "Rect 4", 0.0, Some(frame2)); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.extend([frame1, frame2]); + u.frame(vec![]); + let (row4, row2) = (u.row_at(rect4), u.row_at(rect2)); + click(&mut u, row4, Modifiers::NONE); + click(&mut u, row2, SHIFT); + assert_eq!( + sorted(u.app.session.selection()), + sorted(vec![rect4, frame1]), + "the range keeps Frame 1 and drops its covered children {rect3:?} and {rect2:?}" + ); +} + +#[test] +fn a_second_shift_click_after_a_reverse_cross_frame_range_extends_the_range() { + let mut s = Session::new(); + let frame1 = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "name": "Frame 1"})).unwrap()); + let rect2 = rect(&mut s, "Rect 2", 0.0, Some(frame1)); + let rect3 = rect(&mut s, "Rect 3", 30.0, Some(frame1)); + let frame2 = id(s.execute("frame.create", &json!({"x": 200, "y": 0, "width": 100, "height": 100, "name": "Frame 2"})).unwrap()); + let rect4 = rect(&mut s, "Rect 4", 0.0, Some(frame2)); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.extend([frame1, frame2]); + u.frame(vec![]); + let (row2, row4, row3) = (u.row_at(rect2), u.row_at(rect4), u.row_at(rect3)); + click(&mut u, row2, Modifiers::NONE); + click(&mut u, row4, SHIFT); + assert_eq!(sorted(u.app.session.selection()), sorted(vec![rect4, frame1])); + // Rows run Frame 2, Rect 4, Frame 1, Rect 3, Rect 2: the range from Rect 2 to Rect 3 is those two. + click(&mut u, row3, SHIFT); + assert_eq!(sorted(u.app.session.selection()), sorted(vec![rect3, rect2]), "the range still runs from Rect 2, not a toggle"); +} + +#[test] +fn a_shift_range_inside_one_frame_is_unchanged() { + let mut s = Session::new(); + let frame = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "name": "F"})).unwrap()); + let kids = [0.0, 30.0, 60.0].map(|x| rect(&mut s, "k", x, Some(frame))); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.insert(frame); + u.frame(vec![]); + let (first, last) = (u.row_at(kids[0]), u.row_at(kids[2])); + click(&mut u, first, Modifiers::NONE); + click(&mut u, last, SHIFT); + assert_eq!(sorted(u.app.session.selection()), sorted(kids.to_vec())); +} + /// The centre of `id`'s icon, a top-level row: the row's left edge is the first point from the /// left at which the pointer is over it, and the icon's centre is 8 (margin) + 4 + 22 points /// further right. diff --git a/crates/ui-egui/src/layers_keys_tests.rs b/crates/ui-egui/src/layers_keys_tests.rs index 63f8ce74c..cb9fe17cc 100644 --- a/crates/ui-egui/src/layers_keys_tests.rs +++ b/crates/ui-egui/src/layers_keys_tests.rs @@ -76,6 +76,42 @@ fn up_and_down_walk_the_rows_and_shift_extends() { assert_eq!(doc.node(c).unwrap().transform.translation().x, 200.0); } +#[test] +fn a_keyboard_shift_range_keeps_an_anchor_covered_by_a_selected_frame() { + let mut s = Session::new(); + let frame1 = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100, "name": "Frame 1"})).unwrap()); + let mk = |s: &mut Session, name: &str, parent: NodeId| { + id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20, "parent": parent, "props": {"name": name}})).unwrap()) + }; + let rect2 = mk(&mut s, "Rect 2", frame1); + let rect3 = mk(&mut s, "Rect 3", frame1); + let frame2 = id(s.execute("frame.create", &json!({"x": 200, "y": 0, "width": 100, "height": 100, "name": "Frame 2"})).unwrap()); + let rect4 = mk(&mut s, "Rect 4", frame2); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.expanded.extend([frame1, frame2]); + u.frame(vec![]); + click_row(&mut u, rect2); + let p4 = u.row_at(rect4); + let shift = Modifiers { shift: true, ..Default::default() }; + u.frame_with(vec![Event::PointerMoved(p4)], shift); + let button = |pressed| Event::PointerButton { pos: p4, button: egui::PointerButton::Primary, pressed, modifiers: shift }; + u.frame_with(vec![button(true)], shift); + u.frame_with(vec![button(false)], shift); + let mut got = sel(&u); + got.sort(); + let mut want = vec![rect4, frame1]; + want.sort(); + assert_eq!(got, want, "the pointer range keeps the frame"); + // Rows: Frame 2, Rect 4, Frame 1, Rect 3, Rect 2. Shift+Down runs from Rect 2 (the anchor). + key(&mut u, Key::ArrowDown, true); + let mut got = sel(&u); + got.sort(); + let mut want = vec![rect3, rect2]; + want.sort(); + assert_eq!(got, want, "the keyboard range extends from Rect 2's row, not from the current row"); +} + #[test] fn left_and_right_open_close_and_move_between_levels() { let (mut u, _, frame, child, _) = setup(); diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index b7fe8c308..72c916391 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -637,6 +637,14 @@ fn matching(doc: &Document, id: NodeId, q: &str, out: &mut Vec) { } } +/// The range anchor while it is still part of the selection: selected itself, or covered by a +/// selected frame (a range across parents selects the frame and not its children). +fn live_anchor(app: &FigApp, sel: &[NodeId]) -> Option { + let a = app.ui.layer_anchor?; + let covered = || app.session.ds().is_ok_and(|ds| ds.doc.ancestors(a).iter().any(|p| sel.contains(p))); + (sel.contains(&a) || covered()).then_some(a) +} + /// Arrow keys while the layers panel has the keyboard: Up/Down select the row above or below /// (Shift extends the range from the anchor), Left collapses a row or goes to its parent, Right /// expands a row or goes to its first child. Returns whether the key was used. @@ -669,7 +677,7 @@ pub(crate) fn key_nav(app: &mut FigApp, key: egui::Key, shift: bool) -> bool { let Some((j, next)) = j.and_then(|j| rows.get(j).map(|r| (j, r.id))) else { return true }; if shift { // The rows from the anchor to the new one, with the moving end last. - let anchor = app.ui.layer_anchor.filter(|a| sel.contains(a)).unwrap_or(cur); + let anchor = live_anchor(app, &sel).unwrap_or(cur); let a = rows.iter().position(|r| r.id == anchor).unwrap_or(i); let ids: Vec = if a <= j { rows.get(a..=j).unwrap_or_default().iter().map(|r| r.id).collect() @@ -909,7 +917,8 @@ fn select_clicked(app: &mut FigApp, rows: &[Row], sel: &[NodeId], id: NodeId, m: app.ui.pages_focus = None; let order: Vec = rows.iter().map(|r| r.id).collect(); let pos = |x: NodeId| order.iter().position(|o| *o == x); - let anchor = app.ui.layer_anchor.filter(|a| sel.contains(a)).and_then(pos); + let live = live_anchor(app, sel); + let anchor = live.and_then(pos); if m.shift && let (Some(ai), Some(bi)) = (anchor, pos(id)) { @@ -921,6 +930,11 @@ fn select_clicked(app: &mut FigApp, rows: &[Row], sel: &[NodeId], id: NodeId, m: s.push(*x); } } + // A layer under a selected ancestor is covered by it, not a member of its own. + if let Ok(ds) = app.session.ds() { + let all = s.clone(); + s.retain(|x| !ds.doc.ancestors(*x).iter().any(|a| all.contains(a))); + } app.run("select.set", json!({"ids": s})); } else if m.shift || m.command { let mut s = sel.to_vec(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 94ad714ae..6a9d101fd 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-17 · **Change:** minor (points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -43,7 +43,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Item | Status | Notes | |---|---|---| -| Rows: click, Shift-click range, Cmd/Ctrl-click toggle; the selection follows on the canvas and a canvas selection is revealed | done | `layers_behaviour_tests`; selected hierarchies share a continuous background with rounded outer corners, including nested selections | +| Rows: click, Shift-click range, Cmd/Ctrl-click toggle; the selection follows on the canvas and a canvas selection is revealed | done | `layers_behaviour_tests`; a range across parents keeps a frame and not its covered children (Rect 4 then Shift on Rect 2 in another frame gives Rect 4 and the frame between; measured in Figma's web app, 2026-11-12); selected hierarchies share a continuous background with rounded outer corners, including nested selections | | Expand and collapse: Alt-click opens or closes everything inside; Collapse layers (Alt+L) keeps the way to the selection open | done | Alt-click pinned (the documentation is silent) | | Drag to reorder and into frames, groups and auto layout: insertion line, spring-loaded open, several layers together, Escape cancels | done | several layers dropped together land together (they split apart before); instances and a layer's own children refuse drops | | Eye and padlock: click, or drag across rows to set several in one step; layers in a locked frame show a faint padlock | done | the toggles no longer vanish under the pointer (clicks on them could miss) (a child's padlock can't be toggled while its parent is locked) | @@ -210,6 +210,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-19 | patch | M8: a Shift-click range in the Layers panel keeps a frame and not its covered children: a range across parents selects a frame whose row is inside it, and drops the rows under that frame, as measured in Figma's web app on 2026-11-12 (Rect 4 in one frame, Shift-click Rect 2 in another: Rect 4 and the second frame, 2 selected); a range among siblings is unchanged; Cmd with Shift reduces the combined set the same way, not measured | | 2026-11-19 | patch | M5, #2360: with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child (a press on a layer inside a selected one drags the selection), as in Figma; Cmd/Ctrl, Shift and layers outside the frame are unchanged. | | 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | | 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | From 64b0b4510881d7e7a28e65a8f6b7e10d521ccedd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 00:56:10 +0700 Subject: [PATCH 105/129] M4: Outline stroke on a text without a stroke outlines its glyphs (#2405) A fill-only text was left as it was: Outline stroke skipped every layer without a visible stroke. A text now flattens in place into a vector of its glyphs, filled as the text was and keeping its colour style, constraints, visibility and lock; a text with no glyphs stays. --- crates/engine/src/cmd/structure.rs | 15 ++++++++++++ crates/engine/src/shapes_behaviour_tests.rs | 26 +++++++++++++++++++++ docs/target-app-parity.md | 3 ++- 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index c73ef8b21..bf1c92d2f 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -577,6 +577,21 @@ fn outline_stroke(s: &mut Session, p: &Value) -> Result { let doc = s.doc_mut()?; let n = doc.get(i)?.clone(); if !n.has_visible_stroke() { + // A text without a stroke outlines its glyphs (#2405): flattened in place, filled as it was. + if matches!(n.kind, NodeKind::Text(_)) { + match flatten(s, &json!({"ids": [i]})) { + Ok(r) => { + if let Some(v) = id_of(&r["id"]) { + let o = s.doc_mut()?.get_mut(v)?; + (o.styles.fill, o.styles.effect) = (n.styles.fill, n.styles.effect); + (o.constraints, o.child_layout, o.visible, o.locked) = (n.constraints, n.child_layout, n.visible, n.locked); + out.push(v); + } + } + Err(EngineError::Disabled(..)) => {} // no glyphs (empty, or no font): nothing to outline + Err(e) => return Err(e), + } + } continue; } let closed = figcraft_doc::geometry::is_closed(&n); diff --git a/crates/engine/src/shapes_behaviour_tests.rs b/crates/engine/src/shapes_behaviour_tests.rs index f6611f991..4fad347ac 100644 --- a/crates/engine/src/shapes_behaviour_tests.rs +++ b/crates/engine/src/shapes_behaviour_tests.rs @@ -571,6 +571,32 @@ fn outline_stroke_outlines_every_selected_layer() { } } +#[test] +fn outline_stroke_outlines_a_text_without_a_stroke() { + // Fixed (#2405): a fill-only text was left as it was; its glyphs become a vector filled as the text was. + let mut s = Session::new(); + let t = create(&mut s, "text.create", json!({"text": "OPEN", "x": 10, "y": 20})); + ex(&mut s, "style.create", json!({"type": "paint", "name": "Ink", "value": ["#112233"]})); + ex(&mut s, "style.apply", json!({"ids": [t], "style": "Ink"})); + let before = node(&s, t); + let page = s.page().unwrap(); + let out = ex(&mut s, "vector.outlineStroke", json!({"ids": [t]})); + let ids: Vec = out["ids"].as_array().unwrap().iter().filter_map(id_of).collect(); + // Without a font nothing lays out, so there is nothing to outline (CI has no fonts). + if !figcraft_text::layout_node(&before).is_some_and(|(l, _)| !l.glyphs.is_empty()) { + assert!(ids.is_empty() && matches!(node(&s, t).kind, NodeKind::Text(_)), "no glyphs: the text stays: {out}"); + return; + } + assert_eq!(ids.len(), 1, "one outline: {out}"); + let v = node(&s, ids[0]); + assert!(matches!(v.kind, NodeKind::Vector { .. }), "the glyphs become a vector"); + assert_eq!((&v.fills, v.styles.fill), (&before.fills, before.styles.fill), "filled as the text was, colour style too"); + assert_eq!(s.doc().unwrap().node(page).unwrap().children, ids, "the outline stands in for the text"); + assert_eq!(s.selection(), ids, "the outline is selected"); + s.undo().unwrap(); + assert!(matches!(node(&s, t).kind, NodeKind::Text(_)), "undo brings the text back"); +} + #[test] fn node_set_non_numeric_miter_smoothing_paragraph_is_an_error() { let mut s = Session::new(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 941f4b807..409efe1d7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-19 | patch | M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it (while the view moves, a detail is drawn only while it covers the whole view: past it the capped texture shows alone, with no sharp edge across the view, until the view settles); transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when no `ids` are given, as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | From 98c47144586d11fe257d6a2913681c4251fea5ff Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 01:19:39 +0700 Subject: [PATCH 106/129] M8: dragging near the canvas edge pans the view, as in Figma (#2015) (#2104) The change from #2104 by @TrevorBrown-dev, as one commit. --- crates/engine/src/canvas/tools.rs | 13 + crates/engine/src/lib.rs | 2 + crates/engine/src/view_autopan_tests.rs | 50 ++++ crates/engine/src/view_state.rs | 38 +++ crates/ui-egui/src/canvas.rs | 1 + crates/ui-egui/src/canvas/autopan.rs | 100 +++++++ crates/ui-egui/src/canvas/input.rs | 12 + crates/ui-egui/src/canvas/proto_canvas.rs | 80 +++++- crates/ui-egui/src/canvas_autopan_tests.rs | 301 +++++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + docs/prototyping-parity.md | 5 +- docs/ui-parity.md | 4 +- 12 files changed, 599 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/view_autopan_tests.rs create mode 100644 crates/ui-egui/src/canvas/autopan.rs create mode 100644 crates/ui-egui/src/canvas_autopan_tests.rs diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index c60483fcf..458845f65 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -623,4 +623,17 @@ impl ToolState { pub fn busy(&self) -> bool { !matches!(self.gesture, Gesture::None) } + + /// Whether the gesture under way pans the canvas when the pointer holds near the viewport's + /// edge (#2015): moving layers once past the drag slop, the selection box once it has grown + /// past it, and drawing a shape once it exists. Resizing, rotating, panning, text and vector + /// edits don't. `zoom`: screen px per page unit. + pub fn autopans(&self, zoom: f64) -> bool { + match &self.gesture { + Gesture::Move { moved, .. } => *moved, + Gesture::Marquee { .. } => self.overlay.marquee.is_some_and(|[x0, y0, x1, y1]| ((x1 - x0).hypot(y1 - y0) * zoom) >= DRAG_SLOP_PX), + Gesture::Draw { id, .. } => id.is_some(), + _ => false, + } + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6fe5633ad..82cef7891 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -658,6 +658,8 @@ mod version_preview_tests; #[cfg(test)] mod version_tests; #[cfg(test)] +mod view_autopan_tests; +#[cfg(test)] mod view_behaviour_tests; #[cfg(test)] mod vote_history_tests; diff --git a/crates/engine/src/view_autopan_tests.rs b/crates/engine/src/view_autopan_tests.rs new file mode 100644 index 000000000..0737850ca --- /dev/null +++ b/crates/engine/src/view_autopan_tests.rs @@ -0,0 +1,50 @@ +//! Canvas auto-pan (#2015): the speed a drag held near the viewport's edge pans the view at, as +//! measured in the incumbent at 100% (screen px per second, `40 x (15 - d)` clamped to 0..600, +//! `d` the pointer's distance inside the edge), and which gestures pan. + +use crate::ViewState; + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn the_speed_grows_40_px_per_second_for_each_px_inside_the_zone_up_to_600() { + for (d, speed) in [(40.0, 0.0), (25.0, 0.0), (15.0, 0.0), (12.0, 120.0), (8.0, 280.0), (2.0, 520.0), (0.0, 600.0), (-30.0, 600.0)] { + assert!(near(ViewState::autopan_speed(d), speed), "{d} px inside: {} px/s, wanted {speed}", ViewState::autopan_speed(d)); + } + assert_eq!(ViewState::autopan_speed(f64::NAN), 0.0); + assert!(near(ViewState::autopan_speed(f64::NEG_INFINITY), 600.0)); +} + +#[test] +fn the_velocity_points_toward_the_near_edge_on_each_axis() { + let (w, h) = (1000.0, 600.0); + let v = |x: f64, y: f64| ViewState::autopan_velocity(x, y, w, h); + assert_eq!(v(500.0, 300.0), (0.0, 0.0), "the middle"); + assert_eq!(v(1000.0 - 2.0, 300.0), (520.0, 0.0), "right edge: right"); + assert_eq!(v(2.0, 300.0), (-520.0, 0.0), "left edge: left"); + assert_eq!(v(500.0, 600.0 - 8.0), (0.0, 280.0), "bottom edge: down"); + assert_eq!(v(500.0, 12.0), (0.0, -120.0), "top edge: up"); + assert_eq!(v(1000.0 - 40.0, 300.0), (0.0, 0.0), "40 px in: none"); + assert_eq!(v(1000.0 - 15.0, 300.0), (0.0, 0.0), "15 px in: none"); + // A corner pans on both axes, each by its own distance. + assert_eq!(v(1000.0 - 12.0, 600.0 - 2.0), (120.0, 520.0)); + assert_eq!(v(8.0, 2.0), (-280.0, -520.0)); + // Past the edge, or outside the viewport altogether: the cap. + assert_eq!(v(1030.0, 300.0), (600.0, 0.0)); + assert_eq!(v(-500.0, 900.0), (-600.0, 600.0)); +} + +#[test] +fn panning_moves_the_view_by_the_velocity_in_screen_px_at_any_zoom() { + for zoom in [0.25, 1.0, 4.0] { + let mut v = ViewState { vw: 1000.0, vh: 600.0, zoom, cx: 50.0, cy: 70.0, ..Default::default() }; + assert!(v.autopan(998.0, 300.0, 0.5), "in the zone"); + assert!(near((v.cx - 50.0) * zoom, 260.0), "{zoom}: 520 px/s for half a second is 260 screen px"); + assert_eq!(v.cy, 70.0); + assert!(!v.autopan(500.0, 300.0, 0.5), "out of the zone"); + assert!(!v.autopan(998.0, 300.0, 0.0), "no time"); + assert!(!v.autopan(998.0, 300.0, f64::NAN), "no time"); + } +} diff --git a/crates/engine/src/view_state.rs b/crates/engine/src/view_state.rs index 8a8cc8a01..bff3195e2 100644 --- a/crates/engine/src/view_state.rs +++ b/crates/engine/src/view_state.rs @@ -159,6 +159,44 @@ impl ViewState { self.cx -= dx / z; self.cy -= dy / z; } + /// How near the viewport's edge a drag must hold the pointer to pan the canvas (screen px). + pub const AUTOPAN_ZONE_PX: f64 = 15.0; + /// Auto-pan speed gained for each pixel the pointer is closer to the edge (screen px/s). + pub const AUTOPAN_RATE: f64 = 40.0; + /// The fastest auto-pan, at the edge and beyond it (screen px/s). + pub const AUTOPAN_MAX: f64 = 600.0; + /// The speed (screen px/s) the canvas pans toward an edge while a drag holds the pointer + /// `d` px inside it (negative: outside), as measured in the incumbent: `40 x (15 - d)` + /// clamped to 0..600 (#2015). Constant while the pointer stays put, at every zoom. + pub fn autopan_speed(d: f64) -> f64 { + if d.is_nan() { + return 0.0; + } + (Self::AUTOPAN_RATE * (Self::AUTOPAN_ZONE_PX - d)).clamp(0.0, Self::AUTOPAN_MAX) + } + /// The velocity (screen px/s, positive: right and down) the canvas auto-pans at while a drag + /// holds the pointer at (`px`, `py`) in a viewport of `width` x `height` (both from its + /// top-left corner): toward each edge the pointer is near, each axis by its own distance, so a + /// corner pans both ways. + pub fn autopan_velocity(px: f64, py: f64, width: f64, height: f64) -> (f64, f64) { + let axis = |p: f64, len: f64| { + if p < len / 2.0 { -Self::autopan_speed(p) } else { Self::autopan_speed(len - p) } + }; + (axis(px, width), axis(py, height)) + } + /// Auto-pan for `dt` seconds with the pointer at (`px`, `py`) from the viewport's top-left + /// corner: moves the view by the velocity ([`Self::autopan_velocity`]) in screen px. True when + /// it moved. + pub fn autopan(&mut self, px: f64, py: f64, dt: f64) -> bool { + let (vx, vy) = Self::autopan_velocity(px, py, self.vw, self.vh); + if !(dt.is_finite() && dt > 0.0) || (vx == 0.0 && vy == 0.0) { + return false; + } + let z = self.zoom.max(1e-6); + self.cx += vx * dt / z; + self.cy += vy * dt / z; + true + } pub fn page_to_screen(&self, x: f64, y: f64) -> (f64, f64) { let (ox, oy) = self.origin(); ((x - ox) * self.zoom, (y - oy) * self.zoom) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5de28c832..3d3f05082 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -14,6 +14,7 @@ use crate::i18n::{tr, trf, trn}; use crate::render_worker::{Done, Job, Worker}; use crate::theme::{COMPONENT, Tokens, doc_c32, regular, semibold}; +mod autopan; mod background; mod builder; mod input; diff --git a/crates/ui-egui/src/canvas/autopan.rs b/crates/ui-egui/src/canvas/autopan.rs new file mode 100644 index 000000000..e95f8451d --- /dev/null +++ b/crates/ui-egui/src/canvas/autopan.rs @@ -0,0 +1,100 @@ +//! Auto-pan: a drag that holds the pointer near the canvas's edge, or past it, pans the view +//! toward it, steadily while the pointer stays still (#2015). The rule lives in +//! [`figcraft_engine::ViewState::autopan_velocity`]; this applies it once a frame. + +use egui::{Context, Pos2}; + +use crate::FigApp; + +/// The longest frame the pan counts, so a stall doesn't jump the view. +const MAX_DT: f64 = 0.1; + +/// Pan the view for this frame with a drag's pointer at screen point `pos`. True when it panned, +/// so the caller feeds the engine the pointer again: the dragged layer, box, shape or connection +/// follows the document point now under it. Asks for another frame while the pointer is in the +/// zone, so the pan goes on when nothing else moves. +pub(crate) fn pan(app: &mut FigApp, ctx: &Context, pos: Pos2) -> bool { + let dt = f64::from(ctx.input(|i| i.unstable_dt)).clamp(0.0, MAX_DT); + let min = app.canvas.rect.min; + let (px, py) = (f64::from(pos.x - min.x), f64::from(pos.y - min.y)); + let Ok(ds) = app.session.ds_mut() else { return false }; + let (vx, vy) = figcraft_engine::ViewState::autopan_velocity(px, py, ds.view.vw, ds.view.vh); + if vx == 0.0 && vy == 0.0 { + return false; + } + // In the zone: the next frame pans too, even if the pointer never moves. + ctx.request_repaint(); + if !ds.view.autopan(px, py, dt) { + return false; + } + ds.revision += 1; + true +} + +/// The drag under way pans at the edge: a primary drag of the Move or a drawing tool that +/// [`figcraft_engine::tools::ToolState::autopans`] allows, with no text being edited. Not while a +/// manual pan (Space, or the middle button) is under way: that pan can carry the pointer off the +/// canvas, where the view must follow the pointer, not the edge speed. +pub(super) fn wanted(app: &FigApp, ctx: &Context) -> bool { + let Ok(ds) = app.session.ds() else { return false }; + app.canvas.dragging + && app.canvas.middle_pan.is_none() + && ds.text_edit.is_none() + && ds.vector_edit.is_none() + && ctx.input(|i| i.pointer.primary_down()) + && app.session.tool.autopans(ds.view.zoom) +} + +#[cfg(test)] +mod tests { + use egui::{Context, Pos2, RawInput, pos2}; + use figcraft_engine::Session; + + use crate::layers_drag_tests::Ui; + + /// Whether [`super::pan`] alone, with the pointer at `pos`, asks for the next frame. Run in a + /// context of its own, after a few settling passes, so nothing else in the app asks for one. + fn asks(u: &mut Ui, pos: Pos2) -> bool { + let ctx = Context::default(); + for _ in 0..3 { + ctx.run_ui(RawInput::default(), |_| {}).textures_delta.clear(); + } + let mut out = ctx.run_ui(RawInput::default(), |ui| { + super::pan(&mut u.app, ui.ctx(), pos); + }); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()) + } + + #[test] + fn a_manual_pan_during_a_drag_does_not_autopan() { + let mut u = Ui::new(Session::new()); + let id = figcraft_engine::params::id_of( + &u.app.session.execute("shape.rectangle", &serde_json::json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap()["id"], + ); + assert!(id.is_some()); + u.frame(vec![]); + u.frame(vec![]); + let r = u.app.canvas.rect; + let p = u.app.to_screen(50.0, 25.0); + u.button(p, true); + u.frame(vec![egui::Event::PointerMoved(p + egui::vec2(12.0, 0.0))]); + let off = pos2(r.max.x + 30.0, p.y); + u.frame(vec![egui::Event::PointerMoved(off)]); + assert!(super::wanted(&u.app, &u.ctx), "a plain layer drag held off the canvas autopans"); + u.app.canvas.middle_pan = Some((off, 0.0, 0.0)); + assert!(!super::wanted(&u.app, &u.ctx), "a pan begun during the drag is the user's to steer"); + } + + #[test] + fn in_the_zone_it_asks_for_the_next_frame_and_outside_it_does_not() { + let mut u = Ui::new(Session::new()); + u.frame(vec![]); + u.frame(vec![]); + let r = u.app.canvas.rect; + assert!(asks(&mut u, pos2(r.max.x - 2.0, r.center().y)), "2 px inside the right edge"); + assert!(asks(&mut u, pos2(r.min.x - 20.0, r.max.y + 20.0)), "past the bottom-left corner"); + assert!(!asks(&mut u, r.center()), "the middle of the canvas"); + assert!(!asks(&mut u, pos2(r.max.x - 40.0, r.center().y)), "40 px inside the edge"); + } +} diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 1b177693e..1360697d8 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -226,6 +226,13 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo send(app, PointerKind::Up, at, &mods); } } + // A drag held past the edge pans toward it, the layer or box going with the pointer. + if super::autopan::wanted(app, &ctx) + && let Some(at) = ctx.input(|i| i.pointer.latest_pos()) + && super::autopan::pan(app, &ctx, at) + { + send(app, PointerKind::Move, at, &mods); + } // Leaving the canvas: nothing is hovered there any more. if !app.canvas.dragging && std::mem::take(&mut app.canvas.hovering) { left(app); @@ -377,6 +384,11 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo if force.is_some() { app.canvas.pressure = force; } + // A drag held near the edge pans before the move goes out, so it lands on the document point + // now under the pointer (and the pan goes on while the pointer is still: it asks for frames). + if kind == Some(PointerKind::Move) && super::autopan::wanted(app, &ctx) { + super::autopan::pan(app, &ctx, pos); + } if let Some(k) = kind { let at = if matches!(k, PointerKind::Down) { press_pos.unwrap_or(pos) } else { pos }; send(app, k, at, &mods); diff --git a/crates/ui-egui/src/canvas/proto_canvas.rs b/crates/ui-egui/src/canvas/proto_canvas.rs index b30fc604b..140d690cd 100644 --- a/crates/ui-egui/src/canvas/proto_canvas.rs +++ b/crates/ui-egui/src/canvas/proto_canvas.rs @@ -18,7 +18,9 @@ const HANDLE_R: f32 = 7.0; #[derive(Clone, Copy)] struct Drag { source: NodeId, - from: Pos2, + /// Where the connection leaves the layer, on the page: the view pans under a drag at the + /// edge (#2015). + from: figcraft_geom::Point, pos: Pos2, } @@ -246,13 +248,14 @@ pub fn draw(app: &FigApp, painter: &egui::Painter) { } match dragging { Some(d) => { + let from = app.to_screen(d.from.x, d.from.y); if let Some(t) = target_at(app, doc, page, d.source, d.pos) && let Some(r) = screen_rect(app, doc, t.node()) { painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(2.0, crate::theme::canvas_accent(painter.ctx())), StrokeKind::Outside); } - let dx = ((d.pos.x - d.from.x).abs() * 0.5).max(30.0) * if d.pos.x >= d.from.x { 1.0 } else { -1.0 }; - let pts = [d.from, d.from + vec2(dx, 0.0), d.pos - vec2(dx, 0.0), d.pos]; + let dx = ((d.pos.x - from.x).abs() * 0.5).max(30.0) * if d.pos.x >= from.x { 1.0 } else { -1.0 }; + let pts = [from, from + vec2(dx, 0.0), d.pos - vec2(dx, 0.0), d.pos]; painter.add(egui::epaint::CubicBezierShape::from_points_stroke( pts, false, @@ -260,7 +263,7 @@ pub fn draw(app: &FigApp, painter: &egui::Painter) { Stroke::new(2.0, crate::theme::canvas_accent(painter.ctx())), )); arrow(painter, &pts, crate::theme::canvas_accent(painter.ctx())); - plus_handle(painter, d.from, true); + plus_handle(painter, from, true); } None => { if ds.text_edit.is_none() { @@ -298,10 +301,15 @@ pub fn input(app: &mut FigApp, ui: &egui::Ui, resp: &egui::Response) -> bool { let Ok(ds) = app.session.ds() else { return false }; let (doc, page, sel) = (ds.doc.clone(), ds.page, ds.selection.clone()); if let Some(mut d) = drag { - if let Some(p) = pos { + if let Some(p) = pos.or_else(|| ctx.input(|i| i.pointer.latest_pos())) { d.pos = p; } ctx.request_repaint(); + // Held near the edge of the canvas, or past it, the view pans toward it (#2015); the + // connection's end stays under the pointer, and its start stays on its layer. + if down && !released { + super::autopan::pan(app, &ctx, d.pos); + } if released || !down { ctx.data_mut(|m| m.remove::(drag_id())); let params = target_at(app, &doc, page, d.source, d.pos).map(|t| match t { @@ -331,7 +339,7 @@ pub fn input(app: &mut FigApp, ui: &egui::Ui, resp: &egui::Response) -> bool { return false; } if let Some((source, from)) = over_handle { - ctx.data_mut(|m| m.insert_temp(drag_id(), Drag { source, from, pos })); + ctx.data_mut(|m| m.insert_temp(drag_id(), Drag { source, from: app.to_page(from), pos })); return true; } let hit = noodles(app, &ctx, &doc, page) @@ -373,6 +381,66 @@ mod tests { u.button(at, false); } + /// A connection dragged out of a layer and held at the canvas's edge pans the view toward it + /// (520 px/s 2 px inside), so a frame off screen scrolls under the pointer and the link can + /// reach it (#2015). The connection keeps leaving its layer. + #[test] + fn a_connection_dragged_to_the_edge_pans_until_a_frame_off_screen_is_under_it() { + use egui::Event; + let mut s = figcraft_engine::Session::new(); + let a = s.execute("frame.create", &json!({"x": -300, "y": -100, "width": 200, "height": 150})).unwrap(); + let a = crate::present_tests::id(&a); + // Beyond the right edge of a 1440 x 900 screen at 100%. + let b = s.execute("frame.create", &json!({"x": 1500, "y": -200, "width": 400, "height": 400})).unwrap(); + let b = crate::present_tests::id(&b); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let mut u = crate::layers_drag_tests::Ui::new(s); + u.app.ui.right_tab = RightTab::Prototype; + { + let v = &mut u.app.session.ds_mut().unwrap().view; + v.zoom = 1.0; + v.cx = 0.0; + v.cy = 0.0; + } + u.frame(vec![]); + u.frame(vec![]); + let rect = u.app.canvas.rect; + let doc = u.app.session.doc().unwrap().clone(); + let (_, at) = *handles(&u.app, &doc, &[a]).first().unwrap(); + let start = u.app.to_page(at); + u.button(at, true); + let out = pos2(rect.max.x - 40.0, at.y); + u.frame(vec![Event::PointerMoved(out)]); + u.frame(vec![]); + assert_eq!(u.app.session.ds().unwrap().view.cx, 0.0, "40 px in: no pan"); + let edge = pos2(rect.max.x - 2.0, at.y); + u.frame(vec![Event::PointerMoved(edge)]); + let mut frames = 1; + let under_pointer = |u: &crate::layers_drag_tests::Ui| { + let doc = u.app.session.doc().unwrap().clone(); + frame_at(&u.app, &doc, u.app.session.ds().unwrap().page, edge) + }; + assert_eq!(under_pointer(&u), None, "nothing there yet"); + while under_pointer(&u) != Some(b) && frames < 600 { + u.frame(vec![]); + frames += 1; + } + let cx = u.app.session.ds().unwrap().view.cx; + assert!((cx - 520.0 * f64::from(frames) / 60.0).abs() < 1.0, "{frames} frames panned {cx}"); + // It still leaves the layer where it started, now pushed off to the left on screen. + let drag: Drag = u.ctx.data(|d| d.get_temp(drag_id())).expect("the drag goes on"); + assert_eq!(drag.from, start); + assert!(u.app.to_screen(start.x, start.y).x < at.x - 600.0); + u.button(edge, false); + let doc = u.app.session.doc().unwrap().clone(); + let links = doc.node(a).map(|n| n.interactions.clone()).unwrap_or_default(); + assert_eq!(links.len(), 1, "the link was made"); + assert!( + matches!(links[0].actions.as_slice(), [figcraft_doc::proto::Action::Navigate { dest, .. }] if *dest == b), + "to the frame that scrolled in" + ); + } + #[test] fn curves_leave_the_facing_side() { let a = Rect::from_min_size(pos2(0.0, 0.0), vec2(50.0, 20.0)); diff --git a/crates/ui-egui/src/canvas_autopan_tests.rs b/crates/ui-egui/src/canvas_autopan_tests.rs new file mode 100644 index 000000000..0670f05e4 --- /dev/null +++ b/crates/ui-egui/src/canvas_autopan_tests.rs @@ -0,0 +1,301 @@ +//! Canvas auto-pan (#2015), driven through egui headless at 60 frames per second: a drag that +//! holds the pointer within about 15 px of the canvas's edge, or past it, pans the view toward +//! it at `40 x (15 - d)` screen px per second (d: px inside the edge, at most 600), steadily while +//! the pointer stays still. It covers moving layers, the selection box and drawing a shape (the +//! prototype connection is in `proto_canvas`); resizing, rotating and every other drag leave the +//! view where it is. + +use egui::{Event, Pos2, pos2, vec2}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; + +/// One frame's length, in seconds. +const DT: f64 = 1.0 / 60.0; + +fn id(v: serde_json::Value) -> NodeId { + figcraft_engine::params::id_of(&v["id"]).unwrap() +} + +/// An empty file at 100%, centred on the page's origin, with the canvas laid out. +fn setup() -> Ui { + let mut u = Ui::new(Session::new()); + { + let v = &mut u.app.session.ds_mut().unwrap().view; + v.zoom = 1.0; + v.cx = 0.0; + v.cy = 0.0; + } + u.frame(vec![]); + u.frame(vec![]); + u +} + +fn run(u: &mut Ui, cmd: &str, params: serde_json::Value) -> serde_json::Value { + u.app.session.execute(cmd, ¶ms).unwrap() +} + +/// The view's centre, in page units. +fn centre(u: &Ui) -> (f64, f64) { + let v = &u.app.session.ds().unwrap().view; + (v.cx, v.cy) +} + +fn bounds_x0(u: &Ui, n: NodeId) -> f64 { + u.app.session.doc().unwrap().world_bounds(n).unwrap().x0 +} + +/// Move the pointer to `to` (button held) and hold it there for `frames` frames. +fn hold(u: &mut Ui, to: Pos2, frames: usize) { + u.frame(vec![Event::PointerMoved(to)]); + for _ in 1..frames { + u.frame(vec![]); + } +} + +fn release(u: &mut Ui, at: Pos2) { + u.button(at, false); +} + +/// A 100 x 50 rectangle in the middle of the view, nothing selected; its screen centre. +fn centred_rect(u: &mut Ui) -> (NodeId, Pos2) { + let r = id(run(u, "shape.rectangle", json!({"x": -50, "y": -25, "width": 100, "height": 50}))); + run(u, "select.none", json!({})); + u.frame(vec![]); + (r, u.app.canvas.rect.center()) +} + +/// Press on `p`, drag a little (past the slop) and settle. +fn pick_up(u: &mut Ui, p: Pos2) -> Pos2 { + u.button(p, true); + let moved = p + vec2(12.0, 0.0); + u.frame(vec![Event::PointerMoved(moved)]); + u.frame(vec![]); + moved +} + +#[test] +fn a_layer_held_2_px_inside_the_right_edge_pans_the_view_at_520_px_per_second_and_stays_under_the_pointer() { + let mut u = setup(); + let (r, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + // Out of the zone first (40 px in): no pan, however long. + let rect = u.app.canvas.rect; + let out = pos2(rect.max.x - 40.0, from.y); + hold(&mut u, out, 20); + assert_eq!(centre(&u), (0.0, 0.0), "40 px inside: no pan"); + let at = pos2(rect.max.x - 2.0, from.y); + let n = 30; + let (cx0, x0) = (centre(&u).0, bounds_x0(&u, r)); + let grab = x0 - u.app.to_page(out).x; + hold(&mut u, at, n); + let (cx1, x1) = (centre(&u).0, bounds_x0(&u, r)); + let pan = cx1 - cx0; + let want = 520.0 * n as f64 * DT; + assert!((pan - want).abs() < 0.5, "panned {pan} px for {n} frames, wanted {want}"); + assert_eq!(centre(&u).1, 0.0); + // The layer went with the pointer: the pointer's move into the zone plus the pan. + let went = x1 - x0; + assert!((went - (38.0 + pan)).abs() < 1.5, "the layer moved {went}, the pointer 38 and the view {pan}"); + let now = x1 - u.app.to_page(at).x; + assert!((now - grab).abs() < 1.5, "the layer stays under the pointer: {grab} then {now}"); + // Constant speed: the same again for the same time. + hold(&mut u, at, n); + assert!((centre(&u).0 - cx1 - want).abs() < 0.5, "no acceleration"); + // Back out of the zone it stops; so it does on release. + hold(&mut u, out, 10); + let stopped = centre(&u); + hold(&mut u, out, 10); + assert_eq!(centre(&u), stopped, "out of the zone"); + hold(&mut u, at, 3); + release(&mut u, at); + let done = centre(&u); + for _ in 0..10 { + u.frame(vec![]); + } + assert_eq!(centre(&u), done, "released"); + assert!(!u.app.session.tool.busy()); +} + +#[test] +fn the_speed_depends_on_the_distance_and_a_corner_pans_both_ways() { + let mut u = setup(); + let (_, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + let rect = u.app.canvas.rect; + // 12 px in: 120 px/s; 8 px: 280; past the edge: 600 (the pointer stays on the canvas). + for (d, speed) in [(12.0, 120.0), (8.0, 280.0), (0.0, 600.0)] { + hold(&mut u, pos2(rect.max.x - 40.0, from.y), 2); + let before = centre(&u).0; + hold(&mut u, pos2(rect.max.x - d, from.y), 60); + let pan = centre(&u).0 - before; + assert!((pan - speed).abs() < 3.0, "{d} px in: panned {pan} px in a second, wanted {speed}"); + } + // The bottom-left corner: down by its distance from the bottom, left by its from the left. + hold(&mut u, rect.center(), 2); + let (cx, cy) = centre(&u); + hold(&mut u, pos2(rect.min.x + 8.0, rect.max.y - 2.0), 30); + let (dx, dy) = (centre(&u).0 - cx, centre(&u).1 - cy); + assert!((dx + 280.0 / 2.0).abs() < 2.0, "left at 280 px/s for half a second: {dx}"); + assert!((dy - 520.0 / 2.0).abs() < 2.0, "down at 520 px/s for half a second: {dy}"); +} + +#[test] +fn a_selection_box_held_at_the_bottom_edge_pans_and_grows_over_what_scrolls_in() { + let mut u = setup(); + let below = f64::from(u.app.canvas.rect.height()) / 2.0 + 120.0; + let far = id(run(&mut u, "shape.rectangle", json!({"x": -40, "y": below, "width": 80, "height": 40}))); + run(&mut u, "select.none", json!({})); + u.frame(vec![]); + let rect = u.app.canvas.rect; + let press = rect.center() + vec2(-200.0, -100.0); + u.button(press, true); + let at = pos2(press.x + 250.0, rect.max.y - 2.0); + u.frame(vec![Event::PointerMoved(at)]); + assert!(u.app.session.selection().is_empty(), "not in the box yet"); + let box0 = u.app.session.tool.overlay.marquee.unwrap(); + let cy0 = centre(&u).1; + let n = 45; + for _ in 1..n { + u.frame(vec![]); + } + let pan = centre(&u).1 - cy0; + let want = 520.0 * (n - 1) as f64 * DT; + assert!((pan - want).abs() < 1.0, "panned {pan}, wanted {want}"); + let box1 = u.app.session.tool.overlay.marquee.unwrap(); + assert!((box1[3] - box0[3] - pan).abs() < 1.0, "the box's bottom followed the pointer: {box0:?} then {box1:?}"); + assert_eq!(u.app.session.selection(), vec![far], "the box reached the layer that scrolled in"); + release(&mut u, at); +} + +#[test] +fn a_press_that_has_not_become_a_drag_does_not_pan() { + let mut u = setup(); + let rect = u.app.canvas.rect; + // A click on the empty canvas right by the edge is not a drag. + let at = pos2(rect.max.x - 2.0, rect.center().y); + u.button(at, true); + for _ in 0..30 { + u.frame(vec![]); + } + assert_eq!(centre(&u), (0.0, 0.0)); + release(&mut u, at); +} + +#[test] +fn a_shape_drawn_at_the_edge_pans_and_grows() { + let mut u = setup(); + run(&mut u, "tool.set", json!({"tool": "rectangle"})); + let rect = u.app.canvas.rect; + let press = rect.center(); + u.button(press, true); + u.frame(vec![Event::PointerMoved(press + vec2(30.0, 30.0))]); + let at = pos2(press.x + 30.0, rect.max.y - 2.0); + u.frame(vec![Event::PointerMoved(at)]); + let cy0 = centre(&u).1; + for _ in 0..30 { + u.frame(vec![]); + } + let pan = centre(&u).1 - cy0; + assert!((pan - 520.0 * 30.0 * DT).abs() < 1.0, "panned {pan}"); + release(&mut u, at); + let r = u.app.session.selection()[0]; + let h = u.app.session.doc().unwrap().world_bounds(r).unwrap().height(); + let before = f64::from(at.y - press.y); + assert!(h > before + pan - 2.0, "the rectangle grew with the pan: {h} for a drag of {before} and a pan of {pan}"); +} + +#[test] +fn a_resize_held_at_the_edge_does_not_pan() { + let mut u = setup(); + let r = id(run(&mut u, "shape.rectangle", json!({"x": 100, "y": -25, "width": 100, "height": 50}))); + run(&mut u, "select.set", json!({"ids": [r]})); + u.frame(vec![]); + let rect = u.app.canvas.rect; + let corner = u.app.to_screen(200.0, 25.0); + u.button(corner, true); + let at = pos2(rect.max.x - 2.0, corner.y); + u.frame(vec![Event::PointerMoved(at)]); + for _ in 0..30 { + u.frame(vec![]); + } + let b = u.app.session.doc().unwrap().world_bounds(r).unwrap(); + assert!(b.width() > 100.0, "it resized, so the press was on the handle: {}", b.width()); + assert_eq!(centre(&u), (0.0, 0.0), "a resize does not pan"); + release(&mut u, at); +} + +#[test] +fn a_hand_drag_does_not_pan_on_its_own_at_the_edge() { + let mut u = setup(); + run(&mut u, "tool.set", json!({"tool": "hand"})); + let rect = u.app.canvas.rect; + let at = pos2(rect.max.x - 2.0, rect.center().y); + u.button(rect.center(), true); + hold(&mut u, at, 20); + // The hand moves the view with the pointer, by the drag, and nothing more. + let c = centre(&u); + for _ in 0..20 { + u.frame(vec![]); + } + assert_eq!(centre(&u), c); + release(&mut u, at); +} + +#[test] +fn a_long_frame_pans_for_a_tenth_of_a_second_at_most() { + let mut u = setup(); + let (_, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + let at = pos2(u.app.canvas.rect.max.x - 2.0, from.y); + hold(&mut u, at, 3); + let before = centre(&u).0; + // One frame half a second after the last: it counts as 0.1 s, 52 px at 520 px/s. + let now = u.ctx.input(|i| i.time); + u.advance_clock(now + 0.5); + u.frame(vec![]); + let pan = centre(&u).0 - before; + assert!((pan - 52.0).abs() < 0.5, "a 0.5 s frame panned {pan} px, wanted 52"); + release(&mut u, at); +} + +#[test] +fn past_the_edge_pans_at_the_top_speed_and_the_layer_stays_under_the_pointer() { + let mut u = setup(); + let (r, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + let rect = u.app.canvas.rect; + // 30 px past the right edge, over the panel beside the canvas. + let at = pos2(rect.max.x + 30.0, from.y); + hold(&mut u, at, 2); + let (cx0, grab) = (centre(&u).0, bounds_x0(&u, r) - u.app.to_page(at).x); + hold(&mut u, at, 30); + let pan = centre(&u).0 - cx0; + assert!((pan - 600.0 * 30.0 * DT).abs() < 0.5, "panned {pan} px past the edge, wanted {}", 600.0 * 30.0 * DT); + let now = bounds_x0(&u, r) - u.app.to_page(at).x; + assert!((now - grab).abs() < 1.5, "the layer stays under the pointer: {grab} then {now}"); + release(&mut u, at); +} + +#[test] +fn at_200_percent_the_pan_is_the_same_on_screen_and_the_layer_stays_under_the_pointer() { + let mut u = setup(); + u.app.session.ds_mut().unwrap().view.zoom = 2.0; + u.frame(vec![]); + let (r, p) = centred_rect(&mut u); + let from = pick_up(&mut u, p); + let at = pos2(u.app.canvas.rect.max.x - 2.0, from.y); + hold(&mut u, at, 2); + let (cx0, grab) = (centre(&u).0, bounds_x0(&u, r) - u.app.to_page(at).x); + let n = 30; + hold(&mut u, at, n); + // 520 screen px per second is 260 page units at 200 %. + let pan = centre(&u).0 - cx0; + let want = 520.0 * n as f64 * DT / 2.0; + assert!((pan - want).abs() < 0.5, "panned {pan} page units, wanted {want}"); + let now = bounds_x0(&u, r) - u.app.to_page(at).x; + assert!((now - grab).abs() < 1.0, "the layer stays under the pointer: {grab} then {now}"); + release(&mut u, at); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fecdc3882..f2bb24b5a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -58,6 +58,8 @@ mod bool_menu_icon_tests; #[cfg(test)] mod branch_ui_tests; #[cfg(test)] +mod canvas_autopan_tests; +#[cfg(test)] mod canvas_double_click_tests; #[cfg(test)] mod canvas_drag_tests; diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index b42457172..e56ab3d67 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-10 · **Change:** patch (in the presenter's comment mode (C) a click on the presented frame starts a comment there and the mode stays on for the next one, Escape closes the draft and then the mode, measured in Figma's web app 2026-11-10 (#2209); presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); a connection dragged from a variant, or a layer in it, onto a sibling variant makes Change to, On click, Instant, with the sibling outlined (#2158); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-19 · **Change:** patch (dragging a prototype connection near the canvas edge pans the view toward it, so a link can reach a frame off screen (#2015); in the presenter's comment mode (C) a click on the presented frame starts a comment there and the mode stays on for the next one, Escape closes the draft and then the mode, measured in Figma's web app 2026-11-10 (#2209); presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); a connection dragged from a variant, or a layer in it, onto a sibling variant makes Change to, On click, Instant, with the sibling outlined (#2158); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) **Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except media control, every transition and easing exist; key/gamepad triggers take controller buttons, @@ -81,7 +81,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Feature | Status | Notes | |---|---|---| -| Connections drawn and dragged on the canvas; interaction editor | done | | +| Connections drawn and dragged on the canvas; interaction editor | done | dragging a connection out of a layer and holding the pointer within about 15 px of the canvas edge, or past it, pans the view toward it at `40 x (15 - d)` screen px/s (600 at the edge), so a link can reach a frame off screen (measured in Figma at 100%; #2015; `proto_canvas::tests`) | | Several actions per interaction; drag to reorder; conditional blocks with else-if/else | done | one undo step per edit | | Expressions (`count + 1`, `mode(Theme) == "Dark"`, `accent[Dark]`) | done | checked when entered; `proto.evaluate` computes one where a layer's interaction would run (MCP and agents) | | Flows, starting points, descriptions | done | | @@ -108,6 +108,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-07 | patch | M8, #2015: dragging a prototype connection near the canvas edge pans the view, as measured in Figma: while a drag holds the pointer within about 15 px of the edge (or past it) the view pans toward it at 40 px/s for each px closer, up to 600 px/s at the edge, steadily while the pointer stays still; moving layers, the selection box, drawing a shape and dragging a prototype connection (a link can now reach a frame off screen). Resizing, rotating and other drags don't pan. Tests: `view_autopan_tests`, `canvas_autopan_tests`, `proto_canvas::tests`. | | 2026-11-14 | patch | M5, #2352: a chain of variant changes on After delay plays to the end (A to B to C to D); before, the step a variant had fired stayed marked as fired when the instance changed variant, so the chain stopped after one step, and now each step's delay counts from when its variant appears (`crates/ui-egui/src/present/afterdelay_chain_tests.rs`). Numbers unchanged | | 2026-11-09 | patch | M7, #2158: a connection dragged from a variant (or a layer in it) onto a sibling variant of its set did nothing, because the drop looked only for top-level frames and a variant's top-level frame is its set. It now creates Change to the sibling (On click, Instant, as measured in Figma's web app) and outlines the sibling while dragging; the set's background and the variant itself still add nothing, and a frame outside the set still gets Navigate to | | 2026-11-10 | patch | M7, #2209: the presenter's comment mode showed the frame's pins but nothing started a comment. Measured in Figma's web app: with the mode on (C or the bar's comment button) a click on the presented frame drops a pin at the click and opens an "Add a comment" composer beside it; Enter posts, the pin stays at the same frame-relative spot and the mode stays on; a click on the background does nothing; Escape closes a composer, and with none open turns the mode off; the comment shows on the frame in the editor. Now the same: the click starts the draft at the point mapped back through the presenter's placement, the editor's composer is shared, the post carries the frame's page, the player ignores the pointer while the mode is on (no click interactions or hotspots fire), and Escape closes the draft, then the mode. Tests: `comments_tests::a_click_in_the_presenters_comment_mode_adds_a_comment_on_the_frame` and four more. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6a9d101fd..dab128bf9 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (dragging near the canvas edge pans the view toward it, as measured in Figma: 40 px/s for each px within about 15 px of the edge, 600 px/s at it, for moving layers, the selection box, drawing and prototype connections (#2015); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -114,6 +114,7 @@ interaction feel only partly compared: the interactions measured so far, case by | 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); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); Preferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); 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`) | +| Auto-pan when a drag holds the pointer near the canvas edge | done | measured in Figma (web, 100% zoom, held drags; #2015): while a drag holds the pointer within about 15 px of the canvas viewport's edge, or past it, the view pans toward that edge by itself at `40 x (15 - d)` screen px per second (d: px inside the edge, negative outside; 0 at 15 px or more, 120 at 12 px, about 280 at 8 px, 520 at 2 px, 600 at the edge and beyond), steadily while the pointer stays still, no acceleration; two edges (a corner) pan both axes, each by its own distance. Covers moving layers (once past the drag threshold), the selection box (once it has grown past it), drawing a shape and dragging a prototype connection out of a layer, so a link can reach a frame off screen; the layer, box, shape or connection follows the document point under the pointer. Not for resizing, rotating, the hand or Space panning, text selection or vector edits (not measured). Speed taken as screen px per second at every zoom (other zooms not measured). The rule is `ViewState::autopan_velocity`, applied each frame by the canvas (`view_autopan_tests`, `canvas_autopan_tests`, `proto_canvas`) | | 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 | @@ -210,6 +211,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-19 | patch | M8, #2015: dragging near the canvas edge pans the view, as measured in Figma: while a drag holds the pointer within about 15 px of the edge (or past it) the view pans toward it at 40 px/s for each px closer, up to 600 px/s at the edge, steadily while the pointer stays still; moving layers, the selection box, drawing a shape and dragging a prototype connection (a link can now reach a frame off screen). Resizing, rotating and other drags don't pan. Tests: `view_autopan_tests`, `canvas_autopan_tests`, `proto_canvas::tests`. | | 2026-11-19 | patch | M8: a Shift-click range in the Layers panel keeps a frame and not its covered children: a range across parents selects a frame whose row is inside it, and drops the rows under that frame, as measured in Figma's web app on 2026-11-12 (Rect 4 in one frame, Shift-click Rect 2 in another: Rect 4 and the second frame, 2 selected); a range among siblings is unchanged; Cmd with Shift reduces the combined set the same way, not measured | | 2026-11-19 | patch | M5, #2360: with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child (a press on a layer inside a selected one drags the selection), as in Figma; Cmd/Ctrl, Shift and layers outside the frame are unchanged. | | 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | From 6b625a0d465992be204e7fda314450e2d9a3c10e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 01:28:57 +0700 Subject: [PATCH 107/129] M6: .fig export writes ruler guides (#2336) (#2337) The change from #2337 by @TrevorBrown-dev, as one commit. --- crates/format/src/fig.rs | 2 + crates/format/src/fig/export.rs | 23 +++- crates/format/src/fig/export/common.rs | 24 +++- crates/format/src/fig/export/layer.rs | 8 +- crates/format/src/fig/guides_tests.rs | 162 +++++++++++++++++++++++++ docs/file-format-parity.md | 8 +- 6 files changed, 212 insertions(+), 15 deletions(-) create mode 100644 crates/format/src/fig/guides_tests.rs diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index 033d4f22d..db799ca70 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -25,6 +25,8 @@ mod export; #[cfg(test)] mod export_tests; #[cfg(test)] +mod guides_tests; +#[cfg(test)] mod interop_tests; #[cfg(test)] mod layer_cap_tests; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index c0de279c1..d2f548abd 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -154,6 +154,7 @@ message VectorData uint vectorNetworkBlob=1, Vector normalizedSize=2, NodeChange 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 Guide Axis axis=1, float offset=2, GUID guid=3 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 struct ExportConstraint ExportConstraintType type, float value message ExportSettings string suffix=1, ImageType imageType=2, ExportConstraint constraint=3 @@ -191,7 +192,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, 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, Color prototypeBackgroundColor=141 +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, Color prototypeBackgroundColor=141, Guide[] guides=138 struct Blob byte[] bytes message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4, Blob[] blobs=6 "; @@ -418,6 +419,8 @@ struct Exporter<'d> { /// Grid tracks of written grid frames: (columns, rows) local ids (session [`AUX`]). tracks: BTreeMap, Vec)>, aux: u32, + /// Session of the last guide's GUID: guides count from the session after [`AUX`], one session each, local id 1. + guide_session: u32, overlays: BTreeMap, trigger_size: [f64; 2], /// Flow starting points: layer → (order, name). @@ -458,6 +461,7 @@ impl<'d> Exporter<'d> { child_defs: BTreeMap::new(), tracks: BTreeMap::new(), aux: 0, + guide_session: AUX, overlays: BTreeMap::new(), trigger_size: [0.0, 0.0], starts: BTreeMap::new(), @@ -475,6 +479,23 @@ impl<'d> Exporter<'d> { } } + /// A node's ruler `guides` field: Y is a horizontal guide and X a vertical one, the offset the ruler's reading (a + /// page's in page coordinates, a frame's in the frame's own). + fn guides(&mut self, guides: &[figcraft_doc::Guide], f: &mut Fields) { + // A guide whose offset isn't finite shows nowhere in the document: it is left out, not written at 0. + let list: Vec> = guides + .iter() + .filter(|g| g.offset.is_finite()) + .map(|g| { + self.guide_session = self.guide_session.saturating_add(1); + o(vec![("axis", e(if g.vertical { "X" } else { "Y" })), ("offset", fl(g.offset)), ("guid", guid(self.guide_session, 1))]) + }) + .collect(); + if !list.is_empty() { + f.push(("guides", arr(list))); + } + } + fn next_aux(&mut self) -> u32 { self.aux += 1; self.aux diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index a28951cf8..3ca682682 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -111,11 +111,22 @@ pub(super) fn scaled(a: &Kv<'static>, b: &Kv<'static>, k: f64, slack: f64) -> bo } } +/// A `guides` list without its guids. Every guide written has a guid of its own, so two layers' guides are the same +/// when their axes and offsets are. +fn bare_guides(v: &Kv<'static>) -> Vec> { + let bare = |g: &Kv<'static>| match g { + Kv::Object(f) => o(f.iter().filter(|(k, _)| *k != "guid").cloned().collect()), + other => other.clone(), + }; + v.list().iter().map(bare).collect() +} + /// The fields of `mine` that differ from `theirs` (a layer and the main's layer it mirrors), and /// the ones only `theirs` has at their empty values. pub(super) fn changed(mine: Fields, theirs: &Fields) -> Fields { + let same = |k: &str, a: &Kv<'static>, b: &Kv<'static>| a == b || (k == "guides" && bare_guides(a) == bare_guides(b)); let cleared: Fields = theirs.iter().filter(|(k, _)| !mine.iter().any(|(mk, _)| mk == k)).filter_map(|(k, _)| Some((*k, unset(k)?))).collect(); - let mut out: Fields = mine.into_iter().filter(|(k, v)| !theirs.iter().any(|(tk, tv)| tk == k && tv == v)).collect(); + let mut out: Fields = mine.into_iter().filter(|(k, v)| !theirs.iter().any(|(tk, tv)| tk == k && same(k, tv, v))).collect(); out.extend(cleared); out } @@ -181,9 +192,14 @@ fn unset(key: &str) -> Option> { } "variableConsumptionMap" | "variableModeBySetMap" | "gridColumnsSizing" | "gridRowsSizing" => o(vec![("entries", arr(Vec::new()))]), "mask" | "rectangleCornerRadiiIndependent" | "borderStrokeWeightsIndependent" => b(false), - "effects" | "dashPattern" | "layoutGrids" | "exportSettings" | "prototypeInteractions" | "fillGeometry" | "variableWidthPoints" => { - arr(Vec::new()) - } + "effects" + | "dashPattern" + | "layoutGrids" + | "exportSettings" + | "prototypeInteractions" + | "fillGeometry" + | "variableWidthPoints" + | "guides" => arr(Vec::new()), "cornerSmoothing" | "stackChildPrimaryGrow" => fl(0.0), "stackMode" => e("NONE"), "stackChildAlignSelf" | "stackPositioning" => e("AUTO"), diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index 0ab593f1a..3b718cfc2 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -23,9 +23,7 @@ impl<'d> Exporter<'d> { f.extend([("type", e("CANVAS")), ("name", s(&n.name))]); f.extend(root_fields()); f.extend([("backgroundColor", color(*background)), ("backgroundOpacity", fl(background.a.into())), ("backgroundEnabled", b(true))]); - if !n.guides.is_empty() { - self.warn("ruler guides were left out"); - } + self.guides(&n.guides, &mut f); let defaults = figcraft_doc::proto::PrototypeSettings::default(); // Every page writes its colour, so Figma shows the same one (a page without the field shows Figma's own default). // The colour is written opaque: the record measured has alpha 1, and the import reads the colour as opaque and @@ -318,9 +316,7 @@ impl<'d> Exporter<'d> { f.push(("variableConsumptionMap", o(vec![("entries", arr(bound.entries))]))); } self.modes(n, f); - if !n.guides.is_empty() { - self.warn("ruler guides were left out"); - } + self.guides(&n.guides, f); if !n.annotations.is_empty() || !n.dev_resources.is_empty() || !n.code_links.is_empty() diff --git a/crates/format/src/fig/guides_tests.rs b/crates/format/src/fig/guides_tests.rs new file mode 100644 index 000000000..bf4a6a8e8 --- /dev/null +++ b/crates/format/src/fig/guides_tests.rs @@ -0,0 +1,162 @@ +//! Ruler guides in `.fig` exports: a page's and a frame's `guides`, as a synthetic file saved from +//! Figma's web app wrote them. + +use std::collections::BTreeMap; + +use figcraft_doc::{Document, Guide, NodeId, NodeKind}; + +use super::kiwi::Kv; +use super::{Archive, decode_canvas, export}; + +/// A document with a page guide at `page` and a frame guide at `frame` (both vertical and +/// horizontal), and the frame's id. +fn doc_with(page: &[Guide], frame: &[Guide]) -> (Document, NodeId) { + let mut doc = Document::new("t"); + let p = doc.first_page().unwrap(); + let f = doc.create(p, NodeKind::Frame, "Frame 1", 1000.0, 500.0, 400.0, 300.0).unwrap(); + doc.node_mut(p).unwrap().guides = page.to_vec(); + doc.node_mut(f).unwrap().guides = frame.to_vec(); + (doc, f) +} + +fn vertical(offset: f64) -> Guide { + Guide { vertical: true, offset } +} + +fn horizontal(offset: f64) -> Guide { + Guide { vertical: false, offset } +} + +/// The `guides` of the CANVAS record and of the FRAME record, as (axis, offset, sessionID, localID). +type Written = Option>; + +fn written(doc: &Document) -> (Written, Written, Vec) { + let (bytes, warnings) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let nodes = msg.get("nodeChanges").unwrap().list(); + let of = |ty: &str| { + let n = nodes + .iter() + .find(|n| n.get("type").and_then(Kv::str) == Some(ty) && n.get("name").and_then(Kv::str) != Some("Internal Only Canvas")) + .unwrap(); + n.get("guides").map(|g| { + g.list() + .iter() + .map(|x| { + let id = x.get("guid").unwrap(); + ( + x.get("axis").and_then(Kv::str).unwrap().to_string(), + x.get("offset").and_then(Kv::f64).unwrap() as f32, + id.get("sessionID").and_then(Kv::f64).unwrap() as u64, + id.get("localID").and_then(Kv::f64).unwrap() as u64, + ) + }) + .collect() + }) + }; + (of("CANVAS"), of("FRAME"), warnings) +} + +/// A component with a vertical guide at 24 that holds a frame with a vertical guide at 7, and an instance of it as the +/// engine makes one: its root a copy of the main's, guides included, and its layer mirroring the main's. Returns the +/// instance. +fn component_and_instance() -> (Document, NodeId) { + let mut doc = Document::new("t"); + let p = doc.first_page().unwrap(); + let kind = NodeKind::Component { description: String::new(), props: BTreeMap::new(), prop_order: Vec::new() }; + let main = doc.create(p, kind, "Card", 0.0, 0.0, 200.0, 100.0).unwrap(); + let inner = doc.create(main, NodeKind::Frame, "Inner", 20.0, 30.0, 100.0, 50.0).unwrap(); + doc.node_mut(main).unwrap().guides = vec![vertical(24.0)]; + doc.node_mut(inner).unwrap().guides = vec![vertical(7.0)]; + let inst = doc.alloc_id(); + let mut root = doc.node(main).unwrap().clone(); + (root.id, root.kind, root.parent, root.source) = (inst, NodeKind::Instance { component: main, props: BTreeMap::new() }, None, Some(main)); + root.children.clear(); + doc.insert(root, p, None).unwrap(); + let mut layer = doc.node(inner).unwrap().clone(); + (layer.id, layer.parent, layer.source) = (doc.alloc_id(), None, Some(inner)); + doc.insert(layer, inst, None).unwrap(); + (doc, inst) +} + +/// The `guides` of every instance override row in the file, as (axis, offset). +fn overridden(doc: &Document) -> Vec> { + let (bytes, _) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let nodes = msg.get("nodeChanges").unwrap().list(); + let rows = nodes.iter().flat_map(|n| n.get("symbolData").and_then(|d| d.get("symbolOverrides")).map(Kv::list).unwrap_or_default()); + rows.filter_map(|row| row.get("guides")) + .map(|g| { + g.list() + .iter() + .map(|x| (x.get("axis").and_then(Kv::str).unwrap().to_string(), x.get("offset").and_then(Kv::f64).unwrap() as f32)) + .collect() + }) + .collect() +} + +#[test] +fn a_page_guide_at_120_and_a_frame_guide_at_40_are_written_as_figma_writes_them() { + let (doc, _) = doc_with(&[horizontal(120.0), vertical(120.0)], &[horizontal(40.0), vertical(40.0)]); + let (page, frame, warnings) = written(&doc); + // Axis Y is a horizontal guide and X a vertical one; the offsets are the ruler readings (a frame's in its own + // coordinates); localID is 1 and sessionID counts the file's guides from 3. + assert_eq!(page, Some(vec![("Y".into(), 120.0, 3, 1), ("X".into(), 120.0, 4, 1)])); + assert_eq!(frame, Some(vec![("Y".into(), 40.0, 5, 1), ("X".into(), 40.0, 6, 1)])); + assert!(warnings.iter().all(|w| !w.contains("ruler guides")), "{warnings:?}"); +} + +#[test] +fn a_frame_without_guides_and_a_page_without_guides_write_no_field() { + let (doc, _) = doc_with(&[], &[]); + let (page, frame, warnings) = written(&doc); + assert_eq!(page, None); + assert_eq!(frame, None); + assert!(warnings.iter().all(|w| !w.contains("ruler guides")), "{warnings:?}"); +} + +#[test] +fn a_frame_guide_is_not_shifted_by_the_frames_position() { + let (doc, _) = doc_with(&[], &[vertical(78.0)]); + let (_, frame, _) = written(&doc); + assert_eq!(frame, Some(vec![("X".into(), 78.0, 3, 1)])); +} + +#[test] +fn an_instance_overrides_guides_only_where_they_differ_from_its_mains() { + let (mut doc, inst) = component_and_instance(); + // Untouched: the instance's guides and its layer's are the main's. + assert_eq!(overridden(&doc), Vec::>::new()); + // Its own guide: one override, on the instance. + doc.node_mut(inst).unwrap().guides = vec![horizontal(60.0)]; + assert_eq!(overridden(&doc), vec![vec![("Y".to_string(), 60.0)]]); + // Its guides removed: an empty list, or it would show the main's. + doc.node_mut(inst).unwrap().guides.clear(); + assert_eq!(overridden(&doc), vec![Vec::new()]); +} + +#[test] +fn a_guide_whose_offset_is_not_finite_is_left_out() { + let (doc, _) = doc_with(&[vertical(f64::NAN), vertical(10.0), horizontal(f64::INFINITY)], &[horizontal(f64::NEG_INFINITY)]); + let (page, frame, _) = written(&doc); + assert_eq!(page, Some(vec![("X".into(), 10.0, 3, 1)])); + assert_eq!(frame, None); +} + +#[test] +fn the_schema_numbers_the_guides() { + let s = super::kiwi::Schema::parse(super::export::SCHEMA).unwrap(); + let def = |n: &str| s.defs.iter().find(|d| d.name == n).unwrap(); + let field = |d: &str, f: &str| def(d).fields.iter().find(|x| x.name == f).unwrap().value; + assert_eq!(field("NodeChange", "guides"), 138); + assert_eq!(field("Guide", "axis"), 1); + assert_eq!(field("Guide", "offset"), 2); + assert_eq!(field("Guide", "guid"), 3); + let axis = def("Axis"); + assert_eq!(axis.fields.iter().find(|x| x.name == "X").unwrap().value, 0); + assert_eq!(axis.fields.iter().find(|x| x.name == "Y").unwrap().value, 1); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cee929d66..c5d777bcf 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-17 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.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-19 · **Change:** minor (`.fig` export writes ruler guides (#2336); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.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 @@ -90,7 +90,7 @@ an inherited style link keep their own values and the link; stale copies on the still yield to the style. These cases have synthetic export/import regressions, including nested scales and empty-style clears; they have not been checked in other software. -- **Written:** pages (name, background, prototype background as an opaque colour, for every page); frames, groups, sections, rectangles (as rounded +- **Written:** pages (name, background, ruler guides, prototype background as an opaque colour, for every page); the ruler guides of frames, components and instances, in the layer's own coordinates; 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, each filled area's own paints, plus the outline of their filled areas), text, boolean groups, slices; the fill outline of frames and shapes and the @@ -136,8 +136,7 @@ scales and empty-style clears; they have not been checked in other software. properties, arc fields, font weight: written as the values they give), text styles on part of a text (written as values), the paint frames of vector regions, variables' publishing, code syntax and inheritance settings, extended collections (written as collections of their own), comments, Developer Mode annotations, statuses, - resources, measurements and code links, plugin data, ruler - guides, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush + resources, measurements and code links, plugin data, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush strokes (written plain), strokes wider on one side of their path (written as filled outlines, or with the width on both sides when the shape has a fill too), pattern fills, WebP export settings (written as PNG), glass settings other than frost, springs other than Gentle (written as ease @@ -196,6 +195,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M6, #2336: `.fig` export writes ruler guides: a page's and a frame's `guides` (each an `Axis` Y for a horizontal guide and X for a vertical one, the offset as the ruler reads it, a frame's in its own coordinates, and a guid of its own: local id 1 and a session id counted up from 3), as measured on a page and an unrotated frame in a synthetic file saved from Figma's web app. The "ruler guides were left out" warnings are gone. An instance writes a `guides` override only where its guides differ from its main's, and a guide whose offset isn't finite is left out. Our own import does not read guides yet, so this is checked by reading the written records only, not in other software. Numbers unchanged. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. | | 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software | From 0d70c332b13499d736954240c973aa470e365a9d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 02:00:46 +0700 Subject: [PATCH 108/129] M12: boards: code blocks (doc and engine): a board code block that hugs its lines, with a language (#2237) (#2282) The change from #2282 by @TrevorBrown-dev, as one commit. --- ROADMAP.md | 2 +- crates/doc/src/board.rs | 15 +- crates/doc/src/board_code.rs | 130 ++++++ crates/doc/src/board_code_tests.rs | 58 +++ crates/doc/src/lib.rs | 4 + crates/engine/src/board_code_tests.rs | 541 ++++++++++++++++++++++ crates/engine/src/board_tests.rs | 3 + crates/engine/src/boards/board.rs | 18 +- crates/engine/src/boards/board/code.rs | 260 +++++++++++ crates/engine/src/boards/board/derived.rs | 1 + crates/engine/src/boards/board/edit.rs | 2 +- crates/engine/src/boards/board/items.rs | 9 +- crates/engine/src/canvas/textedit.rs | 20 +- crates/engine/src/cmd/text.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/ui-egui/src/canvas/board_bar.rs | 2 +- docs/boards-parity.md | 6 +- docs/gaps.md | 5 +- docs/mcp.md | 15 +- docs/roadmap.md | 3 +- 20 files changed, 1081 insertions(+), 17 deletions(-) create mode 100644 crates/doc/src/board_code.rs create mode 100644 crates/doc/src/board_code_tests.rs create mode 100644 crates/engine/src/board_code_tests.rs create mode 100644 crates/engine/src/boards/board/code.rs diff --git a/ROADMAP.md b/ROADMAP.md index 107a11f96..5924750e6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through diff --git a/crates/doc/src/board.rs b/crates/doc/src/board.rs index eb0594bab..999631aed 100644 --- a/crates/doc/src/board.rs +++ b/crates/doc/src/board.rs @@ -10,7 +10,7 @@ use figcraft_geom::kurbo::{Ellipse, RoundedRect}; use figcraft_geom::{BezPath, Point, Rect, Shape, Vec2}; use serde::{Deserialize, Serialize}; -use crate::NodeId; +use crate::{CodeLanguage, NodeId}; /// What a file is for: designing screens, or a board to think together on. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -65,6 +65,12 @@ pub enum BoardItem { /// A mind map's node: a frame hugging its text, with no outline. What it hangs from is the /// branch (a connector with `branch`) arriving at it. MindNode, + /// A code block: a dark panel holding one monospace text (its first text layer), as wide as + /// it was made and as tall as its lines. `language` picks the highlighting. + CodeBlock { + #[serde(default)] + language: CodeLanguage, + }, } impl BoardItem { @@ -79,12 +85,16 @@ impl BoardItem { | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode + | BoardItem::CodeBlock { .. } ) } /// Objects whose first text layer is their text (a double-click or Enter edits it). pub fn has_text(&self) -> bool { - matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) + matches!( + self, + BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode | BoardItem::CodeBlock { .. } + ) } /// Who made it (stickies and stamps; empty when unknown). @@ -127,6 +137,7 @@ impl BoardItem { BoardItem::Ink => "ink", BoardItem::Table => "table", BoardItem::MindNode => "mindNode", + BoardItem::CodeBlock { .. } => "codeBlock", } } } diff --git a/crates/doc/src/board_code.rs b/crates/doc/src/board_code.rs new file mode 100644 index 000000000..b31487c25 --- /dev/null +++ b/crates/doc/src/board_code.rs @@ -0,0 +1,130 @@ +//! Code blocks (#2237): the languages a block is highlighted as, and the numbers of its look. +//! Pure data: the engine makes the block ([`crate::BoardItem::CodeBlock`]). + +use figcraft_color::Color; +use serde::{Deserialize, Serialize}; + +/// The language a code block is highlighted as. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CodeLanguage { + Bash, + Cpp, + Css, + Go, + Graphql, + Html, + Javascript, + Json, + Kotlin, + PlainText, + Python, + Ruby, + Rust, + Sql, + Swift, + #[default] + Typescript, +} + +impl CodeLanguage { + /// In menu order: by name. + pub const ALL: [CodeLanguage; 16] = [ + CodeLanguage::Bash, + CodeLanguage::Cpp, + CodeLanguage::Css, + CodeLanguage::Go, + CodeLanguage::Graphql, + CodeLanguage::Html, + CodeLanguage::Javascript, + CodeLanguage::Json, + CodeLanguage::Kotlin, + CodeLanguage::PlainText, + CodeLanguage::Python, + CodeLanguage::Ruby, + CodeLanguage::Rust, + CodeLanguage::Sql, + CodeLanguage::Swift, + CodeLanguage::Typescript, + ]; + + /// The id used in commands and saved files ("cpp", "plainText", "typescript"). + pub fn id(self) -> &'static str { + match self { + CodeLanguage::Bash => "bash", + CodeLanguage::Cpp => "cpp", + CodeLanguage::Css => "css", + CodeLanguage::Go => "go", + CodeLanguage::Graphql => "graphql", + CodeLanguage::Html => "html", + CodeLanguage::Javascript => "javascript", + CodeLanguage::Json => "json", + CodeLanguage::Kotlin => "kotlin", + CodeLanguage::PlainText => "plainText", + CodeLanguage::Python => "python", + CodeLanguage::Ruby => "ruby", + CodeLanguage::Rust => "rust", + CodeLanguage::Sql => "sql", + CodeLanguage::Swift => "swift", + CodeLanguage::Typescript => "typescript", + } + } + + /// The name shown in the UI ("C++", "Plain text", "TypeScript"). + pub fn label(self) -> &'static str { + match self { + CodeLanguage::Bash => "Bash", + CodeLanguage::Cpp => "C++", + CodeLanguage::Css => "CSS", + CodeLanguage::Go => "Go", + CodeLanguage::Graphql => "GraphQL", + CodeLanguage::Html => "HTML", + CodeLanguage::Javascript => "JavaScript", + CodeLanguage::Json => "JSON", + CodeLanguage::Kotlin => "Kotlin", + CodeLanguage::PlainText => "Plain text", + CodeLanguage::Python => "Python", + CodeLanguage::Ruby => "Ruby", + CodeLanguage::Rust => "Rust", + CodeLanguage::Sql => "SQL", + CodeLanguage::Swift => "Swift", + CodeLanguage::Typescript => "TypeScript", + } + } + + /// By id or by name, in any case, trimmed ("cpp", "C++", "plain text"). + pub fn from_id(s: &str) -> Option { + let s = s.trim(); + CodeLanguage::ALL.into_iter().find(|l| l.id().eq_ignore_ascii_case(s) || l.label().eq_ignore_ascii_case(s)) + } +} + +/// The font code is set in (always this family; the machine finds the nearest when it is absent). +pub const CODE_FONT: &str = "Liberation Mono"; +pub const CODE_FONT_SIZE: f64 = 16.0; +/// A line of code: 150% of the size. +pub const CODE_LINE: f64 = 24.0; +/// Room around the code: top, right, bottom, left (the left holds the line numbers). +pub const CODE_PAD: [f64; 4] = [16.0, 16.0, 16.0, 64.0]; +pub const CODE_MIN_LINES: usize = 4; +/// A block's least height: four lines. +pub const CODE_MIN_H: f64 = 128.0; +pub const CODE_WIDTH: f64 = 576.0; +pub const CODE_MIN_W: f64 = 210.0; +pub const CODE_MAX_W: f64 = 100_000.0; +/// The room between a block and the next one made beside it. +pub const CODE_GAP: f64 = 128.0; +pub const CODE_RADIUS: f64 = 10.0; +/// What Tab types in a block. +pub const CODE_TAB: &str = " "; +/// The most characters `board.codeBlock` takes. +pub const CODE_MAX_CHARS: usize = 100_000; +/// The panel: the board's ink. +pub const CODE_PANEL: Color = Color::from_rgb8_const(0x1E, 0x1E, 0x1E); +/// Plain code: the board's gray. +pub const CODE_TEXT: Color = Color::from_rgb8_const(0xE3, 0xE1, 0xDD); + +/// A block's height holding `lines` visual lines (four at least): 32 + 24 a line. +pub fn code_height(lines: usize) -> f64 { + CODE_PAD[0] + CODE_PAD[2] + CODE_LINE * lines.clamp(CODE_MIN_LINES, 1_000_000) as f64 +} diff --git a/crates/doc/src/board_code_tests.rs b/crates/doc/src/board_code_tests.rs new file mode 100644 index 000000000..4f8ec0bb9 --- /dev/null +++ b/crates/doc/src/board_code_tests.rs @@ -0,0 +1,58 @@ +//! Code blocks (#2237): the languages, the saved item, the height rule and the colours. + +use serde_json::json; + +use crate::BoardItem; +use crate::board_code::{CODE_MIN_H, CODE_PAD, CODE_PANEL, CODE_TEXT, CodeLanguage, code_height}; + +#[test] +fn sixteen_languages_by_name_with_typescript_the_default() { + assert_eq!(CodeLanguage::ALL.len(), 16); + let ids: std::collections::BTreeSet<&str> = CodeLanguage::ALL.iter().map(|l| l.id()).collect(); + assert_eq!(ids.len(), 16, "ids are unique"); + let labels: Vec = CodeLanguage::ALL.iter().map(|l| l.label().to_lowercase()).collect(); + assert!(labels.windows(2).all(|w| w[0] < w[1]), "labels ascend: {labels:?}"); + for l in CodeLanguage::ALL { + assert_eq!(CodeLanguage::from_id(l.id()), Some(l)); + assert_eq!(CodeLanguage::from_id(l.label()), Some(l)); + assert_eq!(serde_json::to_value(l).unwrap(), json!(l.id())); + } + assert_eq!(CodeLanguage::from_id("CPP"), Some(CodeLanguage::Cpp)); + assert_eq!(CodeLanguage::from_id("c++"), Some(CodeLanguage::Cpp)); + assert_eq!(CodeLanguage::from_id(" plain text "), Some(CodeLanguage::PlainText)); + assert_eq!(CodeLanguage::from_id("markdown"), None); + assert_eq!(CodeLanguage::from_id(""), None); + assert_eq!(CodeLanguage::default(), CodeLanguage::Typescript); +} + +#[test] +fn a_code_block_item_saves_its_language() { + let item = BoardItem::CodeBlock { language: CodeLanguage::Rust }; + let v = json!({"type": "codeBlock", "language": "rust"}); + assert_eq!(serde_json::to_value(&item).unwrap(), v); + assert_eq!(serde_json::from_value::(v).unwrap(), item); + let plain: BoardItem = serde_json::from_value(json!({"type": "codeBlock"})).unwrap(); + assert_eq!(plain, BoardItem::CodeBlock { language: CodeLanguage::Typescript }); + assert!(serde_json::from_value::(json!({"type": "codeBlock", "language": "klingon"})).is_err()); + assert_eq!(item.kind_id(), "codeBlock"); + assert!(item.is_atom()); + assert!(item.has_text()); +} + +#[test] +fn the_height_is_32_and_24_a_line_from_four_lines_up() { + assert_eq!(code_height(0), 128.0); + assert_eq!(code_height(1), 128.0); + assert_eq!(code_height(4), 128.0); + assert_eq!(code_height(5), 152.0); + assert_eq!(code_height(9), 248.0); + assert!(code_height(usize::MAX).is_finite()); + assert_eq!(CODE_MIN_H, code_height(0)); + assert_eq!(CODE_PAD[0] + CODE_PAD[2], 32.0); + assert_eq!(CODE_PAD[1] + CODE_PAD[3], 80.0); +} + +#[test] +fn plain_code_reads_on_the_panel() { + assert!(CODE_TEXT.contrast(CODE_PANEL) >= 4.5, "{}", CODE_TEXT.contrast(CODE_PANEL)); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index e0dd356e1..170da1a25 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -9,6 +9,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod board; +mod board_code; mod board_mindmap; mod board_route; pub mod colors; @@ -28,6 +29,7 @@ pub mod vector_faces; pub mod vector_regions; pub use board::*; +pub use board_code::*; pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, MindBox, mind_layout}; pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; @@ -1321,6 +1323,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap) { #[cfg(test)] mod blur_tests; #[cfg(test)] +mod board_code_tests; +#[cfg(test)] mod board_mindmap_tests; #[cfg(test)] mod board_route_tests; diff --git a/crates/engine/src/board_code_tests.rs b/crates/engine/src/board_code_tests.rs new file mode 100644 index 000000000..97fc6bfdc --- /dev/null +++ b/crates/engine/src/board_code_tests.rs @@ -0,0 +1,541 @@ +//! Code blocks (#2237): `board.codeBlock` and `board.setLanguage`, the pass that keeps a block as +//! tall as its lines and its text plain code, and the text editor's three literal-typing lines. + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{ + BoardItem, CODE_FONT, CODE_MAX_CHARS, CodeLanguage, EffectKind, FileKind, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, Sizing, + TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration, +}; +use figcraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::board::{is_code_text, text_of}; +use crate::board_tests::{board, id, node}; +use crate::collab_live_tests::Room; +use crate::tools::{PointerEvent, PointerKind}; +use crate::{EngineError, Session}; + +fn bx(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().world_bounds(id).unwrap() +} + +fn td(s: &Session, block: NodeId) -> TextData { + let t = text_of(s.doc().unwrap(), block).unwrap(); + match node(s, t).kind { + NodeKind::Text(td) => td, + other => panic!("not text: {other:?}"), + } +} + +/// `board.codeBlock` with `p`: the frame and its text. +fn block(s: &mut Session, p: Value) -> (NodeId, NodeId) { + let out = s.execute("board.codeBlock", &p).unwrap(); + (id(&out, "id"), id(&out, "text")) +} + +/// How many visual lines the text lays out in. +fn lines(s: &Session, text: NodeId) -> usize { + let n = node(s, text); + figcraft_text::layout_node(&n).map_or(0, |(l, _)| l.lines.len()) +} + +fn solid(hex: (u8, u8, u8)) -> Vec { + vec![Paint::solid(Color::from_rgb8_const(hex.0, hex.1, hex.2))] +} + +fn ten(n: usize) -> String { + vec!["x"; n].join("\n") +} + +fn drag(s: &mut Session, from: (f64, f64), to: (f64, f64)) { + s.pointer(&PointerEvent::at(PointerKind::Down, from.0, from.1, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Move, (from.0 + to.0) / 2.0, (from.1 + to.1) / 2.0, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Move, to.0, to.1, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Up, to.0, to.1, 1.0)).unwrap(); +} + +fn undo(s: &mut Session) { + s.execute("edit.undo", &json!({})).unwrap(); +} + +#[test] +fn a_code_block_is_a_dark_panel_576_by_128_holding_one_monospace_text() { + let mut s = board(); + let before = s.doc().unwrap().ids().count(); + let depth = s.undo_depth().0; + let out = s.execute("board.codeBlock", &json!({"x": 100, "y": 200})).unwrap(); + assert_eq!(out["language"], json!("typescript")); + let (f, t) = (id(&out, "id"), id(&out, "text")); + let n = node(&s, f); + assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Typescript })); + assert!(n.is_board_atom()); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0, r.x1, r.y1), (100.0, 200.0, 676.0, 328.0)); + assert_eq!(n.fills, solid((0x1E, 0x1E, 0x1E))); + assert_eq!(n.corners.radii, [10.0; 4]); + assert_eq!(n.effects.iter().filter(|e| matches!(e.kind, EffectKind::DropShadow(_))).count(), 1); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.padding), (LayoutMode::Vertical, [16.0, 16.0, 16.0, 64.0])); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); + assert_eq!((n.child_layout.min_h, n.child_layout.min_w), (Some(128.0), Some(210.0))); + assert_eq!(n.children, vec![t]); + let tr = bx(&s, t); + assert_eq!((tr.x0, tr.y0, tr.width()), (164.0, 216.0, 496.0)); + let d = td(&s, f); + assert_eq!(d.characters, ""); + assert_eq!((d.style.font_family.as_str(), d.style.font_style.as_str(), d.style.font_size), (CODE_FONT, "Regular", 16.0)); + assert_eq!(d.style.line_height, LineHeight::Percent(150.0)); + assert_eq!((d.auto_resize, d.align_h), (TextAutoResize::Height, TextAlignH::Left)); + assert_eq!(node(&s, t).fills, solid((0xE3, 0xE1, 0xDD))); + assert_eq!((d.features.get("liga"), d.features.get("calt")), (Some(&false), Some(&false))); + assert!(d.runs.is_empty()); + assert_eq!(d.list, ListStyle::None); + assert_eq!(s.selection(), vec![f]); + assert_eq!(s.undo_depth().0, depth + 1); + undo(&mut s); + assert_eq!(s.doc().unwrap().ids().count(), before); +} + +#[test] +fn a_block_without_a_place_is_centred_and_edit_asks_for_typing() { + let mut s = board(); + // Centred on the view without a place. + let (vx, vy) = { + let v = &s.ds().unwrap().view; + (v.cx, v.cy) + }; + let (f, _) = block(&mut s, json!({})); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0), (vx - 288.0, vy - 64.0)); + // Typing starts in it on request. + let (f, _) = block(&mut s, json!({"x": 0, "y": 500, "edit": true})); + assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(f))); +} + +#[test] +fn the_height_is_its_lines_24_each_and_never_under_four() { + let mut s = board(); + let heights = [("a", 128.0), ("a\nb\nc\nd", 128.0), ("a\nb\nc\nd\ne", 152.0)]; + for (text, h) in heights { + let (f, _) = block(&mut s, json!({"x": 100, "y": 200, "text": text})); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0, r.height()), (100.0, 200.0, h), "{text:?}"); + } + let (f, t) = block(&mut s, json!({"x": 100, "y": 200, "text": ten(9)})); + assert_eq!(bx(&s, f).height(), 248.0); + assert_eq!(bx(&s, t).height(), 216.0); + s.execute("text.set", &json!({"id": t, "characters": "a\nb"})).unwrap(); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0, r.height()), (100.0, 200.0, 128.0)); +} + +#[test] +fn long_lines_wrap_and_each_visual_line_adds_24() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "ab ".repeat(400)})); + let n = lines(&s, t); + assert!(n >= 3, "{n}"); + assert_eq!(bx(&s, f).height(), 32.0 + 24.0 * n as f64); + assert_eq!(bx(&s, t).width(), 496.0); + if figcraft_text::has_family(CODE_FONT) { + let (f, _) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": "x".repeat(93)})); + assert_eq!(bx(&s, f).height(), 128.0); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": "x".repeat(94)})); + assert_eq!(lines(&s, t), 2); + assert_eq!(bx(&s, f).height(), 128.0); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": format!("{}\na\nb\nc", "x".repeat(94))})); + assert_eq!(lines(&s, t), 5); + assert_eq!(bx(&s, f).height(), 152.0); + } +} + +#[test] +fn only_the_width_is_the_users() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 100, "y": 200, "text": ten(9)})); + assert_eq!(bx(&s, f).height(), 248.0); + s.execute("node.set", &json!({"id": f, "props": {"height": 400}})).unwrap(); + assert_eq!(bx(&s, f).height(), 248.0); + assert_eq!(node(&s, f).child_layout.sizing_v, Sizing::Hug); + s.execute("transform.resize", &json!({"ids": [f], "width": 300, "height": 500})).unwrap(); + let r = bx(&s, f); + assert_eq!((r.width(), r.height(), bx(&s, t).width()), (300.0, 248.0, 220.0)); + s.execute("node.set", &json!({"id": f, "props": {"width": 100}})).unwrap(); + assert_eq!((bx(&s, f).width(), bx(&s, t).width()), (210.0, 130.0)); + + // A pointer drag of the bottom-right handle. + let mut s = board(); + let (f, _) = block(&mut s, json!({"x": 100, "y": 200})); + let depth = s.undo_depth().0; + drag(&mut s, (676.0, 328.0), (876.0, 628.0)); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0, r.width(), r.height()), (100.0, 200.0, 776.0, 128.0)); + assert_eq!(s.undo_depth().0, depth + 1); + undo(&mut s); + let r = bx(&s, f); + assert_eq!((r.width(), r.height()), (576.0, 128.0)); + + // A narrower block wraps into more lines and grows. + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "ab ".repeat(400)})); + let was = lines(&s, t); + s.execute("node.set", &json!({"id": f, "props": {"width": 300}})).unwrap(); + let now = lines(&s, t); + assert!(now > was, "{now} > {was}"); + assert_eq!(bx(&s, f).height(), 32.0 + 24.0 * now as f64); +} + +/// A block settled after `how` made it incoherent: still 5 lines tall, 576 wide, hugging, with +/// its layout, and a second pass changes nothing. +fn settled_after(how: impl Fn(&mut Session, NodeId)) { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": ten(4)})); + how(&mut s, f); + s.execute("text.set", &json!({"id": t, "characters": ten(5)})).unwrap(); + let n = node(&s, f); + assert!(n.layout.is_some(), "the layout is restored"); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((bx(&s, f).width(), bx(&s, f).height()), (576.0, 152.0)); + assert_eq!(node(&s, t).child_layout.sizing_h, Sizing::Fill); + let doc = s.doc().unwrap().clone(); + let mut again = doc.clone(); + again.mark_dirty(doc.ids().collect::>()); + crate::normalize(&mut again, &doc); + assert_eq!(again, doc, "a second pass changes nothing"); +} + +#[test] +fn the_pass_keeps_a_blocks_layout_and_width_sizing() { + settled_after(|s, f| { + s.execute("layout.remove", &json!({"ids": [f]})).unwrap(); + }); + settled_after(|s, f| { + s.execute("node.set", &json!({"id": f, "props": {"layout": null}})).unwrap(); + }); + settled_after(|s, f| { + s.execute("node.set", &json!({"id": f, "props": {"sizingH": "hug"}})).unwrap(); + }); +} + +#[test] +fn a_block_in_a_section_without_a_place_is_centred_on_the_view_too() { + let mut s = board(); + let (vx, vy) = { + let v = &s.ds().unwrap().view; + (v.cx, v.cy) + }; + let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 1000, "y": 500, "width": 4000, "height": 4000})).unwrap(), "id"); + let (f, _) = block(&mut s, json!({"parent": sec})); + assert_eq!(node(&s, f).parent, Some(sec)); + let r = bx(&s, f); + assert_eq!((r.x0, r.y0), (vx - 288.0, vy - 64.0), "on the page, where a block on the page would be"); +} + +#[test] +fn a_block_in_a_turned_frame_without_a_place_is_centred_on_the_view_and_a_given_place_is_the_frames() { + let mut s = board(); + let (vx, vy) = { + let v = &s.ds().unwrap().view; + (v.cx, v.cy) + }; + let fr = id(&s.execute("node.create", &json!({"type": "frame", "x": 300, "y": -200, "width": 3000, "height": 3000})).unwrap(), "id"); + s.execute("node.set", &json!({"id": fr, "props": {"rotation": 30}})).unwrap(); + // Left out: the block's middle (a four-line block) is on the view's centre, in the page. + let (f, _) = block(&mut s, json!({"parent": fr})); + let c = bx(&s, f).center(); + assert!((c.x - vx).abs() < 1e-6 && (c.y - vy).abs() < 1e-6, "{c:?} vs ({vx}, {vy})"); + // Given: `x`/`y` stay the frame's own coordinates. + let (g, _) = block(&mut s, json!({"parent": fr, "x": 10, "y": 20})); + let t = node(&s, g).transform.translation(); + assert_eq!((t.x, t.y), (10.0, 20.0)); +} + +#[test] +fn a_default_position_is_within_a_billion_too() { + let mut s = board(); + s.execute("view.set", &json!({"cx": 1e300})).unwrap(); + match s.execute("board.codeBlock", &json!({})) { + Err(EngineError::BadParams { .. }) => {} + Err(other) => panic!("not a named refusal: {other:?}"), + Ok(out) => panic!("placed at {out}"), + } +} + +#[test] +fn the_next_block_is_128_to_the_right_as_wide_and_in_the_same_language() { + let mut s = board(); + let (a, _) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "language": "rust", "text": "fn main() {}"})); + let connectors = |s: &Session| s.doc().unwrap().nodes().filter(|n| matches!(n.board, Some(BoardItem::Connector(_)))).count(); + let depth = s.undo_depth().0; + let out = s.execute("board.nextSticky", &json!({"id": a})).unwrap(); + let b = id(&out, "id"); + let r = bx(&s, b); + assert_eq!((r.x0, r.y0, r.width(), r.height()), (1104.0, 0.0, 976.0, 128.0)); + assert_eq!(node(&s, b).board, Some(BoardItem::CodeBlock { language: CodeLanguage::Rust })); + assert_eq!(td(&s, b).characters, ""); + assert_eq!(connectors(&s), 0); + assert_eq!(s.selection(), vec![b]); + assert_eq!(s.undo_depth().0, depth + 1); + undo(&mut s); + assert!(s.doc().unwrap().node(b).is_none()); + // While typing in the source, with no id, and asking for the next one to be typed in. + let t = text_of(s.doc().unwrap(), a).unwrap(); + s.execute("text.edit.begin", &json!({"id": t})).unwrap(); + let out = s.execute("board.nextSticky", &json!({"edit": true})).unwrap(); + let c = id(&out, "id"); + assert_eq!(bx(&s, c).x0, 1104.0); + assert!(s.ds().unwrap().text_edit.is_none(), "the edit has ended"); + assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(c))); + let out = s.execute("board.nextSticky", &json!({"id": a, "side": "below"})).unwrap(); + let r = bx(&s, id(&out, "id")); + assert_eq!((r.x0, r.y0), (0.0, 256.0)); + assert!(s.execute("board.nextSticky", &json!({"id": a, "side": "up"})).is_err()); +} + +#[test] +fn a_block_is_in_one_of_sixteen_languages() { + let mut s = board(); + let (f, _) = block(&mut s, json!({"x": 0, "y": 0})); + let lang = |s: &Session| node(s, f).board; + s.execute("board.setLanguage", &json!({"id": f, "language": "python"})).unwrap(); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Python })); + for name in ["C++", "CPP"] { + s.execute("board.setLanguage", &json!({"id": f, "language": name})).unwrap(); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Cpp })); + } + for l in CodeLanguage::ALL { + s.execute("board.setLanguage", &json!({"id": f, "language": l.id()})).unwrap(); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: l })); + } + s.execute("board.setLanguage", &json!({"id": f, "language": "go"})).unwrap(); + let e = s.execute("board.setLanguage", &json!({"id": f, "language": "klingon"})).unwrap_err().to_string(); + assert!(e.contains("typescript") && e.contains("plainText"), "{e}"); + let sticky = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "id"); + assert!(s.execute("board.setLanguage", &json!({"id": sticky, "language": "go"})).is_err()); + s.execute("select.none", &json!({})).unwrap(); + assert!(matches!(s.execute("board.setLanguage", &json!({"language": "go"})), Err(EngineError::Disabled(..)))); + // While typing in it, the text is the selection and the edit goes on. + let t = text_of(s.doc().unwrap(), f).unwrap(); + s.execute("text.edit.begin", &json!({"id": t})).unwrap(); + s.execute("board.setLanguage", &json!({"language": "ruby"})).unwrap(); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Ruby })); + assert!(s.ds().unwrap().text_edit.is_some()); + s.execute("text.edit.key", &json!({"key": "Escape"})).unwrap(); + undo(&mut s); + assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Go })); + // The creating command refuses what it cannot make. + assert!(s.execute("board.codeBlock", &json!({"language": "nope"})).is_err()); + assert!(s.execute("board.codeBlock", &json!({"width": 5})).is_err()); + assert!(s.execute("board.codeBlock", &json!({"text": "x".repeat(CODE_MAX_CHARS + 1)})).is_err()); +} + +fn insert(s: &mut Session, text: &str) { + s.execute("text.edit.insert", &json!({"text": text})).unwrap(); +} + +fn key(s: &mut Session, key: &str, shift: bool) { + s.execute("text.edit.key", &json!({"key": key, "shift": shift})).unwrap(); +} + +fn characters(s: &Session, t: NodeId) -> String { + match node(s, t).kind { + NodeKind::Text(td) => td.characters, + other => panic!("not text: {other:?}"), + } +} + +#[test] +fn typing_in_a_block_is_literal() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0})); + assert!(is_code_text(s.doc().unwrap(), t)); + s.execute("text.edit.begin", &json!({"id": t})).unwrap(); + insert(&mut s, "-"); + insert(&mut s, " "); + assert_eq!(characters(&s, t), "- "); + assert!(td(&s, f).paragraphs.iter().all(|p| p.list == ListStyle::None) && td(&s, f).list == ListStyle::None); + insert(&mut s, "\n1."); + insert(&mut s, " "); + assert_eq!(characters(&s, t), "- \n1. "); + assert!(td(&s, f).paragraphs.iter().all(|p| p.list == ListStyle::None)); + // Tab types two spaces. + s.execute("text.set", &json!({"id": t, "characters": ""})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap(); + key(&mut s, "Tab", false); + assert_eq!(characters(&s, t), " "); + key(&mut s, "Tab", true); + assert_eq!(characters(&s, t), " ", "Shift+Tab does nothing"); + // Enter keeps the line's indent, and nothing more after a brace. + insert(&mut s, "foo"); + key(&mut s, "Enter", false); + assert_eq!(characters(&s, t), " foo\n "); + s.execute("text.set", &json!({"id": t, "characters": "foo"})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 3})).unwrap(); + key(&mut s, "Enter", false); + assert_eq!(characters(&s, t), "foo\n"); + s.execute("text.set", &json!({"id": t, "characters": "{"})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 1})).unwrap(); + key(&mut s, "Enter", false); + assert_eq!(characters(&s, t), "{\n"); + // Nothing is made smart. + s.execute("text.set", &json!({"id": t, "characters": ""})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap(); + let raw = "\"a\" -- 'b' ... -> != fi"; + insert(&mut s, raw); + let got = characters(&s, t); + assert_eq!(got, raw); + assert!(!got.chars().any(|c| matches!(c, '\u{201C}' | '\u{2019}' | '\u{2014}' | '\u{2026}'))); + // In a sticky the same keys still make a list. + let note = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "text"); + s.execute("text.edit.begin", &json!({"id": note})).unwrap(); + insert(&mut s, "-"); + insert(&mut s, " "); + match node(&s, note).kind { + NodeKind::Text(d) => assert!(d.list == ListStyle::Bulleted || d.paragraphs.iter().any(|p| p.list == ListStyle::Bulleted)), + other => panic!("not text: {other:?}"), + } +} + +#[test] +fn lists_links_and_styled_ranges_do_not_stick() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "one\ntwo"})); + let plain = |s: &Session| { + let d = td(s, f); + assert_eq!(d.list, ListStyle::None); + assert!(d.paragraphs.iter().all(|p| p.list == ListStyle::None)); + assert_eq!(d.style.link, None); + assert_eq!((d.style.decoration, d.style.case), (TextDecoration::None, TextCase::Original)); + assert!(d.runs.is_empty()); + assert_eq!(d.characters, "one\ntwo"); + assert_eq!(d.auto_resize, TextAutoResize::Height); + }; + for (cmd, p) in [ + ("text.bulletList", json!({"ids": [t]})), + ("text.link", json!({"url": "https://example.com", "ids": [t]})), + ("text.underline", json!({"ids": [t]})), + ("text.caseUpper", json!({"ids": [t]})), + ] { + // Done or refused by name, and the block is plain either way. + match s.execute(cmd, &p) { + Ok(_) | Err(EngineError::BadParams { .. } | EngineError::Disabled(..)) => {} + Err(other) => panic!("{cmd}: {other:?}"), + } + plain(&s); + } + s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap(); + for _ in 0..3 { + key(&mut s, "ArrowRight", true); + } + s.execute("text.bold", &json!({})).unwrap(); + s.execute("text.edit.key", &json!({"key": "Escape"})).unwrap(); + plain(&s); + assert_eq!(td(&s, f).style.font_style, "Regular"); + s.execute("node.set", &json!({"id": t, "props": {"textAutoResize": "widthAndHeight"}})).unwrap(); + plain(&s); + // A sticky's note keeps its link (the guard). + let note = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0, "text": "hi"})).unwrap(), "text"); + s.execute("text.link", &json!({"url": "https://example.com", "ids": [note]})).unwrap(); + match node(&s, note).kind { + NodeKind::Text(d) => assert_eq!(d.style.link.as_deref(), Some("https://example.com")), + other => panic!("not text: {other:?}"), + } +} + +#[test] +fn saved_files_live_sessions_and_a_second_pass() { + let mut s = board(); + let (f, _) = block(&mut s, json!({"x": 100, "y": 200, "width": 400, "language": "rust", "text": "a\nb"})); + let doc = s.doc().unwrap(); + let (back, _) = figcraft_format::from_json(&figcraft_format::to_json(doc).unwrap().to_string()).unwrap(); + let n = back.node(f).unwrap(); + assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Rust })); + assert_eq!((n.width, n.height), (400.0, 128.0)); + + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0})); + let mut room = Room::new(s.doc().unwrap().clone(), 2, 7); + room.s(0).execute("text.set", &json!({"id": t, "characters": ten(6)})).unwrap(); + room.s(1).execute("board.setLanguage", &json!({"id": f, "language": "go"})).unwrap(); + room.settle(); + room.check(); + let server = room.server.document(); + let n = server.node(f).unwrap(); + assert_eq!(n.height, 176.0); + assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Go })); + + // A second pass over a settled document changes nothing. + let doc = s.doc().unwrap().clone(); + let mut again = doc.clone(); + again.mark_dirty(doc.ids().collect::>()); + crate::normalize(&mut again, &doc); + assert_eq!(again, doc); + + // Not on design files. + let mut d = Session::new(); + assert_eq!(d.doc().unwrap().kind, FileKind::Design); + assert!(matches!(d.execute("board.codeBlock", &json!({})), Err(EngineError::Disabled(..)))); + assert!(matches!(d.execute("board.setLanguage", &json!({"language": "go"})), Err(EngineError::Disabled(..)))); +} + +#[test] +fn code_blocks_survive_junk_commands() { + let junk = [ + json!({}), + json!(null), + json!({"language": 7, "id": "x", "ids": [1], "side": 3, "text": [1]}), + json!({"language": "nope", "id": 99_999, "side": "up", "width": 1e308, "x": "NaN"}), + ]; + let ids: Vec<&str> = crate::cmd::all_commands() + .iter() + .map(|c| c.id) + .filter(|i| { + i.starts_with("text.") && *i != "text.rescanFonts" || i.starts_with("layout.") || matches!(*i, "board.nextSticky" | "board.setLanguage") + }) + .collect(); + assert!(ids.len() > 20, "{ids:?}"); + for editing in [false, true] { + for cmd in &ids { + for j in &junk { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "a\nb"})); + if editing { + s.execute("text.edit.begin", &json!({"id": t})).unwrap(); + } else { + s.set_selection(vec![f]); + } + if let Err(EngineError::Internal { cmd, msg }) = s.execute(cmd, j) { + panic!("{cmd} panicked on {j} (editing {editing}): {msg}"); + } + } + } + } +} + +#[test] +fn a_structured_text_is_refused_and_no_block_is_made() { + for text in [json!({"a": 1}), json!([1]), json!(7), json!(true)] { + let mut s = board(); + let before = s.doc().unwrap().ids().count(); + let err = s.execute("board.codeBlock", &json!({"x": 0, "y": 0, "text": text})); + assert!(matches!(err, Err(EngineError::BadParams { .. })), "{text}: {err:?}"); + assert_eq!(s.doc().unwrap().ids().count(), before, "{text}"); + } +} + +#[test] +fn the_pass_restores_padding_and_the_minimums() { + let mut s = board(); + let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": ten(6)})); + assert_eq!(bx(&s, f).height(), 176.0); + s.execute("node.set", &json!({"id": f, "props": {"padding": 0}})).unwrap(); + s.execute("text.set", &json!({"id": t, "characters": ten(6)})).unwrap(); + assert_eq!(node(&s, f).layout.unwrap().padding, [16.0, 16.0, 16.0, 64.0]); + assert_eq!(bx(&s, f).height(), 176.0); + + let (f, t) = block(&mut s, json!({"x": 0, "y": 500})); + s.execute("node.set", &json!({"id": f, "props": {"minHeight": null}})).unwrap(); + s.execute("text.set", &json!({"id": t, "characters": "a"})).unwrap(); + assert_eq!(node(&s, f).child_layout.min_h, Some(128.0)); + assert_eq!(bx(&s, f).height(), 128.0); +} diff --git a/crates/engine/src/board_tests.rs b/crates/engine/src/board_tests.rs index dfcb28d32..83b353f96 100644 --- a/crates/engine/src/board_tests.rs +++ b/crates/engine/src/board_tests.rs @@ -465,6 +465,7 @@ fn board_commands_survive_junk() { json!({"end": "from", "target": {"x": 1e308, "y": -1e308}, "side": "inside", "style": "curved"}), json!({"id": 99_999, "end": 7, "target": [1], "style": "wavy"}), json!({"id": 99_999, "relation": 7, "children": "x", "text": [1], "x": "NaN", "y": 1e308}), + json!({"id": 99_999, "language": 7, "text": [1], "width": "wide", "x": "NaN", "y": 1e308, "side": 3}), ]; let ids: Vec<&str> = crate::cmd::all_commands() .iter() @@ -482,6 +483,7 @@ fn board_commands_survive_junk() { let a = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone(); let b = s.execute("board.shape", &json!({"x": 300, "y": 0})).unwrap()["id"].clone(); let _ = s.execute("board.connector", &json!({"from": a, "to": b, "label": "x"})); + let _ = s.execute("board.codeBlock", &json!({"x": 0, "y": 300, "text": "a\nb"})); if let Err(EngineError::Internal { cmd, msg }) = s.execute(cmd, j) { panic!("{cmd} panicked on {j}: {msg}"); } @@ -497,6 +499,7 @@ fn board_commands_survive_junk() { let a = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone(); let b = s.execute("board.stamp", &json!({"x": 300, "y": 0})).unwrap()["id"].clone(); let _ = s.execute("board.connector", &json!({"from": a, "to": b})); + let _ = s.execute("board.codeBlock", &json!({"x": 0, "y": 300, "text": "a\nb"})); if let Err(EngineError::Internal { cmd, msg }) = s.execute(spec.id, j) { panic!("{cmd} panicked on {j}: {msg}"); } diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index ddee2d823..a320ee6f5 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -21,6 +21,7 @@ use crate::params::{boolean, color_of, get, id, id_of, num, num_or, opt_id, req_ use crate::tools::{Gesture, PointerEvent, ToolId}; use crate::{EngineError, Result, Session, bad, spec, textedit}; +mod code; mod connectors; mod derived; mod edit; @@ -29,6 +30,7 @@ mod mindmap; mod reshape; mod tools; +pub use code::is_code_text; pub(crate) use connectors::end_handle_at; pub use connectors::{END_HANDLE_PX, selected_connector_ends}; use connectors::{connector_cmd, reattach}; @@ -144,7 +146,7 @@ pub fn specs() -> Vec { spec!( "board.nextSticky", "Next sticky note", - "{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected", + "{id? (a sticky, shape or code block; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected; after a code block, the next code block beside it (128 away), as wide and in the same language, not joined", true, next_sticky ), @@ -197,6 +199,20 @@ pub fn specs() -> Vec { true, mindmap::mind_map_add ), + spec!( + "board.codeBlock", + "Code block", + "{x?, y? (its top-left in the parent; default a four-line block centred in the view), language? (bash|cpp|css|go|graphql|html|javascript|json|kotlin|plainText|python|ruby|rust|sql|swift|typescript; default typescript), text?, width? (210 to 100000; default 576), parent?, edit? (start typing in it; default false)} → {id, text, language} a dark panel holding monospace text: as wide as it is made, as tall as its lines (four at least)", + true, + code::code_block_cmd + ), + spec!( + "board.setLanguage", + "Code language", + "{id? | ids? (code blocks; default the selected ones, or the one being typed in), language} → {ids}", + true, + code::set_language + ), spec!("board.label", "Connector label", "{id (a connector; default the selection), text (empty removes it)} → {id, label}", true, label_cmd), spec!( "board.stamp", diff --git a/crates/engine/src/boards/board/code.rs b/crates/engine/src/boards/board/code.rs new file mode 100644 index 000000000..226f51bd4 --- /dev/null +++ b/crates/engine/src/boards/board/code.rs @@ -0,0 +1,260 @@ +//! Code blocks (#2237): a frame hugging one monospace text ([`BoardItem::CodeBlock`]), as wide as +//! it was made and as tall as its lines. The commands only make the block; [`settle_code`] keeps +//! it that way in the normalize pass (the height is the lines', the text is plain code), so every +//! entry point (a drag, `node.set`, a styled paste, a live session's edit) ends the same. + +use std::collections::BTreeSet; + +use figcraft_color::Paint; +use figcraft_doc::{ + AutoLayout, BoardItem, CODE_FONT, CODE_FONT_SIZE, CODE_GAP, CODE_MAX_CHARS, CODE_MAX_W, CODE_MIN_H, CODE_MIN_W, CODE_PAD, CODE_PANEL, + CODE_RADIUS, CODE_TEXT, CODE_WIDTH, CodeLanguage, Document, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, ParaList, Sizing, TextAlignH, + TextAutoResize, TextCase, TextData, TextDecoration, +}; +use serde_json::{Value, json}; + +use super::items::{add, add_text, owner_of_text, soft_shadow, text_of}; +use super::{Result, Session, bad, boolean, get, num, parent_of, req_string, req_targets, require, string, textedit}; + +/// How far from the page's middle a block may be put. +const CODE_MAX_COORD: f64 = 1.0e9; + +/// Whether `text` is the text of a code block: what the text editor asks before it converts what +/// is typed (a list from `- `, and any smart punctuation or link to come). +pub fn is_code_text(doc: &Document, text: NodeId) -> bool { + owner_of_text(doc, text).and_then(|o| doc.node(o)).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. }))) +} + +/// The auto layout every code block has: its text stacked inside the padding. +fn block_layout() -> AutoLayout { + AutoLayout { mode: LayoutMode::Vertical, gap: 0.0, padding: CODE_PAD, ..AutoLayout::default() } +} + +/// A code block's frame and its text: `width` wide at `at` in `parent`, holding `text`. +fn make_code_block(doc: &mut Document, parent: NodeId, at: (f64, f64), width: f64, language: CodeLanguage, text: &str) -> Result<(NodeId, NodeId)> { + let frame = add(doc, parent, NodeKind::Frame, "Code block", at, (width, CODE_MIN_H), |n| { + n.fills = vec![Paint::solid(CODE_PANEL)]; + n.corners.radii = [CODE_RADIUS; 4]; + n.effects = vec![soft_shadow()]; + n.clip = false; + n.layout = Some(block_layout()); + n.child_layout.sizing_v = Sizing::Hug; + n.child_layout.min_h = Some(CODE_MIN_H); + n.child_layout.min_w = Some(CODE_MIN_W); + n.board = Some(BoardItem::CodeBlock { language }); + })?; + let inner = width - CODE_PAD[1] - CODE_PAD[3]; + let label = add_text(doc, frame, text, CODE_FONT_SIZE, CODE_TEXT, TextAlignH::Left, inner)?; + if let Some(NodeKind::Text(td)) = doc.node_mut(label).map(|n| &mut n.kind) { + td.style.font_family = CODE_FONT.into(); + td.style.line_height = LineHeight::Percent(150.0); + td.features.insert("liga".into(), false); + td.features.insert("calt".into(), false); + } + Ok((frame, label)) +} + +/// A language from its id or name, or an error listing the ids. +fn language_of(cmd: &str, v: &str) -> Result { + CodeLanguage::from_id(v).ok_or_else(|| { + let known: Vec<&str> = CodeLanguage::ALL.iter().map(|l| l.id()).collect(); + bad(cmd, format!("unknown language `{v}` ({})", known.join("|"))) + }) +} + +/// A coordinate from the params: given, it is a finite number within a billion of the origin. +fn coord(cmd: &str, p: &Value, key: &str, default: f64) -> Result { + let v = if get(p, key).is_none_or(Value::is_null) { Some(default) } else { num(p, key) }; + v.filter(|v| v.is_finite() && v.abs() <= CODE_MAX_COORD).ok_or_else(|| bad(cmd, format!("`{key}` is a position within a billion of the origin"))) +} + +pub(super) fn code_block_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "board.codeBlock"; + require(s, cmd)?; + let parent = parent_of(cmd, s, p)?; + let width = if get(p, "width").is_none_or(Value::is_null) { + CODE_WIDTH + } else { + num(p, "width") + .filter(|w| w.is_finite() && (CODE_MIN_W..=CODE_MAX_W).contains(w)) + .ok_or_else(|| bad(cmd, format!("`width` is a size from {CODE_MIN_W} to {CODE_MAX_W}")))? + }; + // The view's centre is on the page, and `x`/`y` are in the parent: a block in a section or + // frame takes the centre in that parent's coordinates (a parent that can't be inverted gives a + // non-finite centre, which `coord` refuses). + let (vx, vy) = { + let ds = s.ds()?; + let c = ds.doc.world_transform(parent).inverse() * figcraft_geom::Point::new(ds.view.cx, ds.view.cy); + (c.x, c.y) + }; + let x = coord(cmd, p, "x", vx - width / 2.0)?; + let y = coord(cmd, p, "y", vy - CODE_MIN_H / 2.0)?; + let language = match string(p, "language") { + Some(v) => language_of(cmd, &v)?, + None if get(p, "language").is_none_or(Value::is_null) => CodeLanguage::default(), + None => return Err(bad(cmd, "`language` is a language id")), + }; + let text = match get(p, "text") { + None | Some(Value::Null) => String::new(), + Some(Value::String(t)) => t.clone(), + Some(_) => return Err(bad(cmd, "`text` is a string")), + }; + if text.chars().count() > CODE_MAX_CHARS { + return Err(bad(cmd, format!("`text` is at most {CODE_MAX_CHARS} characters"))); + } + let (frame, label) = make_code_block(s.doc_mut()?, parent, (x, y), width, language, &text)?; + s.set_selection(vec![frame]); + if boolean(p, "edit") == Some(true) { + s.request_ui("board.editText", json!({"id": frame})); + } + Ok(json!({"id": frame, "text": label, "language": language.id()})) +} + +pub(super) fn set_language(s: &mut Session, p: &Value) -> Result { + let cmd = "board.setLanguage"; + require(s, cmd)?; + let language = language_of(cmd, &req_string(cmd, p, "language")?)?; + let targets = req_targets(cmd, s, p)?; + let doc = s.doc()?; + let blocks: BTreeSet = targets + .into_iter() + .map(|i| owner_of_text(doc, i).unwrap_or(i)) + .filter(|i| doc.node(*i).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. })))) + .collect(); + if blocks.is_empty() { + return Err(bad(cmd, "select a code block")); + } + let doc = s.doc_mut()?; + for &b in &blocks { + if doc.node(b).is_some_and(|n| n.board != Some(BoardItem::CodeBlock { language })) { + doc.get_mut(b)?.board = Some(BoardItem::CodeBlock { language }); + } + } + Ok(json!({"ids": blocks.into_iter().collect::>()})) +} + +/// `board.nextSticky` on code block `from`: the next one beside it, as wide and in the same +/// language, with no connector. +pub(super) fn next_block(s: &mut Session, from: NodeId, language: CodeLanguage, p: &Value) -> Result { + let cmd = "board.nextSticky"; + let editing = s.ds()?.text_edit.is_some(); + let doc = s.doc()?; + let n = doc.get(from)?; + let parent = n.parent.ok_or_else(|| bad(cmd, "that code block has no parent"))?; + let at = n.transform.translation(); + let (w, h) = (n.width, n.height); + let (x, y) = match string(p, "side").as_deref().unwrap_or("right") { + "right" => (at.x + w + CODE_GAP, at.y), + "left" => (at.x - CODE_GAP - w, at.y), + "below" => (at.x, at.y + h + CODE_GAP), + "above" => (at.x, at.y - CODE_GAP - CODE_MIN_H), + other => return Err(bad(cmd, format!("`side` is right, below, left or above, not `{other}`"))), + }; + if !(x.is_finite() && y.is_finite() && w.is_finite()) { + return Err(bad(cmd, "the next block can't be placed there")); + } + let width = w.clamp(CODE_MIN_W, CODE_MAX_W); + if editing { + textedit::end(s)?; + } + let (frame, label) = make_code_block(s.doc_mut()?, parent, (x, y), width, language, "")?; + s.set_selection(vec![frame]); + if boolean(p, "edit") == Some(true) { + s.request_ui("board.editText", json!({"id": frame})); + } + Ok(json!({"id": frame, "text": label, "language": language.id()})) +} + +/// Whether `td` is already plain code: no list, indent, spacing, link, decoration, case change or +/// hand-made run, and a height that follows its lines. +fn is_plain(td: &TextData) -> bool { + td.auto_resize == TextAutoResize::Height + && td.list == ListStyle::None + && td.paragraphs == plain_paragraphs(&td.paragraphs) + && td.paragraph_indent == 0.0 + && td.paragraph_spacing == 0.0 + && td.list_spacing == 0.0 + && td.style.link.is_none() + && td.style.decoration == TextDecoration::None + && td.style.decoration_look.is_none() + && td.style.case == TextCase::Original + && td.runs.is_empty() +} + +/// `paragraphs` with no list, level or counting offset (the direction stays); empty when that +/// leaves every paragraph at its default. +fn plain_paragraphs(paragraphs: &[ParaList]) -> Vec { + let v: Vec = paragraphs.iter().map(|p| ParaList { direction: p.direction, ..ParaList::default() }).collect(); + if v.iter().all(|p| *p == ParaList::default()) { Vec::new() } else { v } +} + +fn make_plain(td: &mut TextData) { + td.auto_resize = TextAutoResize::Height; + td.list = ListStyle::None; + td.paragraphs = plain_paragraphs(&td.paragraphs); + td.paragraph_indent = 0.0; + td.paragraph_spacing = 0.0; + td.list_spacing = 0.0; + td.style.link = None; + td.style.decoration = TextDecoration::None; + td.style.decoration_look = None; + td.style.case = TextCase::Original; + td.runs.clear(); +} + +/// In the normalize pass, before text is measured and layout runs: every code block an edit +/// touched (or whose text it touched) is as tall as its lines again and holds plain code. Nothing +/// is written for a block already in that form, so a second pass changes nothing. +pub(crate) fn settle_code(doc: &mut Document, touched: &BTreeSet) { + let is_block = |doc: &Document, id: NodeId| doc.node(id).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. }))); + let mut blocks = BTreeSet::new(); + for &id in touched { + if is_block(doc, id) { + blocks.insert(id); + } else if let Some(p) = doc.node(id).and_then(|n| n.parent).filter(|p| is_block(doc, *p)) { + blocks.insert(p); + } + } + for b in blocks { + // The frame's form is complete first: its layout and minimums (or it cannot hug) and a width that + // is not Hug (or its text cannot fill), else normalize puts them back every pass. + if let Some(n) = doc.node_mut(b) { + if n.layout.as_ref() != Some(&block_layout()) { + n.layout = Some(block_layout()); + } + if n.child_layout.min_h != Some(CODE_MIN_H) { + n.child_layout.min_h = Some(CODE_MIN_H); + } + if n.child_layout.min_w != Some(CODE_MIN_W) { + n.child_layout.min_w = Some(CODE_MIN_W); + } + if n.child_layout.sizing_h == Sizing::Hug { + n.child_layout.sizing_h = Sizing::Fixed; + } + } + // A fixed height is not kept: the layout pass sizes the block to its lines again. + if doc.node(b).is_some_and(|n| n.child_layout.sizing_v != Sizing::Hug) + && let Some(n) = doc.node_mut(b) + { + n.child_layout.sizing_v = Sizing::Hug; + } + let Some(t) = text_of(doc, b) else { continue }; + let Some(node) = doc.node(t) else { continue }; + let off = match &node.kind { + NodeKind::Text(td) => !is_plain(td), + _ => continue, + }; + let fill_off = node.child_layout.sizing_h != Sizing::Fill; + if !(off || fill_off) { + continue; + } + if let Some(n) = doc.node_mut(t) { + if fill_off { + n.child_layout.sizing_h = Sizing::Fill; + } + if off && let NodeKind::Text(td) = &mut n.kind { + make_plain(td); + } + } + } +} diff --git a/crates/engine/src/boards/board/derived.rs b/crates/engine/src/boards/board/derived.rs index a6461fb85..e62d41973 100644 --- a/crates/engine/src/boards/board/derived.rs +++ b/crates/engine/src/boards/board/derived.rs @@ -15,6 +15,7 @@ pub(crate) fn settle_text(doc: &mut Document, before: &Document, touched: &BTree return; } crate::board_table::settle_resize(doc, before, touched); + super::code::settle_code(doc, touched); for &id in touched { let Some(n) = doc.node(id) else { continue }; if let Some(BoardItem::Shape { shape }) = n.board diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs index 61a3c5659..6df2fa397 100644 --- a/crates/engine/src/boards/board/edit.rs +++ b/crates/engine/src/boards/board/edit.rs @@ -84,7 +84,7 @@ pub(super) fn set_color(s: &mut Session, p: &Value) -> Result { n.strokes = vec![Paint::solid(line_shade(color))]; } BoardItem::Connector(_) | BoardItem::Ink => doc.get_mut(id)?.strokes = vec![Paint::solid(line_shade(color))], - BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode => continue, + BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode | BoardItem::CodeBlock { .. } => continue, } changed.push(id); } diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index 431a27cf9..481f0ebed 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -26,7 +26,7 @@ pub(super) fn add( } /// A soft shadow under stickies and stamps. -fn soft_shadow() -> Effect { +pub(super) fn soft_shadow() -> Effect { Effect { kind: EffectKind::DropShadow(Shadow { color: Color::new(0.0, 0.0, 0.0, 0.16), offset: (0.0, 2.0), radius: 6.0, ..Shadow::default() }), visible: true, @@ -142,14 +142,17 @@ pub(super) fn next_sticky(s: &mut Session, p: &Value) -> Result { let from = id(p, "id") .or_else(|| editing.and_then(|t| owner_of_text(doc, t))) .or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i))) - .ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky or a shape first".into()))?; + .ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky, a shape or a code block first".into()))?; let n = doc.get(from)?; + if let Some(BoardItem::CodeBlock { language }) = n.board { + return super::code::next_block(s, from, language, p); + } if matches!(n.board, Some(BoardItem::Shape { .. })) { // A shape gets the next one joined to it, as the "+" beside it makes (#1597). return add_connected(s, p); } if !matches!(n.board, Some(BoardItem::Sticky { .. })) { - return Err(bad(cmd, "that isn't a sticky or a shape")); + return Err(bad(cmd, "that isn't a sticky, a shape or a code block")); } let color = n.fills.iter().find_map(Paint::solid_color).unwrap_or(s.tool.board.sticky); let parent = n.parent.ok_or_else(|| bad(cmd, "that sticky has no parent"))?; diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index 51a1640f7..6c8c15071 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -87,6 +87,12 @@ fn text_of(s: &Session, id: NodeId) -> Result { } } +/// Whether the text being edited is a code block's. +fn in_code(s: &Session) -> bool { + let Some(te) = s.ds().ok().and_then(|d| d.text_edit.as_ref()) else { return false }; + s.doc().is_ok_and(|d| crate::board::is_code_text(d, te.id)) +} + /// Start editing text node `id` with the caret at `caret` (None = select all). pub fn begin(s: &mut Session, id: NodeId, caret: Option, created: bool) -> Result<()> { let t = text_of(s, id)?; @@ -282,13 +288,15 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result. " or "1) " typed at the start of a plain paragraph starts a list // (the creation characters of Create bulleted and numbered lists). As measured in Figma // (2026-11-11), a typed "5. " starts the numbered list at 5 (there is no start-number // field). "0. " and a bracket after a number other than 1 are not measured: plain text. - if text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None { + if !code && text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None { let chars: Vec = t.characters.chars().collect(); let start = line_start(&chars, a); let typed: String = chars.get(start..a).unwrap_or(&[]).iter().collect(); @@ -463,6 +471,16 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R if matches!(key, "Tab" | "Backspace" | "Delete" | "Enter") && !word && !line && list_key(s, key, shift)? { return Ok(()); } + // In a code block Tab types two spaces and Enter keeps the line's indent. + if matches!(key, "Tab" | "Enter") && !word && !line && in_code(s) { + if key == "Tab" { + return if shift { Ok(()) } else { insert(s, figcraft_doc::CODE_TAB) }; + } + let (a, _) = range(&te); + let start = line_start(&chars, a); + let indent: String = chars.get(start..a).unwrap_or(&[]).iter().take(256).take_while(|c| matches!(c, ' ' | '\t')).collect(); + return insert(s, &format!("\n{indent}")); + } match key { "Escape" => return end(s), "Enter" => return insert(s, "\n"), diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index c865924c5..177155a8a 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -642,7 +642,7 @@ pub fn specs() -> Vec { spec!( "text.edit.key", "Text key", - "{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out", + "{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent", true, |s, p| { let k = req_string("text.edit.key", p, "key")?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6fe5633ad..a66290647 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -208,6 +208,8 @@ mod batch_undo_snapshot_tests; #[cfg(test)] mod binding_lists_tests; #[cfg(test)] +mod board_code_tests; +#[cfg(test)] mod board_connected_tests; #[cfg(test)] mod board_connector_tests; diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index fa3d5e4e5..95e6db394 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -153,7 +153,7 @@ fn has(app: &FigApp) -> Option { } Some(BoardItem::Label { .. } | BoardItem::MindNode) => h.text = true, Some(BoardItem::Table) => h.table = true, - Some(BoardItem::Stamp { .. }) | None => {} + Some(BoardItem::Stamp { .. } | BoardItem::CodeBlock { .. }) | None => {} } } h.only_lines = h.connector.is_some() && !others; diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 567b9b61e..83a632057 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-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); a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; 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 (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); 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); a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; 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 @@ -58,7 +58,8 @@ all end with the same geometry. | Templates (retrospective, brainstorm, flow chart…) | partial | five built-in templates drawn up for FigCraft (retrospective, brainstorm, weekly planner, flow chart, kanban board), placed from the toolbar's templates picker (each with a picture of itself) or `board.template {name, x?, y?}` as ordinary sections, stickies, shapes, connectors and text in one undo step; `board.templates` lists them. No community templates, no saving your own | | Tables | partial | `board.table {rows, columns, cells?, x?, y?}` (at most 50 × 20): an auto layout frame of rows of cells with text, a tinted header row and lines between rows and columns; a cell's row grows with its text; resizing a table by its bottom edge or its height grows the last row and a corner drag shares the change equally over every row and column (a side drag changes no row), the table keeps hugging its rows and a cell keeps at least 40 each way (measured in FigJam's web app, 2026-11-09: its floor is about 52, FigCraft's is 40, and its right edge grows only the last column); a double-click types in the cell under the pointer; add or remove a row or column from the bar over the selection or `board.tableEdit {id, action, index?}`; cells copied from a spreadsheet (tab-separated text, quoted cells kept whole) paste as a table, up to 50 × 20 with a note when there was more; undoable and synced in live sessions. No per-column widths yet (a width change splits equally), no column resizing by dragging, no cell colours, no Tab between cells; comma-separated text pastes as text | | Mind maps | partial | from commands only so far (#2226): `board.mindMap {x?, y?, text?, children?}` places a first node (bold, no box) with three children on its right, joined by curved branches; `board.mindMapAdd {id?, relation?: child\|sibling}` adds a node. Nodes are text that grows wider as it is typed and taller with line breaks; a node's children stand in one column 88 units right of the widest node of its own column, 48 apart, centred on it, and the map lays itself out again in the normalize pass after every edit, undo and live-session change; moving the first node moves the map; a deleted node's children stay where they are without their branch. Branches are board connectors (`branch`: stroke 4, #757575, round caps), so their style, end points, weight and colour change like any connector's. No toolbar entry, shortcuts, "+" handles, dragging a node onto another, left side or `.jam` import yet | -| Washi tape, code blocks, image cropping on boards | missing | images can be placed as in design files | +| Code blocks | partial | from commands only so far (#2237): `board.codeBlock {x?, y?, language?, text?, width?}` places a dark panel holding monospace text (Liberation Mono 16 on a 24 line where it is embedded or installed), 576 wide; its height is its lines (32 + 24 a line, wrapped lines counted, never under four lines) and only its width can be changed (210 at least); `board.setLanguage {id?, language}` keeps one of 16 languages (TypeScript by default); `board.nextSticky` on a block makes the next one 128 to its right, as wide and in the same language. In a block Tab types two spaces, Enter keeps the line's indent, and lists, links and styled ranges don't apply. No toolbar entry, language menu, highlighting colours, line numbers or `.jam` import yet | +| Washi tape, image cropping on boards | missing | images can be placed as in design files | | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | | 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 | @@ -68,6 +69,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | M12, #2237 (step 1 of 4): code blocks in the document and engine. A code block is a board object of its own (`BoardItem::CodeBlock { language }`): a hugging frame holding one monospace text, 576 wide, 32 + 24 a visual line tall and never under four lines; only its width is kept from a resize. `board.codeBlock` places one, `board.setLanguage` picks one of 16 languages, and `board.nextSticky` makes the next block beside it. The normalize pass keeps a block's text plain code (`board::settle_code`) and the text editor types literally in it (two spaces for Tab, the line's indent after Enter, no list from `- `). The colours are FigCraft's own (the board's ink and tints); the sizes are from a FigJam measurement. Tests: `board_code_tests` in doc (four) and engine (thirteen). Numbers unchanged (no toolbar entry yet). | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Shapes with text, Connectors, Create the next shape already connected. | | 2026-11-12 | minor | M12: a sticky's text-size menu. Measured in FigJam's web app, 2026-11-12: the menu lists Small 16, Medium 24, Large 40, Extra large 64 and Huge 96 (typing 40 shows Large), a fresh sticky is Small = 16 (read twice from the size field; the 18 of 2026-11-09 did not reproduce), the note stays square to Extra large and grows taller at Huge with the same width and shrinks back at Large, choosing a size with two stickies selected sets both, and the sticky tool remembers the last size. `STICKY_TEXT_SIZE` is 16, `STICKY_SIZES` holds the table, `board.setStyle {fontSize}` sizes stickies and sets the tool's size, `board.sticky` takes `fontSize`, and the contextual bar shows a size menu when only stickies carry text (shapes keep S/M/L/XL, unmeasured). Stacks are still missing. Tests: `a_new_sticky_is_small_16`, `the_sticky_sizes_are_figjams`, `set_style_font_size_sizes_every_selected_sticky`, `the_sticky_tool_remembers_the_last_size`, `a_huge_sticky_grows_taller_and_shrinks_back`, `a_selected_sticky_has_a_size_menu_instead_of_the_size_cells` | | 2026-11-09 | minor | M12, #2172: a board table's height change goes into its rows. Measured in FigJam's web app, 2026-11-09 (a table has no lock-proportions control and never scales proportionally): a bottom-edge drag grows only the last row, a corner drag shares the change equally over every row and column, text keeps its size, and a table stops shrinking at about 52 per cell with a row never shorter than its wrapped text. FigCraft already split a width change equally (every cell fills); the bug was height: a bottom or corner resize turned the table from hugging to fixed height, so the rows stayed at 40 with blank space below them (or were clipped when shrunk) and typing no longer grew the table. `board_table::settle_resize`, called first in the normalize pass, finds a table left at a fixed height, puts the change into the rows' minimum height (the last row, or every row when both axes changed), raises a width that is too narrow to `columns x 40`, and returns the table to hugging, so every route (drag, `node.set`, `transform.resize`, MCP, live-session peers) gives the same result, in one undo step. FigCraft's floor is 40 (FigJam's is about 52) and there are no per-column widths yet: a side drag of the right edge still splits equally where FigJam grows only the last column. Numbers unchanged. Tests: `board_tables_tests` (the bottom, corner and side drags, the floor, typing after a resize and undo, live sessions, junk). | diff --git a/docs/gaps.md b/docs/gaps.md index bb3ede386..d13953a32 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -606,7 +606,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe connector's ends drag onto another object or empty canvas (`board.reattach`); curved connectors; elbows that go around the objects they join. - **Missing:** timer music, board widgets, saving your own templates, table column resizing and - cell colours, the mind maps' toolbar entry, shortcuts, drag to re-parent and import, washi tape, code blocks, audio and huddles, quick-create handles, + cell colours, the mind maps' toolbar entry, shortcuts, drag to re-parent and import, washi tape, the code blocks' toolbar entry, language menu, highlighting and import, audio and huddles, quick-create handles, the stamp wheel, emotes and stickers, `.jam` files ([`boards-parity.md`](boards-parity.md)). - **User impact:** boards cover a brainstorm, a retrospective, a flow sketch and a timed, voted @@ -617,6 +617,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`; a block is as tall as its lines and keeps its text plain code, #2237); the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. | | 2026-11-18 | minor | Gap 10: library analytics count insertions and detachments of styles and variables; modes stay on the missing list. | | 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. | | 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` | diff --git a/docs/mcp.md b/docs/mcp.md index 8940fa184..2d6580fd7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -499,7 +499,7 @@ Returns `{fitted: [{id, fontSize, lines, fits, orphan}]}`. Use case: a carousel A board is a file of its own kind for thinking together: `file.newBoard {name?}` opens one (its page is light; `inspect_document` says `kind: "board"`). Board objects are ordinary layers with a -`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink|mindNode, …}`; a connector may say +`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink|mindNode|codeBlock, …}`; a connector may say `branch: true`), so the usual commands move, resize, recolour, copy, delete and undo them. On a design file the board commands refuse; on a board `proto.*`, `dev.*`, `view.prototype` and `view.devMode` refuse. Each of these is @@ -513,6 +513,8 @@ one undo step and returns the ids it made: same colour beside the selected (or edited) one; with `edit: true` the app goes on typing in it (`Shift+Cmd/Ctrl+Enter` in the app does both). On a shape it does what `board.addConnected` does: the next shape, joined to it by a connector (`{id, text, connector}`). + On a code block it makes the next code block 128 units beside it (`side`, default right), as wide and + in the same language, not joined (`{id, text, language}`). - `board.addConnected {id?, side?: right|below|left|above, edit?}` → `{id, text, connector}`: the next sticky or shape of the same kind, size and colour on that side of the selected (or edited) one, 80 units away, joined to it by a connector the way the Connector tool makes one; one undo @@ -533,6 +535,17 @@ one undo step and returns the ids it made: of the map that the given (or selected, or edited) one belongs to: a child below its other children, or a sibling right after it (the first node has none); the map lays itself out again. One undo step. With `edit: true` the app goes on typing in it. +- `board.codeBlock {x?, y?, language?, text?, width?, parent?, edit?}` → `{id, text, language}`: a code + block (`codeBlock` with its `language`): a dark panel holding monospace text (Liberation Mono 16 on a + 24 line where it is embedded or installed). `language` is `bash cpp css go graphql html javascript json + kotlin plainText python ruby rust sql swift typescript` (default `typescript`); `width` is 210 to 100000 + (default 576); `x`/`y` are its top-left corner, by default the view's centre less half the width and less 64 (half the + smallest height, 128), so a block of more lines reaches further down. Its height is its lines: 32 + 24 a visual line, + never under four lines, so only its width can be changed (a set or dragged height is not kept). In its + text Tab types two spaces, Enter keeps the line's indent, and lists, links and styled ranges do not stick. + One undo step. +- `board.setLanguage {id?, ids?, language}` → `{ids}`: the language of the given (or selected, or edited) + code blocks, by id or name (`cpp` or `C++`). - `board.shape {shape, x, y, width?, height?, text?, color?, parent?}` → `{id, text}`: a shape with centred, wrapping text: `rectangle roundedRectangle ellipse diamond triangle triangleDown parallelogramRight parallelogramLeft trapezoid pentagon hexagon octagon star plus arrowLeft arrowRight chevron speechBubble database document predefinedProcess manualInput internalStorage`. - `board.connector {from, to, fromSide?, toSide?, fromAt?, toAt?, style?: straight|elbow|curved, startCap?, endCap?, label?}` diff --git a/docs/roadmap.md b/docs/roadmap.md index b797063a6..27d7af485 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -76,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M12, #2237 (step 1 of 4): code blocks in the document and engine. `board.codeBlock` places a dark panel of monospace text as tall as its lines, `board.setLanguage` picks one of 16 languages, and `board.nextSticky` makes the next block beside it; the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. Numbers unchanged. | | 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | From a4099033f74cf9d6696ba9bae486793cf2c0c35e Mon Sep 17 00:00:00 2001 From: B-uchi Date: Wed, 18 Nov 2026 07:46:14 +0100 Subject: [PATCH 109/129] M8: inspect `fields` accepts dashCap, which node.get already writes node.get and document.inspect write `dashCap` on a layer with a dash cap, but it was missing from NODE_KEYS, so `fields: ["dashCap"]` was refused as an unknown key (and the MCP tools' `fields` schema left it out). A test now walks the keys a varied layer tree writes and checks each is one `fields` accepts. --- crates/engine/src/automation/inspect.rs | 1 + crates/engine/src/inspect_fields_tests.rs | 39 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index a3c0b94e5..359c58bb4 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -27,6 +27,7 @@ pub const NODE_KEYS: &[&str] = &[ "constraints", "cornerRadius", "cornerSmoothing", + "dashCap", "dashes", "description", "devChanged", diff --git a/crates/engine/src/inspect_fields_tests.rs b/crates/engine/src/inspect_fields_tests.rs index 592ca8b94..c121092ef 100644 --- a/crates/engine/src/inspect_fields_tests.rs +++ b/crates/engine/src/inspect_fields_tests.rs @@ -561,3 +561,42 @@ fn modes_property_bindings_and_exposed_instances_are_read() { s.execute("component.exposeInstance", &json!({"id": nested.clone()})).unwrap(); assert_eq!(s.execute("node.get", &json!({"id": nested})).unwrap()["exposedInstance"], true); } + +/// Every key a layer's JSON can have is one `fields` accepts: a key missing from `NODE_KEYS` can be +/// read in full output but is refused when asked for by name (`dashCap` was). +#[test] +fn every_key_node_get_writes_can_be_asked_for() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let frame = s + .execute("node.create", &json!({"type": "frame", "width": 200, "height": 100, "props": {"layout": {"mode": "horizontal"}, "gap": 4}})) + .unwrap()["id"] + .clone(); + let line = s + .execute( + "node.create", + &json!({"type": "line", "parent": frame, "width": 80, "props": { + "strokes": ["#000000"], "strokeWeight": 2, "dashes": [4, 2], "dashCap": "round", "strokeJoin": "round", + "opacity": 0.5, "visible": false, "locked": true}}), + ) + .unwrap()["id"] + .clone(); + s.execute("node.create", &json!({"type": "text", "parent": frame, "text": "Hi", "props": {"textDecoration": "underline"}})).unwrap(); + s.execute("annotation.add", &json!({"id": line, "label": "Note"})).unwrap(); + let mut keys = std::collections::BTreeSet::new(); + fn walk(v: &Value, keys: &mut std::collections::BTreeSet) { + if let Some(o) = v.as_object() { + keys.extend(o.keys().cloned()); + for c in o.get("children").and_then(Value::as_array).into_iter().flatten() { + walk(c, keys); + } + } + } + walk(&node_json(s.doc().unwrap(), crate::params::id_of(&frame).unwrap(), 4), &mut keys); + assert!(keys.contains("dashCap"), "the test sets a dash cap: {keys:?}"); + for key in keys { + assert!(crate::inspect::NODE_KEYS.contains(&key.as_str()), "`{key}` is written but `fields` refuses it"); + let one = InspectOptions::parse(&json!({"fields": [key]})); + assert!(one.is_ok(), "{key}: {one:?}"); + } +} From 79a1ea4a4293edbdc08750de812fff7852904106 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 02:36:08 +0700 Subject: [PATCH 110/129] M8: keep the canvas input under the complexity limit with edge panning (#2104) The pan past the canvas edge moves into a helper of its own. --- crates/ui-egui/src/canvas/input.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 1360697d8..6ecdb948c 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -226,13 +226,7 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo send(app, PointerKind::Up, at, &mods); } } - // A drag held past the edge pans toward it, the layer or box going with the pointer. - if super::autopan::wanted(app, &ctx) - && let Some(at) = ctx.input(|i| i.pointer.latest_pos()) - && super::autopan::pan(app, &ctx, at) - { - send(app, PointerKind::Move, at, &mods); - } + pan_past_edge(app, &ctx, &mods); // Leaving the canvas: nothing is hovered there any more. if !app.canvas.dragging && std::mem::take(&mut app.canvas.hovering) { left(app); @@ -410,6 +404,16 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo } /// Pointer event `kind` at screen point `pos`, to the tools. +/// A drag held past the edge pans toward it, the layer or box going with the pointer. +fn pan_past_edge(app: &mut FigApp, ctx: &egui::Context, mods: &egui::Modifiers) { + if super::autopan::wanted(app, ctx) + && let Some(at) = ctx.input(|i| i.pointer.latest_pos()) + && super::autopan::pan(app, ctx, at) + { + send(app, PointerKind::Move, at, mods); + } +} + fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) { let ev = pointer_event(app, kind, pos, m); // A hover where nothing changed since the last one finds what that one found (the state is From 2d4309c9aa61facdea6c698e0010fee43a2e5558 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Wed, 18 Nov 2026 08:20:59 +0100 Subject: [PATCH 111/129] M8: design context for AI agents inspect.designContext and the MCP tool design_context read the selection (or ids, or a scope) in one call. Each layer keeps apart the values the designer set (explicit), those layout or the file worked out (derived) and those with no direct CSS equivalent (unsupported, with the reason). The variables (every mode's stored and resolved value), styles, components, fonts and assets the tree uses are joined once, and `missing` says what the design doesn't specify. A connected instance gives its code snippet instead of its layers. Large trees are capped and say so, and the MCP tool asks for fewer layers until the result fits the client. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 1 + crates/engine/src/design_context_tests.rs | 288 ++++++++++++++ crates/engine/src/dev.rs | 1 + crates/engine/src/dev/design_context.rs | 434 ++++++++++++++++++++++ crates/engine/src/lib.rs | 3 + crates/mcp/src/tools.rs | 38 ++ crates/mcp/tests/it/inspect_fields.rs | 18 + docs/mcp.md | 36 ++ 9 files changed, 820 insertions(+) create mode 100644 crates/engine/src/design_context_tests.rs create mode 100644 crates/engine/src/dev/design_context.rs diff --git a/ROADMAP.md b/ROADMAP.md index 107a11f96..95e1a67ef 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged | | 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0e90dc198..b90204504 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -100,6 +100,7 @@ fn registry() -> &'static Registry { list.extend(crate::shapebuilder::specs()); list.extend(crate::codegen::specs()); list.extend(crate::devinspect::specs()); + list.extend(crate::design_context::specs()); list.extend(crate::component_codegen::specs()); list.extend(crate::playground::specs()); list.extend(crate::code_connect::specs()); diff --git a/crates/engine/src/design_context_tests.rs b/crates/engine/src/design_context_tests.rs new file mode 100644 index 000000000..3aa0ab09b --- /dev/null +++ b/crates/engine/src/design_context_tests.rs @@ -0,0 +1,288 @@ +//! `inspect.designContext` against documents built with real commands. + +use serde_json::{Value, json}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s +} + +fn id(v: &Value) -> u64 { + v["id"].as_u64().unwrap() +} + +fn node(s: &mut Session, params: Value) -> u64 { + id(&s.execute("node.create", ¶ms).unwrap()) +} + +fn context(s: &mut Session, params: Value) -> Value { + s.execute("inspect.designContext", ¶ms).unwrap() +} + +/// A hugging auto layout card holding a fixed title and a filling line. +fn card(s: &mut Session) -> (u64, u64, u64) { + let f = node(s, json!({"type": "frame", "name": "Card", "x": 40, "y": 30, "width": 300, "height": 200, "props": {"fill": "#FFFFFF"}})); + s.execute("node.set", &json!({"ids": [f], "props": {"layout": {"mode": "vertical"}, "gap": 12, "padding": [16, 16, 16, 16], "sizingV": "hug"}})) + .unwrap(); + let title = node(s, json!({"type": "text", "parent": f, "name": "Title", "text": "Pro plan", "props": {"fontSize": 24}})); + let line = node(s, json!({"type": "rectangle", "parent": f, "name": "Rule", "width": 100, "height": 2, "props": {"sizingH": "fill"}})); + (f, title, line) +} + +fn only(v: &Value) -> &Value { + let nodes = v["nodes"].as_array().unwrap(); + assert_eq!(nodes.len(), 1, "{v}"); + &nodes[0] +} + +#[test] +fn the_selection_is_what_is_read() { + let mut s = session(); + let (f, title, _) = card(&mut s); + let other = node(&mut s, json!({"type": "rectangle", "name": "Elsewhere", "width": 10, "height": 10})); + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let v = context(&mut s, json!({})); + assert_eq!(v["target"]["source"], "selection"); + assert_eq!(only(&v)["id"], f); + assert_eq!(only(&v)["children"][0]["id"], title); + assert_eq!(v["target"]["layers"], 3); + assert!(!v.to_string().contains("Elsewhere"), "the rest of the page stays out"); + let _ = other; +} + +#[test] +fn several_selected_layers_each_come_back() { + let mut s = session(); + let a = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10})); + let b = node(&mut s, json!({"type": "ellipse", "width": 10, "height": 10})); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + assert_eq!(context(&mut s, json!({}))["nodes"].as_array().unwrap().len(), 2); +} + +#[test] +fn ids_and_scopes_choose_the_target() { + let mut s = session(); + let (f, _, _) = card(&mut s); + let other = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10})); + s.execute("select.set", &json!({"ids": [other]})).unwrap(); + assert_eq!(context(&mut s, json!({"ids": [f]}))["target"]["source"], "ids"); + assert_eq!(context(&mut s, json!({"scope": "page"}))["nodes"].as_array().unwrap().len(), 2); + s.execute("page.add", &json!({"name": "Second"})).unwrap(); + assert_eq!(context(&mut s, json!({"scope": "document"}))["target"]["source"], "document"); + assert!(s.execute("inspect.designContext", &json!({"ids": [999_999]})).is_err()); + assert!(s.execute("inspect.designContext", &json!({"scope": "everything"})).is_err()); +} + +#[test] +fn nothing_selected_reads_the_page() { + let mut s = session(); + card(&mut s); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(context(&mut s, json!({}))["target"]["source"], "page"); +} + +#[test] +fn what_layout_decides_is_derived_and_what_the_designer_set_is_explicit() { + let mut s = session(); + let (f, _, _) = card(&mut s); + let v = context(&mut s, json!({"ids": [f]})); + let frame = only(&v); + assert_eq!(frame["explicit"]["width"], 300.0, "a fixed width is the designer's"); + assert_eq!(frame["explicit"]["x"], 40.0); + assert!(frame["explicit"].get("height").is_none(), "a hug height isn't"); + assert!(frame["derived"]["height"].is_number()); + assert!(frame["derived"]["absoluteBounds"].is_object()); + assert_eq!(frame["explicit"]["layout"]["gap"], 12.0); + let (title, rule) = (&frame["children"][0], &frame["children"][1]); + assert!(title["derived"].get("x").is_some(), "its place comes from the flow: {title}"); + assert!(title["explicit"].get("x").is_none()); + assert!(title["derived"].get("width").is_some(), "auto-width text: {title}"); + assert!(rule["derived"].get("width").is_some(), "fill: {rule}"); + assert_eq!(rule["explicit"]["height"], 2.0); +} + +#[test] +fn the_values_are_the_documents() { + let mut s = session(); + let (f, title, _) = card(&mut s); + let v = context(&mut s, json!({"ids": [f]})); + let got = &only(&v)["children"][0]["explicit"]; + let inspected = s.execute("node.get", &json!({"id": title})).unwrap(); + for key in ["characters", "fontFamily", "fontSize", "lineHeight", "letterSpacing", "textAlign", "fontStyle"] { + assert_eq!(got[key], inspected[key], "{key}"); + } + assert_eq!(got["characters"], "Pro plan"); +} + +#[test] +fn tokens_are_joined_with_every_modes_value() { + let mut s = session(); + let c = s.execute("variable.createCollection", &json!({"name": "Theme", "modes": ["Light", "Dark"]})).unwrap(); + let collection = c["id"].clone(); + let var = s + .execute( + "variable.create", + &json!({"collection": collection, "name": "surface", "type": "color", "values": {"Light": "#FFFFFF", "Dark": "#101010"}}), + ) + .unwrap(); + let var_id = var["id"].as_str().unwrap().to_string(); + s.execute("variable.update", &json!({"variable": var_id, "codeSyntax": {"WEB": "var(--surface)"}})).unwrap(); + let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": {"$var": var_id}}})); + let v = context(&mut s, json!({"ids": [r]})); + let bound = only(&v)["tokens"].as_object().unwrap().values().next().unwrap().clone(); + assert_eq!((bound["variable"].as_str(), bound["name"].as_str()), (Some(var_id.as_str()), Some("surface"))); + let entry = &v["variables"][var_id.as_str()]; + assert_eq!((entry["name"].as_str(), entry["collection"].as_str()), (Some("surface"), Some("Theme"))); + assert_eq!(entry["codeSyntax"]["WEB"], "var(--surface)"); + assert_eq!(entry["modes"][0]["mode"], "Light"); + assert_eq!(entry["modes"][1]["resolved"], "#101010"); +} + +#[test] +fn a_shared_style_is_named_and_defined_once() { + let mut s = session(); + let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": "#FF0000"}})); + let st = s.execute("style.create", &json!({"type": "paint", "name": "Brand/Red", "from": r})).unwrap(); + s.execute("style.apply", &json!({"style": st["id"], "ids": [r]})).unwrap(); + let v = context(&mut s, json!({"ids": [r]})); + assert_eq!(only(&v)["tokens"]["style.fill"]["name"], "Brand/Red"); + assert_eq!(v["styles"].as_object().unwrap().len(), 1); + assert_eq!(v["styles"][st["id"].as_str().unwrap()]["name"], "Brand/Red"); +} + +#[test] +fn a_connected_instance_gives_its_code_not_its_layers() { + let mut s = session(); + let b = node(&mut s, json!({"type": "frame", "name": "Button", "width": 80, "height": 32})); + node(&mut s, json!({"type": "text", "parent": b, "text": "Buy"})); + let main = id(&s.execute("component.create", &json!({"ids": [b]})).unwrap()); + let instance = id(&s.execute("instance.create", &json!({"component": main})).unwrap()); + s.execute("codeConnect.set", &json!({"id": main, "language": "react", "importPath": "@/ui/button", "name": "Button", "template": "