diff --git a/ROADMAP.md b/ROADMAP.md index 74638c4cc..54921fb11 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (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-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 | | 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/apps/figcraft-web/src/api.rs b/apps/figcraft-web/src/api.rs index 167ea7687..cb82820b7 100644 --- a/apps/figcraft-web/src/api.rs +++ b/apps/figcraft-web/src/api.rs @@ -37,7 +37,7 @@ use figcraft_ui_egui::{ControlReply, ControlRequest, RequestGate}; use serde_json::{Value, json}; use wasm_bindgen::JsCast; use wasm_bindgen::prelude::*; -use wasm_bindgen_futures::{JsFuture, future_to_promise}; +use wasm_bindgen_futures::JsFuture; use crate::saved_files::SavedFiles; @@ -150,15 +150,6 @@ async fn sleep(ms: i32) { let _ = JsFuture::from(promise).await; } -/// A reply as a promise outcome: the `result`, or an `Error` carrying the `error`. -fn outcome(reply: &Value) -> Result { - if reply.get("ok").and_then(Value::as_bool) == Some(true) { - Ok(to_js(reply.get("result").unwrap_or(&Value::Null))) - } else { - Err(js_sys::Error::new(reply.get("error").and_then(Value::as_str).unwrap_or("error")).into()) - } -} - fn set_fn(obj: &js_sys::Object, name: &str, f: JsValue) -> Result<(), JsValue> { js_sys::Reflect::set(obj, &name.into(), &f).map(|_| ()) } @@ -169,20 +160,20 @@ pub fn install() -> Result<(), JsValue> { Rc::new(PageApi::new(APP, Methods::default(), request)).install()?; let window = web_sys::window().ok_or("no window")?; let obj: js_sys::Object = js_sys::Reflect::get(&window, &APP.into())?.unchecked_into(); - set_fn( - &obj, - "inspect", - Closure:: js_sys::Promise>::new(|| future_to_promise(async { outcome(&send("document.inspect", json!({})).await) })) - .into_js_value(), - )?; + // `inspect` is `docInspect` under its earlier name: the crate's function, so it times out too. + let doc_inspect = js_sys::Reflect::get(&obj, &"docInspect".into())?; + js_sys::Reflect::set(&obj, &"inspect".into(), &doc_inspect)?; + // `openFile` runs `file.open` through the crate's `execute`, so a call the app does not answer times out and is cancelled. + let execute: js_sys::Function = js_sys::Reflect::get(&obj, &"execute".into())?.unchecked_into(); + let this = obj.clone(); set_fn( &obj, "openFile", - Closure:: js_sys::Promise>::new(|name: String, bytes: js_sys::Uint8Array| { + Closure:: JsValue>::new(move |name: String, bytes: js_sys::Uint8Array| { let data = base64::engine::general_purpose::STANDARD.encode(bytes.to_vec()); - future_to_promise(async move { - outcome(&send("engine.execute", json!({"command": "file.open", "params": {"name": name, "data": data}})).await) - }) + execute + .call2(&this, &"file.open".into(), &to_js(&json!({"name": name, "data": data}))) + .unwrap_or_else(|e| js_sys::Promise::reject(&e).into()) }) .into_js_value(), )?; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 5b90b3bff..f9601f362 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -395,7 +395,8 @@ impl NodeKind { ) } - /// Kinds whose corners can be rounded from the panel. + /// Kinds whose corners can be rounded from the panel. A boolean group has one radius for every + /// sharp corner of its result. pub fn has_corner_radius(&self) -> bool { matches!( self, @@ -408,16 +409,19 @@ impl NodeKind { | NodeKind::Star { .. } | NodeKind::Vector { .. } | NodeKind::Section { .. } + | NodeKind::BooleanOp { .. } ) } - /// Kinds with a radius per corner (the others round every corner alike). + /// Kinds with a radius per corner (the others, boolean groups included, round every corner alike). pub fn has_independent_corners(&self) -> bool { - self.has_corner_radius() && !matches!(self, NodeKind::Polygon { .. } | NodeKind::Star { .. } | NodeKind::Vector { .. }) + self.has_corner_radius() + && !matches!(self, NodeKind::Polygon { .. } | NodeKind::Star { .. } | NodeKind::Vector { .. } | NodeKind::BooleanOp { .. }) } /// Kinds whose rounded corners are drawn with corner smoothing: a vector only when its network - /// has a closed region (an open path's rounded points are drawn without it). + /// has a closed region (an open path's rounded points are drawn without it). A boolean group's + /// smoothing applies to its result's corners between straight edges. pub fn has_corner_smoothing(&self) -> bool { match self { NodeKind::Vector { network } => !network.regions.is_empty(), diff --git a/crates/doc/src/props.rs b/crates/doc/src/props.rs index 15d557d88..1c7f16929 100644 --- a/crates/doc/src/props.rs +++ b/crates/doc/src/props.rs @@ -1453,8 +1453,10 @@ pub struct PrintSettings { /// is printed this far out, to be trimmed off. pub bleed: f64, /// Crop marks outside the bleed, at the trim's corners. + #[serde(alias = "crop_marks")] pub crop_marks: bool, /// Bleed marks outside the bleed, at the bleed's corners. + #[serde(alias = "bleed_marks")] pub bleed_marks: bool, /// CMYK colour (converted from RGB) instead of RGB. pub cmyk: bool, @@ -1523,25 +1525,32 @@ pub struct ExportSetting { pub print: PrintSettings, /// Only the layer itself (on), or every layer that shows in its area (off). #[serde(skip_serializing_if = "is_true")] + #[serde(alias = "contents_only")] pub contents_only: bool, /// The layer's own box, cutting off what it paints outside it (shadows, outside strokes). #[serde(skip_serializing_if = "is_false")] + #[serde(alias = "include_bounding_box")] pub include_bounding_box: bool, /// SVG: text as outlines (on) or as `` elements (off). #[serde(skip_serializing_if = "is_true")] + #[serde(alias = "svg_outline_text")] pub svg_outline_text: bool, /// SVG: layer names as `id` attributes. #[serde(skip_serializing_if = "is_false")] + #[serde(alias = "svg_id_attribute")] pub svg_id_attribute: bool, /// SVG: strokes as `stroke` attributes where that's exact (on), else as outlines. #[serde(skip_serializing_if = "is_true")] + #[serde(alias = "svg_simplify_stroke")] pub svg_simplify_stroke: bool, /// Android Vector Drawable: what to do with what a drawable can't hold exactly. #[serde(skip_serializing_if = "VdCompat::is_default")] + #[serde(alias = "vd_compat")] pub vd_compat: VdCompat, /// PNG, JPG and WebP: the color profile the file is written in. SVG, PDF and XML are always /// sRGB, whatever this says. #[serde(skip_serializing_if = "ExportColorProfile::is_default")] + #[serde(alias = "color_profile")] pub color_profile: ExportColorProfile, /// JPG: the encoder's quality, 1 (smallest file) to 100 (see [`ExportSetting::quality`]). #[serde(skip_serializing_if = "is_default_quality")] diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 75dbe7cf1..9d922d6c8 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -902,6 +902,46 @@ fn a_chamfered_rectangles_rounded_fill_is_cut_at_every_point() { } } +/// The reporter's network (#1951): a corner cut off by a segment drawn before the corner point was +/// deleted, so the region's loop is the open chain of the other four segments and the cutting +/// segment, joining the chain's two ends, is in no loop. Rounded, the fill and the region trace +/// the stroke's outline, cut by an arc at the chain's ends as at every other point. +#[test] +fn a_rounded_loop_left_open_where_a_segment_joins_its_ends_follows_that_segment() { + open_loop_follows_the_segment_joining_its_ends([(0, 3), (1, 2), (2, 0), (4, 1), (3, 4)], vec![3, 1, 2, 0]); +} + +/// The same network with the joining segment listed first, and with the loop walked the other way. +#[test] +fn an_open_loop_follows_the_segment_joining_its_ends_listed_first_or_walked_backwards() { + open_loop_follows_the_segment_joining_its_ends([(3, 4), (0, 3), (1, 2), (2, 0), (4, 1)], vec![4, 2, 3, 1]); + open_loop_follows_the_segment_joining_its_ends([(0, 3), (1, 2), (2, 0), (4, 1), (3, 4)], vec![0, 2, 1, 3]); +} + +fn open_loop_follows_the_segment_joining_its_ends(segments: [(usize, usize); 5], open_loop: Vec) { + use figcraft_geom::BezPath; + use figcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest}; + let corners = [Point::new(0.0, 0.0), Point::new(525.0, 525.0), Point::new(0.0, 525.0), Point::new(333.0, 0.0), Point::new(525.0, 183.0)]; + let mut net = VectorNetwork::from_points(&corners, false); + net.segments = segments.iter().map(|&(a, b)| Segment::line(a, b)).collect(); + net.regions.push(Region { loops: vec![open_loop], winding: WindingRule::NonZero, fills: None, paint_space: None }); + for v in &mut net.vertices { + v.radius = 125.0; + } + let keeps_off = |path: &BezPath, p: Point| path.segments().map(|s| s.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min); + let length = |path: &BezPath| path.segments().map(|s| s.arclen(1e-9)).sum::(); + let stroke = net.stroke_path(); + let fill = net.fill_path(); + let region = net.rounded().unwrap().region_path(0).unwrap(); + for (i, p) in corners.iter().enumerate() { + assert!(keeps_off(&stroke, *p) > 2.0, "the stroke is cut at point {i}"); + assert!(keeps_off(&fill, *p) > 2.0, "the fill runs into point {i} ({:.2} from it)", keeps_off(&fill, *p)); + assert!(keeps_off(®ion, *p) > 2.0, "the region runs into point {i} ({:.2} from it)", keeps_off(®ion, *p)); + } + assert!((length(&fill) - length(&stroke)).abs() < 1e-6, "fill {} and stroke {} trace the same outline", length(&fill), length(&stroke)); + assert!((length(®ion) - length(&stroke)).abs() < 1e-6, "region {} and stroke {} trace the same outline", length(®ion), length(&stroke)); +} + #[test] fn stored_variable_ids_resolve_only_their_exact_collection() { let mut vars = crate::proto_expr_tests::vars(); diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 390aa703f..dafbfb1f3 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -293,6 +293,10 @@ pub struct ParaList { /// The paragraph's base direction (Text ▸ Text direction); `Auto` follows its letters. #[serde(skip_serializing_if = "crate::node::is_default")] pub direction: TextDirection, + /// The paragraph's own wrap style (a wrap style can be set on the text layer, a paragraph or a + /// text style); `None` follows the layer's [`TextData::wrap_style`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub wrap: Option, } /// Character style. In runs, every field is an override; `None` means "inherit the base". @@ -337,6 +341,9 @@ pub struct ParagraphStyle { pub paragraph_indent: f64, #[serde(skip_serializing_if = "crate::node::is_default")] pub list: ListStyle, + /// The wrap style (Auto asks nothing). + #[serde(skip_serializing_if = "crate::node::is_default")] + pub wrap_style: WrapStyle, #[serde(skip_serializing_if = "crate::node::is_default")] pub features: std::collections::BTreeMap, } @@ -838,6 +845,33 @@ impl TextData { self.paragraphs.get(p).copied().unwrap_or(ParaList { list: self.list, ..ParaList::default() }) } + /// Paragraph `p`'s wrap style: its own, else the layer's. + pub fn para_wrap_style(&self, p: usize) -> WrapStyle { + self.paragraphs.get(p).and_then(|pl| pl.wrap).unwrap_or(self.wrap_style) + } + + /// The layer level: every paragraph takes wrap style `w` (their own overrides go). + pub fn set_wrap_style(&mut self, w: WrapStyle) { + self.wrap_style = w; + // Every paragraph by index: `para_span` leaves out an empty one after a final newline. + let last = self.paragraph_count() - 1; + self.set_para_lists_between(0, last, false, |pl| pl.wrap = None); + } + + /// The paragraph level: the paragraphs chars `start..end` touch take wrap style `w`; one equal + /// to the layer's is no override. + pub fn set_para_wrap_styles(&mut self, start: usize, end: usize, w: WrapStyle) { + let layer = self.wrap_style; + self.set_para_lists(start, end, |pl| pl.wrap = (w != layer).then_some(w)); + } + + /// The effective wrap style the paragraphs chars `start..end` touch share, or None when they differ. + pub fn common_wrap_style(&self, start: usize, end: usize) -> Option { + let (a, b) = self.para_span(start, end); + let first = self.para_wrap_style(a); + (a..=b).all(|p| self.para_wrap_style(p) == first).then_some(first) + } + /// Spell out every paragraph's list settings in `paragraphs` (and drop extra entries). fn fill_paragraphs(&mut self) { let n = self.paragraph_count(); @@ -930,7 +964,16 @@ impl TextData { Some(first) if self.paragraphs.iter().all(|p| p.list == first.list) => first.list, _ => self.list, }; - ParagraphStyle { paragraph_spacing: self.paragraph_spacing, paragraph_indent: self.paragraph_indent, list, features: self.features.clone() } + // Every paragraph by index: `para_span` leaves out an empty one after a final newline. + let first = self.para_wrap_style(0); + let wrap_style = if (1..self.paragraph_count()).all(|p| self.para_wrap_style(p) == first) { first } else { self.wrap_style }; + ParagraphStyle { + paragraph_spacing: self.paragraph_spacing, + paragraph_indent: self.paragraph_indent, + list, + wrap_style, + features: self.features.clone(), + } } /// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and @@ -942,6 +985,7 @@ impl TextData { // Every paragraph by index: `para_span` leaves out an empty one after a final newline. let last = self.paragraph_count() - 1; self.set_para_lists_between(0, last, false, |pl| pl.list = ps.list); + self.set_wrap_style(ps.wrap_style); } /// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the @@ -952,6 +996,7 @@ impl TextData { self.paragraph_indent = ps.paragraph_indent; self.features.clone_from(&ps.features); self.set_para_lists(start, end, |pl| pl.list = ps.list); + self.set_para_wrap_styles(start, end, ps.wrap_style); } /// Follow text style `id`'s paragraph-level definition wherever chars link to it. @@ -970,6 +1015,7 @@ impl TextData { && self.paragraph_indent == ps.paragraph_indent && self.features == ps.features && self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list) + && self.common_wrap_style(start, end) == Some(ps.wrap_style) } /// Whether the whole text shows what text style `ps` sets at the paragraph and layer level. @@ -1124,6 +1170,69 @@ mod case_tests { assert_eq!(t.para_list(0), ParaList::default()); } + #[test] + fn wrap_style_per_paragraph_loads_from_old_files_and_folds() { + use WrapStyle::{Auto, Balance, Pretty}; + let old = r#"{"list":"numbered","indent":1}"#; + assert_eq!(serde_json::from_str::(old).unwrap().wrap, None); + let mut t = TextData::new("a\nb"); + let key = t.layout_key(); + t.set_para_wrap_styles(0, 0, Balance); + assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (Balance, Auto)); + assert_ne!(t.layout_key(), key); + let back: TextData = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap(); + assert_eq!(back, t); + t.set_para_wrap_styles(0, 0, Auto); + assert!(t.paragraphs.is_empty()); + t.set_para_wrap_styles(0, 0, Balance); + t.set_wrap_style(Pretty); + assert!(t.paragraphs.is_empty()); + assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (Pretty, Pretty)); + } + + #[test] + fn wrap_style_loads_from_old_paragraph_styles_and_texts() { + use WrapStyle::Auto; + // A paragraph style saved before it carried a wrap style. + let old = r#"{"paragraph_spacing":4.0,"list":"bulleted"}"#; + let ps: ParagraphStyle = serde_json::from_str(old).unwrap(); + assert_eq!((ps.wrap_style, ps.paragraph_spacing, ps.list), (Auto, 4.0, ListStyle::Bulleted)); + assert!(!serde_json::to_string(&ParagraphStyle::default()).unwrap().contains("wrap_style"), "Auto is not saved"); + // A text saved before its paragraphs carried a wrap style. + let mut t = TextData::new("a\nb"); + t.set_para_lists(0, 0, |p| p.list = ListStyle::Bulleted); + let mut v = serde_json::to_value(&t).unwrap(); + for p in v["paragraphs"].as_array_mut().unwrap() { + assert!(p.as_object_mut().unwrap().remove("wrap").is_none(), "Auto is not saved"); + } + v.as_object_mut().unwrap().remove("wrap_style"); + let old: TextData = serde_json::from_value(v).unwrap(); + assert_eq!(old.wrap_style, Auto); + assert_eq!(old.paragraphs.len(), 2); + assert!(old.paragraphs.iter().all(|p| p.wrap.is_none())); + assert_eq!((old.para_wrap_style(0), old.para_wrap_style(1)), (Auto, Auto)); + assert_eq!(old, t); + } + + #[test] + fn set_wrap_style_clears_an_override_on_the_empty_last_paragraph() { + use WrapStyle::{Auto, Balance, Pretty}; + let mut t = TextData::new("ab\n"); + assert_eq!(t.paragraph_count(), 2); + // The empty paragraph after the final newline: a caret there reaches it. + t.set_para_wrap_styles(3, 3, Balance); + assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (Auto, Balance)); + t.set_wrap_style(Pretty); + assert!(t.paragraphs.is_empty(), "{:?}", t.paragraphs); + assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (Pretty, Pretty)); + // Back to the layer's own style: no override is left on either paragraph. + t.set_para_wrap_styles(3, 3, Auto); + assert_eq!(t.para_wrap_style(1), Auto); + t.set_wrap_style(Auto); + assert!(t.paragraphs.is_empty()); + assert_eq!(t.common_wrap_style(0, t.char_count()), Some(Auto)); + } + #[test] fn clear_list_starts_touches_only_starts() { use ListStyle::{None as P, Numbered as N}; @@ -1190,4 +1299,16 @@ mod whole_text_paragraph_style_tests { plain.take_paragraph_style(&ps); assert_eq!((plain.list, plain.paragraphs.len()), (t.list, t.paragraphs.len())); } + + #[test] + fn a_style_made_from_the_whole_layer_counts_a_trailing_empty_paragraphs_wrap_style() { + // The first two paragraphs are Balance, the empty one after the final newline keeps the + // layer's Auto: they differ, so the style takes the layer's wrap style, not Balance. + let mut t = TextData::new("a\nb\n"); + t.set_para_wrap_styles(0, 3, WrapStyle::Balance); + assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1), t.para_wrap_style(2)), (WrapStyle::Balance, WrapStyle::Balance, WrapStyle::Auto)); + assert_eq!(t.paragraph_style().wrap_style, WrapStyle::Auto); + t.set_para_wrap_styles(4, 4, WrapStyle::Balance); + assert_eq!(t.paragraph_style().wrap_style, WrapStyle::Balance, "all three Balance"); + } } diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index f53ad4408..fd6d48072 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -184,6 +184,13 @@ fn redirect_last_segment(net: &mut VectorNetwork, loop_segs: &[usize], from: usi } } +/// Which segments are in a loop, and which segments join each pair of points: the lookups +/// [`VectorNetwork::closing_segment`] reads, built once per pass by [`VectorNetwork::loop_index`]. +pub struct LoopIndex { + in_loop: Vec, + by_ends: std::collections::BTreeMap<(usize, usize), Vec>, +} + impl VectorNetwork { /// A network from a polyline / polygon. pub fn from_points(points: &[Point], closed: bool) -> Self { @@ -471,16 +478,16 @@ impl VectorNetwork { // The curves go between the two segments wherever a loop walks through the point, in the // order the loop meets them. Each loop is rebuilt in one pass, so a polygon with many // rounded corners isn't quadratic. + let index = self.loop_index(); for lp in out.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) { - let Some(&first_idx) = lp.first() else { continue }; - let start_v = match (self.segments.get(first_idx), lp.get(1).and_then(|&i| self.segments.get(i))) { - (Some(first), Some(second)) if first.a == second.a || first.a == second.b => first.b, - (Some(first), _) => first.a, - _ => 0, - }; - let mut rebuilt = Vec::with_capacity(lp.len() + by_vertex.len().min(lp.len())); + if lp.is_empty() { + continue; + } + let start_v = self.loop_start(lp).unwrap_or(0); + let mut rebuilt = Vec::with_capacity(lp.len() + by_vertex.len().min(lp.len()) + 1); let mut cur = start_v; - for &x in lp.iter() { + let closing = self.closing_segment(lp, &index); + for &x in lp.iter().chain(closing.iter()) { rebuilt.push(x); let Some(s) = self.segments.get(x) else { continue }; cur = if s.a == cur { s.b } else { s.a }; @@ -497,6 +504,60 @@ impl VectorNetwork { Some(out) } + /// The point loop `lp` is walked from: the end of its first segment that its second does not + /// share. + fn loop_start(&self, lp: &[usize]) -> Option { + let first = self.segments.get(*lp.first()?)?; + match lp.get(1).and_then(|&i| self.segments.get(i)) { + Some(second) if first.a == second.a || first.a == second.b => Some(first.b), + _ => Some(first.a), + } + } + + /// The lookups [`Self::closing_segment`] needs, built once for a pass over every loop. + pub fn loop_index(&self) -> LoopIndex { + let mut in_loop = vec![false; self.segments.len()]; + for &x in self.regions.iter().flat_map(|r| r.loops.iter().flatten()) { + if let Some(f) = in_loop.get_mut(x) { + *f = true; + } + } + let mut by_ends: std::collections::BTreeMap<(usize, usize), Vec> = std::collections::BTreeMap::new(); + for (i, s) in self.segments.iter().enumerate() { + by_ends.entry((s.a.min(s.b), s.a.max(s.b))).or_default().push(i); + } + LoopIndex { in_loop, by_ends } + } + + /// The segment that joins the two ends of an open loop `lp` when it is in no loop of its own + /// (and the only such segment): a corner cut off by a segment drawn before the corner point was + /// deleted leaves the loop open there, and the stroke follows that segment. Only a loop that + /// walks in order as one continuous chain has one. Rounding walks it as the loop's last + /// segment, so the points at the loop's ends are cut by arcs as the stroke's are, and deleting + /// points or segments puts it into the loop (#1951). `index` is this network's [`Self::loop_index`], + /// shared by every loop of one pass. + pub fn closing_segment(&self, lp: &[usize], index: &LoopIndex) -> Option { + let start_v = self.loop_start(lp)?; + let mut cur = start_v; + for &x in lp { + let s = self.segments.get(x)?; + cur = if s.a == cur { + s.b + } else if s.b == cur { + s.a + } else { + return None; + }; + } + if cur == start_v { + return None; + } + let mut joining = + index.by_ends.get(&(cur.min(start_v), cur.max(start_v)))?.iter().copied().filter(|&i| !index.in_loop.get(i).copied().unwrap_or(false)); + let first = joining.next()?; + 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. diff --git a/crates/engine/src/a11y_keys_tests.rs b/crates/engine/src/a11y_keys_tests.rs index e4892bcae..6fc5f2396 100644 --- a/crates/engine/src/a11y_keys_tests.rs +++ b/crates/engine/src/a11y_keys_tests.rs @@ -103,3 +103,24 @@ fn a_settings_file_without_or_with_a_wrong_interface_size_reads_as_the_systems_s let p: crate::Prefs = serde_json::from_value(json!({"ui_scale": 99, "theme": "dark"})).unwrap(); assert_eq!((p.ui_scale, p.theme.as_str()), (crate::UI_SCALE_MAX, "dark")); } + +#[test] +fn the_invert_zoom_preference_toggles_and_is_saved() { + let mut s = Session::new(); + assert!(!s.prefs.invert_zoom, "off by default"); + assert_eq!(s.execute("pref.invertZoom", &json!({})).unwrap()["on"], true); + assert!(s.prefs.invert_zoom); + let saved = serde_json::to_value(&s.prefs).unwrap(); + assert_eq!(saved["invert_zoom"], true); + let loaded: crate::Prefs = serde_json::from_value(saved).unwrap(); + assert!(loaded.invert_zoom); + assert_eq!(s.execute("pref.invertZoom", &json!({"on": false})).unwrap()["on"], false); + assert!(!s.prefs.invert_zoom); + let saved = serde_json::to_value(&s.prefs).unwrap(); + assert_eq!(saved["invert_zoom"], false); + let loaded: crate::Prefs = serde_json::from_value(saved).unwrap(); + assert!(!loaded.invert_zoom, "off persists after being on"); + // Preferences saved before the setting existed read it as off. + let old: crate::Prefs = serde_json::from_value(json!({"theme": "dark"})).unwrap(); + assert!(!old.invert_zoom); +} diff --git a/crates/engine/src/assets/style_vars.rs b/crates/engine/src/assets/style_vars.rs index 13b120f7e..0c8103635 100644 --- a/crates/engine/src/assets/style_vars.rs +++ b/crates/engine/src/assets/style_vars.rs @@ -1,7 +1,8 @@ //! Variables bound inside shared styles. A style's `bound` map names fields of its own value in //! the keys a layer's bindings use (`fills//color`, `fills//stops//color`, //! `effects//`, `layoutGrids//`, a text style's `fontSize`, `lineHeight`, -//! `letterSpacing`, `fontFamily`, `fontStyle`). Each layer using the style sees those fields +//! `letterSpacing`, `fontWeight`, `fontFamily`, `fontStyle`; a number weight and a style name set the +//! same property, the weight wins). Each layer using the style sees those fields //! resolved in its own modes; the style itself stores them resolved in the default modes. use std::borrow::Cow; @@ -32,7 +33,7 @@ pub fn field_type(kind: &StyleKind, key: &str) -> Option { (StyleKind::Effect { effects }, Some((BoundList::Effects, i, field))) => effect_field_type(&effects.get(i)?.kind, field), (StyleKind::Grid { grids }, Some((BoundList::Grids, i, "size" | "count" | "gutter" | "offset"))) => grids.get(i).map(|_| Number), (StyleKind::Text { .. }, None) => match key { - "fontSize" | "lineHeight" | "letterSpacing" => Some(Number), + "fontSize" | "lineHeight" | "letterSpacing" | "fontWeight" => Some(Number), "fontFamily" | "fontStyle" => Some(String), _ => None, }, @@ -70,6 +71,7 @@ pub fn field_scopes(kind: &StyleKind, key: &str) -> Option<&'static [&'static st "letterSpacing" => &["LETTER_SPACING"], "fontFamily" => &["FONT_FAMILY"], "fontStyle" => &["FONT_STYLE"], + "fontWeight" => &["FONT_WEIGHT"], _ => return None, }, _ => return None, @@ -111,6 +113,8 @@ pub fn from_layer(n: &Node, field: &str, kind: &StyleKind) -> BTreeMap StyleKind { let mut kind = st.kind.clone(); + // `bound` is a BTreeMap, so `fontStyle` applies before `fontWeight` and a weight wins when a file carries both + // (pinned by `font_weight_wins_over_font_style_when_a_file_carries_both`). for (key, var) in &st.bound { let Some(val) = vars.resolve(var, modes) else { continue }; match (&mut kind, list_binding(key), &val) { @@ -134,7 +138,14 @@ fn set_text_field(style: &mut TextStyle, key: &str, val: &VariableValue) { ("lineHeight", VariableValue::Number(x)) if x.is_finite() => style.line_height = LineHeight::Pixels(x.clamp(0.0, 100_000.0)), ("letterSpacing", VariableValue::Number(x)) if x.is_finite() => style.letter_spacing = LetterSpacing::Pixels(x.clamp(-10_000.0, 10_000.0)), ("fontFamily", VariableValue::String(f)) if !f.trim().is_empty() => style.font_family = f.clone(), - ("fontStyle", VariableValue::String(f)) if !f.trim().is_empty() => style.font_style = f.clone(), + ("fontStyle", VariableValue::String(f)) if !f.trim().is_empty() => style.set_font_style(f.clone()), + ("fontWeight", VariableValue::Number(x)) if x.is_finite() => { + // The face nearest the number (a static family) and the `wght` axis (a variable font). + let w = x.clamp(1.0, 1000.0); + let italic = style.italic(); + style.set_font_style(crate::cmd::props::styled_name(crate::cmd::props::weight_name(w as u16), italic)); + style.variations.insert("wght".to_string(), w); + } _ => {} } } diff --git a/crates/engine/src/assets/token_roles.rs b/crates/engine/src/assets/token_roles.rs index 3827ecbea..dca86dfd6 100644 --- a/crates/engine/src/assets/token_roles.rs +++ b/crates/engine/src/assets/token_roles.rs @@ -1,6 +1,6 @@ //! What a file's number variables measure, so exported tokens carry the right unit: a radius, //! font size, spacing or other length is in pixels, opacity and font weight are bare numbers. -//! A number's role comes from the layer fields bound to it, else its scopes, and an alias target +//! A number's role comes from the layer fields bound to it (and a text style's weight), else its scopes, and an alias target //! with no role of its own takes the role of the variables that read it (the target of an opacity //! alias stays unitless). A number nothing tells about is a length: design tokens mostly are. @@ -60,6 +60,13 @@ impl Roles { } } } + for st in &doc.styles { + for (field, id) in &st.bound { + if field == "fontWeight" { + roles.entry(id.clone()).or_insert(NumberRole::Unitless); + } + } + } for v in vars.iter().filter(|v| v.kind == VariableType::Number) { if let Some(r) = v.scopes.as_ref().and_then(|s| s.iter().find_map(|s| role_of_scope(s))) { roles.entry(v.id.clone()).or_insert(r); diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index 931280dba..c74829961 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -57,6 +57,7 @@ pub const NODE_KEYS: &[&str] = &[ "lineHeight", "lineIndentations", "lineTypes", + "lineWrapStyles", "listSpacing", "listStartOffsets", "listStyle", @@ -466,8 +467,14 @@ fn text_props(t: &TextData, o: &mut serde_json::Map, options: &In if t.leading_trim != figcraft_doc::LeadingTrim::None { insert_prop(o, options, "leadingTrim", || json!(t.leading_trim)); } - if t.wrap_style != figcraft_doc::WrapStyle::Auto { - insert_prop(o, options, "wrapStyle", || json!(t.wrap_style)); + // The paragraphs' effective wrap styles: one for the layer when they agree, else each one's. + let wraps: Vec = (0..t.paragraph_count()).map(|p| t.para_wrap_style(p)).collect(); + if let Some(first) = wraps.first().copied().filter(|w| *w != figcraft_doc::WrapStyle::Auto) + && wraps.iter().all(|w| *w == first) + { + insert_prop(o, options, "wrapStyle", || json!(first)); + } else if wraps.iter().any(|w| *w != figcraft_doc::WrapStyle::Auto) { + insert_prop(o, options, "lineWrapStyles", || wraps.iter().map(|w| json!(w)).collect()); } if !t.runs.is_empty() { insert_prop(o, options, "styledRuns", || serde_json::to_value(&t.runs).unwrap_or(Value::Null)); diff --git a/crates/engine/src/board_tables_tests.rs b/crates/engine/src/board_tables_tests.rs index 3e7dbad80..3d4d8ce3a 100644 --- a/crates/engine/src/board_tables_tests.rs +++ b/crates/engine/src/board_tables_tests.rs @@ -258,3 +258,187 @@ fn template_and_table_commands_survive_junk() { } } } + +// --------------------------------------------------------------------------------------------- +// Resizing a table (#2172): a height change goes into its rows, never into blank space. + +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(); +} + +/// A selected 3 x 3 table at 0,0 (480 x 122: a line under all but the last row adds 1 to each), with `texts` in the first row. +fn table_3x3(texts: [&str; 3]) -> (Session, NodeId) { + let mut s = board(); + let r = s.execute("board.table", &json!({"x": 0, "y": 0, "cells": [texts, ["", "", ""], ["", "", ""]]})).unwrap(); + (s, id(&r, "id")) +} + +fn rows_of(s: &Session, t: NodeId) -> Vec { + let doc = s.doc().unwrap(); + doc.node(t).unwrap().children.iter().copied().filter(|c| !node(s, *c).child_layout.absolute).collect() +} + +fn row_heights(s: &Session, t: NodeId) -> Vec { + rows_of(s, t).into_iter().map(|r| node(s, r).height).collect() +} + +fn column_widths(s: &Session, t: NodeId) -> Vec { + let r = rows_of(s, t)[0]; + node(s, r).children.iter().map(|c| node(s, *c).width).collect() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 0.6 +} + +fn all_near(got: &[f64], want: &[f64]) -> bool { + got.len() == want.len() && got.iter().zip(want).all(|(a, b)| near(*a, *b)) +} + +fn is_hug(s: &Session, t: NodeId) -> bool { + node(s, t).child_layout.sizing_v == figcraft_doc::Sizing::Hug +} + +#[test] +fn a_bottom_drag_grows_only_the_last_row() { + // The programmatic route. + let (mut s, t) = table_3x3(["Alpha", "", ""]); + s.execute("node.set", &json!({"id": t, "props": {"height": 272}})).unwrap(); + assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 190.0]), "{:?}", row_heights(&s, t)); + let n = node(&s, t); + assert!(near(n.width, 480.0) && near(n.height, 272.0), "{}x{}", n.width, n.height); + assert!(is_hug(&s, t), "still hugging its rows"); + assert!(all_near(&column_widths(&s, t), &[160.0; 3])); + assert!(lines(&s, t).iter().all(|(_, h)| near(*h, 272.0)), "{:?}", lines(&s, t)); + // The pointer route: the bottom edge dragged down by 150. + let (mut s, t) = table_3x3(["Alpha", "", ""]); + drag(&mut s, (240.0, 122.0), (240.0, 272.0)); + assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 190.0]), "{:?}", row_heights(&s, t)); + assert!(near(node(&s, t).height, 272.0) && near(node(&s, t).width, 480.0)); + assert!(is_hug(&s, t)); + assert!(all_near(&column_widths(&s, t), &[160.0; 3])); + assert!(lines(&s, t).iter().all(|(_, h)| near(*h, 272.0)), "{:?}", lines(&s, t)); + // The text keeps its size. + let row0 = rows_of(&s, t)[0]; + let cell = node(&s, node(&s, row0).children[0]); + let NodeKind::Text(td) = &node(&s, cell.children[0]).kind else { panic!("text") }; + assert_eq!(td.style.font_size, 14.0); +} + +#[test] +fn a_corner_drag_shares_the_change_over_every_row_and_column() { + let (mut s, t) = table_3x3(["", "", ""]); + drag(&mut s, (480.0, 122.0), (570.0, 182.0)); + let n = node(&s, t); + assert!(near(n.width, 570.0) && near(n.height, 182.0), "{}x{}", n.width, n.height); + assert!(all_near(&row_heights(&s, t), &[61.0, 61.0, 60.0]), "{:?}", row_heights(&s, t)); + assert!(all_near(&column_widths(&s, t), &[190.0; 3]), "{:?}", column_widths(&s, t)); + let xs: Vec = lines(&s, t).iter().map(|l| l.0).collect(); + assert!(all_near(&xs, &[189.5, 379.5]), "{xs:?}"); + assert!(is_hug(&s, t)); + // The same through `transform.resize`. + let (mut s, t) = table_3x3(["", "", ""]); + s.execute("transform.resize", &json!({"ids": [t], "width": 570, "height": 182})).unwrap(); + assert!(all_near(&row_heights(&s, t), &[61.0, 61.0, 60.0]), "{:?}", row_heights(&s, t)); + assert!(all_near(&column_widths(&s, t), &[190.0; 3]), "{:?}", column_widths(&s, t)); +} + +#[test] +fn a_side_drag_changes_no_row() { + let (mut s, t) = table_3x3(["", "", ""]); + s.execute("node.set", &json!({"id": t, "props": {"width": 680}})).unwrap(); + assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 40.0]), "{:?}", row_heights(&s, t)); + assert!(near(node(&s, t).height, 122.0) && near(node(&s, t).width, 680.0)); + assert!(is_hug(&s, t)); + // A pointer drag of the right edge. + let (mut s, t) = table_3x3(["", "", ""]); + drag(&mut s, (480.0, 60.0), (680.0, 60.0)); + assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 40.0]), "{:?}", row_heights(&s, t)); + assert!(near(node(&s, t).height, 122.0) && near(node(&s, t).width, 680.0)); + assert!(is_hug(&s, t)); +} + +#[test] +fn a_table_never_shrinks_below_its_cells() { + let (mut s, t) = table_3x3(["Alpha", "Bravo longer text", "Charlie"]); + drag(&mut s, (480.0, 122.0), (50.0, 32.0)); + let n = node(&s, t); + assert!(near(n.width, 120.0), "width {}", n.width); + assert!(all_near(&column_widths(&s, t), &[40.0; 3]), "{:?}", column_widths(&s, t)); + let rows = row_heights(&s, t); + assert!(rows[0] > 40.0, "row 1 holds its wrapped text: {rows:?}"); + assert!(near(rows[1], 41.0) && near(rows[2], 40.0), "{rows:?}"); + assert!(near(n.height, rows.iter().sum::()), "{} vs {rows:?}", n.height); + assert!(is_hug(&s, t)); +} + +#[test] +fn a_resized_table_still_grows_with_its_text_and_undoes_in_one_step() { + // Text measures only once system fonts are scanned (without craft-fonts), so scan them here + // without depending on another test having scanned them first. + figcraft_text::scan_system_fonts(); + let (mut s, t) = table_3x3(["", "", ""]); + drag(&mut s, (240.0, 122.0), (240.0, 272.0)); + assert!(near(node(&s, t).height, 272.0)); + // Typing in a last-row cell: the table grows once the text needs more than 190. + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::DoubleClick, 80.0, 200.0, 1.0)).unwrap(); + assert!(s.ds().unwrap().text_edit.is_some(), "typing in the last row's cell"); + let long = (0..12).map(|i| format!("line {i}")).collect::>().join("\n"); + crate::textedit::insert(&mut s, &long).unwrap(); + crate::textedit::end(&mut s).unwrap(); + assert!(node(&s, t).height > 272.0, "grew with its text: {}", node(&s, t).height); + assert!(is_hug(&s, t)); + // Undo: the typing, then the resize, to the table as made. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(node(&s, t).height, 272.0), "{}", node(&s, t).height); + s.execute("edit.undo", &json!({})).unwrap(); + let n = node(&s, t); + assert!(near(n.width, 480.0) && near(n.height, 122.0), "{}x{}", n.width, n.height); + assert!(all_near(&row_heights(&s, t), &[41.0, 41.0, 40.0]), "{:?}", row_heights(&s, t)); +} + +#[test] +fn table_resizes_sync_in_live_sessions() { + let s = board(); + let mut room = Room::new(s.doc().unwrap().clone(), 2, 12); + let t = id(&room.s(0).execute("board.table", &json!({"x": 0, "y": 0})).unwrap(), "id"); + room.settle(); + room.check(); + room.s(0).execute("node.set", &json!({"id": t, "props": {"height": 272}})).unwrap(); + room.settle(); + room.check(); + let doc = room.server.document(); + let heights: Vec = + doc.node(t).unwrap().children.iter().map(|c| doc.node(*c).unwrap()).filter(|n| !n.child_layout.absolute).map(|n| n.height).collect(); + assert!(all_near(&heights, &[41.0, 41.0, 190.0]), "{heights:?}"); + assert!(near(doc.node(t).unwrap().height, 272.0)); + assert_eq!(doc.node(t).unwrap().child_layout.sizing_v, figcraft_doc::Sizing::Hug); +} + +#[test] +fn resizing_a_table_survives_junk_and_saves_the_rows() { + for h in [json!(1e308), json!(-5), json!("NaN"), json!(null), json!(0)] { + let (mut s, t) = table_3x3(["", "", ""]); + if let Err(EngineError::Internal { cmd, msg }) = s.execute("node.set", &json!({"id": t, "props": {"height": h}})) { + panic!("{cmd} panicked on {h}: {msg}"); + } + for p in [json!({"ids": [t], "width": h, "height": h}), json!({"ids": [t], "height": h}), json!({"ids": [t], "width": h})] { + if let Err(EngineError::Internal { cmd, msg }) = s.execute("transform.resize", &p) { + panic!("{cmd} panicked on {p}: {msg}"); + } + } + let n = node(&s, t); + assert!(n.width.is_finite() && n.height.is_finite(), "{h}: {}x{}", n.width, n.height); + } + let (mut s, t) = table_3x3(["", "", ""]); + s.execute("node.set", &json!({"id": t, "props": {"height": 272}})).unwrap(); + let doc = s.doc().unwrap(); + let (back, _) = figcraft_format::from_json(&figcraft_format::to_json(doc).unwrap().to_string()).unwrap(); + let heights: Vec = + back.node(t).unwrap().children.iter().map(|c| back.node(*c).unwrap()).filter(|n| !n.child_layout.absolute).map(|n| n.height).collect(); + assert!(all_near(&heights, &[41.0, 41.0, 190.0]), "{heights:?}"); +} diff --git a/crates/engine/src/boards/board/derived.rs b/crates/engine/src/boards/board/derived.rs index 37a2f9ba9..a6461fb85 100644 --- a/crates/engine/src/boards/board/derived.rs +++ b/crates/engine/src/boards/board/derived.rs @@ -14,6 +14,7 @@ pub(crate) fn settle_text(doc: &mut Document, before: &Document, touched: &BTree if !is_board(doc) { return; } + crate::board_table::settle_resize(doc, before, 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_table.rs b/crates/engine/src/boards/board_table.rs index aef7c8917..b77f343a0 100644 --- a/crates/engine/src/boards/board_table.rs +++ b/crates/engine/src/boards/board_table.rs @@ -3,6 +3,16 @@ //! row's width, so a cell that wraps more text makes its row taller. Each row but the last draws //! a line under itself and the column lines are thin rectangles over the table that stretch with //! it (they are rebuilt after every edit, like the first row's header tint). +//! +//! Resizing (measured in FigJam's web app, 2026-11-09, #2172): a table never scales its text or +//! its rows in proportion. A height change goes into the rows ([`settle_resize`]): the bottom or +//! top edge grows the last row, a corner drag shares the change equally over every row (every +//! cell fills its row, so the width is already shared equally), and the table keeps hugging its +//! rows. A cell is at least [`MIN_CELL`] (40; FigJam's floor is about 52) wide and tall, and a row +//! is never shorter than its wrapped text. There are no per-column widths yet: a side drag of +//! the right edge splits the change equally where FigJam grows only the last column. + +use std::collections::BTreeSet; use figcraft_color::{Color, Paint}; use figcraft_doc::{ @@ -22,6 +32,10 @@ pub const MAX_COLUMNS: usize = 20; /// A new column's width, and a cell's height before its text is measured. const CELL_W: f64 = 160.0; const CELL_H: f64 = 40.0; +/// The least a cell is wide or tall (FigJam's is about 52). +pub(crate) const MIN_CELL: f64 = CELL_H; +/// The most a resize may ask one row to be tall. +const MAX_ROW_H: f64 = 100_000.0; /// Room around a cell's text: [top, right, bottom, left]. const CELL_PAD: [f64; 4] = [10.0, 12.0, 10.0, 12.0]; const TEXT_SIZE: f64 = 14.0; @@ -125,6 +139,7 @@ fn make_cell(doc: &mut Document, row: NodeId, index: Option, width: f64, n.child_layout.sizing_h = Sizing::Fill; n.child_layout.sizing_v = Sizing::Hug; n.child_layout.min_h = Some(CELL_H); + n.child_layout.min_w = Some(MIN_CELL); })?; add_text(doc, cell, text, TEXT_SIZE, INK, TextAlignH::Left, (width - CELL_PAD[1] - CELL_PAD[3]).max(1.0))?; Ok(cell) @@ -259,6 +274,57 @@ fn table_cmd(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// A table resized by its height or a corner (the resize leaves it at a fixed height): the change +/// goes into its rows, as in FigJam, and the table hugs them again. A bottom or top edge (or a +/// height set by command) grows or shrinks the last row; a drag that changed both axes shares the +/// change equally over every row. A row never gets shorter than [`MIN_CELL`] or than its text (the +/// table hugs it), and the table is never narrower than its columns' minimum. A table already +/// hugging (a peer's synced edit, a second pass) is left alone, so the change is made once. +pub(crate) fn settle_resize(doc: &mut Document, before: &Document, touched: &BTreeSet) { + let mut tables = BTreeSet::new(); + for &id in touched { + if let Some(t) = table_of(doc, id) { + tables.insert(t); + } + } + for table in tables { + let (Some(now), Some(was)) = (doc.node(table), before.node(table)) else { continue }; + if now.child_layout.sizing_v != Sizing::Fixed { + continue; + } + let (w, h, bw, bh) = (now.width, now.height, was.width, was.height); + let (rows, _) = parts(doc, table); + let columns = rows.first().map_or(0, |r| cells(doc, *r).len()); + let dh = h - bh; + if dh.is_finite() && dh.abs() > 1e-6 && !rows.is_empty() { + let both = w.is_finite() && bw.is_finite() && (w - bw).abs() > 1e-6; + let targets: Vec = if both { rows.clone() } else { rows.last().copied().into_iter().collect() }; + let share = dh / targets.len() as f64; + for row in targets { + let base = row_content(before, row).or_else(|| row_content(doc, row)).unwrap_or(CELL_H); + let min_h = (base + share).clamp(MIN_CELL, MAX_ROW_H); + for cell in cells(doc, row) { + if let Some(c) = doc.node_mut(cell) { + c.child_layout.min_h = Some(min_h); + } + } + } + } + if let Some(t) = doc.node_mut(table) { + let least = MIN_CELL * columns as f64; + if t.width.is_nan() || t.width < least { + t.width = least; + } + t.child_layout.sizing_v = Sizing::Hug; + } + } +} + +/// How tall a row's cells are: the row's height less the line under it. +fn row_content(doc: &Document, row: NodeId) -> Option { + cells(doc, row).into_iter().filter_map(|c| doc.node(c).map(|n| n.height)).reduce(f64::max) +} + /// The table `id` is or is in. fn table_of(doc: &Document, id: NodeId) -> Option { std::iter::once(id).chain(doc.ancestors(id)).find(|a| doc.node(*a).is_some_and(|n| n.board == Some(BoardItem::Table))) diff --git a/crates/engine/src/boolean_radius_tests.rs b/crates/engine/src/boolean_radius_tests.rs new file mode 100644 index 000000000..f739b3eaf --- /dev/null +++ b/crates/engine/src/boolean_radius_tests.rs @@ -0,0 +1,134 @@ +//! A boolean group's corner radius through the engine: it rounds the result (and the SVG export +//! of it), children keep their own radius, Flatten bakes the arcs and clicks follow the result. + +use serde_json::json; + +use crate::Session; +use crate::booleans_tests::{area, click, ex}; +use crate::params::id_of; +use figcraft_doc::{NodeId, NodeKind}; +use figcraft_geom::{Point, Shape}; + +const L_AREA: f64 = 34656.6; + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&ex(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"]).unwrap() +} + +fn snapping_off(s: &mut Session) { + ex(s, "select.none", json!({})); + let ds = s.ds_mut().unwrap(); + ds.view.snap_objects = false; + ds.view.snap_pixel = false; +} + +fn set_radius(s: &mut Session, id: NodeId, r: f64) { + ex(s, "node.set", json!({"ids": [id], "props": {"cornerRadius": r}})); +} + +/// The L of two rectangles, united, nothing selected, snapping off. +fn l_group(s: &mut Session) -> NodeId { + let (a, b) = (rect(s, 0.0, 0.0, 200.0, 100.0), rect(s, 150.0, 0.0, 100.0, 200.0)); + let g = id_of(&ex(s, "bool.union", json!({"ids": [a, b]}))["id"]).unwrap(); + snapping_off(s); + g +} + +/// Whether the page point is inside the group's drawn result. +fn covers(s: &Session, g: NodeId, x: f64, y: f64) -> bool { + let doc = s.doc().unwrap(); + let (path, _) = figcraft_render::node_outline(doc, doc.node(g).unwrap()).unwrap(); + let p = doc.world_transform(g).inverse() * Point::new(x, y); + path.winding(p) % 2 != 0 +} + +#[test] +fn a_boolean_group_rounds_every_sharp_corner_of_its_result() { + let mut s = Session::new(); + let g = l_group(&mut s); + assert!(covers(&s, g, 1.0, 1.0)); + set_radius(&mut s, g, 20.0); + assert!(!covers(&s, g, 1.0, 1.0) && covers(&s, g, 148.0, 102.0)); + assert!((area(&s, g) - L_AREA).abs() < 1.0, "{}", area(&s, g)); + let doc = s.doc().unwrap(); + let svg = figcraft_svg::export_svg(doc, &[g], &figcraft_svg::SvgOptions::default()).unwrap(); + let d = svg.split("d=\"").nth(1).and_then(|r| r.split('"').next()).unwrap(); + let exported = figcraft_geom::svg_path(d).unwrap(); + assert!((exported.area().abs() - L_AREA).abs() < 1.0, "{}", exported.area()); + s.undo().unwrap(); + assert_eq!(s.doc().unwrap().node(g).unwrap().corners.radii, [0.0; 4], "one undo step"); + assert!((area(&s, g) - 35000.0).abs() < 1.0); +} + +/// The notch of the measurement: A (200 by 100 at the origin) minus a 100 square on its top edge, +/// whose own radius is `a_radius`, under a group radius of `radius`. +fn notch(s: &mut Session, a: NodeId, radius: f64) -> NodeId { + let b = rect(s, 50.0, -50.0, 100.0, 100.0); + let g = id_of(&ex(s, "bool.subtract", json!({"ids": [a, b]}))["id"]).unwrap(); + snapping_off(s); + set_radius(s, g, radius); + g +} + +/// The asserts of the measurement on a notched group at radius 20 under A's own 10. +fn assert_notch_at_20(s: &Session, g: NodeId) { + assert!(covers(s, g, 4.0, 4.0), "A's 10 was not enlarged to 20"); + assert!(!covers(s, g, 48.0, 2.0), "the cut's top corner rounds"); + assert!(covers(s, g, 52.0, 48.0), "the cut's inner corner fills in"); +} + +#[test] +fn children_keep_their_radius_and_a_subtraction_rounds_its_cut() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + set_radius(&mut s, a, 10.0); + let g = notch(&mut s, a, 20.0); + assert_notch_at_20(&s, g); + assert_eq!(s.doc().unwrap().node(a).unwrap().corners.radii, [10.0; 4]); + set_radius(&mut s, g, 500.0); + assert_eq!(s.doc().unwrap().node(g).unwrap().corners.radii[0], 500.0, "the field keeps the value"); + assert!(!covers(&s, g, 40.0, 4.0), "25, not the 20 that half the 40-long edge would give"); + assert!(covers(&s, g, 27.0, 1.0), "and not more than 25"); + assert!(covers(&s, g, 100.0, 51.0) && !covers(&s, g, 100.0, 49.0), "the floor stays straight between 75 and 125"); + assert!(covers(&s, g, 4.0, 4.0)); +} + +#[test] +fn a_nested_group_keeps_its_own_radius() { + let mut s = Session::new(); + let (l, r) = (rect(&mut s, 0.0, 0.0, 120.0, 100.0), rect(&mut s, 80.0, 0.0, 120.0, 100.0)); + let inner = id_of(&ex(&mut s, "bool.union", json!({"ids": [l, r]}))["id"]).unwrap(); + set_radius(&mut s, inner, 10.0); + let g = notch(&mut s, inner, 20.0); + assert_notch_at_20(&s, g); +} + +#[test] +fn flatten_bakes_the_arcs_and_the_vector_has_no_radius() { + let mut s = Session::new(); + let g = l_group(&mut s); + set_radius(&mut s, g, 20.0); + let flat = id_of(&ex(&mut s, "vector.flatten", json!({"ids": [g]}))["id"]).unwrap(); + let doc = s.doc().unwrap(); + let n = doc.node(flat).unwrap(); + let NodeKind::Vector { network } = &n.kind else { panic!("a vector: {:?}", n.kind) }; + assert_eq!(n.corners.radii, [0.0; 4]); + assert!(network.vertices.iter().all(|v| v.radius == 0.0)); + let path = figcraft_doc::geometry::shape_path(n).unwrap(); + assert!((path.area().abs() - L_AREA).abs() < 1.0, "{}", path.area()); + assert!((n.width - 250.0).abs() < 1e-6 && (n.height - 200.0).abs() < 1e-6); +} + +#[test] +fn clicks_follow_the_rounded_result() { + let mut s = Session::new(); + let g = l_group(&mut s); + set_radius(&mut s, g, 20.0); + click(&mut s, 1.0, 1.0, false); + assert!(s.selection().is_empty(), "the cut-off corner reaches what is behind"); + click(&mut s, 148.0, 102.0, false); + assert_eq!(s.selection(), vec![g], "the concave fillet belongs to the group"); + ex(&mut s, "select.none", json!({})); + click(&mut s, 100.0, 50.0, false); + assert_eq!(s.selection(), vec![g]); +} diff --git a/crates/engine/src/booleans_tests.rs b/crates/engine/src/booleans_tests.rs index 068719588..d29c28127 100644 --- a/crates/engine/src/booleans_tests.rs +++ b/crates/engine/src/booleans_tests.rs @@ -11,21 +11,21 @@ use crate::tools::{PointerEvent, PointerKind}; use figcraft_doc::{BoolOp, NodeId, NodeKind}; use figcraft_geom::Shape; -fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { +pub(crate) fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) } -fn ev(kind: PointerKind, x: f64, y: f64, cmd: bool) -> PointerEvent { +pub(crate) fn ev(kind: PointerKind, x: f64, y: f64, cmd: bool) -> PointerEvent { PointerEvent { cmd, ..PointerEvent::at(kind, x, y, 1.0) } } -fn click(s: &mut Session, x: f64, y: f64, cmd: bool) { +pub(crate) fn click(s: &mut Session, x: f64, y: f64, cmd: bool) { s.pointer(&ev(PointerKind::Down, x, y, cmd)).unwrap(); s.pointer(&ev(PointerKind::Up, x, y, cmd)).unwrap(); } /// A layer's filled area (a boolean group's result; none of these have holes). -fn area(s: &Session, id: NodeId) -> f64 { +pub(crate) fn area(s: &Session, id: NodeId) -> f64 { let doc = s.doc().unwrap(); figcraft_render::node_outline(doc, doc.node(id).unwrap()).unwrap().0.area().abs() } diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index a3284cd52..1ccf4f8ca 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -32,7 +32,7 @@ use handles::DRAG_SLOP_PX; pub(crate) use handles::scale_factor; pub use handles::{ PENCIL_STROKE, SMALL_BOX_PX, anchor_name, anchor_of, box_sides_px, handle_at, handle_at_corners, label_at, locked_in, scale_anchor_point, - selection_box, selection_frame, + selection_box, selection_frame, shared_rotation_degrees, }; pub(crate) use handles::{SNAP_PX, handle_cursor, readable_text_fills, resized_box}; #[cfg(test)] @@ -58,6 +58,7 @@ pub enum ToolId { Text, TextOnPath, Comment, + Annotation, Eyedropper, ShapeBuilder, // Board tools. @@ -71,7 +72,7 @@ pub enum ToolId { } impl ToolId { - pub const ALL: [ToolId; 26] = [ + pub const ALL: [ToolId; 27] = [ ToolId::Move, ToolId::Scale, ToolId::Hand, @@ -89,6 +90,7 @@ impl ToolId { ToolId::Text, ToolId::TextOnPath, ToolId::Comment, + ToolId::Annotation, ToolId::Eyedropper, ToolId::ShapeBuilder, ToolId::Sticky, @@ -118,6 +120,7 @@ impl ToolId { ToolId::Text => "text", ToolId::TextOnPath => "textOnPath", ToolId::Comment => "comment", + ToolId::Annotation => "annotation", ToolId::Eyedropper => "eyedropper", ToolId::ShapeBuilder => "shapeBuilder", ToolId::Sticky => "sticky", @@ -129,6 +132,11 @@ impl ToolId { ToolId::Stamp => "stamp", } } + /// Whether Developer Mode keeps this tool: it only inspects, so the tools that edit leave it. + /// The one list behind the engine's pointer routing and command allowlist and the toolbar. + pub fn works_in_dev_mode(self) -> bool { + matches!(self, ToolId::Move | ToolId::Hand | ToolId::Comment | ToolId::Annotation) + } pub fn from_id(s: &str) -> Option { ToolId::ALL.into_iter().find(|t| t.id().eq_ignore_ascii_case(s)) } @@ -151,6 +159,7 @@ impl ToolId { ToolId::Text => "Text", ToolId::TextOnPath => "Text on a path", ToolId::Comment => "Comment", + ToolId::Annotation => "Annotation", ToolId::Eyedropper => "Pick color", ToolId::ShapeBuilder => "Shape builder", ToolId::Sticky => "Sticky note", @@ -445,6 +454,8 @@ pub(crate) enum Gesture { Rotate { center: Point, start_angle: f64, + /// The rotation (Design panel convention) the layers share when the drag began, else 0. + base: f64, ids: Vec, }, Draw { diff --git a/crates/engine/src/canvas/tools/click.rs b/crates/engine/src/canvas/tools/click.rs index 35a97a77a..a7c10d574 100644 --- a/crates/engine/src/canvas/tools/click.rs +++ b/crates/engine/src/canvas/tools/click.rs @@ -360,8 +360,13 @@ impl Session { pub(super) fn eyedrop(&mut self, ev: &PointerEvent) -> Result<()> { let ds = self.ds()?; let doc = ds.doc.clone(); - let view = figcraft_render::View { origin: (ev.x, ev.y), scale: ev.zoom.max(0.01), width: 1, height: 1 }; - let Some(pix) = figcraft_render::render_view(&doc, ds.page, &view, &Default::default()) else { return Ok(()) }; + // One screen pixel centred on the pointer (its top left half a pixel up and to the left). + let scale = ev.zoom.max(0.01); + let view = figcraft_render::View { origin: (ev.x - 0.5 / scale, ev.y - 0.5 / scale), scale, width: 1, height: 1 }; + // As the canvas draws it: an image magnified past 2x shows its pixels, so the colour picked + // is the pixel under the pointer, not a blend with its neighbours (#2189). + let opts = figcraft_render::Options { magnified_image_pixels: true, ..Default::default() }; + let Some(pix) = figcraft_render::render_view(&doc, ds.page, &view, &opts) else { return Ok(()) }; let rgba = figcraft_render::to_rgba8(&pix); let c = figcraft_color::Color::from_rgba8( rgba.first().copied().unwrap_or(0), diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index 94f0e654e..ea336a142 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -1,6 +1,6 @@ use super::handles::{ SNAP_PX, handle_at, in_quad, label_at, locked_in, on_corner_square, paints_below, resized_box, scale_factor, selection_box, selection_frame, - shape_hint, + shape_hint, shared_rotation_degrees, }; use super::{ Affine, ArcHandle, ArcHint, Cursor, Document, Gesture, Guide, Handle, ImageScaleMode, LayoutMode, NodeId, NodeKind, PaintKind, Point, @@ -58,7 +58,8 @@ impl Session { .moved_origin() .unwrap_or_else(|| Point::new(b.iter().map(|c| c.x).sum::() / 4.0, b.iter().map(|c| c.y).sum::() / 4.0)); self.begin_interaction("Rotate")?; - self.tool.gesture = Gesture::Rotate { center, start_angle: (ev.p() - center).atan2(), ids }; + self.tool.gesture = + Gesture::Rotate { center, start_angle: (ev.p() - center).atan2(), base: shared_rotation_degrees(&doc, &ids), ids }; return Ok(()); } let nodes: Vec<(NodeId, Affine, f64, f64)> = @@ -362,10 +363,11 @@ impl Session { } return res; } - Gesture::Rotate { center, start_angle, ids } => { + Gesture::Rotate { center, start_angle, base, ids } => { let mut a = ((ev.p() - *center).atan2() - start_angle).to_degrees(); if ev.shift { - a = (a / 15.0).round() * 15.0; + // The panel rotation is base - a; Shift lands it on a multiple of 15 degrees. + a = base - ((base - a) / 15.0).round() * 15.0; } let (c, ids) = (*center, ids.clone()); self.preview(|doc, _| { diff --git a/crates/engine/src/canvas/tools/handles.rs b/crates/engine/src/canvas/tools/handles.rs index 9fa04d9bb..ecd29e67a 100644 --- a/crates/engine/src/canvas/tools/handles.rs +++ b/crates/engine/src/canvas/tools/handles.rs @@ -132,6 +132,14 @@ pub fn selection_frame(doc: &Document, sel: &[NodeId]) -> Option<(Affine, f64, f Some((rot * Affine::translate((b.x0, b.y0)), b.width(), b.height())) } +/// The rotation `ids` share on the page (degrees, counter-clockwise positive), else 0 (the handle +/// box is page-aligned then). Figma's rotation field shows this page rotation, also for a layer +/// inside a rotated frame or group, and Shift lands it on multiples of 15 degrees. Axis-aligned +/// layers give 0, which is the same as 90, 180 and 270 for stepping in 15 degrees. +pub fn shared_rotation_degrees(doc: &Document, ids: &[NodeId]) -> f64 { + shared_rotation(doc, ids).map_or(0.0, |a| -a.to_degrees()) +} + /// The rotation (radians) every layer in `ids` shares, unless it's a multiple of 90 degrees (the /// page-aligned box is then the same box). Flipped layers count by their axis, not its direction. fn shared_rotation(doc: &Document, ids: &[NodeId]) -> Option { diff --git a/crates/engine/src/canvas/tools/pointer.rs b/crates/engine/src/canvas/tools/pointer.rs index 1e9c645e3..d7a40380e 100644 --- a/crates/engine/src/canvas/tools/pointer.rs +++ b/crates/engine/src/canvas/tools/pointer.rs @@ -110,7 +110,7 @@ impl Session { /// The tool pointer events go to: in Dev Mode every tool but the hand and comments selects. fn acting_tool(&self) -> ToolId { match self.tool.tool { - t if self.tool.dev_mode && !matches!(t, ToolId::Hand | ToolId::Comment) => ToolId::Move, + t if self.tool.dev_mode && !t.works_in_dev_mode() => ToolId::Move, t => t, } } @@ -176,6 +176,7 @@ impl Session { self.request_ui("comment.new", json!({"x": ev.x, "y": ev.y})); Ok(()) } + ToolId::Annotation => self.annotation_down(ev), ToolId::Eyedropper => self.eyedrop(ev), t if t.on_boards() => self.board_down(ev), t if t.draws_shape() => self.draw_down(ev), @@ -206,6 +207,19 @@ impl Session { Ok(true) } + /// The Annotation tool's press: the layer under the pointer is selected and the UI is asked + /// for its note (the engine writes nothing; the note is typed in the Inspect tab). A press on + /// empty canvas does nothing. + fn annotation_down(&mut self, ev: &PointerEvent) -> Result<()> { + let ds = self.ds()?; + let (doc, page) = (ds.doc.clone(), ds.page); + // The same reach as the Move tool's pick (`ev.tol() * 2.0`); never the page itself. + let Some(id) = self.hit(&doc, page, ev.p(), ev.tol() * 2.0).filter(|i| doc.node(*i).is_some_and(|n| !n.is_page())) else { return Ok(()) }; + self.set_selection(vec![id]); + self.request_ui("annotation.new", json!({"id": id})); + Ok(()) + } + pub(super) fn hover(&mut self, ev: &PointerEvent) -> Result<()> { let tool = self.acting_tool(); let ds = self.ds()?; diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs index 749e246c0..ab9fcb79f 100644 --- a/crates/engine/src/canvas/vectoredit.rs +++ b/crates/engine/src/canvas/vectoredit.rs @@ -10,6 +10,8 @@ pub mod ops; pub(crate) mod point_snap; mod pointer; +#[cfg(test)] +mod position_tests; pub mod regions; #[cfg(test)] mod regions_tests; @@ -706,7 +708,61 @@ fn handle_list(p: &Value, key: &str) -> Option> { } } -/// Selection bounds' top-left in the parent's coordinates (what the X/Y fields show). +/// One axis of `vector.edit.position`: left alone, set, or relative to each point's own value. +#[derive(Clone, Copy)] +enum AxisEdit { + Keep, + Set(f64), + Add(f64), + Mul(f64), + Div(f64), +} + +impl AxisEdit { + fn apply(self, cur: f64) -> Result { + let v = match self { + AxisEdit::Keep => cur, + AxisEdit::Set(v) => v, + AxisEdit::Add(n) => cur + n, + AxisEdit::Mul(n) => cur * n, + AxisEdit::Div(n) if n != 0.0 => cur / n, + AxisEdit::Div(_) => return Err(bad("vector.edit.position", "cannot divide by zero")), + }; + if v.is_finite() { Ok(v) } else { Err(bad("vector.edit.position", "the result is not a number")) } + } +} + +/// Parse `p[key]`: absent is `Keep`, a number is `Set`, `{add|mul|div: n}` is relative; anything else is refused. +fn axis_edit(p: &Value, key: &str) -> Result { + let junk = || bad("vector.edit.position", format!("`{key}` must be a number or {{add|mul|div: number}}")); + match get(p, key) { + None => Ok(AxisEdit::Keep), + Some(Value::Object(o)) => { + let (Some((k, v)), 1) = (o.iter().next(), o.len()) else { return Err(junk()) }; + let n = match v { + Value::Number(n) => n.as_f64().filter(|n| n.is_finite()), + _ => None, + } + .ok_or_else(junk)?; + match k.as_str() { + "add" => Ok(AxisEdit::Add(n)), + "mul" => Ok(AxisEdit::Mul(n)), + "div" if n != 0.0 => Ok(AxisEdit::Div(n)), + _ => Err(junk()), + } + } + Some(v) => f64_of(v).filter(|_| !v.is_boolean()).map(AxisEdit::Set).ok_or_else(junk), + } +} + +/// The selected points in the parent's coordinates (what the X/Y fields show). +pub fn selected_parent_points(doc: &Document, ve: &VectorEdit) -> Vec { + let Some(net) = network(doc, ve.id) else { return Vec::new() }; + let t = doc.node(ve.id).map(|n| n.transform).unwrap_or_default(); + selected_points(net, ve).into_iter().filter_map(|v| net.vertices.get(v)).map(|v| t * v.point()).collect() +} + +/// Selection bounds' top-left in the parent's coordinates (the `x` and `y` of `vector.edit.bounds`). pub fn selection_position(doc: &Document, ve: &VectorEdit) -> Option { let net = network(doc, ve.id)?; let t = doc.node(ve.id)?.transform; @@ -935,18 +991,50 @@ pub fn specs() -> Vec { edit_sets(s, sets, |net, v, w| ops::move_vertices(net, v, local_offset(w, d)))?; Ok(json!({"ok": true})) }), - spec!("vector.edit.position", "Point position", "{x?, y?} (the selected points' top-left, in the parent's coordinates)", true, |s, p| { - let ve = editing(s)?; - let doc = s.doc()?; - let cur = selection_position(doc, &ve).ok_or_else(|| bad("vector.edit.position", "select points"))?; - let target = Point::new(num_or(p, "x", cur.x), num_or(p, "y", cur.y)); - let t = doc.node(ve.id).map(|n| n.transform).unwrap_or_default(); - let inv = t.inverse(); - let d = inv * target - inv * cur; - let v = network(doc, ve.id).map(|n| selected_points(n, &ve)).unwrap_or_default(); - edit(s.doc_mut()?, ve.id, |net| ops::move_vertices(net, &v, d))?; - Ok(json!({"ok": true})) - }), + spec!( + "vector.edit.position", + "Point position", + "{x?, y?}: each a number (every selected point's own coordinate becomes it) or {add: n}, {mul: n} or {div: n} (applied to each selected point's own coordinate); in the parent's coordinates", + true, + |s, p| { + let ve = editing(s)?; + let doc = s.doc()?; + let (ax, ay) = (axis_edit(p, "x")?, axis_edit(p, "y")?); + let t = doc.node(ve.id).map(|n| n.transform).unwrap_or_default(); + let inv = t.inverse(); + let net = network(doc, ve.id).ok_or_else(|| bad("vector.edit.position", "select points"))?; + let mut moves: Vec<(usize, Vec2)> = Vec::new(); + for i in selected_points(net, &ve) { + let Some(v) = net.vertices.get(i) else { continue }; + let cur = t * v.point(); + let target = Point::new(ax.apply(cur.x)?, ay.apply(cur.y)?); + let d = inv * target - v.point(); + if !(d.x.is_finite() && d.y.is_finite()) { + return Err(bad("vector.edit.position", "the result is not a number")); + } + moves.push((i, d)); + } + if moves.is_empty() { + return Err(bad("vector.edit.position", "select points")); + } + // Points that all share one offset move as one, so moving every point of a layer + // by one offset still carries the regions' paint frames, as a drag of all of them + // does. Otherwise no one move covers every point, so each point moves alone. + let d0 = moves[0].1; + let uniform = moves.iter().all(|(_, d)| (*d - d0).hypot() < 1e-9); + edit(s.doc_mut()?, ve.id, |net| { + if uniform { + let all: Vec = moves.iter().map(|(i, _)| *i).collect(); + ops::move_vertices(net, &all, d0); + } else { + for (i, d) in &moves { + ops::move_vertices(net, &[*i], *d); + } + } + })?; + Ok(json!({"ok": true})) + } + ), spec!("vector.edit.setHandle", "Set handle", "{segment, start (bool), x, y (local), independent?}", true, |s, p| { let ve = editing(s)?; let seg = index("vector.edit.setHandle", p, "segment")?; diff --git a/crates/engine/src/canvas/vectoredit/ops.rs b/crates/engine/src/canvas/vectoredit/ops.rs index 32b8eef44..222c6f4ff 100644 --- a/crates/engine/src/canvas/vectoredit/ops.rs +++ b/crates/engine/src/canvas/vectoredit/ops.rs @@ -312,6 +312,7 @@ fn remove_vertex_index(net: &mut VectorNetwork, vi: usize) { /// Remove segments (fixing region loops); points left without any segment go too. pub fn remove_segments(net: &mut VectorNetwork, segs: &[usize]) { + let before = net.segments.len(); let mut touched: Vec = segs.iter().filter_map(|s| net.segments.get(*s)).flat_map(|s| [s.a, s.b]).collect(); remove_segments_only(net, segs); touched.sort_unstable(); @@ -322,6 +323,9 @@ pub fn remove_segments(net: &mut VectorNetwork, segs: &[usize]) { } } reopen_loops(net); + if net.segments.len() != before { + close_bridged_loops(net); + } } fn remove_segments_only(net: &mut VectorNetwork, segs: &[usize]) { @@ -349,6 +353,7 @@ fn remove_segments_only(net: &mut VectorNetwork, segs: &[usize]) { /// Delete vertices, joining their neighbours where a vertex had exactly two segments (`heal`). pub fn delete_vertices(net: &mut VectorNetwork, idx: &[usize], heal: bool) { + let before = net.vertices.len(); let mut idx: Vec = idx.to_vec(); idx.sort_unstable(); idx.dedup(); @@ -408,6 +413,9 @@ pub fn delete_vertices(net: &mut VectorNetwork, idx: &[usize], heal: bool) { } net.sanitize(); reopen_loops(net); + if net.vertices.len() != before { + close_bridged_loops(net); + } } /// Handles for the curve that heals over deleted point `vi` between `(vertex, handle)` ends `o1` @@ -470,6 +478,24 @@ fn reopen_loops(net: &mut VectorNetwork) { } } +/// After points or segments were removed: an open loop whose two ends a segment in no loop already +/// joins (a bridge drawn between two points before what lay between them was deleted) closes +/// through that segment, at the loop's end so its winding is kept, as `connect` closes it (#1951). +/// Every loop takes what [`VectorNetwork::closing_segment`] gives it against one snapshot of the +/// network, which is what rounding walks: two fills that shared the removed border share the +/// bridge, as they shared the border. Only a removal can open a loop at two points a segment +/// already joins (a cut's ends are new points), so only `delete_vertices` and `remove_segments` +/// run this, and only when they removed something. +fn close_bridged_loops(net: &mut VectorNetwork) { + let index = net.loop_index(); + let closings: Vec> = net.regions.iter().flat_map(|r| r.loops.iter()).map(|lp| net.closing_segment(lp, &index)).collect(); + for (lp, closing) in net.regions.iter_mut().flat_map(|r| r.loops.iter_mut()).zip(closings) { + if let Some(closing) = closing { + lp.push(closing); + } + } +} + /// Cut a segment at `t` into two open ends at the same spot. Returns the two end vertices. pub fn cut_segment(net: &mut VectorNetwork, seg: usize, t: f64) -> Option<(usize, usize)> { let mid = split_segment(net, seg, t)?; @@ -1107,6 +1133,24 @@ mod tests { assert!(d.vertices.iter().all(|v| v.x.is_finite() && v.y.is_finite())); } + /// A curved bridge between two points of a ring, then the point between them deleted (Delete, + /// no healing): the region's loop closes through the bridge, so the fill follows its curve and + /// is as long as the stroke (#1951). + #[test] + fn deleting_a_point_behind_a_curved_bridge_keeps_the_bridge_in_the_loop() { + use figcraft_geom::BezPath; + use figcraft_geom::kurbo::ParamCurveArclen; + let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y)); + let mut n = VectorNetwork::from_points(&pts, true); + connect(&mut n, 1, 3, (25.0, 25.0), (-25.0, -25.0)).unwrap(); + assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (7, 6), "the ring kept"); + delete_vertices(&mut n, &[2], false); + assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (5, 5), "the loop holds the bridge: {:?}", n.regions); + let length = |p: &BezPath| p.segments().map(|s| s.arclen(1e-9)).sum::(); + let (fill, stroke) = (length(&n.fill_path()), length(&n.stroke_path())); + assert!((fill - stroke).abs() < 1e-6, "fill {fill} and stroke {stroke} follow the same outline"); + } + #[test] fn lasso_polygon() { let pts = [Point::new(5.0, 5.0), Point::new(50.0, 50.0), Point::new(15.0, 5.0)]; @@ -1175,4 +1219,169 @@ mod tests { assert!(ends.iter().any(|x| (x - (centre.x - 0.5)).abs() < 0.01), "{ends:?}"); assert!(ends.iter().any(|x| (x - (centre.x + 0.5)).abs() < 0.01), "{ends:?}"); } + + /// An open chain of four segments over five points whose two ends a fifth segment (in no + /// loop) joins, as a bridge drawn before the point between them was deleted. + fn bridged_open_chain() -> VectorNetwork { + let corners = [ + Point::new(0.0, 0.0), + Point::new(525.0, 525.0), + Point::new(0.0, 525.0), + Point::new(333.0, 0.0), + Point::new(525.0, 183.0), + Point::new(900.0, 900.0), + ]; + let mut n = VectorNetwork::from_points(&corners, false); + n.segments = [(0, 3), (1, 2), (2, 0), (4, 1), (3, 4)].iter().map(|&(a, b)| Segment::line(a, b)).collect(); + n.regions.clear(); + for v in &mut n.vertices { + v.radius = 125.0; + } + n + } + + #[test] + fn regions_over_one_open_chain_all_close_through_the_joining_segment() { + use figcraft_geom::BezPath; + use figcraft_geom::kurbo::ParamCurveArclen; + let mut n = bridged_open_chain(); + for _ in 0..2 { + n.regions.push(Region { loops: vec![vec![3, 1, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() }); + } + delete_vertices(&mut n, &[5], false); + for (i, r) in n.regions.iter().enumerate() { + assert_eq!(r.loops[0], vec![3, 1, 2, 0, 4], "region {i} closes through the segment: {:?}", n.regions); + } + let length = |path: &BezPath| path.segments().map(|s| s.arclen(1e-9)).sum::(); + let stroke = length(&n.stroke_path()); + let rounded = n.rounded().unwrap(); + for i in 0..2 { + let fill = length(&rounded.region_path(i).unwrap()); + assert!((fill - stroke).abs() < 1e-6, "region {i}: fill {fill} and stroke {stroke} trace the same outline"); + } + } + + /// Many independent open chains, each with its own closing segment, all close through it. + #[test] + fn many_open_chains_each_close_through_their_own_segment() { + let one = bridged_open_chain(); + let (nv, ns) = (one.vertices.len(), one.segments.len()); + let mut n = VectorNetwork::default(); + for (i, dx) in (0..50usize).zip((0..50u32).map(|k| f64::from(k) * 1000.0)) { + n.vertices.extend(one.vertices.iter().map(|v| Vertex { x: v.x + dx, ..*v })); + n.segments.extend(one.segments.iter().map(|s| Segment { a: s.a + i * nv, b: s.b + i * nv, ..*s })); + let base = i * ns; + n.regions.push(Region { + loops: vec![vec![base + 3, base + 1, base + 2, base]], + winding: WindingRule::NonZero, + fills: None, + ..Default::default() + }); + } + close_bridged_loops(&mut n); + for (i, r) in n.regions.iter().enumerate() { + assert_eq!(r.loops[0].last(), Some(&(i * ns + 4)), "chain {i} closes through its own segment"); + } + } + + #[test] + fn a_segment_joining_two_different_chains_closes_both() { + let mut n = bridged_open_chain(); + n.regions.push(Region { loops: vec![vec![3, 1, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() }); + n.regions.push(Region { loops: vec![vec![0, 2, 1, 3]], winding: WindingRule::NonZero, fills: None, ..Default::default() }); + delete_vertices(&mut n, &[5], false); + assert_eq!(n.regions[0].loops[0].len(), 5); + assert_eq!(n.regions[1].loops[0].len(), 5, "the same segment set is the same chain"); + let mut m = bridged_open_chain(); + m.segments.push(Segment::line(1, 2)); + m.regions.push(Region { loops: vec![vec![3, 1, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() }); + m.regions.push(Region { loops: vec![vec![3, 5, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() }); + let drawn = m.rounded().unwrap(); + delete_vertices(&mut m, &[5], false); + assert_eq!(m.regions[0].loops[0], vec![3, 1, 2, 0, 4], "{:?}", m.regions); + assert_eq!(m.regions[1].loops[0], vec![3, 5, 2, 0, 4], "different chains share the segment too: {:?}", m.regions); + let after = m.rounded().unwrap(); + for i in 0..2 { + assert_eq!(after.region_path(i).unwrap(), drawn.region_path(i).unwrap(), "region {i} is stored as rounding drew it"); + } + } + + /// Two fills that shared a border, a bridge drawn between the border's ends, then the border's + /// middle point deleted: both fills close through the bridge (#1951). + #[test] + fn two_fills_that_shared_a_deleted_border_both_close_through_the_bridge() { + use figcraft_geom::Shape; + let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y)); + let mut n = VectorNetwork::from_points(&pts, true); + n.vertices.push(Vertex::new(50.0, 50.0)); + n.segments.push(Segment::line(1, 6)); + n.segments.push(Segment::line(6, 4)); + n.regions.clear(); + for lp in [vec![0, 6, 7, 4, 5], vec![1, 2, 3, 7, 6]] { + n.regions.push(Region { loops: vec![lp], winding: WindingRule::NonZero, fills: None, ..Default::default() }); + } + connect(&mut n, 1, 4, (30.0, 30.0), (30.0, -30.0)).unwrap(); + delete_vertices(&mut n, &[6], false); + assert_eq!(n.regions[0].loops[0], vec![4, 5, 0, 6]); + assert_eq!(n.regions[1].loops[0], vec![1, 2, 3, 6], "the second fill closes through the bridge too"); + let area = |i: usize| n.region_path(i).unwrap().area().abs(); + assert!((area(0) + area(1) - 10_000.0).abs() < 1e-6, "the fills meet along the bridge"); + } + + #[test] + fn removing_nothing_leaves_an_open_loop_alone() { + let mut n = bridged_open_chain(); + n.regions.push(Region { loops: vec![vec![3, 1, 2, 0]], winding: WindingRule::NonZero, fills: None, ..Default::default() }); + let before = n.clone(); + remove_segments(&mut n, &[]); + assert_eq!(n, before); + remove_segments(&mut n, &[99]); + assert_eq!(n, before); + delete_vertices(&mut n, &[], false); + assert_eq!(n, before); + delete_vertices(&mut n, &[99], true); + assert_eq!(n, before); + delete_vertices(&mut n, &[5], false); + assert_eq!(n.regions[0].loops[0], vec![3, 1, 2, 0, 4]); + } + + /// The same bridge as the curved-bridge test, reached by removing segments. + #[test] + fn removing_segments_behind_a_curved_bridge_keeps_the_bridge_in_the_loop() { + let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y)); + let mut n = VectorNetwork::from_points(&pts, true); + connect(&mut n, 1, 3, (25.0, 25.0), (-25.0, -25.0)).unwrap(); + remove_segments(&mut n, &[1, 2]); + assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (5, 5)); + assert_eq!(n.regions[0].loops[0], vec![1, 2, 3, 0, 4]); + } + + #[test] + fn many_open_loops_with_no_closing_segment_round_as_before() { + let mut n = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false); + n.segments.clear(); + n.vertices.clear(); + for k in 0..40 { + let x = f64::from(k) * 100.0; + let base = n.vertices.len(); + for p in [(x, 0.0), (x + 50.0, 0.0), (x + 50.0, 50.0), (x, 50.0)] { + n.vertices.push(Vertex { radius: 8.0, ..Vertex::new(p.0, p.1) }); + } + let first = n.segments.len(); + // Three sides of a square, an open loop with nothing to close it. + for (a, b) in [(0, 1), (1, 2), (2, 3)] { + n.segments.push(Segment::line(base + a, base + b)); + } + n.regions.push(Region { + loops: vec![vec![first, first + 1, first + 2]], + winding: WindingRule::NonZero, + fills: None, + ..Default::default() + }); + } + let r = n.rounded().unwrap(); + assert_eq!(r.regions.len(), 40); + // Each loop gained only its two inner corners' arcs (two corners, one arc each). + assert!(r.regions.iter().all(|reg| reg.loops[0].len() == 5), "{:?}", r.regions[0]); + } } diff --git a/crates/engine/src/canvas/vectoredit/position_tests.rs b/crates/engine/src/canvas/vectoredit/position_tests.rs new file mode 100644 index 000000000..efbddab8d --- /dev/null +++ b/crates/engine/src/canvas/vectoredit/position_tests.rs @@ -0,0 +1,171 @@ +//! `vector.edit.position`: with several points, a number sets every selected point's own +//! coordinate, and `{add}`, `{mul}`, `{div}` apply to each point's own. + +use serde_json::json; + +use super::tests::{ex, net, rect}; +use super::*; +use crate::Session; + +/// Every point in the parent's coordinates (the layer re-fits its box after an edit, so its own +/// coordinates shift). +fn xs(s: &Session, id: NodeId) -> Vec<(f64, f64)> { + let t = s.doc().unwrap().node(id).unwrap().transform; + net(s, id).vertices.iter().map(|v| t * v.point()).map(|p| (p.x, p.y)).collect() +} + +fn parent_xy(s: &Session) -> Vec<(f64, f64)> { + let ve = s.ds().unwrap().vector_edit.clone().unwrap(); + selected_parent_points(s.doc().unwrap(), &ve).iter().map(|p| (p.x, p.y)).collect() +} + +fn undo_steps(s: &Session) -> usize { + s.ds().unwrap().history.undo.len() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +#[test] +fn a_number_sets_every_selected_points_own_coordinate() { + let mut s = Session::new(); + let id = rect(&mut s); + let before = xs(&s, id); + ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]})); + // The rectangle's points 0 and 1 differ in x; both end at -200 and keep their y. + assert!(!near(before[0].0, before[1].0)); + ex(&mut s, "vector.edit.position", json!({"x": -200})); + let after = xs(&s, id); + assert!(near(after[0].0, -200.0) && near(after[1].0, -200.0), "{after:?}"); + assert!(near(after[0].1, before[0].1) && near(after[1].1, before[1].1)); + assert_eq!(after[2], before[2]); + // One undo step restores. + assert!(s.undo().unwrap()); + assert_eq!(xs(&s, id), before); +} + +#[test] +fn one_point_sets_its_own_coordinates() { + let mut s = Session::new(); + let id = rect(&mut s); + let before = xs(&s, id); + ex(&mut s, "vector.edit.select", json!({"vertices": [2]})); + ex(&mut s, "vector.edit.position", json!({"x": 7, "y": 9})); + let after = xs(&s, id); + assert!(near(after[2].0, 7.0) && near(after[2].1, 9.0)); + assert_eq!(after[0], before[0]); +} + +#[test] +fn relative_edits_apply_to_each_points_own_value() { + let mut s = Session::new(); + let id = rect(&mut s); + let before = xs(&s, id); + ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]})); + ex(&mut s, "vector.edit.position", json!({"x": {"add": 10}})); + let a = xs(&s, id); + assert!(near(a[0].0, before[0].0 + 10.0) && near(a[1].0, before[1].0 + 10.0), "{a:?}"); + ex(&mut s, "vector.edit.position", json!({"y": {"mul": 2}})); + let b = xs(&s, id); + assert!(near(b[0].1, a[0].1 * 2.0) && near(b[1].1, a[1].1 * 2.0), "{b:?}"); + ex(&mut s, "vector.edit.position", json!({"x": {"div": 2}})); + let c = xs(&s, id); + assert!(near(c[0].0, a[0].0 / 2.0) && near(c[1].0, a[1].0 / 2.0), "{c:?}"); +} + +#[test] +fn a_point_keeps_its_handles_relative_to_it() { + let mut s = Session::new(); + let id = rect(&mut s); + ex(&mut s, "vector.edit.select", json!({"vertices": [1]})); + ex(&mut s, "vector.edit.smooth", json!({})); + let before = net(&s, id); + assert!(before.segments.iter().any(|g| g.ta != (0.0, 0.0) || g.tb != (0.0, 0.0))); + ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]})); + ex(&mut s, "vector.edit.position", json!({"x": {"add": 25}})); + let after = net(&s, id); + let tangents = |n: &VectorNetwork| n.segments.iter().map(|g| (g.ta, g.tb)).collect::>(); + assert_eq!(tangents(&before), tangents(&after)); +} + +#[test] +fn the_values_are_in_the_parents_coordinates() { + let mut s = Session::new(); + let r = ex(&mut s, "shape.rectangle", json!({"x": 40, "y": 30, "width": 100, "height": 100})); + let id = crate::params::id_of(&r["id"]).unwrap(); + ex(&mut s, "vector.edit.begin", json!({"id": id})); + ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]})); + let before = parent_xy(&s); + assert!(near(before[0].0, 40.0), "{before:?}"); + ex(&mut s, "vector.edit.position", json!({"x": 10})); + let after = parent_xy(&s); + assert!(near(after[0].0, 10.0) && near(after[1].0, 10.0), "{after:?}"); + assert!(near(after[0].1, before[0].1)); +} + +#[test] +fn moving_every_point_by_one_offset_carries_the_regions_paint_frame() { + // `{add}` on every point is a plain translation: the region's paint frame goes with the + // points, as when they are dragged together. + let mut s = Session::new(); + let id = rect(&mut s); + { + let node = s.doc_mut().unwrap().get_mut(id).unwrap(); + let NodeKind::Vector { network } = &mut node.kind else { panic!("expected a vector") }; + assert!(!network.regions.is_empty(), "the rectangle has a region"); + for region in &mut network.regions { + region.paint_space = Some(figcraft_doc::RegionPaintSpace { width: 100.0, height: 100.0, transform: Affine::IDENTITY }); + } + } + let frame = |s: &Session| { + let world = s.doc().unwrap().world_transform(id); + world * net(s, id).regions[0].paint_space.as_ref().unwrap().transform + }; + let before = frame(&s); + let all: Vec = (0..net(&s, id).vertices.len()).collect(); + ex(&mut s, "vector.edit.select", json!({"vertices": all})); + ex(&mut s, "vector.edit.position", json!({"x": {"add": 10}})); + let (want, got) = ((Affine::translate((10.0, 0.0)) * before).as_coeffs(), frame(&s).as_coeffs()); + assert!(want.iter().zip(got).all(|(a, b)| near(*a, b)), "{got:?} vs {want:?}"); +} + +#[test] +fn junk_is_refused_and_changes_nothing() { + let mut s = Session::new(); + let id = rect(&mut s); + let before = xs(&s, id); + ex(&mut s, "vector.edit.select", json!({"vertices": [0, 1]})); + let steps = undo_steps(&s); + for junk in [ + json!({"x": {"div": 0}}), + json!({"x": {"pow": 2}}), + json!({"x": "a"}), + json!({"x": {"add": 1, "mul": 2}}), + json!({"y": {"add": "x"}}), + json!({"x": {}}), + json!({"x": [1]}), + json!({"x": true}), + json!({"x": {"add": true}}), + // A valid x with a refused y changes neither. + json!({"x": 5, "y": {"div": 0}}), + // Point 1's x of 100 overflows; point 0's 0 alone would not. + json!({"x": {"mul": 1e308}}), + ] { + assert!(s.execute("vector.edit.position", &junk).is_err(), "{junk}"); + } + assert_eq!(xs(&s, id), before); + assert_eq!(undo_steps(&s), steps, "a refused edit leaves no undo step"); +} + +#[test] +fn nothing_selected_is_refused() { + let mut s = Session::new(); + let id = rect(&mut s); + ex(&mut s, "vector.edit.select", json!({"vertices": []})); + let (before, steps) = (xs(&s, id), undo_steps(&s)); + assert!(parent_xy(&s).is_empty()); + let err = s.execute("vector.edit.position", &json!({"x": 5})).unwrap_err(); + assert!(err.to_string().contains("select points"), "{err}"); + assert_eq!((xs(&s, id), undo_steps(&s)), (before, steps)); +} diff --git a/crates/engine/src/canvas/vectoredit/tests.rs b/crates/engine/src/canvas/vectoredit/tests.rs index 3812c1b7b..ebe849761 100644 --- a/crates/engine/src/canvas/vectoredit/tests.rs +++ b/crates/engine/src/canvas/vectoredit/tests.rs @@ -659,6 +659,27 @@ fn a_rounded_chamfer_made_other_ways_fills_along_its_arcs() { fill_traces_stroke(&s, id, "drawn with the pen"); } +/// The reporter's sequence (#1951): a bridge drawn between the two new points while the corner is +/// still there (both have two segments, so the region keeps its ring), then the corner deleted with +/// Delete. The region's loop must close through the bridge, so the rounded fill traces the stroke. +#[test] +fn deleting_the_corner_behind_a_pen_bridge_closes_the_loop_through_the_bridge() { + let mut s = Session::new(); + let id = rect(&mut s); + ex(&mut s, "vector.edit.addVertex", json!({"segment": 0, "t": 0.5})); + ex(&mut s, "vector.edit.addVertex", json!({"segment": 1, "t": 0.5})); + let n = net(&s, id); + let (top, right) = (vertex_at(&n, 50.0, 0.0), vertex_at(&n, 100.0, 50.0)); + ex(&mut s, "vector.edit.connect", json!({"a": top, "b": right})); + let n = net(&s, id); + assert_eq!((n.segments.len(), n.regions[0].loops[0].len()), (7, 6), "bridged, the ring kept: {:?}", n.regions); + let corner = vertex_at(&n, 100.0, 0.0); + ex(&mut s, "vector.edit.select", json!({"vertices": [corner]})); + ex(&mut s, "vector.edit.delete", json!({})); + ex(&mut s, "vector.edit.cornerRadius", json!({"radius": 43, "vertices": [0, 1, 2, 3, 4]})); + fill_traces_stroke(&s, id, "bridged, then the corner deleted"); +} + /// The rounded chamfered rectangle `id` (five points on the origin's 100×100 box, the top-right /// corner cut off between (50, 0) and (100, 50)): one region with every segment in its loop, and a /// fill that keeps off every sharp point and traces the same outline as the stroke. diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs index 576e42cb6..4236d3fad 100644 --- a/crates/engine/src/catalog.rs +++ b/crates/engine/src/catalog.rs @@ -291,6 +291,7 @@ pub static MENU: &[MenuItem] = &[ m!("Tools", "Pencil", "tool.pencil"), m!("Tools", "Text", "tool.text"), m!("Tools", "Comment", "tool.comment"), + m!("Tools", "Annotation", "tool.annotation"), m!("Tools", "Shape builder", "tool.shapeBuilder"), m!("Tools", "Actions", "app.actions"), ]; diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index e7f04d7a1..c39f8abe2 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -113,8 +113,12 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result { // A new rotation for the selection turns it about its moved rotation origin: each layer's // point under the origin stays put. let ds = s.ds()?; - let pivot = - ds.moved_origin().filter(|_| props.contains_key("rotation") && !props.contains_key("x") && !props.contains_key("y") && ds.selection == ids); + let pivot = ds.moved_origin().filter(|_| { + (props.contains_key("rotation") || props.contains_key("absoluteRotation")) + && !props.contains_key("x") + && !props.contains_key("y") + && ds.selection == ids + }); let pinned: Vec<(NodeId, figcraft_geom::Point)> = match pivot { Some(o) => roots(&ds.doc, &ids) .into_iter() @@ -161,6 +165,11 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result { } let doc = s.doc_mut()?; let before = crate::cmd::styles::bound_before(doc, &ids); + let mut ids = ids; + if props.contains_key("absoluteRotation") { + // A page angle depends on the parents': turn a selected parent before the layers in it. + ids.sort_by_key(|i| doc.ancestors(*i).len()); + } for i in ids { crate::cmd::props::apply("node.set", doc, i, skipped.get(&i).unwrap_or(&props))?; } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index ca83292ec..2916d4aac 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -26,8 +26,8 @@ pub(crate) use export::FORBIDDEN_FILE_NAME_CHARS; use export::add_member; pub(super) use export::export_setting; pub use export::{ - ExportJob, copy_png, drawn_layers, export_area, export_bytes, export_bytes_with, export_jobs, export_scale, exportable_layers, fig_bytes, - frames_pdf, jobs_for, penpot_bytes, safe_file_name, + ExportJob, backdrop_layers, copy_png, drawn_layers, export_area, export_bytes, export_bytes_with, export_jobs, export_scale, exportable_layers, + fig_bytes, frames_pdf, jobs_for, penpot_bytes, safe_file_name, }; use export::{export, export_frames_pdf, export_layers, pdf_bytes}; use load::font_report; @@ -409,7 +409,10 @@ pub fn export_file(doc: &Document, ids: &[NodeId], setting: &ExportSetting, scal Ok((pdf_bytes(doc, &groups, &setting.print, (!own_area).then_some(area))?, Vec::new())) } _ => { - let mut pix = figcraft_render::render_area(doc, &drawn, area, scale) + // Layers exported on their own still read the page beneath them for a background blur + // or glass (#2213); a "contents only" off export already draws the whole page. + let page = if setting.contents_only { backdrop_layers(doc, ids) } else { Vec::new() }; + let mut pix = figcraft_render::render_area_over(doc, &drawn, &page, area, scale) .ok_or_else(|| EngineError::Other("render failed (empty or too large)".into()))?; // The render is in the document's profile; the setting's profile converts the pixels // (out-of-gamut colors clip) and tags the file. diff --git a/crates/engine/src/cmd/file/export.rs b/crates/engine/src/cmd/file/export.rs index de426ba89..bbc52e1b5 100644 --- a/crates/engine/src/cmd/file/export.rs +++ b/crates/engine/src/cmd/file/export.rs @@ -55,6 +55,12 @@ pub fn drawn_layers(doc: &Document, ids: &[NodeId], setting: &ExportSetting) -> crate::cmd::edit::z_sorted(doc, &crate::cmd::edit::roots(doc, &own)) } +/// The top-level layers of the page of `ids`, bottom to top: what a background blur or glass in an +/// export of `ids` reads from (empty when `ids` are on no page). +pub fn backdrop_layers(doc: &Document, ids: &[NodeId]) -> Vec { + ids.first().and_then(|i| doc.page_of(*i)).and_then(|p| doc.node(p)).map(|p| p.children.clone()).unwrap_or_default() +} + /// The frame or group a slice sits in: None on the page or in a section. fn slice_container(doc: &Document, slice: NodeId) -> Option { let parent = doc.node(slice)?.parent?; diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 2e5da37bd..0e928793e 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -16,7 +16,7 @@ use crate::{Result, bad}; pub const STROKE_SIDES: [&str; 4] = ["strokeTopWeight", "strokeRightWeight", "strokeBottomWeight", "strokeLeftWeight"]; /// Keys `node.set` understands (documented for agents). -pub const KEYS: &str = "name, visible, locked, opacity (0-1 or \"50%\"), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), \ +pub const KEYS: &str = "name, visible, locked, opacity (0-1 or \"50%\"), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page: the layer's angle plus its parents', what the Design panel's field shows; one of the two per call), \ fills (paints or colours; gradients as {type: linearGradient|radialGradient|angularGradient|diamondGradient, stops: [\"#hex\", ...], from?, to?} too), fill (colour, {$var: variable id or name}, or \"none\"/null: no fill), strokes, stroke (colour, {$var: variable id or name}, or \"none\"/null: no stroke), strokeWeight, strokeAlign (inside|center|outside), strokeSides [t,r,b,l], strokeTopWeight / strokeRightWeight / strokeBottomWeight / strokeLeftWeight (one side; turns on individual strokes), \ strokeCap / startCap / endCap, strokeJoin, miterAngle (degrees: sharper joins bevel; or miterLimit as a ratio), dashes [..], dashCap (none|round|square; null: dashes take startCap and endCap), widthProfile (preset uniform|wedge|taper|eye|rounded|pinch, [[t, scale], ...] or null), brush (preset id, {preset, spacing, sizeJitter, rotationJitter, scatter, seed} or null), cornerRadius (n or [tl,tr,br,bl]), cornerSmoothing (0-1), effects, \ clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, padding (n or [t,r,b,l]), paddingTop/Right/Bottom/Left, \ @@ -29,7 +29,7 @@ fontSize, lineHeight (auto|px|\"150%\"), letterSpacing (px|\"2%\"), textAlign (l (auto|px|\"10%\" of the font size; the offset runs from the baseline down to an underline's top edge), textDecorationSkipInk (underlines break around descenders), \ textDecorationColor (colour, or auto/null: the text's), textCase (original|upper|lower|title|smallCaps), paragraphSpacing, paragraphIndent, \ listStyle (none|bulleted|numbered; with start/end: the paragraphs those chars touch), indentation (list nesting level 0-8, same range rule), \ -listSpacing (px between list items, in place of paragraphSpacing), hangingPunctuation, hangingList (markers outside the box), leadingTrim (vertical trim: none|capHeight), maxLines, features ({tag: bool}, e.g. {\"liga\": false, \"tnum\": true}), \ +listSpacing (px between list items, in place of paragraphSpacing), wrapStyle (auto|balance|pretty; with start/end: the paragraphs those chars touch), hangingPunctuation, hangingList (markers outside the box), leadingTrim (vertical trim: none|capHeight), maxLines, features ({tag: bool}, e.g. {\"liga\": false, \"tnum\": true}), \ fontVariations / variationSettings ({axis: number}, e.g. {\"wght\": 550, \"wdth\": 85}; null = none), \ path (a vector's SVG path data: replaces its geometry, keeping the layer, its paints, styles and bindings; width/height in the same call scale it as \ node.create does; its own box goes at the layer's x/y, or with x/y given, at x + its left edge and y + its top as node.create places it), pointCount, innerRadius, arcStart, arcSweep, \ @@ -456,7 +456,7 @@ fn apply_order(k: &str, v: &Value) -> u8 { match k { "path" | "width" | "height" | "w" | "h" => 0, "layout" | "layoutMode" => 1, - "rotation" => 3, + "rotation" | "absoluteRotation" => 3, "x" | "y" => 4, "fillStyle" | "strokeStyle" | "effectStyle" | "textStyle" | "gridStyle" => 5, "boundVariables" => 6, @@ -595,6 +595,27 @@ fn apply_geometry( let n = doc.get_mut(id)?; n.transform = figcraft_geom::set_rotation_about_center(n.transform, n.width, n.height, deg); } + "absoluteRotation" => { + let deg = f64_of(v).ok_or_else(|| bad(cmd, "`absoluteRotation` must be degrees"))?; + if props.contains_key("rotation") { + return Err(bad(cmd, "give one of `rotation` and `absoluteRotation`")); + } + let (w, h) = { + let n = doc.get(id)?; + (n.width, n.height) + }; + let world = figcraft_geom::set_rotation_about_center(doc.world_transform(id), w, h, deg); + let parent = doc.get(id)?.parent; + let pw = parent.map(|p| doc.world_transform(p)).unwrap_or(figcraft_geom::Affine::IDENTITY); + let local = pw.inverse() * world; + if local.as_coeffs().iter().all(|c| c.is_finite()) { + doc.get_mut(id)?.transform = local; + } else { + // A degenerate parent can't be inverted: turn the local angle instead. + let n = doc.get_mut(id)?; + n.transform = figcraft_geom::set_rotation_about_center(n.transform, n.width, n.height, deg); + } + } _ => return Ok(false), } Ok(true) @@ -1008,7 +1029,14 @@ fn apply_text(cmd: &str, doc: &mut Document, id: NodeId, props: &Map text_mut(cmd, doc.get_mut(id)?)?.leading_trim = enum_of(v).ok_or_else(|| bad(cmd, "leadingTrim: none|capHeight"))?, "wrapStyle" | "textWrap" => { - text_mut(cmd, doc.get_mut(id)?)?.wrap_style = enum_of(v).ok_or_else(|| bad(cmd, "wrapStyle: auto|balance|pretty"))? + let w: figcraft_doc::WrapStyle = enum_of(v).ok_or_else(|| bad(cmd, "wrapStyle: auto|balance|pretty"))?; + let t = text_mut(cmd, doc.get_mut(id)?)?; + if props.contains_key("start") || props.contains_key("end") { + let (start, end) = range_of(props, t.char_count()); + t.set_para_wrap_styles(start, end, w); + } else { + t.set_wrap_style(w); + } } "maxLines" => { let lines = f64_of(v).unwrap_or(0.0).clamp(0.0, 10_000.0) as u32; diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index 34cc91fbb..c73ef8b21 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -496,7 +496,9 @@ fn collect_flatten_parts( } let part = match &node.kind { NodeKind::Vector { network } => { - let mut part = network.clone(); + // Rounded points bake into the path (the arc's end points joined by curves), drawn the way + // the layer draws them, so the shape looks the same and the box fits the real geometry. + let mut part = figcraft_doc::geometry::drawn_network(network, node.corners.smoothing).into_owned(); if !part.regions.is_empty() && part.regions.iter().all(|region| region.fills.is_none() && region.paint_space.is_none()) { let winding = if part.regions.iter().any(|region| region.winding == WindingRule::EvenOdd) { WindingRule::EvenOdd diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 9ba420c43..710eec76e 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { spec!( "style.bind", "Bind variable in style", - "{style, field, variable? (id or name; none: unbind)} bind a variable to a field of the style's value: a paint style's `fills//color` (or `fill`: its first paint) and `fills//stops//color`, an effect style's `effects//` (glass: `lightAngle|lightIntensity|refraction|depth|dispersion|radius|splay`), a grid style's `layoutGrids//`, a text style's `fontSize|lineHeight|letterSpacing` (numbers, px) and `fontFamily|fontStyle` (strings). Every layer using the style shows the field resolved in its own modes; the style keeps it resolved in the default modes", + "{style, field, variable? (id or name; none: unbind)} bind a variable to a field of the style's value: a paint style's `fills//color` (or `fill`: its first paint) and `fills//stops//color`, an effect style's `effects//` (glass: `lightAngle|lightIntensity|refraction|depth|dispersion|radius|splay`), a grid style's `layoutGrids//`, a text style's `fontSize|lineHeight|letterSpacing|fontWeight` (numbers; line height and letter spacing in px, as the reference tool applies them; a weight picks the family's face nearest it and the `wght` axis of a variable font) and `fontFamily|fontStyle` (strings; a weight bound as a number replaces a bound style name and the reverse). Every layer using the style shows the field resolved in its own modes; the style keeps it resolved in the default modes", true, bind_style ), @@ -275,6 +275,9 @@ fn paragraph_style_json(cmd: &str, v: &Value) -> Result { "paragraphSpacing" | "paragraph_spacing" => ps.paragraph_spacing = length(k, x)?, "paragraphIndent" | "paragraph_indent" => ps.paragraph_indent = length(k, x)?, "listStyle" | "list" => ps.list = super::props::enum_of(x).ok_or_else(|| bad(cmd, "listStyle: none|bulleted|numbered"))?, + "wrapStyle" | "textWrap" | "wrap_style" => { + ps.wrap_style = super::props::enum_of(x).ok_or_else(|| bad(cmd, "wrapStyle: auto|balance|pretty"))?; + } "features" | "openTypeFeatures" | "fontFeatures" | "textFeatures" => { ps.features = super::props::features_of(cmd, x)?.into_iter().filter_map(|(tag, on)| Some((tag, on?))).collect(); } @@ -289,10 +292,11 @@ fn paragraph_style_json(cmd: &str, v: &Value) -> Result { fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option { let t = n.kind.text()?; let mut ps = t.paragraph_style(); - if let Some((a, b)) = range - && let Some(pl) = t.common_para_list(a, b) - { - ps.list = pl.list; + if let Some((a, b)) = range { + if let Some(pl) = t.common_para_list(a, b) { + ps.list = pl.list; + } + ps.wrap_style = t.common_wrap_style(a, b).unwrap_or(t.wrap_style); } Some(ps) } @@ -520,6 +524,11 @@ fn bind_style(s: &mut Session, p: &Value) -> Result { { rebind_paint_alpha(paints, &mut [], &key, true); } + match key.as_str() { + "fontWeight" => style.bound.remove("fontStyle"), + "fontStyle" => style.bound.remove("fontWeight"), + _ => None, + }; style.bound.insert(key, id); } None => { diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 5bc191d7c..c865924c5 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -98,6 +98,15 @@ fn set_direction(s: &mut Session, p: &Value, d: TextDirection) -> Result para_range(s, p, |t, a, b| t.set_para_lists(a, b, |pl| pl.direction = d)) } +/// The wrap style of the targeted texts: the edited paragraphs while editing (the paragraph +/// level), else the whole layer (the layer level: every paragraph, overrides included). +fn set_wrap_style(s: &mut Session, p: &Value, w: figcraft_doc::WrapStyle) -> Result { + match textedit::selected_range(s) { + Some((_, a, b)) => para(s, p, |t| t.set_para_wrap_styles(a, b, w)), + None => para(s, p, |t| t.set_wrap_style(w)), + } +} + /// Whether every targeted char has `pred` (to decide toggle direction). fn all_have(s: &Session, p: &Value, pred: impl Fn(&TextStyle) -> bool) -> bool { let Ok(doc) = s.doc() else { return false }; @@ -445,12 +454,12 @@ pub fn specs() -> Vec { spec!( "text.wrapStyle", "Wrap style", - "{style: auto|balance|pretty, ids?} where lines break when the text wraps: Auto fits as many words as fit on each line, Balance makes the lines close to the same length, Pretty keeps lines full but leaves no one word alone on the last", + "{style: auto|balance|pretty, ids?} where lines break when the text wraps (while editing: the selected paragraphs; else the whole layer): Auto fits as many words as fit on each line, Balance makes the lines close to the same length, Pretty keeps lines full but leaves no one word alone on the last", true, |s, p| { let w: figcraft_doc::WrapStyle = get(p, "style").and_then(super::props::enum_of).ok_or_else(|| bad("text.wrapStyle", "`style`: auto|balance|pretty"))?; - para(s, p, |t| t.wrap_style = w) + set_wrap_style(s, p, w) } ), spec!( diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 46ca701ff..dc58926fe 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -100,12 +100,16 @@ fn zoom_to(s: &mut Session, z: f64) -> Result { Ok(json!({"zoom": v.zoom})) } -/// How far an arrow key pans the view with nothing selected (screen pixels; Shift: ten times). -pub const PAN_STEP_PX: f64 = 20.0; +/// How far an arrow key pans the view with nothing selected (screen pixels). Measured in Figma at +/// 100% zoom: about 64 px (62-64 in two trials, +/-3 px). +pub const PAN_STEP_PX: f64 = 64.0; + +/// Shift multiplies the arrow pan by this much (Figma: about 320 px, five steps). +pub const PAN_BIG_STEPS: f64 = 5.0; /// `view.pan`: the arrow keys with nothing selected move the view by keyboard steps. fn pan(s: &mut Session, p: &Value) -> Result { - let step = if boolean(p, "big").unwrap_or(false) { PAN_STEP_PX * 10.0 } else { PAN_STEP_PX }; + let step = if boolean(p, "big").unwrap_or(false) { PAN_STEP_PX * PAN_BIG_STEPS } else { PAN_STEP_PX }; let dir = |k| num(p, k).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-100.0, 100.0) * step; let (dx, dy) = (dir("dx"), dir("dy")); let v = view(s)?; @@ -235,6 +239,26 @@ pub(crate) fn tool(s: &mut Session, t: ToolId) -> Result { Ok(json!({"tool": t.id()})) } +/// Shift+T and choosing the Annotation tool: with a layer selected (or named by `id`/`ids`) the UI +/// is asked for its note at once; in the tool, a press on a layer selects it and asks (the engine +/// never writes the note). A named target is checked first: one that isn't a layer in the document +/// is an error and the tool stays as it was. +fn annotation(s: &mut Session, p: &Value) -> Result { + let named = p.get("id").is_some_and(|v| !v.is_null()) || p.get("ids").is_some_and(|v| !v.is_null()); + let first = crate::params::targets(s, p).into_iter().find(|i| s.doc().is_ok_and(|d| d.node(*i).is_some_and(|n| !n.is_page()))); + if named && first.is_none() { + return Err(bad("tool.annotation", "`id` must name a layer in this document (not a page)".to_string())); + } + let r = tool(s, ToolId::Annotation)?; + if let Some(id) = first { + if named { + crate::cmd::edit::select_and_page(s, vec![id])?; + } + s.request_ui("annotation.new", json!({"id": id})); + } + Ok(r) +} + /// The View menu's commands and their parameters. pub fn specs() -> Vec { vec![ @@ -298,7 +322,7 @@ pub fn specs() -> Vec { spec!("view.multiplayerCursors", "Multiplayer cursors", "{on?} others' cursors in a live session", false, |s, p| { toggle(s, p, "view.multiplayerCursors") }), - spec!("view.pan", "Pan the view", "{dx, dy (arrow-key steps, e.g. 1 or -1), big? (ten times as far, like Shift)}", false, pan), + spec!("view.pan", "Pan the view", "{dx, dy (arrow-key steps, e.g. 1 or -1), big? (five times as far, like Shift)}", false, pan), spec!("view.outlines", "Outlines", "{on?}", false, |s, p| toggle(s, p, "view.outlines")), spec!("view.outlinesSelection", "Outlines for selection", "{on?} outline mode for the selected layers only", false, |s, p| { toggle(s, p, "view.outlinesSelection") @@ -410,6 +434,13 @@ pub fn specs() -> Vec { false, |s, p| pref(s, p, |x| &mut x.scroll_wheel_zoom) ), + spec!( + "pref.invertZoom", + "Invert zoom direction", + "{on?} reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in (a trackpad pinch and panning are unchanged) → {on}", + false, + |s, p| pref(s, p, |x| &mut x.invert_zoom) + ), spec!("pref.reduceMotion", "Reduce motion", "{on?}", false, |s, p| pref(s, p, |x| &mut x.reduce_motion)), spec!( "pref.uiScale", @@ -528,7 +559,7 @@ pub fn specs() -> Vec { spec!( "tool.set", "Choose tool", - "{tool: move|scale|hand|frame|section|slice|rectangle|line|arrow|ellipse|polygon|star|pen|pencil|text|comment|shapeBuilder | on boards: sticky|shape|connector|marker|highlighter|eraser|stamp}", + "{tool: move|scale|hand|frame|section|slice|rectangle|line|arrow|ellipse|polygon|star|pen|pencil|text|comment|annotation|shapeBuilder | on boards: sticky|shape|connector|marker|highlighter|eraser|stamp}", false, |s, p| { let t = req_string("tool.set", p, "tool")?; @@ -536,6 +567,9 @@ pub fn specs() -> Vec { if t.on_boards() { crate::board::require(s, &format!("tool.{}", t.id()))?; } + if t == ToolId::Annotation { + return annotation(s, &json!({})); + } tool(s, t) } ), @@ -638,6 +672,9 @@ pub fn specs() -> Vec { tool(s, ToolId::TextOnPath) }), spec!("tool.comment", "Comment", "{}", false, |s, _| tool(s, ToolId::Comment)), + // Shift+T: with a layer selected (or an `id`) the UI is asked for its note at once; in the + // tool, a press on a layer selects it and asks (the engine never writes the note). + spec!("tool.annotation", "Annotation", "{id?|ids?}", false, annotation), spec!("tool.shapeBuilder", "Shape builder", "{}", false, |s, _| tool(s, ToolId::ShapeBuilder)), // `apply: false` is for the UI colour picker: the eyedropper only samples (into // `ToolState::picked`) and the picker writes the colour to the paint it edits. @@ -672,4 +709,45 @@ mod start_on_home_tests { let old: crate::Prefs = serde_json::from_value(json!({"theme": "dark"})).unwrap(); assert!(!old.start_on_home); } + + #[test] + fn the_arrows_pan_64_px_and_320_with_shift_as_measured_in_figma() { + let mut s = crate::Session::new(); + s.execute("view.set", &json!({"zoom": 1.0, "cx": 300, "cy": 200})).unwrap(); + s.execute("view.pan", &json!({"dx": 1})).unwrap(); + let v = &s.ds().unwrap().view; + assert_eq!((v.cx, v.cy), (364.0, 200.0), "one press pans 64 px"); + s.execute("view.pan", &json!({"dy": -1, "big": true})).unwrap(); + let v = &s.ds().unwrap().view; + assert_eq!((v.cx, v.cy), (364.0, -120.0), "Shift pans 320 px"); + } + + #[test] + fn the_arrow_pan_is_the_same_screen_distance_at_any_zoom_on_both_axes() { + // (zoom, dx, dy, big, expected centre change in document px) + let cases = [ + (2.0, 1.0, 0.0, false, 32.0, 0.0), + (0.5, 1.0, 0.0, false, 128.0, 0.0), + (2.0, 0.0, 1.0, true, 0.0, 160.0), + (0.5, 0.0, 1.0, true, 0.0, 640.0), + (1.0, -1.0, 0.0, false, -64.0, 0.0), + (1.0, 1.0, 0.0, true, 320.0, 0.0), + (1.0, -1.0, 0.0, true, -320.0, 0.0), + (1.0, 0.0, -1.0, false, 0.0, -64.0), + (1.0, 0.0, 1.0, false, 0.0, 64.0), + (1.0, 0.0, -1.0, true, 0.0, -320.0), + ]; + for (zoom, dx, dy, big, ex, ey) in cases { + let mut s = crate::Session::new(); + s.execute("view.set", &json!({"zoom": zoom, "cx": 300, "cy": 200})).unwrap(); + s.execute("view.pan", &json!({"dx": dx, "dy": dy, "big": big})).unwrap(); + let v = &s.ds().unwrap().view; + let got = (v.cx - 300.0, v.cy - 200.0); + assert!( + (got.0 - ex).abs() < 1e-6 && (got.1 - ey).abs() < 1e-6, + "zoom {zoom} dx {dx} dy {dy} big {big}: moved {got:?}, expected {:?}", + (ex, ey) + ); + } + } } diff --git a/crates/engine/src/cursor_tests.rs b/crates/engine/src/cursor_tests.rs index 86122c533..7c88e3f09 100644 --- a/crates/engine/src/cursor_tests.rs +++ b/crates/engine/src/cursor_tests.rs @@ -107,6 +107,7 @@ fn each_tool_has_its_cursor_by_modifier_and_what_is_under_the_pointer() { (ToolId::TextOnPath, NONE, ON_SQUARE_EDGE, Text, "the I-beam over a shape's path: a click puts text on it"), (ToolId::Pen, NONE, EMPTY, Pen(PenCursor::New), "the pen: a new point"), (ToolId::Comment, NONE, EMPTY, Comment, "the comment pin"), + (ToolId::Annotation, NONE, ON_SQUARE, Crosshair, "the annotation tool marks the layer it is pressed on"), (ToolId::Eyedropper, NONE, ON_SQUARE, Eyedropper, "the eyedropper"), ]; for (tool, m, at, want, why) in rows { diff --git a/crates/engine/src/dev/codegen/css.rs b/crates/engine/src/dev/codegen/css.rs index d521674e9..46f579123 100644 --- a/crates/engine/src/dev/codegen/css.rs +++ b/crates/engine/src/dev/codegen/css.rs @@ -302,10 +302,12 @@ fn text_decls(doc: &Document, n: &Node, tx: &figcraft_doc::TextData, t: &mut Tok TextAlignH::Right => put("text-align", "right".into()), TextAlignH::Justified => put("text-align", "justify".into()), } - match tx.wrap_style { - figcraft_doc::WrapStyle::Auto => {} - figcraft_doc::WrapStyle::Balance => put("text-wrap", "balance".into()), - figcraft_doc::WrapStyle::Pretty => put("text-wrap", "pretty".into()), + // CSS has one `text-wrap` per element: written when every paragraph has the same one. + let wrap = (0..tx.paragraph_count()).map(|p| tx.para_wrap_style(p)).collect::>(); + match wrap.first().copied().filter(|w| wrap.iter().all(|x| x == w)) { + Some(figcraft_doc::WrapStyle::Balance) => put("text-wrap", "balance".into()), + Some(figcraft_doc::WrapStyle::Pretty) => put("text-wrap", "pretty".into()), + _ => {} } // A base direction forced on every paragraph (CSS has one per element). let dir = tx.paragraphs.first().map(|p| p.direction).filter(|d| tx.paragraphs.iter().all(|p| p.direction == *d)); diff --git a/crates/engine/src/dev/devinspect.rs b/crates/engine/src/dev/devinspect.rs index 3daf7d1b0..5ac74b9ee 100644 --- a/crates/engine/src/dev/devinspect.rs +++ b/crates/engine/src/dev/devinspect.rs @@ -230,7 +230,7 @@ pub fn dev_mode_allows(id: &str) -> bool { // Edits recorded as one grouped undo step, so their spec says no history of its own. const GROUPED: [&str; 1] = ["data.fill"]; match id.strip_prefix("tool.") { - Some(t) => matches!(t, "move" | "hand" | "comment"), + Some(t) => crate::tools::ToolId::from_id(t).is_some_and(crate::tools::ToolId::works_in_dev_mode), None if id == "file.revert" || GROUPED.contains(&id) => false, None => OWN.iter().any(|p| id.starts_with(p)) || crate::cmd::find_command(id).is_none_or(|c| !c.history), } diff --git a/crates/engine/src/devmode_behaviour_tests.rs b/crates/engine/src/devmode_behaviour_tests.rs index 47c33aa29..7414a297b 100644 --- a/crates/engine/src/devmode_behaviour_tests.rs +++ b/crates/engine/src/devmode_behaviour_tests.rs @@ -99,6 +99,102 @@ fn the_dev_mode_canvas_selects_and_pans_but_never_edits() { assert!(s.doc().unwrap().node(r).is_some_and(|n| n.transform.as_coeffs()[4] > 100.0), "moved"); } +/// The `annotation.new` requests queued so far, as the layer ids they name. +fn note_requests(s: &Session) -> Vec { + s.ui_requests.iter().filter(|r| r.kind == "annotation.new").filter_map(|r| crate::params::id_of(&r.data["id"])).collect() +} + +fn click(s: &mut Session, x: f64, y: f64) { + s.pointer(&ev(PointerKind::Down, x, y)).unwrap(); + s.pointer(&ev(PointerKind::Up, x, y)).unwrap(); +} + +#[test] +fn the_annotation_tool_picks_a_layer_and_asks_for_its_note() { + for dev_mode in [true, false] { + let mut s = Session::new(); + let f = frame(&mut s, 0.0, "Screen"); + let r = rect(&mut s, f, 20.0); + s.tool.dev_mode = dev_mode; + ex(&mut s, "select.set", json!({"ids": []})); + ex(&mut s, "tool.annotation", json!({})); + assert_eq!(s.tool.tool, ToolId::Annotation); + assert!(note_requests(&s).is_empty(), "nothing selected: no note is asked for yet"); + let (doc_before, undo_before) = (s.doc().unwrap().clone(), s.undo_labels(1000).len()); + // A press on empty canvas does nothing. + click(&mut s, 1000.0, 1000.0); + assert!(note_requests(&s).is_empty(), "empty canvas asks for nothing (dev_mode {dev_mode})"); + // A press on the rectangle selects it and asks for its note. + click(&mut s, 40.0, 40.0); + assert_eq!(s.selection(), vec![r], "dev_mode {dev_mode}"); + assert_eq!(note_requests(&s), vec![r], "dev_mode {dev_mode}"); + assert_eq!(s.tool.tool, ToolId::Annotation, "the tool stays until V or Escape"); + // The tool writes nothing. + assert_eq!(*s.doc().unwrap(), doc_before); + assert_eq!(s.undo_labels(1000).len(), undo_before); + } + // The keyboard flow: with a layer selected, choosing the tool asks at once. + let mut s = Session::new(); + let f = frame(&mut s, 0.0, "Screen"); + let r = rect(&mut s, f, 20.0); + ex(&mut s, "select.set", json!({"ids": [r]})); + ex(&mut s, "tool.annotation", json!({})); + assert_eq!(note_requests(&s), vec![r]); + // And with an `id`. + let mut s = Session::new(); + let f = frame(&mut s, 0.0, "Screen"); + let r = rect(&mut s, f, 20.0); + ex(&mut s, "tool.annotation", json!({"id": r})); + assert_eq!(note_requests(&s), vec![r]); + assert_eq!(s.selection(), vec![r]); +} + +/// A named target that isn't a layer (a page, an unknown id) is an error, and the tool is left as it +/// was; several targets pick the first layer among them and select it. +#[test] +fn the_annotation_tool_checks_the_layer_it_is_named_for_before_changing_anything() { + let mut s = Session::new(); + let f = frame(&mut s, 0.0, "Screen"); + let r = rect(&mut s, f, 20.0); + let page = s.page().unwrap(); + assert!(s.execute("tool.annotation", &json!({"id": page})).is_err(), "a page is not a layer"); + assert!(s.execute("tool.annotation", &json!({"id": "9999:9999"})).is_err(), "no such layer"); + assert!(s.execute("tool.annotation", &json!({"ids": []})).is_err(), "nothing named"); + assert_eq!(s.tool.tool, ToolId::Move, "the tool did not change"); + assert!(note_requests(&s).is_empty()); + // The page first, then the rectangle: the rectangle is the target, and selected. + ex(&mut s, "tool.annotation", json!({"ids": [page, r]})); + assert_eq!((s.tool.tool, s.selection(), note_requests(&s)), (ToolId::Annotation, vec![r], vec![r])); +} + +/// Choosing the tool with `tool.set` (the toolbar) asks for the selected layer's note like Shift+T. +#[test] +fn choosing_the_annotation_tool_from_the_toolbar_asks_for_the_selected_layers_note() { + let mut s = Session::new(); + let f = frame(&mut s, 0.0, "Screen"); + let r = rect(&mut s, f, 20.0); + ex(&mut s, "select.set", json!({"ids": [r]})); + ex(&mut s, "tool.set", json!({"tool": "annotation"})); + assert_eq!((s.tool.tool, note_requests(&s)), (ToolId::Annotation, vec![r])); +} + +/// A drag with the tool never moves the layer it starts on, in Developer Mode or out of it. +#[test] +fn dragging_with_the_annotation_tool_moves_nothing() { + for dev_mode in [true, false] { + let mut s = Session::new(); + let f = frame(&mut s, 0.0, "Screen"); + rect(&mut s, f, 20.0); + s.tool.dev_mode = dev_mode; + ex(&mut s, "select.set", json!({"ids": []})); + ex(&mut s, "tool.annotation", json!({})); + let (doc_before, undo_before) = (s.doc().unwrap().clone(), s.undo_labels(1000).len()); + drag(&mut s, (40.0, 40.0), (140.0, 90.0)); + assert_eq!(*s.doc().unwrap(), doc_before, "dev_mode {dev_mode}"); + assert_eq!(s.undo_labels(1000).len(), undo_before, "dev_mode {dev_mode}"); + } +} + #[test] fn dev_mode_runs_its_own_edits_and_refuses_design_edits_from_menus_and_shortcuts() { for id in [ @@ -121,6 +217,7 @@ fn dev_mode_runs_its_own_edits_and_refuses_design_edits_from_menus_and_shortcuts "tool.move", "tool.hand", "tool.comment", + "tool.annotation", "inspect.code", ] { assert!(dev_mode_allows(id), "{id} runs in Dev Mode"); diff --git a/crates/engine/src/export_behaviour_tests.rs b/crates/engine/src/export_behaviour_tests.rs index 492fbf881..913c9feaf 100644 --- a/crates/engine/src/export_behaviour_tests.rs +++ b/crates/engine/src/export_behaviour_tests.rs @@ -385,6 +385,167 @@ fn copy_as_png_svg_and_code() { assert!(css.contains("background: #FF0000;"), "Copy as CSS is the layer's CSS from Inspect"); } +/// A red square with a fill-less pane over its right part, holding `effect` (#2213). +fn pane_scene(effect: EffectKind) -> (figcraft_doc::Document, NodeId, NodeId) { + use figcraft_doc::{Document, NodeKind}; + let mut d = Document::new("blur-export"); + let page = d.first_page().unwrap(); + let under = d.create(page, NodeKind::Rectangle, "Under", 0.0, 0.0, 120.0, 120.0).unwrap(); + d.get_mut(under).unwrap().fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::from_hex("E03030").unwrap())]; + let pane = d.create(page, NodeKind::Rectangle, "Glass", 60.0, 20.0, 120.0, 80.0).unwrap(); + d.get_mut(pane).unwrap().fills = vec![]; + d.get_mut(pane).unwrap().effects = vec![Effect { kind: effect, visible: true }]; + (d, under, pane) +} + +/// The PNG export of `ids` as the Export command makes it, and what the canvas draws there. +fn export_vs_canvas(d: &figcraft_doc::Document, ids: &[NodeId]) -> (image::RgbaImage, image::RgbaImage) { + let setting = figcraft_doc::ExportSetting::default(); + let page = d.first_page().unwrap(); + let area = crate::cmd::file::export_area(d, ids, &setting).unwrap(); + let canvas = figcraft_render::render_area(d, &d.get(page).unwrap().children.clone(), area, 1.0).unwrap(); + let canvas = image::RgbaImage::from_raw(canvas.width(), canvas.height(), figcraft_render::to_rgba8(&canvas)).unwrap(); + let (bytes, _) = crate::cmd::file::export_file(d, ids, &setting, 1.0).unwrap(); + (pixels(&bytes), canvas) +} + +/// #2213: a layer with a background blur exported on its own shows the same pixels as the canvas +/// shows for that area: the blur reads what lies under it, so the export must draw the layers +/// beneath it as the backdrop (clipped to the layer) rather than blurring nothing. +#[test] +fn exporting_a_background_blur_layer_keeps_the_blurred_backdrop() { + let (d, _, pane) = pane_scene(EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(12.0))); + let (exported, canvas) = export_vs_canvas(&d, &[pane]); + // The pane's left half sits over the red square, which ends at x = 120 (60 px into the pane). + assert_ne!(canvas.get_pixel(60, 40).0, [0, 0, 0, 0], "the canvas draws the blurred backdrop"); + assert_eq!(exported.get_pixel(60, 40), canvas.get_pixel(60, 40), "export lost the backdrop the blur reads"); + assert_eq!(exported.dimensions(), (120, 80), "the pane's own bounds"); +} + +/// #2213, as reported and as measured in Figma (2026-11-10): the pane inside a frame, exported on +/// its own, keeps the frame's fill and the blurred layer beneath it, opaque. +#[test] +fn a_blurred_pane_inside_a_frame_keeps_the_frame_and_the_layer_beneath() { + use figcraft_doc::{Document, NodeKind}; + let mut d = Document::new("blur-export-frame"); + let page = d.first_page().unwrap(); + let art = d.create(page, NodeKind::Frame, "Art", 0.0, 0.0, 300.0, 200.0).unwrap(); + d.get_mut(art).unwrap().fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::from_hex("FFFFFF").unwrap())]; + let under = d.create(art, NodeKind::Rectangle, "Under", 0.0, 0.0, 120.0, 120.0).unwrap(); + d.get_mut(under).unwrap().fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::from_hex("E03030").unwrap())]; + let pane = d.create(art, NodeKind::Rectangle, "Glass", 60.0, 20.0, 120.0, 80.0).unwrap(); + d.get_mut(pane).unwrap().fills = vec![]; + d.get_mut(pane).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(12.0)), visible: true }]; + let (exported, canvas) = export_vs_canvas(&d, &[pane]); + assert_eq!(exported.get_pixel(60, 40), canvas.get_pixel(60, 40), "the blurred square under the pane"); + assert_eq!(exported.get_pixel(100, 40).0[3], 255, "the frame's white behind the pane, opaque"); +} + +/// #2213: the same for Glass. +#[test] +fn exporting_a_glass_layer_keeps_the_backdrop_it_bends() { + let (d, _, pane) = pane_scene(EffectKind::Glass(figcraft_doc::Glass::default())); + let (exported, canvas) = export_vs_canvas(&d, &[pane]); + assert_ne!(canvas.get_pixel(30, 40).0, [0, 0, 0, 0]); + assert_eq!(exported.get_pixel(30, 40), canvas.get_pixel(30, 40), "export lost the backdrop the glass reads"); + assert_eq!(exported.get_pixel(60, 40), canvas.get_pixel(60, 40)); +} + +/// Measured in Figma 2026-11-10: inside the pane's bounds the export is opaque where the backdrop +/// is (the blurred red), and the layers over the pane stay out. +#[test] +fn a_blur_export_is_opaque_inside_the_pane_and_leaves_layers_above_out() { + let (mut d, _, pane) = pane_scene(EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(12.0))); + let page = d.first_page().unwrap(); + let above = d.create(page, figcraft_doc::NodeKind::Rectangle, "Above", 0.0, 0.0, 200.0, 200.0).unwrap(); + d.get_mut(above).unwrap().fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::from_hex("0000FF").unwrap())]; + let (exported, _) = export_vs_canvas(&d, &[pane]); + let left = exported.get_pixel(10, 40).0; + assert_eq!(left[3], 255, "red under the pane: opaque"); + assert!(left[0] > 150 && left[2] < 60, "red, not the blue layer above: {left:?}"); + // The far right of the pane has no square under it: nothing to read, nothing drawn. + assert_eq!(exported.get_pixel(110, 40).0[3], 0); +} + +/// Guard: a layer without backdrop effects over another still exports alone ("contents only"). +#[test] +fn a_layer_without_backdrop_effects_still_leaves_the_layers_below_out() { + let (mut d, _, pane) = pane_scene(EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(0.0))); + d.get_mut(pane).unwrap().effects.clear(); + let (exported, _) = export_vs_canvas(&d, &[pane]); + assert!(exported.pixels().all(|p| p.0 == [0, 0, 0, 0]), "a fill-less pane alone exports clear"); +} + +#[test] +fn node_set_takes_back_the_export_settings_node_get_returns() { + use figcraft_doc::{ExportColorProfile, ExportFormat, ExportSetting, PrintSettings, VdCompat}; + + // Every multi-word field (and `quality`) away from its default. + let expected = ExportSetting { + format: ExportFormat::Jpg, + suffix: "@3x".into(), + print: PrintSettings { bleed: 9.0, crop_marks: true, bleed_marks: true, cmyk: true }, + contents_only: false, + include_bounding_box: true, + svg_outline_text: false, + svg_id_attribute: true, + svg_simplify_stroke: false, + vd_compat: VdCompat::Exact, + color_profile: ExportColorProfile::DisplayP3, + quality: 55, + ..Default::default() + }; + let default = ExportSetting::default(); + for (field, differs) in [ + ("print", expected.print != default.print), + ("contents_only", expected.contents_only != default.contents_only), + ("include_bounding_box", expected.include_bounding_box != default.include_bounding_box), + ("svg_outline_text", expected.svg_outline_text != default.svg_outline_text), + ("svg_id_attribute", expected.svg_id_attribute != default.svg_id_attribute), + ("svg_simplify_stroke", expected.svg_simplify_stroke != default.svg_simplify_stroke), + ("vd_compat", expected.vd_compat != default.vd_compat), + ("color_profile", expected.color_profile != default.color_profile), + ("quality", expected.quality != default.quality), + ] { + assert!(differs, "{field} must be non-default in the expected setting"); + } + + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0, 40.0, 20.0, "#FF0000", None); + let stored = |s: &Session| s.doc().unwrap().node(a).unwrap().exports.clone(); + ex( + &mut s, + "export.add", + json!({"ids": [a], "setting": { + "format": "jpg", "suffix": "@3x", "bleed": 9, "cropMarks": true, "bleedMarks": true, "cmyk": true, + "contentsOnly": false, "includeBoundingBox": true, "svgOutlineText": false, "svgIdAttribute": true, + "svgSimplifyStroke": false, "vdCompat": "exact", "colorProfile": "displayP3", "quality": 55, + }}), + ); + assert_eq!(stored(&s), vec![expected.clone()], "export.add stores every field"); + + // What node.get returns goes back through node.set unchanged. + let got = ex(&mut s, "node.get", json!({"id": a}))["exports"].clone(); + set(&mut s, &[a], json!({"exports": []})); + assert!(stored(&s).is_empty()); + set(&mut s, &[a], json!({"exports": got})); + assert_eq!(stored(&s), vec![expected.clone()], "node.set stores what node.get returned, unchanged"); + + // The snake_case spelling is taken too. + set(&mut s, &[a], json!({"exports": []})); + set( + &mut s, + &[a], + json!({"exports": [{ + "format": "jpg", "suffix": "@3x", + "print": {"bleed": 9, "crop_marks": true, "bleed_marks": true, "cmyk": true}, + "contents_only": false, "include_bounding_box": true, "svg_outline_text": false, "svg_id_attribute": true, + "svg_simplify_stroke": false, "vd_compat": "exact", "color_profile": "displayP3", "quality": 55, + }]}), + ); + assert_eq!(stored(&s), vec![expected], "node.set takes the snake_case keys"); +} + #[test] fn export_rejects_an_invalid_layer_id_instead_of_exporting_the_page() { let mut s = Session::new(); diff --git a/crates/engine/src/eyedropper_image_tests.rs b/crates/engine/src/eyedropper_image_tests.rs new file mode 100644 index 000000000..b5e55cd23 --- /dev/null +++ b/crates/engine/src/eyedropper_image_tests.rs @@ -0,0 +1,42 @@ +//! #2189: the eyedropper picks the colour the canvas shows under the pointer. A magnified image +//! draws its pixels on the canvas (`magnified_image_pixels`), so the picked colour is that pixel's, +//! not a blend with its neighbours. + +use base64::Engine as _; +use serde_json::json; + +use crate::Session; +use crate::tools::{PointerEvent, PointerKind}; + +/// A 9 x 9 image of `back` with a 1 px vertical line of `line` in column 4 (a thin border in a +/// screenshot, as in the report). +fn line_png(back: [u8; 3], line: [u8; 3]) -> Vec { + let mut p = figcraft_render::Pixmap::new(9, 9).unwrap(); + for (i, px) in p.data_mut().chunks_exact_mut(4).enumerate() { + let c = if i % 9 == 4 { line } else { back }; + px.copy_from_slice(&[c[0], c[1], c[2], 255]); + } + figcraft_render::encode_png(&p).unwrap() +} + +/// The colour the eyedropper picks at page point (x, y) at `zoom`. +fn picked(png: &[u8], x: f64, y: f64, zoom: f64) -> String { + let mut s = Session::new(); + let data = base64::engine::general_purpose::STANDARD.encode(png); + s.execute("image.place", &json!({"data": data, "x": 0, "y": 0})).unwrap(); + s.execute("edit.pickColor", &json!({"apply": false})).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Down, x, y, zoom)).unwrap(); + s.tool.picked.map(|c| c.to_hex()).unwrap_or_default() +} + +#[test] +fn the_eyedropper_picks_a_magnified_images_pixel_not_a_blend_with_its_neighbours() { + // The reporter's colours: a #3D444D border, 1 px wide, beside a darker background. + let png = line_png([0x15, 0x1B, 0x23], [0x3D, 0x44, 0x4D]); + for zoom in [2.0, 8.0, 20.0] { + assert_eq!(picked(&png, 4.5, 4.5, zoom), "3D444D", "on the line at {zoom}x"); + assert_eq!(picked(&png, 2.5, 4.5, zoom), "151B23", "beside it at {zoom}x"); + } + // At 1:1 the canvas pixel is the image's pixel too. + assert_eq!(picked(&png, 4.5, 4.5, 1.0), "3D444D", "on the line at 1x"); +} diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index e45ced8d4..11e7e316a 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -192,6 +192,7 @@ pub static KEYS: &[Binding] = &[ k(Tools, "tool.pencil", &["Shift+P"]), k(Tools, "tool.text", &["T"]), k(Tools, "tool.comment", &["C"]), + k(Tools, "tool.annotation", &["Shift+T"]), k(Tools, "tool.shapeBuilder", &["Shift+M"]), // Board tools (on boards only), on keys nothing else uses. k(Tools, "tool.sticky", &["Q"]), diff --git a/crates/engine/src/keymap_tests.rs b/crates/engine/src/keymap_tests.rs index 67c5bf258..59206c5ff 100644 --- a/crates/engine/src/keymap_tests.rs +++ b/crates/engine/src/keymap_tests.rs @@ -206,6 +206,8 @@ fn tool_keys_come_from_the_keymap() { assert_eq!(ToolId::Eyedropper.shortcut(), "I"); assert_eq!(ToolId::Polygon.shortcut(), ""); assert_eq!(crate::catalog::shortcut("tool.text"), Some("T")); + assert_eq!(ToolId::Annotation.shortcut(), "Shift+T"); + assert_eq!(crate::catalog::shortcut("tool.annotation"), Some("Shift+T")); } #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2627d7efd..39ead2e82 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -227,6 +227,8 @@ mod board_tools_tests; #[cfg(test)] mod boolean_cap_tests; #[cfg(test)] +mod boolean_radius_tests; +#[cfg(test)] mod booleans_tests; #[cfg(test)] mod bound_alpha_tests; @@ -325,6 +327,8 @@ mod extended_chain_tests; #[cfg(test)] mod eyedropper_create_tests; #[cfg(test)] +mod eyedropper_image_tests; +#[cfg(test)] mod facilitate_tests; #[cfg(test)] mod fig_export_assets_tests; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 48d68a901..4225963f5 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -36,6 +36,9 @@ pub struct Prefs { /// A mouse wheel zooms the canvas about the pointer, and Cmd/Ctrl+wheel scrolls it (off: the /// other way round). Trackpads are unchanged. pub scroll_wheel_zoom: bool, + /// Wheel zoom goes the other way: Cmd/Ctrl+wheel (and a plain mouse wheel with Scroll wheel + /// zoom on) zooms out where it would zoom in. A trackpad pinch is unchanged. + pub invert_zoom: bool, /// "system" by default; an explicit "light" or "dark" choice stays saved. pub theme: String, /// The widths of the main window's left and right panels (the interface keeps them within its @@ -136,6 +139,7 @@ impl Default for Prefs { number_keys_opacity: true, show_dimensions: true, scroll_wheel_zoom: false, + invert_zoom: false, theme: "system".into(), panel_widths: (240.0, 240.0), pages_height: None, diff --git a/crates/engine/src/rotation_origin_tests.rs b/crates/engine/src/rotation_origin_tests.rs index 38878a0f0..181559a05 100644 --- a/crates/engine/src/rotation_origin_tests.rs +++ b/crates/engine/src/rotation_origin_tests.rs @@ -90,6 +90,17 @@ fn rotation_field_and_rotate_commands_turn_about_a_moved_origin() { assert!(s.execute("transform.setRotationOrigin", &json!({"x": 1})).is_err(), "x without y"); } +#[test] +fn the_absolute_rotation_key_turns_about_a_moved_origin_too() { + let mut s = Session::new(); + let r = rect(&mut s); + s.execute("transform.setRotationOrigin", &json!({"x": 100, "y": 100})).unwrap(); + s.execute("node.set", &json!({"ids": [r], "props": {"absoluteRotation": 30}})).unwrap(); + let doc = s.doc().unwrap(); + assert!(near(doc.world_transform(r) * Point::new(100.0, 100.0), Point::new(100.0, 100.0))); + assert!((figcraft_geom::rotation_degrees(doc.world_transform(r)) - 30.0).abs() < 1e-6); +} + #[test] fn origin_lasts_as_long_as_its_selection() { let mut s = Session::new(); diff --git a/crates/engine/src/shapes_behaviour_tests.rs b/crates/engine/src/shapes_behaviour_tests.rs index ca2d16390..39cf2c29b 100644 --- a/crates/engine/src/shapes_behaviour_tests.rs +++ b/crates/engine/src/shapes_behaviour_tests.rs @@ -189,6 +189,7 @@ fn corner_radius_follows_the_documented_rules() { (NodeKind::Polygon { count: 5 }, true, false, "polygons: one radius for every corner"), (NodeKind::Star { count: 5, inner_ratio: 0.4 }, true, false, "stars: one radius for every corner"), (NodeKind::Vector { network: Default::default() }, true, false, "vectors: a radius, and one per point in edit mode"), + (NodeKind::BooleanOp { op: BoolOp::Union }, true, false, "boolean groups: one radius for every sharp corner of the result"), (NodeKind::Line, false, false, "lines and arrows take no radius"), ]; for (kind, radius, independent, why) in doc_rows { @@ -241,6 +242,7 @@ fn corner_smoothing_follows_the_documented_rules() { "vector networks that are closed shapes", ), (NodeKind::Vector { network: Default::default() }, false, "an open vector has no closed shape to smooth"), + (NodeKind::BooleanOp { op: BoolOp::Union }, true, "boolean groups (the plugin API's corner mixin; the look is pinned)"), (NodeKind::Line, false, "lines take no radius, so no smoothing"), ]; for (kind, smoothing, why) in doc_rows { diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index ae73b022d..e15a164b8 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -110,6 +110,7 @@ static ROWS: &[Row] = &[ doc(Tools, "Pencil tool", &["Shift+P"], &[], Bound("tool.pencil"), ""), doc(Tools, "Text tool", &["T"], &[], Bound("tool.text"), ""), doc(Tools, "Comment mode", &["C"], &[], Bound("tool.comment"), ""), + doc(Tools, "Annotation tool", &["Shift+T"], &[], Bound("tool.annotation"), "Accessibility at Figma, Add an annotation; Developer Mode"), doc(Tools, "Hand tool while held", &["Space"], &[], Gesture("Pan the canvas"), "held, not pressed"), doc(Tools, "Pan with the arrows when nothing is selected (Shift: farther)", &["ArrowRight"], &[], Gesture("Pan with nothing selected (Shift: farther)"), "view.pan; nudges move the selection when there is one"), @@ -416,7 +417,7 @@ fn counts_match_the_docs() { let reserved = documented.iter().filter(|r| !r.reserved.is_empty()).count(); let pinned = ROWS.len() - documented.len(); // docs/ui-parity.md quotes these. - assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (136, 135, 1, 0, 2, 57)); + assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (137, 136, 1, 0, 2, 57)); } #[test] diff --git a/crates/engine/src/slot_tests.rs b/crates/engine/src/slot_tests.rs index adb96d541..4fbe5066a 100644 --- a/crates/engine/src/slot_tests.rs +++ b/crates/engine/src/slot_tests.rs @@ -417,12 +417,16 @@ fn assert_slot_text(s: &mut Session, instance: NodeId, expected: &str) { assert!(html.contains(&format!(">{expected}

")), "slot Label HTML: {html}"); } -fn assert_local_slot_text(s: &mut Session, instance: NodeId, expected: &str) { +fn assert_stored_slot_text(s: &Session, instance: NodeId, expected: &str) { assert!( matches!(&node(s, instance).kind, NodeKind::Instance { props, .. } if props.get("Text") == Some(&json!(expected))), "instance {instance} must store its own Text value {expected:?}: {:?}", node(s, instance).kind ); +} + +fn assert_local_slot_text(s: &mut Session, instance: NodeId, expected: &str) { + assert_stored_slot_text(s, instance, expected); let properties = props_of(s, instance); let text = properties.iter().find(|p| p["name"] == "Text").unwrap_or_else(|| panic!("instance {instance} has no Text property: {properties:?}")); assert_eq!(text["value"], expected, "instance {instance} Text property"); @@ -475,14 +479,15 @@ fn slot_text_properties_do_not_read_an_unbound_base_property() { ex(&mut s, "component.addProperty", json!({"id": base, "name": "Text", "type": "text", "default": "Wrong owner"})); let i = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 400}))); let nested_base = kids(&s, i)[0]; - assert_local_slot_text(&mut s, nested_base, "Wrong owner"); + // Bound to no layer, the base's Text isn't listed on its instance (#2269); its value stays stored. + assert_stored_slot_text(&s, nested_base, "Wrong owner"); let nested = copy_of(&s, i, main_content); assert_local_slot_text(&mut s, nested, "Default"); assert_slot_text(&mut s, nested, "Default"); ex(&mut s, "instance.setProperties", json!({"ids": [nested], "properties": {"Text": "Custom"}})); assert_local_slot_text(&mut s, nested, "Custom"); assert_slot_text(&mut s, nested, "Custom"); - assert_local_slot_text(&mut s, nested_base, "Wrong owner"); + assert_stored_slot_text(&s, nested_base, "Wrong owner"); assert_slot_text(&mut s, main_content, "Default"); healthy(&s); } diff --git a/crates/engine/src/style_vars_tests.rs b/crates/engine/src/style_vars_tests.rs index 66768daa7..536b27f6b 100644 --- a/crates/engine/src/style_vars_tests.rs +++ b/crates/engine/src/style_vars_tests.rs @@ -160,6 +160,7 @@ fn what_a_style_cannot_bind_is_refused() { ("fills/3/color", "bg", "no field"), ("effects/0/radius", "blur", "no field"), ("fontSize", "size", "no field"), + ("fontWeight", "bg", "no field"), ("opacity", "size", "no field"), ("fill", "nope", "no such variable"), ] { @@ -209,6 +210,7 @@ fn style_fields_offer_their_properties_scopes() { (&body, "letterSpacing", Some(&["LETTER_SPACING"][..])), (&body, "fontFamily", Some(&["FONT_FAMILY"][..])), (&body, "fontStyle", Some(&["FONT_STYLE"][..])), + (&body, "fontWeight", Some(&["FONT_WEIGHT"][..])), // Grid fields take any number variable, as on layers; fields a style lacks take none. (&grid, "layoutGrids/0/size", None), (&sid, "fills/3/color", None), @@ -244,3 +246,118 @@ fn rest_and_fig_carry_style_bindings() { assert!(got.bound.is_empty() && got.styles.fill.as_deref() == Some(st.id.as_str()), "{got:?}"); } } + +/// A text style "Body" (made from a layer, or from `value`) used by a layer in the Light frame +/// and one in the Dark one; returns (light layer, dark layer, style id). +fn body_style(s: &mut Session, value: Option) -> (NodeId, NodeId, String) { + let (_, dark, a, _, _) = two_modes(s); + let light = node(s, a).parent.unwrap(); + let text = |s: &mut Session, f: NodeId| id(run(s, "text.create", json!({"text": "Hello", "x": 0, "y": 60, "parent": f}))); + let (t1, t2) = (text(s, light), text(s, dark)); + let from = match &value { + Some(v) => json!({"type": "text", "name": "Body", "value": v}), + None => json!({"type": "text", "name": "Body", "from": t1}), + }; + let body = run(s, "style.create", from)["id"].as_str().unwrap().to_string(); + run(s, "style.apply", json!({"ids": [t1, t2], "style": body})); + (t1, t2, body) +} + +fn text_of(s: &Session, n: NodeId) -> figcraft_doc::TextStyle { + node(s, n).kind.text().unwrap().style.clone() +} + +#[test] +fn a_number_weight_picks_the_face_and_the_wght_axis() { + let mut s = Session::new(); + let (t1, t2, body) = body_style(&mut s, None); + run(&mut s, "variable.create", json!({"collection": "Theme", "name": "weight", "type": "number", "values": {"Light": 700, "Dark": 400}})); + run(&mut s, "style.bind", json!({"style": body, "field": "fontWeight", "variable": "weight"})); + let face = |s: &Session, n: NodeId| { + let t = text_of(s, n); + (t.font_style, t.variations.get("wght").copied()) + }; + assert_eq!(face(&s, t1), ("Bold".to_string(), Some(700.0))); + assert_eq!(face(&s, t2), ("Regular".to_string(), Some(400.0))); + run(&mut s, "variable.set", json!({"variable": "weight", "mode": "Dark", "value": 650})); + assert_eq!(face(&s, t2), ("Bold".to_string(), Some(650.0))); + let e = s.execute("style.bind", &json!({"style": body, "field": "fontWeight", "variable": "bg"})).unwrap_err().to_string(); + assert!(e.contains("takes a number variable"), "{e}"); + // A style name bound afterwards replaces the number binding. + run(&mut s, "variable.createCollection", json!({"name": "Names", "modes": ["Only"]})); + run(&mut s, "variable.create", json!({"collection": "Names", "name": "face", "type": "string", "values": {"Only": "Light"}})); + run(&mut s, "style.bind", json!({"style": body, "field": "fontStyle", "variable": "face"})); + let bound = s.doc().unwrap().style(&body).unwrap().bound.clone(); + assert!(bound.contains_key("fontStyle") && !bound.contains_key("fontWeight"), "{bound:?}"); + // The name replaces the number's weight: no stale `wght` axis keeps drawing 700. + assert_eq!(face(&s, t1), ("Light".to_string(), None)); + assert_eq!(text_of(&s, t1).weight(), 300); +} + +#[test] +fn junk_weight_values_clamp_to_the_lightest_and_heaviest_face() { + let mut s = Session::new(); + let (t1, _, body) = body_style(&mut s, None); + run(&mut s, "variable.create", json!({"collection": "Theme", "name": "weight", "type": "number", "values": {"Light": -50, "Dark": 5000}})); + run(&mut s, "style.bind", json!({"style": body, "field": "fontWeight", "variable": "weight"})); + let face = |s: &Session| { + let t = text_of(s, t1); + (t.font_style, t.variations.get("wght").copied()) + }; + assert_eq!(face(&s), ("Thin".to_string(), Some(1.0))); + run(&mut s, "variable.set", json!({"variable": "weight", "mode": "Light", "value": 5000})); + assert_eq!(face(&s), ("Black".to_string(), Some(1000.0))); +} + +#[test] +fn font_weight_wins_over_font_style_when_a_file_carries_both() { + let mut s = Session::new(); + let (t1, _, body) = body_style(&mut s, None); + run(&mut s, "variable.create", json!({"collection": "Theme", "name": "weight", "type": "number", "values": {"Light": 700, "Dark": 400}})); + run(&mut s, "variable.createCollection", json!({"name": "Names", "modes": ["Only"]})); + run(&mut s, "variable.create", json!({"collection": "Names", "name": "face", "type": "string", "values": {"Only": "Light"}})); + let doc = s.doc_mut().unwrap(); + let (w, f) = (doc.variables.get("weight").unwrap().id.clone(), doc.variables.get("face").unwrap().id.clone()); + let st = doc.styles.iter_mut().find(|x| x.id == body).unwrap(); + st.bound.insert("fontStyle".into(), f); + st.bound.insert("fontWeight".into(), w); + crate::style_vars::after_load(doc); + assert_eq!(text_of(&s, t1).font_style, "Bold"); +} + +#[test] +fn a_number_bound_to_a_percent_line_height_applies_as_pixels() { + let mut s = Session::new(); + let (t1, _, body) = body_style(&mut s, Some(json!({"fontSize": 24, "lineHeight": "150%"}))); + run(&mut s, "variable.create", json!({"collection": "Theme", "name": "lh", "type": "number", "values": {"Light": 150, "Dark": 36}})); + run(&mut s, "style.bind", json!({"style": body, "field": "lineHeight", "variable": "lh"})); + let lh = |s: &Session| match &s.doc().unwrap().style(&body).unwrap().kind { + StyleKind::Text { style, .. } => style.line_height, + k => panic!("{k:?}"), + }; + assert_eq!(lh(&s), figcraft_doc::LineHeight::Pixels(150.0)); + assert_eq!(text_of(&s, t1).line_height, figcraft_doc::LineHeight::Pixels(150.0)); + assert_eq!(node(&s, t1).height, 150.0); + run(&mut s, "variable.set", json!({"variable": "lh", "mode": "Light", "value": 36})); + assert_eq!((lh(&s), node(&s, t1).height), (figcraft_doc::LineHeight::Pixels(36.0), 36.0)); +} + +#[test] +fn a_text_style_binding_round_trips_through_fig() { + let mut s = Session::new(); + let (_, _, body) = body_style(&mut s, None); + run(&mut s, "variable.create", json!({"collection": "Theme", "name": "weight", "type": "number", "values": {"Light": 700, "Dark": 400}})); + for (field, var) in [("fontSize", "size"), ("lineHeight", "size"), ("fontWeight", "weight")] { + run(&mut s, "style.bind", json!({"style": body, "field": field, "variable": var})); + } + let doc = s.doc().unwrap().clone(); + let (bytes, warnings) = figcraft_format::fig::export(&doc, None).unwrap(); + let (mut back, _) = figcraft_format::fig::import(&bytes, "x").unwrap(); + crate::style_vars::after_load(&mut back); + let st = back.styles.iter().find(|x| x.name == "Body").unwrap(); + assert!(st.bound.contains_key("fontSize") && st.bound.contains_key("lineHeight"), "{st:?}"); + // The format has no weight field yet: the settled name comes back, not the binding (the file has no `wght` axis field yet). + assert!(warnings.iter().any(|w| w.contains("no field for")), "{warnings:?}"); + let StyleKind::Text { style, .. } = &st.kind else { panic!("{st:?}") }; + assert_eq!(style.font_style, "Bold"); +} diff --git a/crates/engine/src/styles_behaviour_tests.rs b/crates/engine/src/styles_behaviour_tests.rs index 73fe1edef..6fd0ff829 100644 --- a/crates/engine/src/styles_behaviour_tests.rs +++ b/crates/engine/src/styles_behaviour_tests.rs @@ -418,6 +418,51 @@ fn text_styles_carry_paragraph_spacing_indent_lists_and_features() { assert!(s.execute("style.create", &json!({"type": "text", "name": "Bad", "value": {"paragraphSpacing": "wide"}})).is_err()); } +#[test] +fn text_styles_carry_the_wrap_style() { + // Explore text properties: a wrap style can be set on the text layer, a paragraph or a text + // style. A style made from a text takes its wrap style, applying it sets it, + // editing it on a styled text unlinks it. + use figcraft_doc::WrapStyle::{Auto, Balance, Pretty}; + let mut s = Session::new(); + let td = |s: &Session, n: NodeId| -> TextData { node(s, n).kind.text().unwrap().clone() }; + let t = text(&mut s, 0.0); + run(&mut s, "node.set", json!({"id": t, "props": {"characters": "One\nTwo", "wrapStyle": "balance"}})); + let st = sid(run(&mut s, "style.create", json!({"type": "text", "name": "Even", "from": t}))); + let listed = run(&mut s, "style.list", json!({"type": "text"})); + let even = listed.as_array().unwrap().iter().find(|x| x["id"] == json!(st)).unwrap(); + assert_eq!(even["paragraph"]["wrap_style"], json!("balance"), "{even}"); + // Applying it sets the layer's wrap style, with no paragraph overrides, and links the layer. + let t2 = text(&mut s, 300.0); + run(&mut s, "node.set", json!({"id": t2, "props": {"characters": "A\nB"}})); + run(&mut s, "style.apply", json!({"ids": [t2], "style": st})); + let d = td(&s, t2); + assert_eq!(d.wrap_style, Balance); + assert!(d.paragraphs.iter().all(|p| p.wrap.is_none()), "{:?}", d.paragraphs); + assert_eq!(node(&s, t2).styles.text.as_deref(), Some(st.as_str())); + // Redefining the style moves the layer and keeps the link. + run(&mut s, "style.update", json!({"style": st, "value": {"wrapStyle": "pretty"}})); + let d = td(&s, t2); + assert_eq!((d.para_wrap_style(0), d.para_wrap_style(1)), (Pretty, Pretty)); + assert_eq!(node(&s, t2).styles.text.as_deref(), Some(st.as_str()), "still linked after the update"); + // Editing the wrap style on the styled text unlinks it. + run(&mut s, "node.set", json!({"id": t2, "props": {"wrapStyle": "auto"}})); + assert_eq!(td(&s, t2).wrap_style, Auto); + assert_eq!(node(&s, t2).styles.text, None, "wrap style edited: unlinked"); + // On a range, the paragraphs touched take it as their own and the layer keeps its style. + let t3 = text(&mut s, 600.0); + run(&mut s, "node.set", json!({"id": t3, "props": {"characters": "A\nB"}})); + run(&mut s, "style.apply", json!({"ids": [t3], "style": st, "start": 0, "end": 1})); + let d = td(&s, t3); + assert_eq!((d.wrap_style, d.para_wrap_style(0), d.para_wrap_style(1)), (Auto, Pretty, Auto)); + // A definition given as a value takes the node.set spellings; junk is refused. + let st2 = sid(run(&mut s, "style.create", json!({"type": "text", "name": "Note", "value": {"wrapStyle": "balance"}}))); + let want = ParagraphStyle { wrap_style: Balance, ..Default::default() }; + assert!(matches!(&s.doc().unwrap().style(&st2).unwrap().kind, StyleKind::Text { paragraph, .. } if **paragraph == want)); + assert!(s.execute("style.create", &json!({"type": "text", "name": "Bad", "value": {"wrapStyle": "zigzag"}})).is_err()); + assert!(s.execute("style.create", &json!({"type": "text", "name": "Bad", "value": {"textWrap": 3}})).is_err()); +} + #[test] fn styles_are_organised_by_slash_names_order_and_duplicates() { // Documented: "/" in a name groups styles in folders; moving a style to another folder renames diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index f41ad28f3..74a013e90 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -495,6 +495,92 @@ fn balance_and_pretty_wrap_styles_break_lines_as_documented() { assert_eq!(lines(&s), [(0, 9), (9, 16), (16, 21)]); } +#[test] +fn wrap_style_per_paragraph_overrides_the_layers() { + // Explore text properties: a wrap style can be set on the text layer, a paragraph or a text + // style. A paragraph's own wrap style beats the layer's; setting the layer + // sets every paragraph again. + let font = test_mono_font(); + let mut s = Session::new(); + let t = text(&mut s, "aaa bbb ccc ddd eee\naaa bbb ccc ddd eee", json!({"fontFamily": font, "fontSize": 16, "lineHeight": 24})); + s.execute("node.set", &json!({"id": t, "props": {"textAutoResize": "height", "width": 136}})).unwrap(); + let lines = |s: &Session| -> Vec<(usize, usize)> { + let (l, _) = figcraft_text::layout_node(s.doc().unwrap().node(t).unwrap()).unwrap(); + l.lines.iter().map(|l| (l.char_start, l.char_end)).collect() + }; + let inspect = |s: &Session| crate::inspect::node_json(s.doc().unwrap(), t, 0); + let css = |s: &mut Session| s.execute("inspect.code", &json!({"id": t})).unwrap()["code"].as_str().unwrap().to_string(); + let paragraphs = |s: &Session| s.doc().unwrap().node(t).unwrap().kind.text().unwrap().paragraphs.clone(); + assert_eq!(lines(&s), [(0, 16), (16, 20), (20, 36), (36, 39)], "Auto: four words and one in each paragraph"); + // The second paragraph alone, by a range on node.set. + s.execute("node.set", &json!({"id": t, "props": {"wrapStyle": "balance", "start": 20, "end": 20}})).unwrap(); + assert_eq!(lines(&s), [(0, 16), (16, 20), (20, 32), (32, 39)]); + assert_eq!(inspect(&s)["lineWrapStyles"], json!(["auto", "balance"])); + assert!(inspect(&s).get("wrapStyle").is_none()); + assert!(!css(&mut s).contains("text-wrap"), "{}", css(&mut s)); + // While editing, the caret's paragraph (the Wrap style control). + s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap(); + s.execute("text.wrapStyle", &json!({"style": "pretty"})).unwrap(); + s.execute("text.edit.end", &json!({})).unwrap(); + assert_eq!(lines(&s), [(0, 12), (12, 20), (20, 32), (32, 39)]); + assert_eq!(inspect(&s)["lineWrapStyles"], json!(["pretty", "balance"])); + // Undo restores the paragraph's override. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(lines(&s), [(0, 16), (16, 20), (20, 32), (32, 39)]); + assert_eq!(inspect(&s)["lineWrapStyles"], json!(["auto", "balance"])); + // Enter inside the balanced paragraph carries the style to the new paragraph. + s.execute("text.edit.begin", &json!({"id": t, "caret": 22})).unwrap(); + s.execute("text.edit.insert", &json!({"text": "\n"})).unwrap(); + s.execute("text.edit.end", &json!({})).unwrap(); + assert_eq!(inspect(&s)["lineWrapStyles"], json!(["auto", "balance", "balance"])); + // The layer level sets every paragraph and folds the overrides away. + s.execute("node.set", &json!({"id": t, "props": {"wrapStyle": "balance"}})).unwrap(); + assert!(paragraphs(&s).iter().all(|p| p.wrap.is_none()), "{:?}", paragraphs(&s)); + assert_eq!(inspect(&s)["wrapStyle"], json!("balance")); + assert!(css(&mut s).contains("text-wrap: balance;"), "{}", css(&mut s)); + assert!(s.execute("node.set", &json!({"id": t, "props": {"wrapStyle": "zigzag", "start": 0, "end": 0}})).is_err()); +} + +#[test] +fn text_wrap_style_without_editing_sets_the_layer_and_folds_paragraph_overrides() { + let mut s = Session::new(); + let t = text(&mut s, "one\ntwo\nthree", json!({})); + let inspect = |s: &Session| crate::inspect::node_json(s.doc().unwrap(), t, 0); + let td = |s: &Session| s.doc().unwrap().node(t).unwrap().kind.text().unwrap().clone(); + s.execute("node.set", &json!({"id": t, "props": {"wrapStyle": "balance", "start": 5, "end": 5}})).unwrap(); + s.execute("node.set", &json!({"id": t, "props": {"wrapStyle": "pretty", "start": 9, "end": 9}})).unwrap(); + assert_eq!(inspect(&s)["lineWrapStyles"], json!(["auto", "balance", "pretty"])); + assert!(s.ds().unwrap().text_edit.is_none(), "no edit session"); + s.execute("text.wrapStyle", &json!({"ids": [t], "style": "balance"})).unwrap(); + let after = td(&s); + assert!(after.paragraphs.iter().all(|p| p.wrap.is_none()), "{:?}", after.paragraphs); + assert_eq!(after.wrap_style, figcraft_doc::WrapStyle::Balance); + assert!((0..3).all(|p| after.para_wrap_style(p) == figcraft_doc::WrapStyle::Balance)); + assert_eq!(inspect(&s)["wrapStyle"], json!("balance")); + assert!(inspect(&s).get("lineWrapStyles").is_none()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(inspect(&s)["lineWrapStyles"], json!(["auto", "balance", "pretty"]), "undo restores the overrides"); +} + +#[test] +fn inspect_reports_wrap_style_only_when_not_auto_and_counts_a_trailing_empty_paragraph() { + let mut s = Session::new(); + let t = text(&mut s, "one\ntwo\n", json!({})); + let inspect = |s: &Session| crate::inspect::node_json(s.doc().unwrap(), t, 0); + let quiet = |s: &Session| inspect(s).get("wrapStyle").is_none() && inspect(s).get("lineWrapStyles").is_none(); + assert!(quiet(&s), "uniform Auto says nothing"); + // An override on the empty last paragraph (a caret after the final newline) is listed with the others. + s.execute("node.set", &json!({"id": t, "props": {"wrapStyle": "balance", "start": 8, "end": 8}})).unwrap(); + assert_eq!(inspect(&s)["lineWrapStyles"], json!(["auto", "auto", "balance"])); + assert!(inspect(&s).get("wrapStyle").is_none()); + // Every paragraph the same non-Auto style: the one key; back to Auto: neither. + s.execute("node.set", &json!({"id": t, "props": {"wrapStyle": "balance"}})).unwrap(); + assert_eq!(inspect(&s)["wrapStyle"], json!("balance")); + assert!(inspect(&s).get("lineWrapStyles").is_none()); + s.execute("node.set", &json!({"id": t, "props": {"wrapStyle": "auto"}})).unwrap(); + assert!(quiet(&s)); +} + #[test] fn max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines() { // "Max lines is available only if truncate text is enabled, and: Text resizing is set to diff --git a/crates/engine/src/transform_behaviour_tests.rs b/crates/engine/src/transform_behaviour_tests.rs index e22eb0418..7b0354b2e 100644 --- a/crates/engine/src/transform_behaviour_tests.rs +++ b/crates/engine/src/transform_behaviour_tests.rs @@ -369,6 +369,73 @@ fn resizing_and_flipping_one_layer() { assert!(near(rotation(&s, t).abs(), 30.0), "Shift: the nearest 15° step: {}", rotation(&s, t)); } +/// A rotate-handle drag on a layer at `start` degrees, turning it by `turn` degrees in the Design +/// panel's convention (positive is counter-clockwise on screen); returns the rotation it ends at. +fn rotate_drag_from(start: f64, turn: f64, m: Mods) -> f64 { + let mut s = session(); + let r = rect(&mut s, 0.0, 200.0, 100.0, 100.0, None); + set(&mut s, &[r], json!({"rotation": start})); + ex(&mut s, "select.set", json!({"ids": [r]})); + // The handle sits just outside the top-left corner of the turned box; the pointer then circles + // the centre by `turn` (the page angle runs the other way round, y being down). + let world = s.doc().unwrap().world_transform(r); + let (c, corner) = (world * Point::new(50.0, 50.0), world * Point::ZERO); + let from = corner + (corner - c) * 0.15; + let a = (from - c).atan2() - turn.to_radians(); + let to = c + figcraft_geom::Vec2::from_angle(a) * 80.0; + drag(&mut s, from, to, m); + rotation(&s, r) +} + +#[test] +fn shift_rotating_lands_on_multiples_of_15_not_steps_from_the_start() { + // Measured in Figma: a layer at 7° (or -4.27°) Shift-rotated by its corner ends at 15°, so the + // steps are absolute multiples of 15°, not 15° steps from where the drag began. + let got = rotate_drag_from(7.0, 37.0, SHIFT); + assert!(near(got, 45.0), "7° turned by 37° is 44°, nearest multiple of 15 is 45°: {got}"); + // Without Shift the turn is free. + let got = rotate_drag_from(7.0, 37.0, NONE); + assert!(near(got, 44.0), "a free turn: {got}"); + // A small turn: 7° + 3° = 10°, nearest multiple of 15 is 15° (not 7° or 10°). + let got = rotate_drag_from(7.0, 3.0, SHIFT); + assert!(near(got, 15.0), "10° rounds to 15°: {got}"); + let got = rotate_drag_from(-4.27, 2.0, SHIFT); + assert!(near(got, 0.0), "-2.27° rounds to 0°: {got}"); +} + +/// Rotates a 120 × 80 layer inside a frame turned `frame_rot`, the layer at `start` on the page, +/// by `turn` from its corner, and returns its rotation on the page. +fn rotate_drag_in_frame(frame_rot: f64, start: f64, turn: f64, m: Mods) -> f64 { + let mut s = session(); + let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 100, "width": 400, "height": 400}))); + set(&mut s, &[f], json!({"rotation": frame_rot})); + let r = rect(&mut s, 100.0, 100.0, 120.0, 80.0, Some(f)); + set(&mut s, &[r], json!({"rotation": start - frame_rot})); + let page = |s: &Session| rotation_degrees(s.doc().unwrap().world_transform(r)); + assert!(near(page(&s), start), "the layer starts at {start}° on the page: {}", page(&s)); + ex(&mut s, "select.set", json!({"ids": [r]})); + let world = s.doc().unwrap().world_transform(r); + let (c, corner) = (world * Point::new(60.0, 40.0), world * Point::ZERO); + let from = corner + (corner - c) * 0.15; + let a = (from - c).atan2() - turn.to_radians(); + let to = c + figcraft_geom::Vec2::from_angle(a) * 80.0; + drag(&mut s, from, to, m); + page(&s) +} + +#[test] +fn shift_rotating_inside_a_rotated_frame_lands_the_page_rotation_on_multiples_of_15() { + // Measured in Figma (2026-11-10): the rotation field of a layer inside a frame turned 10° shows + // its rotation on the page, and Shift lands that on multiples of 15°: from 7°, turns of 40°, + // 6° and -10° end at 45°, 15° and 0°; without Shift 6° ends at 13°. Groups behave the same. + for (turn, want) in [(40.0, 45.0), (6.0, 15.0), (-10.0, 0.0)] { + let got = rotate_drag_in_frame(10.0, 7.0, turn, SHIFT); + assert!(near(got, want), "7° on the page turned by {turn}° with Shift: {got}, want {want}"); + } + let got = rotate_drag_in_frame(10.0, 7.0, 6.0, NONE); + assert!(near(got, 13.0), "a free turn: {got}"); +} + #[test] fn groups_scale_children_keeping_their_rotation_and_flip() { let mut s = session(); @@ -466,6 +533,61 @@ fn design_panel_edits_reach_every_selected_layer() { assert!(near(rotation(&s, a), 30.0) && flipped(&s, a), "{}", rotation(&s, a)); } +#[test] +fn absolute_rotation_sets_the_rotation_on_the_page_keeping_the_centre() { + let mut s = session(); + let page = |s: &Session, i: NodeId| rotation_degrees(s.doc().unwrap().world_transform(i)); + let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 100, "width": 400, "height": 400}))); + set(&mut s, &[f], json!({"rotation": 10})); + let r = rect(&mut s, 100.0, 100.0, 120.0, 80.0, Some(f)); + assert!(near(page(&s, r), 10.0) && near(rotation(&s, r), 0.0)); + let centre = s.doc().unwrap().world_transform(r) * Point::new(60.0, 40.0); + set(&mut s, &[r], json!({"absoluteRotation": 7})); + assert!(near(page(&s, r), 7.0), "{}", page(&s, r)); + assert!(near(rotation(&s, r), -3.0), "{}", rotation(&s, r)); + let c = s.doc().unwrap().world_transform(r) * Point::new(60.0, 40.0); + assert!((c - centre).hypot() < 1e-6, "the centre stays put"); + set(&mut s, &[r], json!({"absoluteRotation": 0})); + assert!(near(page(&s, r), 0.0) && near(rotation(&s, r), -10.0)); + // `node.get` still reports the local angle. + let got = ex(&mut s, "node.get", json!({"id": r})); + let rot = got["rotation"].as_f64().unwrap_or(f64::NAN); + assert!(near(rot, -10.0), "{got}"); + // Groups: a child reads and sets the page angle, its sibling keeps its own. + let a = rect(&mut s, 0.0, 600.0, 50.0, 50.0, None); + let b = rect(&mut s, 100.0, 600.0, 50.0, 50.0, None); + let g = id(&ex(&mut s, "object.group", json!({"ids": [a, b]}))); + set(&mut s, &[g], json!({"rotation": 10})); + assert!(near(page(&s, a), 10.0)); + set(&mut s, &[a], json!({"absoluteRotation": 7})); + assert!(near(page(&s, a), 7.0) && near(page(&s, b), 10.0)); + // Several layers: one value on the page for all, one undo step. + let top = rect(&mut s, 800.0, 0.0, 50.0, 50.0, None); + let steps = undo_steps(&s); + set(&mut s, &[r, top], json!({"absoluteRotation": 45})); + assert!(near(page(&s, r), 45.0) && near(page(&s, top), 45.0)); + assert_eq!(undo_steps(&s), steps + 1); + // A flip is kept. + ex(&mut s, "object.flipH", json!({"ids": [r]})); + set(&mut s, &[r], json!({"absoluteRotation": 30})); + assert!(near(page(&s, r), 30.0) && flipped(&s, r), "{}", page(&s, r)); + // One of the two keys per call. + assert!(s.execute("node.set", &json!({"ids": [r], "props": {"rotation": 1, "absoluteRotation": 2}})).is_err()); +} + +#[test] +fn absolute_rotation_on_a_frame_and_a_layer_inside_it_lands_both_on_the_page_angle() { + let mut s = session(); + let page = |s: &Session, i: NodeId| rotation_degrees(s.doc().unwrap().world_transform(i)); + let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 100, "width": 400, "height": 400}))); + set(&mut s, &[f], json!({"rotation": 10})); + let r = rect(&mut s, 100.0, 100.0, 120.0, 80.0, Some(f)); + // The layer inside comes first in the ids: the frame's turn must not carry it past 45. + set(&mut s, &[r, f], json!({"absoluteRotation": 45})); + assert!(near(page(&s, f), 45.0), "{}", page(&s, f)); + assert!(near(page(&s, r), 45.0), "{}", page(&s, r)); +} + #[test] fn constrain_proportions_keeps_the_other_side_in_ratio() { let mut s = session(); diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index eba692802..fc032d007 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -562,6 +562,19 @@ fn css_export_gives_lengths_a_unit_and_keeps_opacity_bare() { assert!(css.contains("--card: 12px;") && css.contains("--fade: 0.5;") && css.contains("--half: 0.5;"), "{css}"); } +#[test] +fn css_export_keeps_a_style_weight_bare() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Brand"})); + ex(&mut s, "variable.create", json!({"collection": "Brand", "name": "weight", "type": "number", "value": 700})); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hi", "x": 0, "y": 0}))); + let st = ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "from": t}))["id"].as_str().unwrap_or_default().to_string(); + ex(&mut s, "style.bind", json!({"style": st, "field": "fontWeight", "variable": "weight"})); + let css = ex(&mut s, "variable.export", json!({"format": "css"}))["text"].as_str().unwrap_or_default().to_string(); + // A weight bound only to a text style is still a bare number, not a length. + assert!(css.contains("--weight: 700;") && !css.contains("700px"), "{css}"); +} + #[test] fn review_a_long_alias_chain_keeps_its_role_to_the_end() { let mut s = Session::new(); diff --git a/crates/engine/src/vector_behaviour_tests.rs b/crates/engine/src/vector_behaviour_tests.rs index d1d6907ee..1a3eb4fe0 100644 --- a/crates/engine/src/vector_behaviour_tests.rs +++ b/crates/engine/src/vector_behaviour_tests.rs @@ -881,3 +881,68 @@ fn vector_points_take_the_requested_size() { let e = s.execute("vector.create", &json!({"points": points, "width": 16, "height": -1})).unwrap_err().to_string(); assert!(e.contains("positive"), "{e}"); } + +/// A vector from `points` with a corner radius per point (`radii`), via `vector.create`. +fn rounded_vector(s: &mut Session, points: &[(f64, f64)], radii: &[f64], closed: bool) -> NodeId { + let pts: Vec = points.iter().map(|p| json!([p.0, p.1])).collect(); + let id = id_of(&ex(s, "vector.create", json!({"points": pts, "closed": closed}))["id"]).unwrap(); + if let NodeKind::Vector { network } = &mut s.doc_mut().unwrap().get_mut(id).unwrap().kind { + for (v, r) in network.vertices.iter_mut().zip(radii) { + v.radius = *r; + } + } + id +} + +/// #2195: Flatten bakes a vector's point radii into its path: the rounded vertex becomes the +/// arc's end points joined by curves, the layer stays a vector, the box fits the real geometry. +#[test] +fn flatten_bakes_a_vectors_point_radius() { + // An open V with the apex rounded. + let mut s = Session::new(); + let v = rounded_vector(&mut s, &[(0.0, 0.0), (184.0, 245.0), (368.0, 0.0)], &[0.0, 60.0, 0.0], false); + let before = net(&s, v); + let drawn = before.rounded().unwrap().stroke_path().perimeter(1e-4); + let h_before = s.doc().unwrap().node(v).unwrap().height; + let out = ex(&mut s, "vector.flatten", json!({"ids": [v]})); + let f = id_of(&out["id"]).unwrap(); + let after = net(&s, f); + assert_eq!(after.vertices.len(), 4, "the apex became two points: 3 + 1"); + assert!(after.vertices.iter().all(|p| p.radius == 0.0), "no radius left"); + let len = after.stroke_path().perimeter(1e-4); + assert!((len - drawn).abs() < 0.5, "the outline is the same: {len} vs {drawn}"); + let h = s.doc().unwrap().node(f).unwrap().height; + let bb = after.bounds().unwrap(); + assert!(h < h_before && (h - 245.0).abs() > 1.0, "the box shrinks from 245: {h}"); + assert!((h - bb.height()).abs() < 1e-6 && bb.y0.abs() < 1e-6, "the box is the baked path's bounds: {h} vs {bb:?}"); + println!("open V: points {} -> {}, height {h_before} -> {h}", before.vertices.len(), after.vertices.len()); + s.undo().unwrap(); + assert!(s.doc().unwrap().node(v).is_some() && s.doc().unwrap().node(f).is_none(), "one undo step"); + assert_eq!(net(&s, v).vertices[1].radius, 60.0); + + // A closed triangle rounded at every point. + let mut s = Session::new(); + let v = rounded_vector(&mut s, &[(0.0, 0.0), (368.0, 0.0), (184.0, 245.0)], &[40.0; 3], true); + let drawn = net(&s, v).rounded().unwrap(); + let (len, area) = (drawn.stroke_path().perimeter(1e-4), drawn.fill_path().area().abs()); + let f = id_of(&ex(&mut s, "vector.flatten", json!({"ids": [v]}))["id"]).unwrap(); + let after = net(&s, f); + assert_eq!(after.vertices.len(), 6, "each corner became two points"); + assert!(after.vertices.iter().all(|p| p.radius == 0.0)); + assert_eq!(after.regions.len(), 1, "still one filled region"); + assert!((after.stroke_path().perimeter(1e-4) - len).abs() < 0.5); + assert!((after.fill_path().area().abs() - area).abs() < 0.5, "same fill area"); + let n = s.doc().unwrap().node(f).unwrap().clone(); + let bb = after.bounds().unwrap(); + assert!(n.height < 245.0 && (n.height - bb.height()).abs() < 1e-6 && (n.width - bb.width()).abs() < 1e-6); + println!("triangle: points 3 -> {}, height 245 -> {}", after.vertices.len(), n.height); + + // Guard: no radius, nothing changes. + let mut s = Session::new(); + let v = rounded_vector(&mut s, &[(0.0, 0.0), (184.0, 245.0), (368.0, 0.0)], &[0.0; 3], false); + let before = net(&s, v); + let f = id_of(&ex(&mut s, "vector.flatten", json!({"ids": [v]}))["id"]).unwrap(); + assert_eq!(net(&s, f).vertices.len(), 3); + assert_eq!(s.doc().unwrap().node(f).unwrap().height, 245.0); + assert_eq!(net(&s, f).vertices, before.vertices); +} diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index f7547c3d0..24268da3c 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -148,7 +148,7 @@ fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result let max_nodes = layer_budget(packed); drop(message); let file_name = archive.file_name.as_deref().filter(|n| !n.trim().is_empty()).unwrap_or(name); - let (mut json, mut warnings, networks) = map::to_rest(&msg, file_name, max_nodes); + let (mut json, mut warnings, networks) = map::to_rest_for(&msg, file_name, max_nodes, board); // The message goes before the layers are built, so the images it carries are copied out first. let embedded = embedded_copies(&msg); drop(msg); diff --git a/crates/format/src/fig/board_import_tests.rs b/crates/format/src/fig/board_import_tests.rs index dcf52c46c..89c6cba83 100644 --- a/crates/format/src/fig/board_import_tests.rs +++ b/crates/format/src/fig/board_import_tests.rs @@ -446,10 +446,106 @@ fn a_jam_file_imports_like_a_fig() { let (doc, warnings) = import(&bytes, "Synthetic board").unwrap(); assert_eq!(doc.kind, figcraft_doc::FileKind::Board, "a FigJam whiteboard opens as a board"); let note = named(&doc, "Board object"); - assert!(matches!(note.kind, NodeKind::Frame) && note.children.len() == 3, "the sticky with its background, note and author"); + assert!(matches!(note.kind, NodeKind::Frame) && note.children.len() == 2, "the sticky is native: its note and author"); + assert_eq!(note.board, Some(figcraft_doc::BoardItem::Sticky { author: "Test Author".into() })); assert!(matches!(named(&doc, "Synthetic table").kind, NodeKind::Frame)); assert!(doc.nodes().all(|n| n.name != "Unknown object"), "left out"); assert!(warnings.iter().any(|w| w.contains("table layers import as")), "{warnings:?}"); assert!(warnings.iter().any(|w| w.contains("SYNTHETIC_JAM_ONLY")), "a note says what was left out: {warnings:?}"); } } + +/// Import `layer` through the public importer as a FigJam whiteboard (`fig-jam.` header). +fn jam(layer: Kv<'static>) -> (Document, Vec) { + let mut bytes = canvas(&board_schema(), &message(layer)); + bytes.splice(..8, *b"fig-jam."); + import(&bytes, "Synthetic board").unwrap() +} + +/// On a whiteboard a sticky is a native sticky: its colour, size, text and author come along. +#[test] +fn a_jam_sticky_is_a_native_sticky_with_its_colour_text_and_author() { + let (doc, warnings) = jam(board_node("STICKY")); + assert_eq!(doc.kind, figcraft_doc::FileKind::Board); + let frame = named(&doc, "Board object"); + assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Sticky { author: "Test Author".into() })); + assert_eq!(frame.fills[0].solid_color().unwrap().to_rgba8(), [255, 191, 64, 255]); + assert_eq!((frame.width, frame.height), (240.0, 240.0)); + assert_eq!(frame.opacity, 0.5); + let layout = frame.layout.as_ref().expect("sticky auto layout"); + assert_eq!(layout.padding, [20.0; 4]); + assert_eq!(frame.child_layout.min_h, Some(240.0)); + assert_eq!(frame.children.len(), 2, "the note and its author, no background vector"); + let texts: Vec<_> = frame.children.iter().map(|id| doc.node(*id).unwrap()).collect(); + assert!(texts.iter().all(|n| n.kind.text().is_some())); + let note = texts[0].kind.text().unwrap(); + assert_eq!(note.characters, "Olá\nIdea"); + assert_eq!(note.style.font_size, 24.0); + assert!(note.runs.iter().any(|r| r.style.font_size == 18.0), "inline styles survive"); + let author = texts[1].kind.text().unwrap(); + assert_eq!(author.characters, "Test Author"); + assert_eq!(author.style.font_size, 12.0); + assert!(!warnings.iter().any(|w| w.contains("skipped")), "{warnings:?}"); +} + +/// A sticky whose author line is not saved has an empty author and just its note. +#[test] +fn a_jam_sticky_without_an_author_line_has_no_author() { + let mut layer = board_node("STICKY"); + let background = record(0, vec![("fillPaints", arr(vec![solid(1.0, 0.75, 0.25)]))]); + set(&mut layer, "nodeGenerationData", o(vec![("overrides", arr(vec![background, record(1, text("Olá\nIdea", 24.0))]))])); + let (doc, _) = jam(layer); + let frame = named(&doc, "Board object"); + assert_eq!(frame.children.len(), 1); + let Some(figcraft_doc::BoardItem::Sticky { author }) = &frame.board else { panic!("{:?}", frame.board) }; + assert!(author.is_empty()); +} + +/// A sticky record that isn't complete keeps today's generated layers and no board item. +#[test] +fn a_damaged_jam_sticky_keeps_the_generated_layers() { + let gradient = o(vec![("type", e("GRADIENT_LINEAR")), ("visible", Kv::Bool(true))]); + let cases: Vec> = { + let mut v = Vec::new(); + // Layout version 2. + let mut a = board_node("STICKY"); + set(&mut a, "derivedImmutableFrameData", o(vec![("version", u(2))])); + v.push(a); + // Background record missing. + let mut b = board_node("STICKY"); + set(&mut b, "nodeGenerationData", o(vec![("overrides", arr(vec![record(1, text("Olá", 24.0))]))])); + v.push(b); + // A stroke on the background. + let mut c = board_node("STICKY"); + let stroked = record(0, vec![("fillPaints", arr(vec![solid(1.0, 0.75, 0.25)])), ("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)]))]); + set(&mut c, "nodeGenerationData", o(vec![("overrides", arr(vec![stroked, record(1, text("Olá", 24.0))]))])); + v.push(c); + // A gradient on the background. + let mut d = board_node("STICKY"); + let graded = record(0, vec![("fillPaints", arr(vec![gradient]))]); + set(&mut d, "nodeGenerationData", o(vec![("overrides", arr(vec![graded, record(1, text("Olá", 24.0))]))])); + v.push(d); + // Blank note. + let mut f = board_node("STICKY"); + let background = record(0, vec![("fillPaints", arr(vec![solid(1.0, 0.75, 0.25)]))]); + set(&mut f, "nodeGenerationData", o(vec![("overrides", arr(vec![background, record(1, text(" ", 24.0))]))])); + v.push(f); + v + }; + for (i, layer) in cases.into_iter().enumerate() { + let (as_fig, _) = imported(layer.clone()); + let (doc, _) = jam(layer); + let frame = named(&doc, "Board object"); + assert!(frame.board.is_none(), "case {i}"); + assert_eq!(frame.children.len(), named(&as_fig, "Board object").children.len(), "case {i}: the generated layers, as in a .fig"); + } +} + +/// The same sticky in a `.fig` stays the design frame it always was. +#[test] +fn a_fig_sticky_stays_a_design_frame() { + let (doc, _) = imported(board_node("STICKY")); + let frame = named(&doc, "Board object"); + assert!(frame.board.is_none()); + assert_eq!(frame.children.len(), 3); +} diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 4fd533545..221cd7cd9 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -811,6 +811,21 @@ fn generated_documents_round_trip() { } } +#[test] +fn a_boolean_groups_corner_radius_round_trips() { + let mut doc = Document::new("t"); + let page = doc.first_page().unwrap(); + let g = doc.create(page, NodeKind::BooleanOp { op: BoolOp::Union }, "G", 0.0, 0.0, 0.0, 0.0).unwrap(); + doc.create(g, NodeKind::Rectangle, "A", 0.0, 0.0, 200.0, 100.0).unwrap(); + doc.create(g, NodeKind::Rectangle, "B", 150.0, 0.0, 100.0, 200.0).unwrap(); + doc.fit_to_children(g).unwrap(); + doc.get_mut(g).unwrap().corners = Corners { radii: [20.0; 4], smoothing: 0.6 }; + let (back, _) = round_trip(&doc, "boolean radius"); + let n = back.nodes().find(|n| matches!(n.kind, NodeKind::BooleanOp { .. })).unwrap(); + assert!(n.corners.radii.iter().all(|r| (r - 20.0).abs() < 1e-4), "{:?}", n.corners); + assert!((n.corners.smoothing - 0.6).abs() < 1e-4, "{:?}", n.corners); +} + #[test] fn round_trip_keeps_the_details() { let doc = generate(3); diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index aa0db5cf4..d150e5c63 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -17,6 +17,7 @@ use serde_json::{Map, Value, json}; use super::kiwi::Kv; use super::network; +mod board; mod component; mod connector; mod document; @@ -50,8 +51,16 @@ const MAX_ASSET_PART: usize = 256; /// The REST API file JSON for message `msg`, with the warnings about what was skipped and the /// vector networks its layers name by `vectorNetworkRef` (for [`crate::rest::import_with_networks`]). +#[cfg(test)] pub(super) fn to_rest(msg: &Kv, name: &str, max_nodes: usize) -> (Value, Vec, Vec>) { + to_rest_for(msg, name, max_nodes, false) +} + +/// The REST JSON (as `to_rest`) for a FigJam whiteboard (`board`) or a design file: a +/// whiteboard's stickies come out as native board items. +pub(super) fn to_rest_for(msg: &Kv, name: &str, max_nodes: usize, board: bool) -> (Value, Vec, Vec>) { let mut m = Mapper::new(msg, max_nodes); + m.board = board; let _canon = VarCanon::install(&m); let doc = m.document(); // Large values are moved in, never passed through `json!`, which serialises its arguments: @@ -362,6 +371,8 @@ struct Mapper<'a> { /// Region paint elements (paints and gradient stops) read so far: one budget for the whole /// file, since layers with region paints don't share their network. region_paint_elements: usize, + /// The file is a FigJam whiteboard: its objects are built as native board items. + board: bool, } impl<'a> Mapper<'a> { @@ -439,6 +450,7 @@ impl<'a> Mapper<'a> { max_nodes, reserved: 0, networks: Vec::new(), + board: false, network_ids: HashMap::new(), region_paint_elements: 0, } diff --git a/crates/format/src/fig/map/board.rs b/crates/format/src/fig/map/board.rs new file mode 100644 index 000000000..7dcf57cfe --- /dev/null +++ b/crates/format/src/fig/map/board.rs @@ -0,0 +1,88 @@ +//! FigJam whiteboard objects as native board items: what a `.jam` import builds in place of the +//! generated frames a `.fig` keeps. The REST JSON carries them as a `board` field +//! ([`crate::rest`] reads it). + +use super::layer::{own_text, valid_size}; +use super::paint::paint; +use super::{Affine, Kv, MAX_DEPTH, Mapper, Obj, Value, View, generated_record, json, num}; + +impl<'a> Mapper<'a> { + /// A sticky as a native board sticky: its frame (size, place, opacity and shadows as saved, + /// the saved colour) holding the note and, when saved, the author line. `None` (nothing + /// changed) unless every generated record is complete: then the caller keeps the generated + /// layers. + pub(super) fn native_sticky(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option> { + if v.get("nodeGenerationData").is_none() || v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) { + return None; + } + let record = |id: u32| { + let (style, bounds) = (generated_record(v, "nodeGenerationData", id)?, generated_record(v, "derivedImmutableFrameData", id)?); + let view = View::of(style).with([(bounds, 1.0)]); + (valid_size(view.get("size")).is_some() && view.transform().is_some()).then_some(view) + }; + let background = record(0)?; + let fills = background.list("fillPaints"); + let solid = matches!(fills, [p] if p.get("type").and_then(Kv::str) == Some("SOLID") && p.get("visible").and_then(Kv::bool) != Some(false)); + if !solid || !background.list("strokePaints").is_empty() { + return None; + } + let note = record(1).filter(|n| own_text(n).is_some())?; + let author = record(2).filter(|a| a.flag("visible") != Some(false) && own_text(a).is_some()); + let wanted = 1 + usize::from(author.is_some()); + if depth >= MAX_DEPTH || self.count.saturating_add(wanted) > self.budget() { + return None; + } + let (w, h) = v.size().or_else(|| o.get("size").and_then(|s| Some((s.get("x")?.as_f64()?, s.get("y")?.as_f64()?))))?; + let at = note.transform().unwrap_or_default().as_coeffs(); + let pad = |x: f64| if x.is_finite() { x.clamp(0.0, (w.min(h) / 2.0).max(0.0)) } else { 0.0 }; + let (pad_x, pad_y) = (pad(at[4]), pad(at[5])); + // Everything is valid: build. + let paints: Vec = fills.iter().filter_map(|p| paint(p, &mut |m| self.warn(m))).collect(); + o.insert("fills".into(), Value::Array(paints)); + o.insert("strokes".into(), json!([])); + o.insert("clipsContent".into(), json!(false)); + match background.len("cornerRadius") { + Some(r) => o.insert("cornerRadius".into(), json!(r)), + None => o.remove("cornerRadius"), + }; + for (k, val) in [ + ("layoutMode", json!("VERTICAL")), + ("primaryAxisAlignItems", json!("SPACE_BETWEEN")), + ("counterAxisAlignItems", json!("MIN")), + ("primaryAxisSizingMode", json!("AUTO")), + ("counterAxisSizingMode", json!("FIXED")), + ("minHeight", json!(h)), + ("itemSpacing", json!(8.0)), + ("paddingTop", json!(pad_y)), + ("paddingBottom", json!(pad_y)), + ("paddingLeft", json!(pad_x)), + ("paddingRight", json!(pad_x)), + ] { + o.insert(k.into(), val); + } + let mut kids = Vec::new(); + let mut written = String::new(); + for (local, view) in [(1, Some(note)), (2, author)] { + let Some(view) = view else { continue }; + let chars = own_text(&view).unwrap_or_default(); + let mut layer = Obj::new(); + layer.insert("id".into(), json!(format!("{rest_id};generated{local}"))); + layer.insert("type".into(), json!("TEXT")); + layer.insert("name".into(), json!(if local == 1 { chars.chars().take(40).collect::() } else { "Author".to_string() })); + self.common(&mut layer, &view, "TEXT", Affine::IDENTITY, None); + self.text(&mut layer, &view); + if let Some(Value::Object(style)) = layer.get_mut("style") { + style.insert("textAutoResize".into(), json!("HEIGHT")); + style.insert("textAlignHorizontal".into(), json!("LEFT")); + } + layer.insert("layoutSizingHorizontal".into(), json!("FILL")); + if local == 2 { + written = chars.trim().to_string(); + } + self.count += 1; + kids.push(Value::Object(layer)); + } + o.insert("board".into(), json!({"type": "sticky", "author": written})); + Some(kids) + } +} diff --git a/crates/format/src/fig/map/layer.rs b/crates/format/src/fig/map/layer.rs index a69bb7d46..869686537 100644 --- a/crates/format/src/fig/map/layer.rs +++ b/crates/format/src/fig/map/layer.rs @@ -174,7 +174,9 @@ impl<'a> Mapper<'a> { // A label without a snapshot: the connector becomes a frame holding its line and its label. let connector_label = own == "CONNECTOR" && !connector_snapshot && self.connector_label_fits(&view, depth); let ty = if connector_label { "FRAME" } else { Self::mapped_type(own, &view, connector_snapshot, connector_terminal, stand)? }; - if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH") { + // A whiteboard's sticky says it imports as a frame only when it can't be a native one. + let native_sticky = self.board && own == "STICKY"; + if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH" && !native_sticky) { self.warn(format!("{} layers import as {what}", own.to_ascii_lowercase().replace('_', " "))); } if connector_snapshot { @@ -262,12 +264,18 @@ impl<'a> Mapper<'a> { }); kids.splice(0..0, connector_kids); if stand.is_some_and(|s| s.0 == "FRAME") { - if let Some(snapshot) = self.board_snapshot(&mut o, &view, own, &rest_id, depth) { + let native = if native_sticky { self.native_sticky(&mut o, &view, &rest_id, depth) } else { None }; + if let Some(native) = native { + kids.splice(0..0, native); + } else if let Some(snapshot) = self.board_snapshot(&mut o, &view, own, &rest_id, depth) { kids.splice(0..0, snapshot); } else { kids.splice(0..0, self.shape_with_text(&mut o, &view, own, &rest_id)); kids.extend(self.inner_text(&o, &view, &rest_id, own == "STICKY")); } + if native_sticky && !o.contains_key("board") { + self.warn("sticky layers import as frames with their text"); + } } if !kids.is_empty() { o.insert("children".into(), Value::Array(kids)); diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index a8abf56fe..e024920a7 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -1583,7 +1583,8 @@ fn dump_samples() { std::fs::write(format!("{out}/{stem}.schema.txt"), txt).unwrap(); let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); std::fs::write(format!("{out}/{stem}.json"), serde_json::to_string_pretty(&debug_json(&msg)).unwrap()).unwrap(); - let (rest, ..) = map::to_rest(&msg, &stem, super::layer_budget(message.len())); + // A whiteboard's dump shows its native board items as the import makes them. + let (rest, ..) = map::to_rest_for(&msg, &stem, super::layer_budget(message.len()), a.canvas.starts_with(super::JAM_HEADER)); std::fs::write(format!("{out}/{stem}.rest.json"), serde_json::to_string_pretty(&rest).unwrap()).unwrap(); } } diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 99acbab2f..8797d9efa 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -442,6 +442,8 @@ pub(crate) struct Ctx<'a> { set_defs: BTreeMap>, /// Prototype starting points: (page, name, REST node id). flows: Vec<(NodeId, String, String)>, + /// Board connectors and labels, resolved once every layer is imported (their ends name layers). + pending_boards: Vec<(NodeId, &'a Value)>, /// Layers with prototype interactions, resolved once every layer is imported. protos: Vec<(NodeId, &'a Value)>, /// Layers that carry overlay settings (position, background, outside clicks), by REST id. @@ -478,6 +480,7 @@ impl<'a> Ctx<'a> { swap_defaults: Vec::new(), set_defs: BTreeMap::new(), flows: Vec::new(), + pending_boards: Vec::new(), protos: Vec::new(), overlay_meta: BTreeMap::new(), var_kinds: BTreeMap::new(), @@ -781,6 +784,9 @@ impl<'a> Ctx<'a> { self.overlay_meta.entry(rid).or_insert(j); } self.bindings(n, j); + if let Some(b) = j.get("board") { + self.board_item(n, b); + } let restored = j.get("outlinedStroke").is_some_and(|original| restore_stroke(n, original)); // Styles and bindings were read against the stroke: they follow its paints to the fill. if outlined && !restored { @@ -788,6 +794,36 @@ impl<'a> Ctx<'a> { } } + /// The `board` field (a FigCraft extension): what the object is on a board. A sticky or shape + /// is set at once; anything else, or junk, is ignored with a warning. + fn board_item(&mut self, n: &mut Node, b: &'a Value) { + // A sticky or shape is a frame holding its layers: on anything else it is ignored. + let frame = n.kind.is_frame_like(); + let item = match text(b, "type") { + Some("sticky") if frame => { + let author = text(b, "author").unwrap_or("").trim(); + Some(figcraft_doc::BoardItem::Sticky { author: author.chars().filter(|c| !c.is_control()).take(64).collect() }) + } + Some("shape") if frame => { + text(b, "shape").and_then(figcraft_doc::BoardShape::from_id).map(|shape| figcraft_doc::BoardItem::Shape { shape }) + } + _ => None, + }; + match item { + Some(item) => n.board = Some(item), + None => self.warn(format!("unknown board item on {} was ignored", n.name)), + } + } + + /// Board items that name other layers (connector ends, a label's connector), once every + /// layer is imported and `ids` can resolve them. + fn resolve_boards(&mut self) { + for (id, _) in std::mem::take(&mut self.pending_boards) { + let name = self.doc.node(id).map(|n| n.name.clone()).unwrap_or_default(); + self.warn(format!("unknown board item on {name} was ignored")); + } + } + /// A vector's network: the editable one when the JSON carries it (`vectorNetwork`, or /// `vectorNetworkRef` naming one built by the `.fig` import: our extensions), else from its /// geometry. A stroke-only vector uses the stroke outline, painted with the stroke paints @@ -1096,6 +1132,7 @@ impl<'a> Ctx<'a> { } } self.resolve_instances(); + self.resolve_boards(); if let Some(sources) = self.fig_sources.take() { let missing = sources.apply(&mut self.doc, &self.ids); if missing > 0 { diff --git a/crates/format/src/rest/import_regression_tests.rs b/crates/format/src/rest/import_regression_tests.rs index 5aeb4548b..5d5bfb48e 100644 --- a/crates/format/src/rest/import_regression_tests.rs +++ b/crates/format/src/rest/import_regression_tests.rs @@ -93,3 +93,29 @@ fn thousands_of_distinct_style_references_import_in_linear_time() { assert!(start.elapsed() < std::time::Duration::from_secs(10), "{:?}", start.elapsed()); assert_eq!(doc.styles.len(), n); } + +#[test] +fn a_board_field_becomes_the_nodes_board_item() { + let frame = json!({"id": "1:1", "name": "Note", "type": "FRAME", "relativeTransform": at(0.0, 0.0), "size": {"x": 200, "y": 200}, + "board": {"type": "sticky", "author": "A\u{7}"}}); + let (doc, warnings) = import(&file(json!([frame])), &no_images).unwrap(); + assert_eq!(named(&doc, "Note").board, Some(figcraft_doc::BoardItem::Sticky { author: "A".into() })); + assert!(!warnings.iter().any(|w| w.contains("board item")), "{warnings:?}"); +} + +#[test] +fn junk_board_fields_are_ignored_with_a_warning() { + for junk in [json!(5), json!({"type": "nope"}), json!({"type": "shape", "shape": "blob"}), json!({"type": "connector"})] { + let frame = + json!({"id": "1:1", "name": "Junk", "type": "FRAME", "relativeTransform": at(0.0, 0.0), "size": {"x": 20, "y": 20}, "board": junk}); + let (doc, warnings) = import(&file(json!([frame])), &no_images).unwrap(); + assert!(named(&doc, "Junk").board.is_none(), "{junk}"); + assert!(warnings.iter().any(|w| w.contains("unknown board item on Junk was ignored")), "{junk}: {warnings:?}"); + } + // A sticky is a frame holding its layers: on a rectangle the item is ignored. + let rect = json!({"id": "1:2", "name": "Rect", "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 20, "y": 20}, + "board": {"type": "sticky", "author": "A"}}); + let (doc, warnings) = import(&file(json!([rect])), &no_images).unwrap(); + assert!(named(&doc, "Rect").board.is_none()); + assert!(warnings.iter().any(|w| w.contains("unknown board item on Rect was ignored")), "{warnings:?}"); +} diff --git a/crates/format/src/rest/tests.rs b/crates/format/src/rest/tests.rs index 3ea88fad1..6dc710979 100644 --- a/crates/format/src/rest/tests.rs +++ b/crates/format/src/rest/tests.rs @@ -290,6 +290,8 @@ fn vectors_ellipses_stars_and_booleans() { counted["pointCount"] = json!(6); let mut boolean = base("Bool", "BOOLEAN_OPERATION"); boolean["booleanOperation"] = json!("SUBTRACT"); + boolean["cornerRadius"] = json!(12); + boolean["cornerSmoothing"] = json!(0.6); boolean["children"] = json!([base("A", "RECTANGLE"), {"id": "B", "name": "B", "type": "ELLIPSE", "relativeTransform": at(5.0, 5.0), "size": {"x": 10, "y": 10}}]); let (doc, warnings) = one(json!([tri, wire, empty, arc, star, plain_star, counted, boolean])); @@ -311,6 +313,8 @@ fn vectors_ellipses_stars_and_booleans() { assert!(matches!(b.kind, NodeKind::BooleanOp { op: BoolOp::Subtract })); assert_eq!(b.children.len(), 2); assert!(close(b.width, 15.0), "booleans wrap their children"); + assert_eq!(b.corners.radii, [12.0; 4], "a boolean group keeps its corner radius"); + assert!(close(b.corners.smoothing, 0.6)); } #[test] diff --git a/crates/format/src/rest/text.rs b/crates/format/src/rest/text.rs index 391fa4e1c..f53eb0684 100644 --- a/crates/format/src/rest/text.rs +++ b/crates/format/src/rest/text.rs @@ -278,6 +278,7 @@ fn lists(v: &Value, td: &mut TextData) { Some("RTL") => TextDirection::Rtl, _ => TextDirection::Auto, }, + wrap: None, }) .collect(); // Clamp the levels and fold one style for all back into the layer's list style. diff --git a/crates/layout/src/behaviour_tests.rs b/crates/layout/src/behaviour_tests.rs index 50dcc79ad..c0b9b983b 100644 --- a/crates/layout/src/behaviour_tests.rs +++ b/crates/layout/src/behaviour_tests.rs @@ -674,27 +674,48 @@ fn grid_rules() { rects: &[(0.0, 0.0, 60.0, 20.0), (60.0, 0.0, 240.0, 20.0)], }, Case { - rule: "fr tracks behave like the CSS fr unit: a fixed child taller than its share keeps its row", - // Share 50 < 80: row 1 keeps 80, row 2 gets the remaining 20. + rule: "fr tracks as measured in Figma: a fixed child taller than its share keeps its row's share and overflows", + // Share 50 < 80: rows stay 50 / 50, child 1 overflows into row 2. frame: Frame { mode: Grid, size: (100.0, 100.0), columns: &[fr(1.0)], rows: &[fr(1.0), fr(1.0)], ..FRAME }, kids: &[kid(20.0, 80.0), Kid { sizing: (Fixed, Fill), ..KID }], want: (100.0, 100.0), - rects: &[(0.0, 0.0, 20.0, 80.0), (0.0, 80.0, 20.0, 20.0)], + rects: &[(0.0, 0.0, 20.0, 80.0), (0.0, 50.0, 20.0, 50.0)], }, Case { - rule: "fr tracks: children bigger than every share keep their sizes (the grid overflows)", + rule: "fr tracks as measured in Figma: children bigger than every share keep their sizes (the grid overflows)", frame: Frame { mode: Grid, size: (100.0, 100.0), columns: &[fr(1.0)], rows: &[fr(1.0), fr(1.0)], ..FRAME }, kids: &[kid(20.0, 80.0), kid(20.0, 70.0)], want: (100.0, 100.0), - rects: &[(0.0, 0.0, 20.0, 80.0), (0.0, 80.0, 20.0, 70.0)], + rects: &[(0.0, 0.0, 20.0, 80.0), (0.0, 50.0, 20.0, 70.0)], }, Case { - rule: "fr columns: a fixed child wider than its share keeps its column", - // Share 100 < 150: column 1 keeps 150; column 2 (2fr alone) gets the other 150. + rule: "fr columns as measured in Figma: a fixed child wider than its share overflows its column", + // Share 100 < 150: columns stay 100 / 200. frame: Frame { mode: Grid, size: (300.0, 20.0), columns: &[fr(1.0), fr(2.0)], ..FRAME }, kids: &[kid(150.0, 20.0), Kid { sizing: (Fill, Fixed), ..KID }], want: (300.0, 20.0), - rects: &[(0.0, 0.0, 150.0, 20.0), (150.0, 0.0, 150.0, 20.0)], + rects: &[(0.0, 0.0, 150.0, 20.0), (100.0, 0.0, 200.0, 20.0)], + }, + Case { + rule: "fr rows as measured in Figma: 300 x 200, 1fr / 1fr, a 150-tall child does not widen its row", + frame: Frame { mode: Grid, size: (300.0, 200.0), columns: &[fr(1.0)], rows: &[fr(1.0), fr(1.0)], ..FRAME }, + kids: &[kid(100.0, 150.0), kid(100.0, 20.0)], + want: (300.0, 200.0), + rects: &[(0.0, 0.0, 100.0, 150.0), (0.0, 100.0, 100.0, 20.0)], + }, + Case { + rule: "fr rows as measured in Figma: the row gap comes off first (95 / 95, second child at 105)", + frame: Frame { mode: Grid, size: (300.0, 200.0), cross_gap: 10.0, columns: &[fr(1.0)], rows: &[fr(1.0), fr(1.0)], ..FRAME }, + kids: &[kid(100.0, 150.0), kid(100.0, 20.0)], + want: (300.0, 200.0), + rects: &[(0.0, 0.0, 100.0, 150.0), (0.0, 105.0, 100.0, 20.0)], + }, + Case { + rule: "fr rows as measured in Figma: with the frame on Hug the rows size to content (150 / 20, frame 170)", + frame: Frame { mode: Grid, size: (300.0, 200.0), sizing: (Fixed, Hug), columns: &[fr(1.0)], rows: &[fr(1.0), fr(1.0)], ..FRAME }, + kids: &[kid(100.0, 150.0), kid(100.0, 20.0)], + want: (300.0, 170.0), + rects: &[(0.0, 0.0, 100.0, 150.0), (0.0, 150.0, 100.0, 20.0)], }, Case { rule: "placement: left to right, top to bottom; rows grow to fit the children", diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index b3d8e27f0..443cc9310 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -794,9 +794,9 @@ fn track_spec(specs: &[figcraft_doc::GridTrack], i: usize) -> (Sizing, f64) { } /// Resolve track sizes: fixed tracks keep their size, hug tracks fit their content, fill tracks -/// share what is left by their fractional units like the CSS `fr` unit (a track never gets less -/// than its content: one whose share is too small keeps its content size and the others share the -/// rest). `avail` is None when the frame hugs that axis (fill tracks then hug their content too). +/// share what is left by their fractional units (a track whose share is below its content, which +/// only a Fill child's minimum or a spanning child asks for, keeps that size and the others share +/// the rest). `avail` is None when the frame hugs that axis (fill tracks then hug their content too). fn resolve_tracks(specs: &[figcraft_doc::GridTrack], content: &[f64], avail: Option) -> Vec { let mut out: Vec = (0..content.len()) .map(|i| match track_spec(specs, i) { @@ -891,13 +891,29 @@ pub fn grid_geometry(doc: &Document, frame: NodeId) -> Option { let gy = finite_or_zero(al.cross_gap).max(0.0); let hug_w = f.child_layout.sizing_h == Sizing::Hug; let hug_h = f.child_layout.sizing_v == Sizing::Hug; - // What each child asks of its tracks: its size, or (filling a non-hugging axis) its minimum. + // What each child asks of its tracks: its size, its minimum when it fills a non-hugging axis, or + // nothing when it sits alone in a Fill track of a non-hugging axis. let (mut ws, mut hs) = (Vec::with_capacity(cells.len()), Vec::with_capacity(cells.len())); for c in &cells { let (w, h) = outer_size(doc, c.id); let cl = doc.node(c.id).map(|n| n.child_layout.clone()).unwrap_or_default(); - ws.push(if cl.sizing_h == Sizing::Fill && !hug_w { cl.min_w.unwrap_or(0.0) } else { w }); - hs.push(if cl.sizing_v == Sizing::Fill && !hug_h { cl.min_h.unwrap_or(0.0) } else { h }); + // Measured in Figma: a Fill track of a fixed-size axis shares the space by its fraction and + // ignores a fixed-size (or hug-size) child in it, which overflows into the next track. + let in_fill = |tracks: &[figcraft_doc::GridTrack], start: usize, span: usize| span == 1 && track_spec(tracks, start).0 == Sizing::Fill; + ws.push(if cl.sizing_h == Sizing::Fill && !hug_w { + cl.min_w.unwrap_or(0.0) + } else if !hug_w && in_fill(&al.column_tracks, c.column, c.column_span) { + 0.0 + } else { + w + }); + hs.push(if cl.sizing_v == Sizing::Fill && !hug_h { + cl.min_h.unwrap_or(0.0) + } else if !hug_h && in_fill(&al.row_tracks, c.row, c.row_span) { + 0.0 + } else { + h + }); } let col_content = track_content(&cells, &ws, &al.column_tracks, cols, gx, true, hug_w); let row_content = track_content(&cells, &hs, &al.row_tracks, rows, gy, false, hug_h); diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 5d4296f01..9a546dc2a 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -208,7 +208,7 @@ fn tools() -> Vec { tool( "set_properties", "Set properties", - "Set properties on one or more layers as one undo step (engine `node.set`). Keys: name, visible, locked, opacity (0-1), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), fill (colour) / fills (array of paints: \"#hex\" or {\"type\":\"solid\",\"color\":\"#hex\"} or {\"type\":\"linearGradient\",\"stops\":[\"#hex\",\"#hex\"]} or stops [{\"position\":0..1,\"color\":\"#hex\"}], optional from/to handles in the unit box; radialGradient too), stroke / strokes, strokeWeight, strokeAlign (inside|center|outside), cornerRadius (n or [tl,tr,br,bl]), effects (array, e.g. {\"type\":\"dropShadow\",\"color\":\"#00000040\",\"offset\":[0,4],\"radius\":8}), clip, layout (null|horizontal|vertical|grid), gap, padding (n or [t,r,b,l]), mainAlign (min|center|max|spaceBetween|spaceAround|spaceEvenly), crossAlign, wrap, contentAlign (auto|spaceBetween: wrapped lines), sizingH / sizingV (fixed|hug|fill), constraints {horizontal, vertical}, characters, fontFamily, fontStyle, fontSize, lineHeight, letterSpacing, textAlign, textAutoResize. Auto layout keys (gap, padding, mainAlign, crossAlign, wrap, …) apply to frames, components and instances only: other layers among the ids are skipped and named in `warnings`, and with none that can take them the call is an error. A fontStyle draws in the family's nearest face; `warnings` says when that face has another weight or slant than the name asks for. Run list_commands with filter \"node.set\" for the full list. Unknown keys are an error. Returns the updated layers.", + "Set properties on one or more layers as one undo step (engine `node.set`). Keys: name, visible, locked, opacity (0-1), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page), fill (colour) / fills (array of paints: \"#hex\" or {\"type\":\"solid\",\"color\":\"#hex\"} or {\"type\":\"linearGradient\",\"stops\":[\"#hex\",\"#hex\"]} or stops [{\"position\":0..1,\"color\":\"#hex\"}], optional from/to handles in the unit box; radialGradient too), stroke / strokes, strokeWeight, strokeAlign (inside|center|outside), cornerRadius (n or [tl,tr,br,bl]), effects (array, e.g. {\"type\":\"dropShadow\",\"color\":\"#00000040\",\"offset\":[0,4],\"radius\":8}), clip, layout (null|horizontal|vertical|grid), gap, padding (n or [t,r,b,l]), mainAlign (min|center|max|spaceBetween|spaceAround|spaceEvenly), crossAlign, wrap, contentAlign (auto|spaceBetween: wrapped lines), sizingH / sizingV (fixed|hug|fill), constraints {horizontal, vertical}, characters, fontFamily, fontStyle, fontSize, lineHeight, letterSpacing, textAlign, textAutoResize. Auto layout keys (gap, padding, mainAlign, crossAlign, wrap, …) apply to frames, components and instances only: other layers among the ids are skipped and named in `warnings`, and with none that can take them the call is an error. A fontStyle draws in the family's nearest face; `warnings` says when that face has another weight or slant than the name asks for. Run list_commands with filter \"node.set\" for the full list. Unknown keys are an error. Returns the updated layers.", obj( json!({"ids": ids_schema("Layer ids (default: the selection)"), "props": {"type": "object", "description": "Property values to set"}}), &["props"], @@ -336,7 +336,7 @@ fn tools() -> Vec { "y": num("Page y"), "to": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2, "description": "Drag end [x, y] (page)"}, "steps": int("Intermediate move events for drag (default 8)"), - "tool": {"type": "string", "description": "Tool to choose first: move|scale|hand|frame|section|slice|rectangle|line|arrow|ellipse|polygon|star|pen|pencil|text|comment"}, + "tool": {"type": "string", "description": "Tool to choose first: move|scale|hand|frame|section|slice|rectangle|line|arrow|ellipse|polygon|star|pen|pencil|text|comment|annotation"}, "shift": boolean("Shift held"), "alt": boolean("Alt/Option held"), "cmd": boolean("Cmd (macOS) / Ctrl held"), diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 85f1ecd10..0e418155d 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -4,6 +4,8 @@ //! sweep-line topology from `linesweeper`); results use the even-odd rule. //! - [`stroke_outline`]: a stroke as a fill, with Figma's Inside / Center / Outside alignment, //! dashes, caps, joins, arrowheads, variable width profiles ([`width`]) and brushes ([`brush`]). +//! - [`round_corners`]: a corner radius (and smoothing) on every corner still sharp in a closed path, +//! as a boolean group draws its result. //! //! Every sweep is capped ([`MAX_SEGMENTS`], [`MAX_CROSSINGS`], and [`MAX_FOLD_SEGMENTS`] over a //! fold): past the caps an operation is refused with [`PathOpsError::TooComplex`]. @@ -24,6 +26,9 @@ mod dot_dash_tests; #[cfg(test)] mod ops_tests; mod points; +mod round; +#[cfg(test)] +mod round_tests; #[cfg(test)] mod rounded_side_strokes_tests; #[cfg(test)] @@ -36,6 +41,7 @@ use figcraft_doc::{BoolOp, StrokeAlign, StrokeCap, StrokeJoin, StrokeProps, Vect use figcraft_geom::kurbo::{self, BezPath, Cap, Join, PathEl, PathSeg, Point, Shape, Vec2}; pub use budget::{Complexity, FoldBudget, MAX_CROSSINGS, MAX_FOLD_SEGMENTS, MAX_SEGMENTS, complexity}; +pub use round::round_corners; #[derive(Debug, PartialEq)] pub enum PathOpsError { diff --git a/crates/pathops/src/round.rs b/crates/pathops/src/round.rs new file mode 100644 index 000000000..385f1faba --- /dev/null +++ b/crates/pathops/src/round.rs @@ -0,0 +1,314 @@ +//! A corner radius on a closed path: every vertex that is still sharp rounds with a circular arc, +//! convex and concave alike, the way a boolean group draws its result. +//! +//! What a sweep hands back is noisy: straight edges split at collinear points, pieces a hair long, +//! one real corner cut into two half turns. So each subpath is cleaned first ([`clean`]), then each +//! vertex is judged by the turn it makes, and a corner that does not fit shrinks to what the edges +//! beside it can hold ([`Ctx::corner`]). + +use figcraft_geom::kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen, ParamCurveDeriv, PathEl, PathSeg, Point, Shape, Vec2}; +use std::f64::consts::PI; + +/// The smallest turn (radians) that counts as a corner. The sweep moves end points by up to its +/// own 1e-6 accuracy, which can tilt a short piece by more than 1e-6 rad. +const SHARP_TURN: f64 = 1e-3; +/// Accuracy of arc length measurements. +const ACC: f64 = 1e-6; + +#[derive(Clone, Copy)] +enum Seg { + Line(Point, Point), + Cubic(CubicBez), +} + +impl Seg { + fn start(&self) -> Point { + match self { + Self::Line(a, _) => *a, + Self::Cubic(c) => c.p0, + } + } + + fn end(&self) -> Point { + match self { + Self::Line(_, b) => *b, + Self::Cubic(c) => c.p3, + } + } + + fn set_start(&mut self, p: Point) { + match self { + Self::Line(a, _) => *a = p, + Self::Cubic(c) => c.p0 = p, + } + } + + fn is_line(&self) -> bool { + matches!(self, Self::Line(..)) + } + + /// As a cubic (a line gets its handles at the thirds). + fn cubic(&self) -> CubicBez { + match self { + Self::Line(a, b) => CubicBez::new(*a, a.lerp(*b, 1.0 / 3.0), a.lerp(*b, 2.0 / 3.0), *b), + Self::Cubic(c) => *c, + } + } + + fn len(&self) -> f64 { + match self { + Self::Line(a, b) => (*b - *a).hypot(), + Self::Cubic(c) => c.arclen(ACC), + } + } + + /// The length of the control polygon: cheap, and zero only for a point. + fn span(&self) -> f64 { + let c = self.cubic(); + (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot() + } + + /// The cubic leaving the start of the segment, or (`from_start` false) leaving its end. + fn outward(&self, from_start: bool) -> CubicBez { + let c = self.cubic(); + if from_start { c } else { CubicBez::new(c.p3, c.p2, c.p1, c.p0) } + } +} + +/// Unit direction in which `c` leaves its start (skipping coincident handles). +fn start_dir(c: &CubicBez) -> Option { + [c.p1, c.p2, c.p3].into_iter().map(|p| p - c.p0).find(|d| d.hypot() > 1e-9).map(|d| d / d.hypot()) +} + +/// The point `t` along `c` from its start, the unit direction back toward the start there, and the +/// parameter reached. +fn trim(c: &CubicBez, t: f64, line: bool, len: f64) -> Option<(Point, Vec2, f64)> { + if line { + if !len.is_finite() || len <= 0.0 { + return None; + } + let u = (c.p3 - c.p0) / len; + return Some((c.p0 + u * t, -u, t / len)); + } + let k = c.inv_arclen(t, ACC).clamp(0.0, 1.0); + let d = c.deriv().eval(k).to_vec2(); + let back = if d.hypot() > 1e-9 { -d / d.hypot() } else { -start_dir(c)? }; + Some((c.eval(k), back, k)) +} + +/// One rounded corner: the curves from the cut on the incoming segment to the cut on the outgoing +/// one, and where those cuts sit on their segments (each segment's own parameter). +struct Corner { + curves: Vec, + t_in: f64, + t_out: f64, +} + +/// `path` with every corner still sharp rounded by `radius` (and corner `smoothing`, 0..=1, between +/// straight edges). A corner shrinks to what its edges can hold: two corners wanting more than +/// half an edge share it half and half, a corner whose far end is smooth may use all of it. A +/// closed subpath with no sharp corner, an open one, and a path with a bad radius or coordinates +/// come back as they are. +pub fn round_corners(path: &BezPath, radius: f64, smoothing: f64) -> BezPath { + if !(radius.is_finite() && radius > 0.0) || path.elements().is_empty() || !crate::finite(path) { + return path.clone(); + } + let smoothing = if smoothing.is_finite() { smoothing.clamp(0.0, 1.0) } else { 0.0 }; + let mut out = BezPath::new(); + for sub in figcraft_geom::split_subpaths(path) { + // Each contour's own size sets its cleanup tolerance, so a large contour can't weld away + // the real short edges of a small island or hole beside it. + let bb = sub.bounding_box(); + let weld = (bb.width().max(bb.height()) * 1e-6).max(1e-9); + let closed = matches!(sub.elements().last(), Some(PathEl::ClosePath)); + match closed.then(|| round_subpath(&sub, radius, smoothing, weld)).flatten() { + Some(p) => out.extend(p.elements().iter().copied()), + None => out.extend(sub.elements().iter().copied()), + } + } + out +} + +/// The segments of a closed subpath without the sweep's noise: pieces shorter than `weld` dropped, +/// each segment starting where the one before ends, and straight runs merged into one line. +fn clean(sub: &BezPath, weld: f64) -> Vec { + let mut segs: Vec = sub + .segments() + .map(|s| match s { + PathSeg::Line(l) => Seg::Line(l.p0, l.p1), + other => Seg::Cubic(other.to_cubic()), + }) + .filter(|s| s.span() >= weld) + .collect(); + let n = segs.len(); + for i in 0..n { + let prev_end = segs.get((i + n - 1) % n).map(Seg::end); + if let (Some(p), Some(s)) = (prev_end, segs.get_mut(i)) { + s.set_start(p); + } + } + merge_runs(segs, weld) +} + +/// Two lines A-B and B-C become A-C when B lies within `weld` of that line and between A and C +/// (a distance test, so a long edge with a real slight kink is not straightened). Cyclic. +fn merge_runs(segs: Vec, weld: f64) -> Vec { + let mergeable = |a: &Seg, b: &Seg| match (a, b) { + (Seg::Line(p, q), Seg::Line(_, r)) => { + let (d, e) = (*r - *p, *q - *p); + let l = d.hypot(); + l > 1e-12 && (d.cross(e) / l).abs() <= weld && e.dot(*r - *q) > 0.0 + } + _ => false, + }; + let mut merged: Vec = Vec::with_capacity(segs.len()); + for s in segs { + match merged.last_mut() { + Some(last) if mergeable(last, &s) => *last = Seg::Line(last.start(), s.end()), + _ => merged.push(s), + } + } + while merged.len() > 2 { + let (Some(first), Some(last)) = (merged.first().copied(), merged.last().copied()) else { break }; + if !mergeable(&last, &first) { + break; + } + if let Some(f) = merged.first_mut() { + *f = Seg::Line(last.start(), first.end()); + } + merged.pop(); + } + merged +} + +/// Everything the corner of one vertex needs. Vertex `i` is where segment `i - 1` ends and +/// segment `i` starts. +struct Ctx<'a> { + segs: &'a [Seg], + /// Segment lengths, measured only for segments with a corner at one end. + lens: &'a [Option], + /// Per vertex: the turn between its segments and the length it wants along each of them. + wants: &'a [Option<(f64, f64)>], + radius: f64, + smoothing: f64, + weld: f64, +} + +/// The angle between the segments at each vertex (pi is straight on, 0 folded back) and the +/// length a corner there wants along each; `None` where the vertex is not a corner. +fn wants(segs: &[Seg], radius: f64, smoothing: f64) -> Vec> { + let n = segs.len(); + (0..n) + .map(|i| { + let (a, b) = (segs.get((i + n - 1) % n)?, segs.get(i)?); + let (u1, u2) = (start_dir(&a.outward(false))?, start_dir(&b.outward(true))?); + let angle = u1.dot(u2).clamp(-1.0, 1.0).acos(); + if angle < 1e-6 || PI - angle < SHARP_TURN { + return None; + } + let t = radius / (angle / 2.0).tan(); + let want = if a.is_line() && b.is_line() { (1.0 + smoothing) * t } else { t }; + want.is_finite().then_some((angle, want)) + }) + .collect() +} + +impl Ctx<'_> { + fn want(&self, i: usize) -> f64 { + self.wants.get(i % self.segs.len().max(1)).copied().flatten().map_or(0.0, |(_, w)| w) + } + + /// What a corner may use of a segment of `len`: half of it, or what the corner at its other + /// end leaves, whichever is more. + fn room(len: f64, other: f64) -> f64 { + (len / 2.0).max(len - other) + } + + fn corner(&self, i: usize) -> Option { + let n = self.segs.len(); + let (angle, _) = self.wants.get(i).copied().flatten()?; + let prev = (i + n - 1) % n; + let (a, b) = (self.segs.get(prev)?, self.segs.get(i)?); + let (la, lb) = (self.lens.get(prev).copied().flatten()?, self.lens.get(i).copied().flatten()?); + let room = Self::room(la, self.want(prev)).min(Self::room(lb, self.want(i + 1))); + if !room.is_finite() || room <= self.weld { + return None; + } + let (c1, c2) = (a.outward(false), b.outward(true)); + if a.is_line() && b.is_line() { + self.between_lines(&c1, &c2, room, (la, lb)) + } else { + self.beside_curve((&c1, a.is_line(), la), (&c2, b.is_line(), lb), room, angle) + } + } + + fn between_lines(&self, c1: &CubicBez, c2: &CubicBez, room: f64, (la, lb): (f64, f64)) -> Option { + let (u1, u2) = (start_dir(c1)?, start_dir(c2)?); + let curves = figcraft_geom::smoothed_corner(c1.p0, u1, u2, room, self.radius, self.smoothing)?; + let (first, last) = (curves.first()?, curves.last()?); + let (t_in, t_out) = (1.0 - (first.p0 - c1.p0).hypot() / la, (last.p3 - c1.p0).hypot() / lb); + (t_in.is_finite() && t_out.is_finite() && curves.iter().all(|c| [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()))) + .then_some(Corner { curves, t_in, t_out }) + } + + /// One cubic between the cuts on both sides, its handles along each side's direction at its cut. + fn beside_curve( + &self, + (c1, line1, la): (&CubicBez, bool, f64), + (c2, line2, lb): (&CubicBez, bool, f64), + room: f64, + angle: f64, + ) -> Option { + let t = (self.radius / (angle / 2.0).tan()).min(room); + let ((p, d1, k1), (q, d2, k2)) = (trim(c1, t, line1, la)?, trim(c2, t, line2, lb)?); + let turn = (-d1.dot(d2)).clamp(-1.0, 1.0).acos(); + let chord = (q - p).hypot(); + let k = if turn < 1e-9 { chord / 3.0 } else { 4.0 / 3.0 * (turn / 4.0).tan() * chord / (2.0 * (turn / 2.0).sin()) }; + let ok = k.is_finite() && [p, q].iter().all(|x| x.x.is_finite() && x.y.is_finite()); + ok.then(|| Corner { curves: vec![CubicBez::new(p, p + d1 * k, q + d2 * k, q)], t_in: 1.0 - k1, t_out: k2 }) + } +} + +/// The subpath with its corners rounded, or `None` when no vertex of it is a corner that rounds +/// (the caller keeps the subpath exactly as it came in). +fn round_subpath(sub: &BezPath, radius: f64, smoothing: f64, weld: f64) -> Option { + let segs = clean(sub, weld); + let n = segs.len(); + if n < 2 { + return None; + } + let wants = wants(&segs, radius, smoothing); + let touches = |i: usize| wants.get(i).is_some_and(Option::is_some) || wants.get((i + 1) % n).is_some_and(Option::is_some); + let lens: Vec> = segs.iter().enumerate().map(|(i, s)| touches(i).then(|| s.len())).collect(); + let ctx = Ctx { segs: &segs, lens: &lens, wants: &wants, radius, smoothing, weld }; + let corners: Vec> = (0..n).map(|i| ctx.corner(i)).collect(); + corners.iter().any(Option::is_some).then(|| emit(&segs, &corners))? +} + +/// Walk the segments: what is left of each between the corner at its start and the one at its +/// end, then the next corner's curves. +fn emit(segs: &[Seg], corners: &[Option]) -> Option { + let n = segs.len(); + let mut out = BezPath::new(); + let first = segs.first()?; + out.move_to(corners.first().and_then(Option::as_ref).and_then(|c| c.curves.last()).map_or(first.start(), |c| c.p3)); + for (i, seg) in segs.iter().enumerate() { + let next = corners.get((i + 1) % n).and_then(Option::as_ref); + let t0 = corners.get(i).and_then(Option::as_ref).map_or(0.0, |c| c.t_out); + let t1 = next.map_or(1.0, |c| c.t_in); + if t1 - t0 > 1e-9 { + match seg { + Seg::Line(a, b) => out.line_to(a.lerp(*b, t1)), + Seg::Cubic(c) => { + let q = c.subsegment(t0..t1); + out.curve_to(q.p1, q.p2, q.p3); + } + } + } + for c in next.iter().flat_map(|c| c.curves.iter()) { + out.curve_to(c.p1, c.p2, c.p3); + } + } + out.close_path(); + crate::finite(&out).then_some(out) +} diff --git a/crates/pathops/src/round_tests.rs b/crates/pathops/src/round_tests.rs new file mode 100644 index 000000000..0c22b5363 --- /dev/null +++ b/crates/pathops/src/round_tests.rs @@ -0,0 +1,256 @@ +//! `round_corners`: every sharp corner of a closed path, convex or concave, rounds with a circular +//! arc; smooth joins and straight-run leftovers of the sweep do not count; a radius larger than the +//! edges allow shrinks to fit. + +use figcraft_doc::BoolOp; +use figcraft_geom::kurbo::{Affine, BezPath, PathEl, PathSeg, Point, Shape, Vec2}; +use figcraft_geom::{ellipse, rounded_rect, split_subpaths}; + +use crate::{boolean, boolean_step, round_corners}; + +fn rect(x: f64, y: f64, w: f64, h: f64) -> BezPath { + kurbo_rect(x, y, w, h).to_path(0.1) +} + +fn kurbo_rect(x: f64, y: f64, w: f64, h: f64) -> figcraft_geom::Rect { + figcraft_geom::Rect::new(x, y, x + w, y + h) +} + +fn l_shape() -> BezPath { + boolean(&[rect(0.0, 0.0, 200.0, 100.0), rect(150.0, 0.0, 100.0, 200.0)], BoolOp::Union).unwrap() +} + +/// A (200 by 100, radius 10) with a 100 square cut out of its top edge: the notch of the measurement. +fn notch() -> BezPath { + let a = rounded_rect(200.0, 100.0, [10.0; 4], 0.0); + boolean_step(&a, &rect(50.0, -50.0, 100.0, 100.0), BoolOp::Subtract).unwrap() +} + +/// Every `CurveTo` as `[from, c1, c2, to]`. +fn arcs(path: &BezPath) -> Vec<[Point; 4]> { + let mut cur = Point::ZERO; + let mut out = Vec::new(); + for el in path.elements() { + match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => cur = p, + PathEl::CurveTo(a, b, c) => { + out.push([cur, a, b, c]); + cur = c; + } + _ => {} + } + } + out +} + +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-3 +} + +fn pt(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +/// Some curve runs through exactly these four points, in either direction. +fn has_arc(path: &BezPath, want: [(f64, f64); 4]) -> bool { + let w = want.map(|(x, y)| pt(x, y)); + let rev = [w[3], w[2], w[1], w[0]]; + arcs(path).iter().any(|a| a.iter().zip(w).all(|(p, q)| near(*p, q)) || a.iter().zip(rev).all(|(p, q)| near(*p, q))) +} + +/// Some curve joins these two end points, in either direction. +fn has_arc_between(path: &BezPath, from: (f64, f64), to: (f64, f64)) -> bool { + let (f, t) = (pt(from.0, from.1), pt(to.0, to.1)); + arcs(path).iter().any(|a| (near(a[0], f) && near(a[3], t)) || (near(a[0], t) && near(a[3], f))) +} + +fn passes_through(path: &BezPath, p: Point) -> bool { + path.elements().iter().any(|el| match el { + PathEl::MoveTo(q) | PathEl::LineTo(q) | PathEl::CurveTo(_, _, q) => near(*q, p), + _ => false, + }) +} + +fn unit(v: Vec2) -> Option { + (v.hypot() > 1e-9).then(|| v / v.hypot()) +} + +fn start_dir(s: PathSeg) -> Option { + let c = s.to_cubic(); + [c.p1, c.p2, c.p3].into_iter().find_map(|p| unit(p - c.p0)) +} + +fn end_dir(s: PathSeg) -> Option { + let c = s.to_cubic(); + [c.p2, c.p1, c.p0].into_iter().find_map(|p| unit(c.p3 - p)) +} + +/// The largest direction change at any vertex of a closed subpath, in radians. +fn sharpest_turn(path: &BezPath) -> f64 { + let mut worst: f64 = 0.0; + for sub in split_subpaths(path) { + let segs: Vec = sub.segments().collect(); + for (i, s) in segs.iter().enumerate() { + let next = segs[(i + 1) % segs.len()]; + if let (Some(a), Some(b)) = (end_dir(*s), start_dir(next)) { + worst = worst.max(a.dot(b).clamp(-1.0, 1.0).acos()); + } + } + } + worst +} + +fn area(p: &BezPath) -> f64 { + p.area().abs() +} + +fn all_finite(p: &BezPath) -> bool { + crate::finite(p) +} + +#[test] +fn every_sharp_corner_of_the_result_rounds_convex_and_concave() { + let r = round_corners(&l_shape(), 20.0, 0.0); + assert_eq!(arcs(&r).len(), 6); + assert!(has_arc(&r, [(230.0, 0.0), (241.046, 0.0), (250.0, 8.95431), (250.0, 20.0)])); + assert!(has_arc(&r, [(150.0, 120.0), (150.0, 108.954), (141.046, 100.0), (130.0, 100.0)])); + assert!((area(&r) - (35000.0 - 4.0 * 85.84)).abs() < 0.5, "{}", area(&r)); + assert_eq!(r.winding(pt(1.0, 1.0)), 0); + assert_ne!(r.winding(pt(148.0, 102.0)), 0); + let bb = r.bounding_box(); + assert!((bb.width() - 250.0).abs() < 1e-6 && (bb.height() - 200.0).abs() < 1e-6); +} + +#[test] +fn a_childs_rounded_corners_are_kept_and_do_not_stack() { + let r = round_corners(¬ch(), 20.0, 0.0); + assert_eq!(arcs(&r).len(), 8); + assert!(has_arc(&r, [(30.0, 0.0), (41.0457, 0.0), (50.0, 8.954), (50.0, 20.0)])); + assert!(has_arc(&r, [(50.0, 30.0), (50.0, 41.0457), (58.954, 50.0), (70.0, 50.0)])); + assert!(has_arc_between(&r, (130.0, 50.0), (150.0, 30.0))); + assert!(has_arc_between(&r, (150.0, 20.0), (170.0, 0.0))); + assert!(has_arc(&r, [(0.0, 10.0), (0.0, 4.477), (4.477, 0.0), (10.0, 0.0)])); +} + +#[test] +fn a_radius_larger_than_the_edges_clamps_to_what_they_hold() { + let r = round_corners(¬ch(), 500.0, 0.0); + assert!(has_arc(&r, [(25.0, 0.0), (38.8071, 0.0), (50.0, 11.1929), (50.0, 25.0)])); + assert!(has_arc(&r, [(50.0, 25.0), (50.0, 38.807), (61.193, 50.0), (75.0, 50.0)])); + assert!(has_arc_between(&r, (125.0, 50.0), (150.0, 25.0))); + assert!(has_arc_between(&r, (150.0, 25.0), (175.0, 0.0))); + assert!(has_arc(&r, [(0.0, 10.0), (0.0, 4.477), (4.477, 0.0), (10.0, 0.0)])); + assert!(all_finite(&r)); + let l = round_corners(&l_shape(), 500.0, 0.0); + assert!(has_arc_between(&l, (0.0, 50.0), (50.0, 0.0))); + assert!(has_arc_between(&l, (150.0, 0.0), (250.0, 100.0))); + assert!((area(&round_corners(&l_shape(), 1e300, 0.0)) - area(&l)).abs() < 1e-6); +} + +#[test] +fn nothing_sharp_nothing_changes() { + let round = rounded_rect(100.0, 60.0, [20.0; 4], 0.0); + let oval = ellipse(100.0, 60.0, 0.0, std::f64::consts::TAU, 0.0); + assert_eq!(round_corners(&round, 20.0, 0.0), round); + assert_eq!(round_corners(&oval, 20.0, 0.0), oval); + let l = l_shape(); + for radius in [0.0, -5.0, f64::NAN, f64::INFINITY] { + assert_eq!(round_corners(&l, radius, 0.0), l); + } + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((50.0, 0.0)); + open.line_to((50.0, 50.0)); + assert_eq!(round_corners(&open, 10.0, 0.0), open); +} + +#[test] +fn points_the_sweep_leaves_on_an_edge_are_not_corners() { + let mut p = BezPath::new(); + for (i, q) in [(0.0, 0.0), (20.0, 0.0), (100.0, 0.0), (100.0, 0.0), (100.0, 60.0), (100.0 + 1e-11, 60.0), (100.0, 100.0), (0.0, 100.0)] + .into_iter() + .enumerate() + { + if i == 0 { + p.move_to(q); + } else { + p.line_to(q); + } + } + p.close_path(); + let r = round_corners(&p, 500.0, 0.0); + assert_eq!(arcs(&r).len(), 4); + assert!(has_arc_between(&r, (0.0, 50.0), (50.0, 0.0))); +} + +fn two_circles(op: BoolOp) -> BezPath { + let c = ellipse(100.0, 100.0, 0.0, std::f64::consts::TAU, 0.0); + boolean(&[c.clone(), Affine::translate((70.0, 0.0)) * c], op).unwrap() +} + +#[test] +fn corners_beside_curves_round_too() { + for op in [BoolOp::Union, BoolOp::Intersect] { + let sharp = two_circles(op); + assert!(sharpest_turn(&sharp) > 1.0); + let r = round_corners(&sharp, 10.0, 0.0); + assert!(sharpest_turn(&r) < 1e-3, "{}", sharpest_turn(&r)); + assert!(all_finite(&r)); + match op { + BoolOp::Union => assert!(area(&r) > area(&sharp)), + _ => assert!(area(&r) < area(&sharp)), + } + } +} + +#[test] +fn smoothing_draws_the_polygon_profile_between_straight_edges() { + let l = l_shape(); + let plain = round_corners(&l, 20.0, 0.0); + let smooth = round_corners(&l, 20.0, 0.6); + assert!(passes_through(&smooth, pt(0.0, 32.0)) && passes_through(&smooth, pt(32.0, 0.0))); + assert!((area(&smooth) - area(&plain)).abs() > 1.0); + let circles = two_circles(BoolOp::Union); + assert_eq!(round_corners(&circles, 10.0, 0.6), round_corners(&circles, 10.0, 0.0)); +} + +#[test] +fn junk_never_panics() { + let mut bad = BezPath::new(); + bad.move_to((f64::NAN, 0.0)); + bad.line_to((10.0, f64::INFINITY)); + bad.close_path(); + assert_eq!(round_corners(&bad, 5.0, 0.0).elements().len(), 3); + assert!(round_corners(&BezPath::new(), 5.0, 0.0).elements().is_empty()); + let mut one = BezPath::new(); + one.move_to((0.0, 0.0)); + one.line_to((10.0, 0.0)); + one.close_path(); + assert!(all_finite(&round_corners(&one, 5.0, 0.5))); + assert!(all_finite(&round_corners(&rect(0.0, 0.0, 1.0, 0.5), 0.1, 0.0))); + let mut zig = BezPath::new(); + zig.move_to((0.0, 0.0)); + for i in 1..40_000 { + zig.line_to((f64::from(i) * 0.5, f64::from(i % 2))); + } + zig.close_path(); + assert!(all_finite(&round_corners(&zig, 2.0, 0.0))); +} + +/// The cleanup tolerance is each contour's own: a contour a million units wide doesn't weld away +/// the half-unit notch of a separate small contour in the same path. +#[test] +fn a_large_contour_does_not_weld_a_small_ones_short_edges() { + let mut p = rect(0.0, 0.0, 1e6, 1e6); + let x = 2e6; + for (i, (dx, y)) in [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (5.5, 10.0), (5.5, 9.5), (5.0, 9.5), (5.0, 10.0), (0.0, 10.0)].into_iter().enumerate() + { + if i == 0 { p.move_to((x + dx, y)) } else { p.line_to((x + dx, y)) } + } + p.close_path(); + let out = round_corners(&p, 0.001, 0.0); + let reaches = |q: Point| { + out.elements().iter().any(|el| matches!(el, PathEl::MoveTo(e) | PathEl::LineTo(e) | PathEl::CurveTo(_, _, e) if (*e - q).hypot() < 0.01)) + }; + assert!(reaches(pt(x + 5.0, 9.5)) && reaches(pt(x + 5.5, 9.5)), "the notch's floor is kept"); +} diff --git a/crates/render/src/boolean.rs b/crates/render/src/boolean.rs index 7fc642082..039a3967b 100644 --- a/crates/render/src/boolean.rs +++ b/crates/render/src/boolean.rs @@ -7,6 +7,11 @@ //! edited one are never recombined, and groups whose operands didn't change aren't recomputed at //! all. The caches drop their least recently used half when full, so a long drag doesn't evict //! every other group's result. +//! +//! The group's own corner radius is applied to the finished fold ([`result_cached`]) and cached in a +//! separate, smaller map keyed by the folded path plus the radius and smoothing: the fold's caches +//! are keyed by the operands alone, so scrubbing the radius never redoes the fold or evicts its +//! prefixes, and a rounded path is never stored where a fold would find it. use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; @@ -109,6 +114,30 @@ pub fn fold_cached(operands: &[(BezPath, BoolOp)]) -> Option { } } +fn rounded() -> &'static Mutex { + static C: OnceLock> = OnceLock::new(); + C.get_or_init(|| Mutex::new(PathCache::new(512))) +} + +/// A boolean group's result as it is drawn: the fold of `operands` ([`fold_cached`]), then the +/// group's corner `radius` and `smoothing` on every corner still sharp. +pub fn result_cached(operands: &[(BezPath, BoolOp)], radius: f64, smoothing: f64) -> Option { + let folded = fold_cached(operands)?; + if !(radius.is_finite() && radius > 0.0) { + return Some(folded); + } + let mut h = DefaultHasher::new(); + hash_path(&folded, &mut h); + (radius.to_bits(), smoothing.to_bits(), 0x52u8).hash(&mut h); + let key = h.finish(); + if let Some(p) = locked(rounded()).get(key) { + return Some((*p).clone()); + } + let out = figcraft_pathops::round_corners(&folded, radius, smoothing); + locked(rounded()).insert(key, Arc::new(out.clone())); + Some(out) +} + /// `keys[i]`: the cache key of the fold of operands `0..=i`. fn fold_keys(operands: &[(BezPath, BoolOp)]) -> Vec { let mut h = DefaultHasher::new(); diff --git a/crates/render/src/boolean_cache_tests.rs b/crates/render/src/boolean_cache_tests.rs index 7a34bf4f2..51e422425 100644 --- a/crates/render/src/boolean_cache_tests.rs +++ b/crates/render/src/boolean_cache_tests.rs @@ -7,12 +7,12 @@ use figcraft_color::{Color, Paint}; use figcraft_doc::{BoolOp, Document, NodeId, NodeKind, WidthPoint, WidthProfile}; use figcraft_geom::kurbo::{BezPath, Shape}; -fn dark(p: &Pixmap, x: u32, y: u32) -> bool { +pub(crate) fn dark(p: &Pixmap, x: u32, y: u32) -> bool { let i = ((y * p.width() + x) * 4) as usize; p.data().get(i).is_some_and(|r| *r < 40) } -fn render(d: &Document, p: NodeId) -> Pixmap { +pub(crate) fn render(d: &Document, p: NodeId) -> Pixmap { render_view(d, p, &View { origin: (0.0, 0.0), scale: 1.0, width: 200, height: 200 }, &Options::default()).unwrap() } @@ -28,7 +28,7 @@ fn row_of_squares(op: BoolOp, n: usize) -> (Document, NodeId, NodeId, Vec BezPath { +pub(crate) fn outline(d: &Document, id: NodeId) -> BezPath { node_outline(d, d.node(id).unwrap()).unwrap().0 } diff --git a/crates/render/src/boolean_radius_tests.rs b/crates/render/src/boolean_radius_tests.rs new file mode 100644 index 000000000..dfe98af03 --- /dev/null +++ b/crates/render/src/boolean_radius_tests.rs @@ -0,0 +1,60 @@ +//! A boolean group's corner radius: it rounds the result the canvas draws, and keys a cache of its +//! own so the fold underneath is not redone. + +use crate::boolean::boolean_steps; +use crate::boolean_cache_tests::{dark, outline, render}; +use figcraft_color::{Color, Paint}; +use figcraft_doc::{BoolOp, Document, NodeId, NodeKind}; +use figcraft_geom::kurbo::Shape; + +/// The L of the measurement: a union of 200 by 100 and 100 by 200 rectangles, on a page of its own. +fn l_group() -> (Document, NodeId, NodeId, NodeId) { + let mut d = Document::new("t"); + let p = d.first_page().unwrap(); + let g = d.create(p, NodeKind::BooleanOp { op: BoolOp::Union }, "G", 0.0, 0.0, 0.0, 0.0).unwrap(); + d.get_mut(g).unwrap().fills = vec![Paint::solid(Color::BLACK)]; + d.create(g, NodeKind::Rectangle, "A", 0.0, 0.0, 200.0, 100.0).unwrap(); + let b = d.create(g, NodeKind::Rectangle, "B", 150.0, 0.0, 100.0, 200.0).unwrap(); + d.fit_to_children(g).unwrap(); + (d, p, g, b) +} + +fn set_radius(d: &mut Document, g: NodeId, r: f64) { + d.get_mut(g).unwrap().corners.radii = [r; 4]; +} + +fn area(d: &Document, g: NodeId) -> f64 { + outline(d, g).area().abs() +} + +#[test] +fn a_boolean_groups_radius_rounds_what_the_canvas_draws() { + let (mut d, p, g, _) = l_group(); + let pix = render(&d, p); + assert!(dark(&pix, 1, 1) && !dark(&pix, 148, 102)); + set_radius(&mut d, g, 20.0); + let pix = render(&d, p); + assert!(!dark(&pix, 1, 1), "the corner is cut off"); + assert!(dark(&pix, 148, 102), "the concave corner is filled in"); + assert!(dark(&pix, 100, 50)); + assert!((area(&d, g) - 34656.6).abs() < 1.0, "{}", area(&d, g)); +} + +#[test] +fn the_radius_keys_the_result_and_the_fold_is_not_redone() { + let (mut d, _, g, b) = l_group(); + let sharp = outline(&d, g); + set_radius(&mut d, g, 20.0); + let _ = outline(&d, g); + let before = boolean_steps(); + set_radius(&mut d, g, 40.0); + // Four net corners of 343.36 each, plus the cubic arcs' own slight excess over a circle. + assert!((area(&d, g) - 33626.6).abs() < 2.0, "{}", area(&d, g)); + assert_eq!(boolean_steps(), before, "a new radius reuses the fold"); + set_radius(&mut d, g, 0.0); + assert_eq!(outline(&d, g), sharp, "radius 0 draws the fold itself"); + set_radius(&mut d, g, 20.0); + let rounded = area(&d, g); + d.get_mut(b).unwrap().transform = figcraft_geom::Affine::translate((10.0, 0.0)) * d.node(b).unwrap().transform; + assert!((area(&d, g) - rounded).abs() > 1.0, "moving an operand does not draw a stale rounded path"); +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index bf5e8953c..a5010006b 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -347,8 +347,9 @@ fn node_outline_at(doc: &Document, n: &Node, depth: usize) -> Option<(BezPath, F Some((p, c.bool_op.unwrap_or(*op))) }) .collect(); - // Past the path operations' caps the group has no outline: it draws without its result. - crate::boolean::fold_cached(&operands).map(|p| (p, FillRule::EvenOdd)) + // Past the path operations' caps the group has no outline: it draws without its result. The + // group's corner radius rounds what is still sharp in the fold. + crate::boolean::result_cached(&operands, n.corners.radii[0], n.corners.smoothing).map(|p| (p, FillRule::EvenOdd)) } NodeKind::Text(_) => { let (l, dy) = figcraft_text::layout_node(n)?; diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 5eea7033d..46453d333 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -33,7 +33,7 @@ const MAX_CACHED_IMAGES: usize = 256; /// The largest sides of the copies the canvas draws larger images from while they show smaller /// (device pixels): two 16 000 × 10 000 images take 640 MB each in full, past the cache's budget /// together, and 42 MB each at 4096 (168 MB at 8192). -pub const DISPLAY_SIDES: [u32; 2] = [4096, 8192]; +pub const DISPLAY_SIDES: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192]; /// Decoded pixmaps by image, filters and profile, holding at most a byte budget of pixels: adding /// one past the budget (or past [`MAX_CACHED_IMAGES`]) drops the least recently used first, so diff --git a/crates/render/src/large_image_tests.rs b/crates/render/src/large_image_tests.rs index be3de57f2..d4467b01f 100644 --- a/crates/render/src/large_image_tests.rs +++ b/crates/render/src/large_image_tests.rs @@ -8,7 +8,7 @@ use figcraft_color::{ImageScaleMode, Paint}; use figcraft_doc::{Document, ImageData, NodeId, NodeKind}; use tiny_skia::Pixmap; -use crate::images::{self, DISPLAY_SIDES, MAX_CACHED_BYTES}; +use crate::images::{self, MAX_CACHED_BYTES}; use crate::{Options, View, render_view}; const W: u32 = 6000; @@ -63,12 +63,11 @@ fn sharp_stripes(p: &Pixmap, y: u32, black_first: bool, each: u32) -> bool { #[test] fn zoomed_out_the_canvas_draws_both_images_from_copies_that_stay_decoded() { let (d, page, keys) = doc("zoomed-out"); - // At 25% each shows 1500 px long: drawn from 4096 px copies, not decoded in full. render_view(&d, page, &view(0.25), &canvas()).unwrap(); let first = keys.each_ref().map(|k| shown(&d, k, 1500.0)); for (k, p) in keys.iter().zip(&first) { - assert_eq!((p.width(), p.height()), (DISPLAY_SIDES[0], 5), "{k}"); - assert_eq!(images::cached_sides(k), vec![DISPLAY_SIDES[0]], "{k}: only its copy is decoded"); + assert_eq!((p.width(), p.height()), (2048, 3), "{k}"); + assert_eq!(images::cached_sides(k), vec![2048], "{k}: only its copy is decoded"); } // Drawn again (a drag, a pan), both are still the copies decoded the first time. render_view(&d, page, &view(0.25), &canvas()).unwrap(); @@ -93,13 +92,15 @@ fn exports_and_close_ups_draw_from_the_image_itself() { #[test] fn the_copy_is_the_smallest_that_holds_what_shows() { let side = |long, shown| images::display_side(long, shown); - assert_eq!(side(6000, 1500.0), 4096); + assert_eq!(side(6000, 1500.0), 2048); assert_eq!(side(16_000, 4096.0), 4096); assert_eq!(side(16_000, 4097.0), 8192); + assert_eq!(side(4096, 100.0), 256); + assert_eq!(side(3000, 20.0), 256); // Shown at more than the largest copy, or an image no larger than the copy: the image itself. assert_eq!(side(16_000, 9000.0), 16_384); assert_eq!(side(6000, 5000.0), 16_384); - assert_eq!(side(4096, 100.0), 16_384); + assert_eq!(side(200, 100.0), 16_384); // An unknown size or a meaningless scale: the image itself. assert_eq!(side(0, 100.0), 16_384); assert_eq!(side(16_000, f64::NAN), 16_384); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f138521ae..6700fbc72 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -266,11 +266,11 @@ fn render_one(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Opti /// Render several nodes (in z-order) into an existing pixmap through `view`. pub fn render_nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap) { - nodes_into(doc, ids, view, pix, 0.0); + nodes_into(doc, ids, view, pix, 0.0, None); } /// [`render_nodes_into`] `time` seconds into animated GIFs. -fn nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap, time: f64) { +fn nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap, time: f64, under: Option<&backdrop::Under>) { let bounds = draw::Bounds::default(); let ctx = draw::Ctx { doc, @@ -282,7 +282,7 @@ fn nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap, tim lod: false, preview: false, magnified_image_pixels: false, - under: None, + under, time, bounds: &bounds, }; @@ -353,16 +353,24 @@ pub fn render_node(doc: &Document, id: NodeId, scale: f64) -> Option { /// [`render_node`] `time` seconds into animated GIFs (the presenter plays them). pub fn render_node_at(doc: &Document, id: NodeId, scale: f64, time: f64) -> Option { - area_at(doc, &[id], export_bounds(doc, id)?, scale, time) + area_at(doc, &[id], None, export_bounds(doc, id)?, scale, time) } /// Rasterise `ids` (bottom to top) over page area `b` at `scale` (export): the image starts at the /// area's top-left and its sides round up to whole pixels. `None` past 16384 pixels a side. pub fn render_area(doc: &Document, ids: &[NodeId], b: Rect, scale: f64) -> Option { - area_at(doc, ids, b, scale, 0.0) + area_at(doc, ids, None, b, scale, 0.0) } -fn area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Option { +/// [`render_area`] for an export of layers that sit among `page_layers` (the page's top-level +/// layers, in z-order): a background blur or glass in `ids` reads what lies under the first of +/// them on that page, clipped to the area (#2213). Only `ids` are drawn; the layers above stay +/// out. Without such an effect it is [`render_area`]. +pub fn render_area_over(doc: &Document, ids: &[NodeId], page_layers: &[NodeId], b: Rect, scale: f64) -> Option { + area_at(doc, ids, Some(page_layers), b, scale, 0.0) +} + +fn area_at(doc: &Document, ids: &[NodeId], page_layers: Option<&[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); let h = (b.height() * scale - 1e-6).ceil().max(1.0); @@ -371,7 +379,31 @@ fn area_at(doc: &Document, ids: &[NodeId], b: Rect, scale: f64, time: f64) -> Op } let view = View { origin: (b.x0, b.y0), scale, width: w as u32, height: h as u32 }; let mut pix = new_pixmap(view.width, view.height)?; - nodes_into(doc, ids, &view, &mut pix, time); + // What the backdrop effects read: the page under the first layer, with the margin they reach. + let reach = page_layers.and_then(|_| { + ids.iter() + .flat_map(|i| doc.subtree(*i)) + .filter_map(|i| doc.node(i)) + .filter(|n| n.visible && backdrop::has_effects(n)) + .map(|n| backdrop::pad(n, scale)) + .max() + }); + let beneath = match (page_layers, ids.first(), reach) { + (Some(layers), Some(first), Some(m)) => { + let m = i32::try_from(m).unwrap_or(0); + let p = f64::from(m) / scale; + let around = View { + origin: (b.x0 - p, b.y0 - p), + scale, + width: view.width.saturating_add(m.unsigned_abs() * 2), + height: view.height.saturating_add(m.unsigned_abs() * 2), + }; + backdrop::render_beneath(doc, layers, *first, &around).map(|back| (back, m)) + } + _ => None, + }; + let under = beneath.as_ref().map(|(back, m)| backdrop::Under::new(back, (*m, *m), None)); + nodes_into(doc, ids, &view, &mut pix, time, under.as_ref()); Some(pix) } @@ -518,6 +550,8 @@ mod boolean_budget_tests; #[cfg(test)] mod boolean_cache_tests; #[cfg(test)] +mod boolean_radius_tests; +#[cfg(test)] mod bounds_memo_tests; #[cfg(test)] mod dots_tests; diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 1a5719a9e..a003deb42 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -869,7 +869,7 @@ fn line_width(items: &[Item], (start, end, _, _): LineRange) -> f64 { /// to give a word to the lines after it ("keeps each line full, but adjusts the last four lines to /// avoid an orphan"). `rebreak` lays the text out again with a width per paragraph and line. fn restyle_breaks( - style: WrapStyle, + style_of: &dyn Fn(usize) -> WrapStyle, w: f64, lines: Vec, items: &[Item], @@ -905,7 +905,7 @@ fn restyle_breaks( } // Words wider than the box break where they must; the re-breaking adds no such break. let base = emergency_breaks(items, word_breaks, ¶); - match style { + match style_of(p) { WrapStyle::Auto => {} WrapStyle::Balance => { // The narrowest width that still gives `n` lines, to half a pixel. @@ -992,8 +992,8 @@ fn wrapped_lines( let lines = from_saved.or_else(|| breaks(&|_, _| wrap, None)).unwrap_or_default(); // Balance and Pretty re-break the paragraphs at narrower widths (never saved breaks). match wrap { - Some(w) if !followed && text.wrap_style != WrapStyle::Auto => { - restyle_breaks(text.wrap_style, w, lines, items, word_breaks, line_indent_of, hung_of, &|wrap_of| { + Some(w) if !followed && (0..text.paragraph_count()).any(|p| text.para_wrap_style(p) != WrapStyle::Auto) => { + restyle_breaks(&|p| text.para_wrap_style(p), w, lines, items, word_breaks, line_indent_of, hung_of, &|wrap_of| { breaks(wrap_of, None).unwrap_or_default() }) } diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index a11325d5b..fb3808d3d 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -122,6 +122,7 @@ name = "English" "Android Vector Drawable" = "Android Vector Drawable" "Angular" = "Angular" "Animation" = "Animation" +"Annotation" = "Annotation" "Annotations" = "Annotations" "Annotations shown on the canvas" = "Annotations shown on the canvas" "Another server, or one that needs its key. The usual server is set in Preferences." = "Another server, or one that needs its key. The usual server is set in Preferences." @@ -534,6 +535,9 @@ name = "English" "Edit padding on all sides" = "Edit padding on all sides" "Edit style" = "Edit style" "Edit variable" = "Edit variable" +"Edit variables" = "Edit variables" +"Scope" = "Scope" +"No scope is shared by all the selected variables" = "No scope is shared by all the selected variables" "Edit with the builder" = "Edit with the builder" "Edited {when}" = "Edited {when}" "Effect settings" = "Effect settings" @@ -883,6 +887,7 @@ name = "English" "Pasted design layers; the clipboard didn't carry the images of: {layers}" = "Pasted design layers; the clipboard didn't carry the images of: {layers}" "Remove these results from the file" = "Remove these results from the file" "Scroll wheel zoom" = "Scroll wheel zoom" +"Invert zoom direction" = "Invert zoom direction" "Shared by your team on {server}" = "Shared by your team on {server}" "Slot name" = "Slot name" "Mar" = "Mar" @@ -1886,6 +1891,7 @@ name = "English" "some vector segments refer to style settings missing from the file; they use the layer's stroke" = "some vector segments refer to style settings missing from the file; they use the layer's stroke" "stale or invalid grid track sizing entries were ignored" = "stale or invalid grid track sizing entries were ignored" "stars and polygons without point counts or geometry use the default point count" = "stars and polygons without point counts or geometry use the default point count" +"sticky layers import as frames with their text" = "sticky layers import as frames with their text" "style settings of some vector segments aren't supported; those segments use the layer's stroke" = "style settings of some vector segments aren't supported; those segments use the layer's stroke" "text path underline or strikethrough decoration is not rendered" = "text path underline or strikethrough decoration is not rendered" "text style overrides refer to missing table entries" = "text style overrides refer to missing table entries" diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index 16ec3350c..5a65c5524 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -22,6 +22,7 @@ status = "draft — needs native review" "Along the top" = "A lo largo del borde superior" "An earlier vote" = "Una votación anterior" "Android Vector Drawable" = "Android Vector Drawable" +"Annotation" = "Anotación" "Best effort" = "Mejor aproximación" "Between the selected layers" = "Entre las capas seleccionadas" "Brainstorm" = "Lluvia de ideas" @@ -35,6 +36,7 @@ status = "draft — needs native review" "Couldn't download the variables" = "No se pudieron descargar las variables" "Couldn't download {name}" = "No se pudo descargar {name}" "Create from color" = "Crear a partir del color" +"Invert zoom direction" = "Invertir la dirección del zoom" "New collection" = "Nueva colección" "Delete results" = "Eliminar resultados" "Pasted design layers" = "Capas de diseño pegadas" @@ -2215,6 +2217,7 @@ status = "draft — needs native review" "plugins.runLast" = "Ejecutar el último plugin" "pref.autoSave" = "Guardar archivos automáticamente" "pref.highlightHover" = "Resaltar capas al pasar el cursor" +"pref.invertZoom" = "Invertir la dirección del zoom" "pref.keepTool" = "Mantener la herramienta tras usarla" "pref.language" = "Idioma de la interfaz" "pref.nudge" = "Cantidad de desplazamiento" @@ -2366,6 +2369,7 @@ status = "draft — needs native review" "text.underline" = "Subrayado" "text.weightDown" = "Reducir peso de fuente" "text.weightUp" = "Aumentar peso de fuente" +"tool.annotation" = "Anotación" "tool.arrow" = "Flecha" "tool.comment" = "Comentario" "tool.connector" = "Conector" diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index 1f7dcf9af..a64458182 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -128,6 +128,7 @@ name = "Svenska" "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." "Any status" = "Valfri status" "Anyone on your network with this code can edit the file, while this app stays open." = "Alla i ditt nätverk som har den här koden kan redigera filen så länge appen är öppen." +"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Alla i ditt nätverk som har den här koden kan titta på filen, men inte ändra den, så länge appen är öppen." "Anyone with the edit link can change the file; the view link only lets people look. The links carry their secrets: share them like passwords. `figcraft-server links` makes more and revokes them." = "Alla med redigeringslänken kan ändra filen; visningslänken låter bara andra titta. Länkarna innehåller sina hemligheter: dela dem som lösenord. `figcraft-server links` skapar fler och återkallar dem." "Anyone with this code can edit the file." = "Alla med den här koden kan redigera filen." "Anyone with this code can look at the file, not change it." = "Alla med den här koden kan titta på filen, men inte ändra den." @@ -388,6 +389,8 @@ name = "Svenska" "Crop marks" = "Skärmärken" "Ctrl+arrows" = "Ctrl+piltangenter" "Ctrl+click" = "Ctrl+klick" +"Ctrl+click a padding field" = "Ctrl+klicka på ett padding-fält" +"⌘ click a padding field" = "⌘ klicka på ett padding-fält" "Ctrl+scroll" = "Ctrl+rullning" "Current name" = "Aktuellt namn" "Current version" = "Aktuell version" @@ -407,6 +410,40 @@ name = "Svenska" "Decoration style" = "Dekorationsstil" "Decoration" = "Dekoration" "Deep select" = "Djupmarkering" +"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Dragjustera ett fält snabbare (2x) eller långsammare (1/2, 1/4)" +"Move up or down while dragging its label" = "Flytta upp eller ned medan du drar dess etikett" +"Scrubbing at 2x" = "Dragjustering med 2x hastighet" +"Scrubbing at 1x" = "Dragjustering med 1x hastighet" +"Scrubbing at 1/2" = "Dragjustering med 1/2 hastighet" +"Scrubbing at 1/4" = "Dragjustering med 1/4 hastighet" +"Delete {n} variables" = { one = "Radera {n} variabel", other = "Radera {n} variabler" } +"Move out of any group" = "Flytta ut ur alla grupper" +"Move to group {group}" = "Flytta till gruppen {group}" +"Scope: all supported properties" = "Omfång: alla egenskaper som stöds" +"Scope: hidden from pickers" = "Omfång: dold i väljare" +"Scope: only {scope}" = "Omfång: endast {scope}" +"Disconnected. Reconnecting…" = "Frånkopplad. Återansluter…" +"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Frånkopplad. Dina redigeringar finns kvar här och synkas när anslutningen är tillbaka. Återansluter…" +"Dismiss" = "Stäng" +"Not connected: {reason}. Your work is still in this tab." = "Inte ansluten: {reason}. Ditt arbete finns kvar i den här fliken." +"Retry now" = "Försök igen nu" +"Save a copy…" = "Spara en kopia…" +"Wrap style" = "Radbrytningsstil" +"Text direction" = "Textriktning" +"Auto: by the first letter with a direction" = "Auto: efter den första bokstaven som har en riktning" +"Left to right" = "Vänster till höger" +"Right to left" = "Höger till vänster" +"Balance" = "Balans" +"Pretty" = "Snygg" +"Auto: as many words as fit on each line" = "Auto: så många ord som får plats på varje rad" +"Balance: every line close to the same length" = "Balans: alla rader ungefär lika långa" +"Pretty: full lines, no one word alone on the last" = "Snygg: fulla rader, inget ensamt ord på den sista" +"Set hug contents" = "Ställ in Omslut innehåll" +"Set fill container" = "Ställ in Fyll behållaren" +"Double-click an edge of an auto layout frame" = "Dubbelklicka på en kant av en auto layout-frame" +"{name}, disconnected from its live session" = "{name}, frånkopplad från sin livesession" +"⌥ double-click an edge of an auto layout child" = "⌥ dubbelklicka på en kant av ett underordnat objekt i auto layout" +"Alt+double-click an edge of an auto layout child" = "Alt+dubbelklicka på en kant av ett underordnat objekt i auto layout" "Default" = "Standard" "Default content" = "Standardinnehåll" "Default value (the top-left variant)" = "Standardvärde (varianten längst upp till vänster)" @@ -494,6 +531,7 @@ name = "Svenska" "Edit dev resource" = "Redigera utvecklarresurs" "Edit link" = "Redigeringslänk" "Edit link copied" = "Redigeringslänken har kopierats" +"Edit padding on all sides" = "Redigera padding på alla sidor" "Edit style" = "Redigera stil" "Edit variable" = "Redigera variabel" "Edit with the builder" = "Redigera med byggaren" @@ -531,6 +569,7 @@ name = "Svenska" "Exclusion" = "Uteslutning" "Exit focus view (Esc)" = "Lämna fokusvyn (Esc)" "Expand" = "Expandera" +"Expand the interface" = "Expandera gränssnittet" "Export" = "Exportera" "Export all" = "Exportera alla" "Export frames and layers as PNG, JPG, SVG or PDF" = "Exportera frames och lager som PNG, JPG, SVG eller PDF" @@ -1073,6 +1112,7 @@ name = "Svenska" "Pages: {pages}" = "Sidor: {pages}" "Paint bucket" = "Färghink" "Pan the canvas" = "Panorera arbetsytan" +"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Visa och flytta placeringshårkorset (med dess verktyg valt och inget markerat)" "Pan with nothing selected (Shift: farther)" = "Panorera när inget är markerat (Shift: längre)" "Panels" = "Paneler" "Paper" = "Papper" @@ -1297,6 +1337,7 @@ name = "Svenska" "See all templates" = "Se alla mallar" "Select layers and they space themselves as their content changes" = "Markera lager så fördelar de avståndet själva när innehållet ändras" "SHA-256: {sha}…" = "SHA-256: {sha}…" +"Same as file ({profile})" = "Samma som filen ({profile})" "Same as layer" = "Samma som lagret" "Saturation" = "Mättnad" "Save" = "Spara" @@ -1969,6 +2010,17 @@ name = "Svenska" "⌘ click" = "⌘ klicka" "⌘ scroll" = "⌘ rulla" "⌥ drag" = "⌥ dra" +"Selection box: switch to pick select" = "Markeringsruta: växla till plockmarkering" +"Pick select: next or previous layer" = "Plockmarkering: nästa eller föregående lager" +"Pick select: into a layer, out to its parent" = "Plockmarkering: in i ett lager, ut till dess överordnade" +"Pick select: select the picked layer" = "Plockmarkering: markera det valda lagret" +"⇥ or ⌥ Space again" = "⇥ eller ⌥ Blanksteg igen" +"Tab or Ctrl+Space again" = "Tab eller Ctrl+Blanksteg igen" +"↵ / ⇧↵" = "↵ / ⇧↵" +"Enter / Shift+Enter" = "Enter / Shift+Enter" +"Space" = "Blanksteg" +"Nothing to pick: the page is empty" = "Inget att välja: sidan är tom" +"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Plockmarkering: Tab och Shift+Tab flyttar mellan lager, Enter går in i ett, Shift+Enter ut, Blanksteg markerar, Esc avbryter" [commands] @@ -2005,6 +2057,7 @@ name = "Svenska" "board.label" = "Kopplingsetikett" "board.nextSticky" = "Nästa lapp" "board.reattach" = "Koppla om koppling" +"board.reshape" = "Omforma koppling" "board.setColor" = "Whiteboardfärg" "board.setStyle" = "Whiteboardstil" "board.shape" = "Form med text" @@ -2047,6 +2100,7 @@ name = "Svenska" "collab.openFile" = "Öppna onlinefil" "collab.peers" = "Personer i den här filen" "collab.publish" = "Publicera på server" +"collab.reconnect" = "Återanslut livesessionen" "collab.recoverFile" = "Återställ onlinefil" "collab.registerLinks" = "Öppna inbjudningslänkar i FigCraft" "collab.removePerson" = "Ta bort från session" @@ -2195,6 +2249,7 @@ name = "Svenska" "image.deletePreset" = "Radera förinställning" "image.place" = "Placera bild" "image.presets" = "Bildförinställningar" +"image.replace" = "Ersätt bild" "image.savePreset" = "Spara förinställning" "inspect.assets" = "Resurser" "inspect.code" = "Kod" @@ -2212,6 +2267,7 @@ name = "Svenska" "layers.collapseAll" = "Fäll ihop alla" "layout.add" = "Lägg till auto layout" "layout.remove" = "Ta bort auto layout" +"layout.removeAll" = "Ta bort all auto layout" "layout.setTrack" = "Ange spår" "layout.suggest" = "Föreslå layout" "libraries.open" = "Öppna bibliotek" @@ -2306,6 +2362,9 @@ name = "Svenska" "pref.showDimensions" = "Visa dimensioner på objekt" "pref.startOnHome" = "Börja på Start" "pref.uiScale" = "Gränssnittsstorlek" +"pref.uiScaleDown" = "Mindre gränssnitt" +"pref.uiScaleReset" = "Standardstorlek för gränssnittet" +"pref.uiScaleUp" = "Större gränssnitt" "pref.userName" = "Ditt namn" "proto.action.add" = "Lägg till prototypåtgärd" "proto.action.move" = "Ändra ordning på prototypåtgärd" @@ -2353,6 +2412,7 @@ name = "Svenska" "selection.applyColorStyle" = "Använd färgformatmall på markeringen" "selection.bindColorVariable" = "Använd färgvariabel på markeringen" "selection.colors" = "Markeringsfärger" +"selection.createColorStyle" = "Skapa färgstil från markeringen" "selection.detachColor" = "Koppla bort markeringsfärg" "selection.selectColor" = "Markera lager med den här färgen" "selection.setPaint" = "Ändra markeringens färg" @@ -2399,6 +2459,10 @@ name = "Svenska" "text.caseUpper" = "Versaler" "text.create" = "Text" "text.decoration" = "Dekoration" +"text.direction" = "Textriktning" +"text.directionAuto" = "Textriktning: auto" +"text.directionLtr" = "Textriktning: vänster till höger" +"text.directionRtl" = "Textriktning: höger till vänster" "text.edit.begin" = "Redigera text" "text.edit.caret" = "Placera markören" "text.edit.end" = "Sluta redigera text" @@ -2423,6 +2487,7 @@ name = "Svenska" "text.missingFonts" = "Saknade typsnitt" "text.numberList" = "Numrerad lista" "text.onPath" = "Text på bana" +"text.openLink" = "Öppna länk" "text.paragraphIndent" = "Styckeindrag" "text.paragraphSpacing" = "Styckeavstånd" "text.pathOptions" = "Alternativ för textbana" @@ -2442,9 +2507,11 @@ name = "Svenska" "text.underline" = "Understrykning" "text.weightDown" = "Minska teckenvikten" "text.weightUp" = "Öka teckenvikten" +"text.wrapStyle" = "Radbrytningsstil" "tool.arrow" = "Pil" "tool.comment" = "Kommentar" "tool.connector" = "Koppling" +"tool.crosshair" = "Flytta placeringshårkorset" "tool.ellipse" = "Ellips" "tool.eraser" = "Suddgummi" "tool.frame" = "Frame" @@ -2488,6 +2555,7 @@ name = "Svenska" "variable.deleteCollection" = "Radera samling" "variable.duplicate" = "Duplicera variabel" "variable.export" = "Exportera variabler" +"variable.extendCollection" = "Utöka samlingen" "variable.import" = "Importera variabler" "variable.list" = "Lista variabler" "variable.moveMode" = "Flytta läge" @@ -2561,6 +2629,7 @@ name = "Svenska" "view.layoutGrids" = "Layoutrutnät" "view.leftSidebar" = "Visa/dölj vänster sidofält" "view.maskOutlines" = "Konturlinjer för masker" +"view.minimize" = "Minimera gränssnittet" "view.multiplayerCursors" = "Samarbetsmarkörer" "view.nextFrame" = "Zooma till nästa frame" "view.nextPage" = "Nästa sida" diff --git a/crates/ui-egui/locales/ta.toml b/crates/ui-egui/locales/ta.toml index 6ae9473ec..1fe649d13 100644 --- a/crates/ui-egui/locales/ta.toml +++ b/crates/ui-egui/locales/ta.toml @@ -1575,7 +1575,6 @@ status = "draft — needs native review" "Texts" = "உரைகள்" "Texture" = "அமைப்பு" "The bars are hidden. {shortcut} shows them again" = "பட்டைகள் மறைக்கப்பட்டுள்ளன. {shortcut} அவற்றை மீண்டும் காட்டும்" -"The canvas previews colors in sRGB; exported PNG, JPG and WebP files are tagged Display P3." = "கேன்வாஸ் நிறங்களை sRGB இல் காட்டுகிறது; ஏற்றுமதி செய்த PNG, JPG, WebP கோப்புகள் Display P3 எனக் குறிக்கப்படும்." "The destination document is unavailable. Nothing was imported." = "இலக்கு ஆவணம் கிடைக்கவில்லை. எதுவும் இறக்குமதி செய்யப்படவில்லை." "The destination document was closed. Nothing was imported." = "இலக்கு ஆவணம் மூடப்பட்டது. எதுவும் இறக்குமதி செய்யப்படவில்லை." "The destination page was removed. Nothing was imported." = "இலக்குப் பக்கம் அகற்றப்பட்டது. எதுவும் இறக்குமதி செய்யப்படவில்லை." diff --git a/crates/ui-egui/src/a11y.rs b/crates/ui-egui/src/a11y.rs index 502452765..d0e34d6fe 100644 --- a/crates/ui-egui/src/a11y.rs +++ b/crates/ui-egui/src/a11y.rs @@ -883,9 +883,17 @@ pub fn tab(resp: &Response, label: &str, selected: bool) { } pub fn checkbox(resp: &Response, label: &str, on: bool) { + checkbox_tri(resp, label, Some(on)); +} + +/// A checkbox that can be mixed (`None`, announced as "mixed" rather than unchecked). +pub fn checkbox_tri(resp: &Response, label: &str, state: Option) { node(resp, label, |n| { n.set_role(Role::CheckBox); - n.set_toggled(toggled(on)); + n.set_toggled(match state { + Some(on) => toggled(on), + None => Toggled::Mixed, + }); }); } diff --git a/crates/ui-egui/src/a11y_tests.rs b/crates/ui-egui/src/a11y_tests.rs index 14be637dd..941f5854b 100644 --- a/crates/ui-egui/src/a11y_tests.rs +++ b/crates/ui-egui/src/a11y_tests.rs @@ -431,3 +431,80 @@ fn the_custom_panel_edges_never_enter_the_keyboard_or_focus_order() { } assert!(!seen.contains(&left) && !seen.contains(&right), "Tab never stops on a panel edge: {seen:?}"); } + +#[test] +fn a_mixed_checkbox_is_announced_as_mixed_and_a_checked_one_as_true() { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + crate::widgets::checkbox_tri(ui, None, "Mixed one"); + crate::widgets::checkbox_tri(ui, Some(true), "Checked one"); + crate::widgets::checkbox_tri(ui, Some(false), "Plain one"); + }); + out.textures_delta.clear(); + let nodes: Vec = out.platform_output.accesskit_update.expect("an AccessKit update").nodes.into_iter().map(|(_, n)| n).collect(); + assert_eq!(find(&nodes, Role::CheckBox, "Mixed one").toggled(), Some(Toggled::Mixed)); + assert_eq!(find(&nodes, Role::CheckBox, "Checked one").toggled(), Some(Toggled::True)); + assert_eq!(find(&nodes, Role::CheckBox, "Plain one").toggled(), Some(Toggled::False)); +} + +/// Runs one headless frame of a lone tri-state checkbox; returns whether it was clicked. +fn tri_frame(ctx: &egui::Context, state: Option, events: Vec) -> bool { + let mut clicked = false; + let input = egui::RawInput { events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + clicked = crate::widgets::checkbox_tri(ui, state, "Keyed one"); + }); + out.textures_delta.clear(); + clicked +} + +fn key(key: Key, pressed: bool) -> Event { + Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE } +} + +#[test] +fn a_checkbox_is_keyboard_operable_tab_to_it_then_space_or_enter_toggles_it() { + for activate in [Key::Space, Key::Enter] { + let ctx = egui::Context::default(); + tri_frame(&ctx, Some(false), vec![]); + tri_frame(&ctx, Some(false), vec![key(Key::Tab, true), key(Key::Tab, false)]); + assert!(ctx.memory(|m| m.focused()).is_some(), "Tab focuses the checkbox"); + tri_frame(&ctx, Some(false), vec![]); + let clicked = tri_frame(&ctx, Some(false), vec![key(activate, true), key(activate, false)]); + assert!(clicked, "{activate:?} on the focused checkbox toggles it"); + } +} + +/// The marks (paths, meshes, segments) painted inside the 14-point box of a lone checkbox. +fn box_marks(state: Option) -> Vec { + fn walk(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + egui::Shape::Path(_) | egui::Shape::Mesh(_) | egui::Shape::LineSegment { .. } => out.push(s.visual_bounding_rect()), + _ => {} + } + } + let ctx = egui::Context::default(); + let mut out = Vec::new(); + for _ in 0..2 { + let mut o = ctx.run_ui(egui::RawInput::default(), |ui| { + crate::widgets::checkbox_tri(ui, state, "Painted one"); + }); + o.textures_delta.clear(); + out.clear(); + o.shapes.iter().for_each(|c| walk(&c.shape, &mut out)); + } + out +} + +#[test] +fn a_mixed_checkbox_paints_a_dash_and_a_checked_one_a_tick() { + // Icon::Minus is one flat bar; Icon::Check is a taller path. + let mixed = box_marks(None); + assert!(mixed.iter().any(|r| r.width() >= 5.0 && r.height() <= 2.5), "a flat dash is painted for the mixed state: {mixed:?}"); + let checked = box_marks(Some(true)); + assert!(checked.iter().any(|r| r.width() >= 5.0 && r.height() > 3.5), "a tick is painted for the checked state: {checked:?}"); + assert!(!checked.iter().any(|r| r.width() >= 5.0 && r.height() <= 2.5), "no dash on a checked box: {checked:?}"); + assert!(box_marks(Some(false)).is_empty(), "an empty box paints no mark"); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 45dc80f09..537dea1e6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -22,7 +22,11 @@ impl FigApp { /// state. pub fn new(session: Session, services: Box) -> Self { // The main window's panels open as wide as they were left. + // Widths saved under other limits are clamped to the current ones, not rejected; one that + // isn't finite falls back to the default. let (left_width, right_width) = session.prefs.panel_widths; + let within = |w: f32, range: std::ops::RangeInclusive| if w.is_finite() { w.clamp(*range.start(), *range.end()) } else { PANEL_DEFAULT }; + let (left_width, right_width) = (within(left_width, LEFT_PANEL), within(right_width, RIGHT_PANEL)); let pages_height = session.prefs.pages_height; Self { ui: UiState { left_width, right_width, pages_height, ..UiState::default() }, @@ -302,6 +306,8 @@ impl FigApp { self.ui.narrow = narrow; // A narrow window shows the right panel when its button asks for it, a board's too. let right_open = (self.right_panel_shown(hidden) && !narrow && !right_minimized) || mobile == Some(MobilePanel::Right); + // A highlighted fill, stroke or effect row goes with the panel it's in, before it draws. + crate::property_rows::reconcile(self, &ctx, right_open); // A right-to-left UI language mirrors the window: the "left" rail and panel go on the // right, the "right" (Design) panel on the left. Their ids and widths stay as they are. let mirrored = self.ui.mirrored; diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index abca326e5..e36471b42 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -266,6 +266,18 @@ impl FigApp { self.ui.comments.show(id); } } + "annotation.new" => { + // The Annotation tool: show the Inspect tab (never toggle it away) and put the + // caret in the layer's new-note field. + // Only a selected layer's field can show; a request for anything else would wait + // and take the keyboard later. + let shown = + |id| self.session.selection().contains(&id) && self.session.doc().is_ok_and(|d| d.node(id).is_some_and(|n| !n.is_page())); + if let Some(id) = r.data.get("id").and_then(figcraft_engine::params::id_of).filter(|id| shown(*id)) { + self.ui.right_tab = RightTab::Inspect; + self.ui.dev.focus_new_note = Some(id); + } + } "comment.new" => { let x = r.data.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0); let y = r.data.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 02d0415ff..51507b0a5 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 background; mod builder; mod input; mod outline; @@ -339,15 +340,20 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_seq = done.seq; } let painter = ui.painter_at(rect); - painter.rect_filled(rect, CornerRadius::ZERO, bg); crate::theme::set_canvas_page(&ctx, bg); - if let (Some(tex), Some(v), true) = (&app.canvas.texture, &app.canvas.tex_view, shown.is_some() && app.canvas.tex_of == shown) { + let image = if let (Some(tex), Some(v), true) = (&app.canvas.texture, &app.canvas.tex_view, shown.is_some() && app.canvas.tex_of == shown) { // Re-project the last render onto the current view. let tl = app.to_screen(v.origin.0, v.origin.1); let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0); let pixel_preview = app.session.ds().ok().and_then(|ds| ds.view.pixel_preview_scale()) == Some(v.scale); let image_rect = presented_image_rect(tl, v, zoom, ppp, pixel_preview); - painter.image(tex.id(), image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + Some((tex.id(), image_rect)) + } else { + None + }; + background::paint(&painter, rect, bg, image.map(|(_, r)| r)); + 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); } crate::dev_mode::refresh_measurements(app); app.session.tool.labels = overlays(app, &painter, &t); diff --git a/crates/ui-egui/src/canvas/background.rs b/crates/ui-egui/src/canvas/background.rs new file mode 100644 index 000000000..f7eadd640 --- /dev/null +++ b/crates/ui-egui/src/canvas/background.rs @@ -0,0 +1,230 @@ +//! The transparency grid behind the page; rendered pixels already contain the page colour. + +use egui::{Color32, CornerRadius, Id, Painter, Rect, TextureHandle, pos2}; + +/// Reuse the checkerboard texture, updating its pixels when the active theme changes. +fn grid_texture(ctx: &egui::Context) -> TextureHandle { + let id = Id::unique("canvas_transparency_grid"); + let tokens = crate::theme::Tokens::get(ctx); + let colors = [tokens.panel, tokens.canvas]; + let cached = ctx.data(|data| data.get_temp::<(TextureHandle, [Color32; 2])>(id)); + if let Some((texture, old_colors)) = &cached + && *old_colors == colors + { + return texture.clone(); + } + let image = egui::ColorImage::new([2, 2], vec![colors[0], colors[1], colors[1], colors[0]]); + let texture = match cached { + Some((mut texture, _)) => { + texture.set(image, egui::TextureOptions::NEAREST_REPEAT); + texture + } + None => ctx.load_texture("canvas-transparency", image, egui::TextureOptions::NEAREST_REPEAT), + }; + ctx.data_mut(|data| data.insert_temp(id, (texture.clone(), colors))); + 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) { + 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 { + Some(r) => [ + Rect::from_min_max(rect.min, pos2(rect.right(), r.top())), + Rect::from_min_max(pos2(rect.left(), r.bottom()), rect.max), + Rect::from_min_max(pos2(rect.left(), r.top()), r.left_bottom()), + Rect::from_min_max(r.right_top(), pos2(rect.right(), r.bottom())), + ], + 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); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::{Mesh, TextureId, vec2}; + + /// Paint a small canvas and consume its texture uploads as the UI harness does. + 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); + }); + out.textures_delta.clear(); + out + } + + /// Fixed canvas bounds make clipping and uncovered-area checks independent of UI layout. + fn canvas() -> Rect { + Rect::from_min_size(egui::Pos2::ZERO, vec2(100.0, 100.0)) + } + + /// Check the actual checkerboard quad, including clipping and its screen-sized UV mapping. + fn assert_grid(out: &egui::FullOutput, tile: TextureId, rect: Rect) -> usize { + let meshes: Vec<_> = out + .shapes + .iter() + .enumerate() + .filter_map(|(index, shape)| match &shape.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id == tile => Some((index, shape.clip_rect, mesh)), + _ => None, + }) + .collect(); + assert_eq!(meshes.len(), 1, "one checkerboard covers the canvas"); + let (index, clip, mesh) = meshes[0]; + assert_eq!(mesh.calc_bounds(), rect); + assert!(clip.contains_rect(rect), "the whole checkerboard is visible"); + assert_eq!(mesh.vertices.len(), 4); + for vertex in &mesh.vertices { + let expected = (vertex.pos - rect.min) / 16.0; + assert!((vertex.uv.to_vec2() - expected).length() < 0.001, "UVs keep the squares at a fixed screen size"); + } + index + } + + /// Assert strips have the correct colour and partition exactly the area outside the render. + fn assert_partition(alpha: u8, rendered: Option) { + let out = shapes(alpha, rendered); + let fills: Vec<_> = out + .shapes + .iter() + .enumerate() + .filter_map(|(index, s)| match &s.shape { + egui::Shape::Rect(r) => Some((index, r)), + _ => None, + }) + .collect(); + let covered = rendered.map(|r| r.intersect(canvas())).filter(|r| r.is_positive()); + let background = Color32::from_rgba_unmultiplied(255, 0, 0, alpha); + for (i, (_, strip)) in fills.iter().enumerate() { + assert_eq!(strip.fill.a(), alpha, "each fallback strip applies alpha exactly once"); + assert_eq!(strip.fill, background, "the fallback keeps the page colour too"); + assert!(strip.rect.is_positive() && canvas().contains_rect(strip.rect)); + if let Some(covered) = covered { + assert!(!strip.rect.intersect(covered).is_positive(), "no fallback beneath rendered pixels"); + } + for (_, other) in fills.iter().skip(i + 1) { + assert!(!strip.rect.intersect(other.rect).is_positive(), "fallback strips do not overlap"); + } + } + let area: f32 = fills.iter().map(|(_, strip)| strip.rect.area()).sum(); + assert_eq!(area, canvas().area() - covered.map_or(0.0, |r| r.area()), "no uncovered gaps"); + if covered == Some(canvas()) { + assert!(fills.is_empty(), "full coverage needs no fallback fills"); + } + let meshes: Vec<&Mesh> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Mesh(mesh) => Some(mesh.as_ref()), + _ => None, + }) + .collect(); + if alpha < 255 { + assert_eq!(meshes.len(), 1); + let index = assert_grid(&out, meshes[0].texture_id, canvas()); + assert!(fills.iter().all(|(fill_index, _)| *fill_index > index), "the grid is behind every fallback strip"); + } else { + assert!(meshes.is_empty(), "opaque pages need no checkerboard"); + } + } + + /// Exercise the real canvas with a render present, checking the grid covers it and draws first. + #[test] + fn the_canvas_draws_the_transparency_grid_for_a_transparent_page() { + let mut ui = crate::layers_drag_tests::Ui::new(figcraft_engine::Session::new()); + ui.app.run("page.setBackground", serde_json::json!({"color": "#FF000000"})); + let ds = ui.app.session.ds().unwrap(); + let shown = (ds.uid, ds.page); + // Seed an image so this test does not depend on when the asynchronous worker finishes. + ui.app.canvas.texture = + Some(ui.ctx.load_texture("test-page-render", egui::ColorImage::filled([16, 16], Color32::TRANSPARENT), egui::TextureOptions::NEAREST)); + ui.app.canvas.tex_view = Some(figcraft_render::View { origin: (0.0, 0.0), scale: 1.0, width: 16, height: 16 }); + ui.app.canvas.tex_of = Some(shown); + let out = ui.frame_output(vec![]); + let (tile, _) = + ui.ctx.data(|d| d.get_temp::<(TextureHandle, [Color32; 2])>(Id::unique("canvas_transparency_grid"))).expect("the canvas checkerboard"); + let grid_index = assert_grid(&out, tile.id(), ui.app.canvas.rect); + let rendered = ui.app.canvas.texture.as_ref().unwrap().id(); + let render_index = + out.shapes.iter().position(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id == rendered)).expect("the rendered page"); + assert!(grid_index < render_index, "the checkerboard is behind the rendered page"); + } + + /// Theme changes must reach drawing, update the pixels used by its mesh and reuse the texture. + #[test] + fn the_grid_updates_its_colours_when_the_theme_changes() { + let ctx = egui::Context::default(); + 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 (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()); + assert!(out.shapes.iter().enumerate().all(|(index, s)| !matches!(&s.shape, egui::Shape::Rect(_)) || index > grid_index)); + if let Some(previous_id) = previous_id { + assert_eq!(tile.id(), previous_id, "changing theme updates the same texture"); + } + let delta = out.textures_delta.set.get(&tile.id()).and_then(|d| d.first()).expect("updated checkerboard pixels"); + let egui::ImageData::Color(image) = &delta.image; + assert_eq!(image.pixels, [tokens.panel, tokens.canvas, tokens.canvas, tokens.panel]); + previous_id = Some(tile.id()); + out.textures_delta.clear(); + } + } + + /// Interior, edge-straddling and fully covering renders must all apply the page alpha once. + #[test] + fn translucent_pages_show_the_grid_without_applying_page_alpha_twice() { + let renders = [ + Rect::from_min_max(pos2(20.0, 20.0), pos2(80.0, 80.0)), + Rect::from_min_max(pos2(-20.0, 20.0), pos2(80.0, 80.0)), + Rect::from_min_max(pos2(20.0, -20.0), pos2(80.0, 80.0)), + Rect::from_min_max(pos2(20.0, 20.0), pos2(120.0, 80.0)), + Rect::from_min_max(pos2(20.0, 20.0), pos2(80.0, 120.0)), + Rect::from_min_max(pos2(-20.0, -20.0), pos2(80.0, 80.0)), + canvas(), + Rect::from_min_max(pos2(-20.0, -20.0), pos2(120.0, 120.0)), + ]; + for alpha in [0, 128, 255] { + for rendered in renders { + assert_partition(alpha, Some(rendered)); + } + } + } + + /// Missing, offscreen and merely edge-touching images leave exactly one fallback page fill. + #[test] + fn absent_or_offscreen_renders_fill_the_page_once() { + for rendered in + [None, Some(Rect::from_min_size(pos2(200.0, 200.0), vec2(10.0, 10.0))), Some(Rect::from_min_max(pos2(-20.0, 20.0), pos2(0.0, 80.0)))] + { + for alpha in [0, 128, 255] { + assert_partition(alpha, rendered); + let out = shapes(alpha, rendered); + let fills: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Rect(r) => Some(r), + _ => None, + }) + .collect(); + assert_eq!(fills.len(), 1); + assert_eq!(fills[0].rect, canvas()); + } + } + } +} diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index dec2a1b31..d518dde37 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -1,7 +1,7 @@ //! The pointer on the canvas: each engine cursor ([`figcraft_engine::tools::Cursor`]) as one of //! the system's cursors, or as a small glyph FigCraft draws at the pointer with the system's //! hidden (a rotate cursor turned to its corner, the pen's states, the eyedropper, the comment -//! pin). The glyphs are original, drawn from lines and the code-drawn icons: no cursor images. +//! pin, the crosshair of the shape and Text tools). The glyphs are original, drawn from lines and the code-drawn icons: no cursor images. use egui::{Color32, CursorIcon, Painter, Pos2, Shape, Stroke, pos2, vec2}; use figcraft_engine::tools::{Cursor, PenCursor}; @@ -17,6 +17,9 @@ pub enum Glyph { Pen(PenCursor), Eyedropper, Comment, + /// A plus open at the centre, for the shape and Text tools (the system's follows the + /// system's pointer colour, and a white one is lost on a white frame). + Crosshair, } /// What the pointer shows. @@ -46,7 +49,7 @@ pub fn of(cursor: Cursor) -> Shown { use Shown::{Drawn, System}; match cursor { Cursor::Default => System(CursorIcon::Default), - Cursor::Crosshair => System(CursorIcon::Crosshair), + Cursor::Crosshair => Drawn(Glyph::Crosshair), Cursor::Move => System(CursorIcon::Move), Cursor::Resize(a) if a.is_finite() => System(resize_icon(a)), Cursor::Resize(_) => System(CursorIcon::Default), @@ -85,7 +88,7 @@ impl Shown { /// A name for it (`ui.inspect`): the CSS cursor names where there is one ("default", /// "nwse-resize", "copy"), and "rotate" (with its angle), "pen", "pen-close", "pen-add", - /// "pen-bend", "eyedropper" and "comment" for the drawn ones. + /// "pen-bend", "eyedropper", "comment" and "crosshair" for the drawn ones. pub fn name(self) -> String { match self { Shown::System(i) => match i { @@ -114,6 +117,7 @@ impl Shown { Shown::Drawn(Glyph::Pen(PenCursor::Bend)) => "pen-bend".into(), Shown::Drawn(Glyph::Eyedropper) => "eyedropper".into(), Shown::Drawn(Glyph::Comment) => "comment".into(), + Shown::Drawn(Glyph::Crosshair) => "crosshair".into(), } } @@ -127,7 +131,7 @@ impl Shown { } /// Dark lines over a light edge: readable on any page and artwork. -const INK: Color32 = Color32::from_rgb(0x1E, 0x1E, 0x1E); +pub(crate) const INK: Color32 = Color32::from_rgb(0x1E, 0x1E, 0x1E); const EDGE: Color32 = Color32::WHITE; /// A line through `pts` with the light edge under it. @@ -167,6 +171,22 @@ pub fn paint(painter: &Painter, at: Pos2, glyph: Glyph) { line(painter, &[tip - t * 4.5 + n * 3.5, tip + t * 1.0, tip - t * 4.5 - n * 3.5]); } } + Glyph::Crosshair => { + // A plus centred on the pointer, open at the centre so its pixel stays visible; the + // light edge goes under both arms of each line first, then the dark line on top. + let arms = [ + (vec2(-8.0, 0.0), vec2(-2.0, 0.0)), + (vec2(2.0, 0.0), vec2(8.0, 0.0)), + (vec2(0.0, -8.0), vec2(0.0, -2.0)), + (vec2(0.0, 2.0), vec2(0.0, 8.0)), + ]; + for (a, b) in arms { + painter.add(Shape::line_segment([at + a, at + b], Stroke::new(3.0, EDGE))); + } + for (a, b) in arms { + painter.add(Shape::line_segment([at + a, at + b], Stroke::new(1.0, INK))); + } + } Glyph::Pen(state) => { // A cross open at the centre (the point it lands on stays visible), and what a click // does at its lower right. diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 5187fe866..b4cff10aa 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -81,10 +81,18 @@ fn wheel_zoom(app: &mut FigApp, ctx: &egui::Context, zoom: f32, shift: bool) -> if let Some(mouse) = latest { app.canvas.wheel_is_mouse = mouse; } + let invert = app.session.prefs.invert_zoom && !pinch; if !app.session.prefs.scroll_wheel_zoom || !app.canvas.wheel_is_mouse || pinch { - return (wheel, zoom); + return (wheel, if invert { invert_zoom_factor(zoom) } else { zoom }); } - swap_wheel(wheel, zoom, shift, speed) + let (scroll, zoom) = swap_wheel(wheel, zoom, shift, speed); + (scroll, if invert { invert_zoom_factor(zoom) } else { zoom }) +} + +/// The zoom factor for the opposite direction (Preferences ▸ Invert zoom direction): its +/// reciprocal. A factor that is zero, negative or not finite is left as it is. +pub(crate) fn invert_zoom_factor(zoom: f32) -> f32 { + if zoom.is_finite() && zoom > 0.0 { 1.0 / zoom } else { zoom } } /// Whether a scroll event came from a mouse wheel. Only macOS says which device scrolled; elsewhere diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index f4ce8cce0..3e15693f9 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -209,6 +209,61 @@ fn layout_grids(app: &FigApp, painter: &egui::Painter, doc: &Document, c: NodeId } } +/// The solid colour of the fill the next typed character gets (the character before the caret, +/// the first one's at 0, the base style for an empty text): the style's own fills when it has +/// them, else the layer's. `None` when the topmost visible paint isn't a solid (gradient, image, +/// no visible fill), so the caller uses [`caret_fallback`]. Opaque on purpose: Figma's caret +/// is one colour, and the fill's and paint's opacity weren't measured, so it must stay visible. +fn caret_fill(n: &figcraft_doc::Node, caret: usize) -> Option { + let t = n.kind.text()?; + let style = t.style_at(caret.saturating_sub(1)); + let paints = style.fills.as_ref().unwrap_or(&n.fills); + paints.iter().rev().find(|p| p.visible).and_then(|p| match &p.kind { + figcraft_color::PaintKind::Solid { color } => Some(color.with_alpha(1.0)), + _ => None, + }) +} + +/// [`caret_fill`] as a screen colour. +fn caret_color(ctx: &egui::Context, n: &figcraft_doc::Node, caret: usize) -> Option { + caret_fill(n, caret).map(|c| doc_c32(ctx, c)) +} + +/// The caret of a text without a solid fill (a gradient, an image, no visible fill): black on a +/// light surface, white on a dark one. The surface is the nearest layer around the text whose +/// topmost visible fill is a solid at least half opaque as drawn (its colour's alpha times its paint's +/// opacity times its own and its containers' 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 +/// vanishes on the default light page (#2190). +fn caret_fallback(doc: &Document, id: NodeId) -> Color32 { + let chain = doc.ancestors(id); + // Each layer's opacity as drawn: its own times every container's above it. + let drawn: Vec = { + let mut acc = 1.0f32; + let mut out: Vec = chain + .iter() + .rev() + .map(|a| { + acc *= doc.node(*a).map_or(1.0, |n| if n.opacity.is_finite() { n.opacity.clamp(0.0, 1.0) } else { 1.0 }); + acc + }) + .collect(); + out.reverse(); + out + }; + let under = chain.iter().zip(drawn).find_map(|(a, alpha)| { + let n = doc.node(*a)?; + match &n.kind { + NodeKind::Page { background, .. } => Some(*background), + _ => n.fills.iter().rev().find(|p| p.visible).and_then(|p| match &p.kind { + figcraft_color::PaintKind::Solid { color } if color.a * p.opacity * alpha >= 0.5 => Some(*color), + _ => None, + }), + } + }); + if under.is_some_and(|c| c.is_dark()) { Color32::WHITE } else { Color32::BLACK } +} + fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Document, te: &figcraft_engine::TextEdit, zoom: f64) { let preedit = app.preedit_view(); let edoc: &Document = preedit.map(|p| &*p.doc).unwrap_or(doc); @@ -242,7 +297,8 @@ fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Do let caret = preedit.map(|p| p.cursor).unwrap_or(te.caret); let blink = (painter.ctx().input(|i| i.time) * 2.0) as i64 % 2 == 0; if blink || a != b { - painter.line_segment(text.caret(app, caret, zoom), stroke(t.text, 1.0)); + let col = edoc.node(te.id).and_then(|n| caret_color(painter.ctx(), n, caret)).unwrap_or_else(|| caret_fallback(edoc, te.id)); + painter.line_segment(text.caret(app, caret, zoom), stroke(col, 1.0)); } painter.ctx().request_repaint_after(std::time::Duration::from_millis(500)); } @@ -782,3 +838,99 @@ fn pick_outline(app: &FigApp, painter: &egui::Painter, doc: &Document) { draw_outline(app, painter, doc, p, stroke(crate::handles::PINK, 2.0)); } } + +#[cfg(test)] +mod caret_tests { + use super::*; + use figcraft_color::{Color, Paint}; + use figcraft_doc::{Node, NodeId, NodeKind, StyleRun, TextData}; + + fn text(chars: &str, fills: Vec) -> Node { + let mut n = Node::new(NodeId(1), NodeKind::Text(TextData { characters: chars.into(), ..TextData::default() }), "Text", 100.0, 20.0); + n.fills = fills; + n + } + + fn hex(s: &str) -> Color { + Color::from_hex(s).unwrap() + } + + #[test] + fn red_text_has_a_red_caret() { + let n = text("Caret", vec![Paint::solid(hex("#FF0000"))]); + assert_eq!(caret_fill(&n, 2), Some(hex("#FF0000"))); + assert_eq!(caret_color(&egui::Context::default(), &n, 2), Some(Color32::from_rgb(255, 0, 0))); + } + + #[test] + fn light_grey_text_keeps_its_own_colour_whatever_is_behind_it() { + // Inside a #222222 frame: the frame's fill plays no part. + let n = text("Caret", vec![Paint::solid(hex("#DDDDDD"))]); + assert_eq!(caret_fill(&n, 5), Some(hex("#DDDDDD"))); + assert_eq!(caret_color(&egui::Context::default(), &n, 0), Some(Color32::from_rgb(0xDD, 0xDD, 0xDD))); + } + + #[test] + fn the_caret_follows_the_run_of_the_character_before_it() { + let mut n = text("ab cd", vec![Paint::solid(hex("#000000"))]); + if let Some(t) = n.kind.text_mut() { + let mut style = t.style.clone(); + style.fills = Some(vec![Paint::solid(hex("#FF0000"))]); + t.runs.push(StyleRun { start: 3, end: 5, style }); + } + assert_eq!(caret_fill(&n, 2), Some(hex("#000000")), "after a black character"); + assert_eq!(caret_fill(&n, 4), Some(hex("#FF0000")), "after a red character"); + assert_eq!(caret_fill(&n, 0), Some(hex("#000000")), "at the start: the first character's"); + } + + #[test] + fn the_caret_is_opaque_whatever_the_fill_opacity() { + let mut p = Paint::solid(hex("#336699")); + p.opacity = 0.2; + assert_eq!(caret_fill(&text("x", vec![p]), 1).map(|c| c.a), Some(1.0)); + } + + /// #2190: a caret without a solid fill reads on the page: black on the default light page, + /// white on a dark one (the interface's text colour was white in the dark theme). + #[test] + fn without_a_solid_fill_the_caret_contrasts_with_the_page() { + let mut s = figcraft_engine::Session::new(); + let r = s.execute("text.create", &serde_json::json!({"text": "Caret", "x": 0, "y": 0})).unwrap(); + let id = figcraft_engine::params::id_of(&r["id"]).unwrap(); + assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::BLACK, "the default light page"); + s.execute("page.setBackground", &serde_json::json!({"color": "#1E1E1E"})).unwrap(); + assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::WHITE, "a dark page"); + } + + /// CodeRabbit on #2163: a dark frame on a light page is the surface under its text. + #[test] + fn without_a_solid_fill_the_caret_contrasts_with_the_frame_around_it() { + let mut s = figcraft_engine::Session::new(); + let ex = |s: &mut figcraft_engine::Session, c: &str, p: serde_json::Value| s.execute(c, &p).unwrap(); + let f = ex(&mut s, "frame.create", serde_json::json!({"x": 0, "y": 0, "width": 300, "height": 200})); + let f = figcraft_engine::params::id_of(&f["id"]).unwrap(); + ex(&mut s, "node.set", serde_json::json!({"id": f, "props": {"fill": "#222222"}})); + let r = ex(&mut s, "text.create", serde_json::json!({"text": "Caret", "x": 20, "y": 20, "parent": f})); + let id = figcraft_engine::params::id_of(&r["id"]).unwrap(); + assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::WHITE, "inside a dark frame on the light page"); + ex(&mut s, "node.set", serde_json::json!({"id": f, "props": {"fill": "#F0F0F0"}})); + assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::BLACK, "inside a light frame"); + // A dark frame drawn at 20% opacity shows the light page through it. + ex(&mut s, "node.set", serde_json::json!({"id": f, "props": {"fill": "#222222", "opacity": 0.2}})); + assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::BLACK, "a faint dark frame on the light page"); + // The same through the colour's own alpha. + ex(&mut s, "node.set", serde_json::json!({"id": f, "props": {"fill": "#22222233", "opacity": 1.0}})); + assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::BLACK, "a dark fill at 20% alpha"); + } + + #[test] + fn gradient_or_missing_fills_have_no_fill_colour() { + let mut g = Paint::solid(hex("#FF0000")); + g.kind = figcraft_color::PaintKind::Gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, hex("#FF0000"))); + assert_eq!(caret_fill(&text("Caret", vec![g]), 2), None); + assert_eq!(caret_fill(&text("Caret", vec![]), 2), None); + let mut hidden = Paint::solid(hex("#FF0000")); + hidden.visible = false; + assert_eq!(caret_fill(&text("Caret", vec![hidden]), 2), None); + } +} diff --git a/crates/ui-egui/src/canvas/wheel_zoom_tests.rs b/crates/ui-egui/src/canvas/wheel_zoom_tests.rs index 5b196a4d4..b5a36a7de 100644 --- a/crates/ui-egui/src/canvas/wheel_zoom_tests.rs +++ b/crates/ui-egui/src/canvas/wheel_zoom_tests.rs @@ -6,7 +6,7 @@ use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, Pos2, RawInput, R use figcraft_engine::Session; use serde_json::json; -use super::input::{is_mouse_wheel, swap_wheel}; +use super::input::{invert_zoom_factor, is_mouse_wheel, swap_wheel}; use crate::{FigApp, NoServices}; /// The view's zoom, cx and cy. @@ -25,8 +25,13 @@ fn wheel(unit: MouseWheelUnit, dy: f32, modifiers: Modifiers) -> Event { impl Canvas { fn new(scroll_wheel_zoom: bool) -> Self { + Self::with_invert(scroll_wheel_zoom, false) + } + + fn with_invert(scroll_wheel_zoom: bool, invert_zoom: bool) -> Self { let mut c = Self { ctx: egui::Context::default(), app: FigApp::new(Session::new(), Box::new(NoServices)), time: 0.0 }; c.app.run("pref.scrollWheelZoom", json!({"on": scroll_wheel_zoom})); + c.app.run("pref.invertZoom", json!({"on": invert_zoom})); for _ in 0..3 { c.frame(vec![], Modifiers::NONE); } @@ -126,3 +131,63 @@ fn the_swap_keeps_egui_rates() { assert_eq!(swap_wheel(vec2(40.0, 0.0), 1.0, true, speed), (vec2(40.0, 0.0), 1.0)); assert_eq!(swap_wheel(Vec2::ZERO, 1.0, false, speed), (Vec2::ZERO, 1.0)); } + +#[test] +fn invert_zoom_reverses_cmd_or_ctrl_wheel_by_the_same_factor() { + for mods in [Modifiers::COMMAND, Modifiers::CTRL] { + let (mut off, mut on) = (Canvas::with_invert(false, false), Canvas::with_invert(false, true)); + let (a, b, _) = off.gesture(wheel(MouseWheelUnit::Line, 3.0, mods), mods); + let (c, d, _) = on.gesture(wheel(MouseWheelUnit::Line, 3.0, mods), mods); + assert!(b.0 > a.0 * 1.05, "{mods:?} off zooms in: {a:?} -> {b:?}"); + assert!(d.0 < c.0 / 1.05, "{mods:?} on zooms out: {c:?} -> {d:?}"); + assert!(((b.0 / a.0) * (d.0 / c.0) - 1.0).abs() < 1e-3, "{mods:?} by the same factor"); + } +} + +#[test] +fn invert_zoom_reverses_a_plain_mouse_wheel_with_scroll_wheel_zoom_on() { + let (mut off, mut on) = (Canvas::with_invert(true, false), Canvas::with_invert(true, true)); + let (a, b, _) = off.gesture(wheel(MouseWheelUnit::Line, 3.0, Modifiers::NONE), Modifiers::NONE); + let (c, d, _) = on.gesture(wheel(MouseWheelUnit::Line, 3.0, Modifiers::NONE), Modifiers::NONE); + assert!(b.0 > a.0 * 1.05, "off zooms in: {a:?} -> {b:?}"); + assert!(d.0 < c.0 / 1.05, "on zooms out: {c:?} -> {d:?}"); + assert!(((b.0 / a.0) * (d.0 / c.0) - 1.0).abs() < 1e-3, "by the same factor"); +} + +/// Panning is never inverted: the scroll vector is the same with the preference on and off. +#[test] +fn invert_zoom_leaves_panning_unchanged() { + // (Scroll wheel zoom, modifiers): a plain wheel without it, Cmd/Ctrl+wheel with it, Shift+wheel. + for (swz, mods) in [(false, Modifiers::NONE), (true, Modifiers::COMMAND), (true, Modifiers::CTRL), (true, Modifiers::SHIFT)] { + let (mut off, mut on) = (Canvas::with_invert(swz, false), Canvas::with_invert(swz, true)); + let (a, b, _) = off.gesture(wheel(MouseWheelUnit::Line, -3.0, mods), mods); + let (c, d, _) = on.gesture(wheel(MouseWheelUnit::Line, -3.0, mods), mods); + assert!((b.0 - a.0).abs() < 1e-9 && (d.0 - c.0).abs() < 1e-9, "{mods:?} no zoom"); + assert!(b.1 != a.1 || b.2 != a.2, "{mods:?} off pans: {a:?} -> {b:?}"); + assert!( + ((b.1 - a.1) - (d.1 - c.1)).abs() < 1e-9 && ((b.2 - a.2) - (d.2 - c.2)).abs() < 1e-9, + "{mods:?} same pan: {a:?} -> {b:?} vs {c:?} -> {d:?}" + ); + } +} + +#[test] +fn a_pinch_zooms_the_same_with_invert_zoom_on_and_off() { + for (swz, invert, factor) in + [(false, false, 1.5), (false, true, 1.5), (true, false, 1.5), (true, true, 1.5), (true, true, 0.5), (false, true, 0.5)] + { + let mut c = Canvas::with_invert(swz, invert); + let (a, b, _) = c.gesture(Event::Zoom(factor), Modifiers::NONE); + assert!((b.0 / a.0 - f64::from(factor)).abs() < 1e-3, "scroll wheel zoom {swz}, invert {invert}, x{factor}: {a:?} -> {b:?}"); + } +} + +#[test] +fn the_inverted_factor_is_the_reciprocal_and_guards_bad_values() { + assert!((invert_zoom_factor(2.0) - 0.5).abs() < 1e-6); + assert_eq!(invert_zoom_factor(1.0), 1.0); + for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] { + let r = invert_zoom_factor(bad); + assert!(r == bad || (r.is_nan() && bad.is_nan()), "{bad} left alone"); + } +} diff --git a/crates/ui-egui/src/corner_individual_tests.rs b/crates/ui-egui/src/corner_individual_tests.rs index 281ab6f2a..117b90db3 100644 --- a/crates/ui-egui/src/corner_individual_tests.rs +++ b/crates/ui-egui/src/corner_individual_tests.rs @@ -166,25 +166,42 @@ fn polygons_and_stars_take_corner_smoothing() { for cmd in ["shape.polygon", "shape.star"] { let mut s = Session::new(); let id = NodeId(s.execute(cmd, &json!({"x": 0, "y": 0, "width": 120, "height": 120})).unwrap()["id"].as_u64().unwrap()); - s.execute("node.set", &json!({"ids": [id], "props": {"cornerRadius": 8}})).unwrap(); - s.execute("select.set", &json!({"ids": [id]})).unwrap(); - let mut u = Ui::new(s); - // With no corners of their own, the button is named for what it opens. - let t = named_button(&mut u, "Corner smoothing"); - click(&mut u, t); - assert!((0..4).all(|k| u.ctx.read_response(Id::unique(("corner", k)).with("field")).is_none()), "{cmd}: one radius, no corner fields"); - let smoothing = u.ctx.read_response(Id::unique("smoothing").with("field")).expect("the smoothing field shows").rect.center(); - let history = u.app.session.undo_depth().0; - click(&mut u, smoothing); - u.frame(vec![Event::Text("60".into())]); - enter(&mut u); - u.frame(vec![]); - let n = u.app.session.doc().unwrap().node(id).unwrap().clone(); - assert!((n.corners.smoothing - 0.6).abs() < 1e-9, "{cmd}: {}", n.corners.smoothing); - assert_eq!(u.app.session.undo_depth().0, history + 1, "{cmd}: one undo step"); + takes_corner_smoothing(s, id, cmd); } } +/// A boolean group has one radius for its whole result (#2222): like a polygon, its button opens +/// corner smoothing, with no field per corner. +#[test] +fn a_boolean_group_opens_corner_smoothing_and_has_no_corner_fields() { + let mut s = Session::new(); + let rect = |s: &mut Session, x: i32| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap()["id"].clone(); + let (a, b) = (rect(&mut s, 0), rect(&mut s, 60)); + let g = NodeId(s.execute("bool.union", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap()); + takes_corner_smoothing(s, g, "bool.union"); +} + +/// With `id` rounded at 8 and selected: the panel's button is named Corner smoothing and opens +/// the smoothing field with no field per corner, and typing 60 sets the smoothing in one undo step. +fn takes_corner_smoothing(mut s: Session, id: NodeId, what: &str) { + s.execute("node.set", &json!({"ids": [id], "props": {"cornerRadius": 8}})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let mut u = Ui::new(s); + // With no corners of their own, the button is named for what it opens. + let t = named_button(&mut u, "Corner smoothing"); + click(&mut u, t); + assert!((0..4).all(|k| u.ctx.read_response(Id::unique(("corner", k)).with("field")).is_none()), "{what}: one radius, no corner fields"); + let smoothing = u.ctx.read_response(Id::unique("smoothing").with("field")).expect("the smoothing field shows").rect.center(); + let history = u.app.session.undo_depth().0; + click(&mut u, smoothing); + u.frame(vec![Event::Text("60".into())]); + enter(&mut u); + u.frame(vec![]); + let n = u.app.session.doc().unwrap().node(id).unwrap().clone(); + assert!((n.corners.smoothing - 0.6).abs() < 1e-9, "{what}: {}", n.corners.smoothing); + assert_eq!(u.app.session.undo_depth().0, history + 1, "{what}: one undo step"); +} + /// A closed vector shows the same Corner smoothing control, and its iOS button sets 60% in one /// undo step; an open vector, which has no closed shape to smooth, shows no smoothing control. #[test] diff --git a/crates/ui-egui/src/cursors_tests.rs b/crates/ui-egui/src/cursors_tests.rs index 94109dc22..bb24a2469 100644 --- a/crates/ui-egui/src/cursors_tests.rs +++ b/crates/ui-egui/src/cursors_tests.rs @@ -22,7 +22,7 @@ fn every_engine_cursor_has_a_system_cursor_or_a_glyph() { // (engine cursor, what shows, its name in `ui.inspect`) let rows: Vec<(Cursor, Shown, &str)> = vec![ (Cursor::Default, System(CursorIcon::Default), "default"), - (Cursor::Crosshair, System(CursorIcon::Crosshair), "crosshair"), + (Cursor::Crosshair, Drawn(Glyph::Crosshair), "crosshair"), (Cursor::Move, System(CursorIcon::Move), "move"), (Cursor::Resize(0.0), System(CursorIcon::ResizeHorizontal), "ew-resize"), (Cursor::Resize(90.0), System(CursorIcon::ResizeVertical), "ns-resize"), @@ -59,6 +59,44 @@ fn every_engine_cursor_has_a_system_cursor_or_a_glyph() { assert_eq!(of(Cursor::Rotate(f64::INFINITY)), Drawn(Glyph::Rotate(0.0))); } +#[test] +fn the_crosshair_is_drawn_dark_with_a_white_edge_so_it_shows_on_white() { + use egui::epaint::Shape; + let shown = of(Cursor::Crosshair); + assert_eq!(shown, Shown::Drawn(Glyph::Crosshair)); + // The system's pointer is hidden under it, whatever its colour. + assert_eq!(shown.icon(), CursorIcon::None); + let at = pos2(50.0, 40.0); + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let ctx = ui.ctx().clone(); + let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("crosshair_test")); + crate::cursors::paint(&ctx.layer_painter(layer), at, Glyph::Crosshair); + }); + out.textures_delta.clear(); + let mut strokes = Vec::new(); + for clipped in &out.shapes { + if let Shape::LineSegment { points, stroke } = &clipped.shape { + strokes.push((points.to_vec(), stroke.color, stroke.width)); + } + } + let dark: Vec<_> = strokes.iter().filter(|s| s.1 == crate::cursors::INK).collect(); + let white: Vec<_> = strokes.iter().filter(|s| s.1 == egui::Color32::WHITE).collect(); + assert!(!dark.is_empty() && !white.is_empty(), "{strokes:?}"); + // The white edge is wider than the dark line and is painted first. + assert!(white.iter().all(|w| w.2 > dark[0].2), "{strokes:?}"); + assert_eq!(strokes[0].1, egui::Color32::WHITE); + // The arms are centred on the pointer and leave its pixel clear. + for (pts, ..) in &dark { + for p in pts { + let d = (p.x - at.x).abs().max((p.y - at.y).abs()); + assert!((2.0..=8.0).contains(&d), "{p:?}"); + assert!((p.x - at.x).abs() < 0.01 || (p.y - at.y).abs() < 0.01, "{p:?}"); + } + } + assert_eq!(dark.len(), 4); +} + #[test] fn resize_arrows_follow_the_angle_in_eighths() { // (degrees, the two-headed arrow): each covers 45° about its own direction, any turn. @@ -134,10 +172,10 @@ fn the_window_asks_for_the_cursor_of_the_tool_under_the_pointer() { ("move", edge, &[], no, CursorIcon::ResizeHorizontal, "ew-resize"), ("move", on, &[], alt, CursorIcon::Copy, "copy"), ("hand", empty, &[], no, CursorIcon::Grab, "grab"), - ("rectangle", empty, &[], no, CursorIcon::Crosshair, "crosshair"), - ("frame", on, &[], no, CursorIcon::Crosshair, "crosshair"), - ("slice", empty, &[], no, CursorIcon::Crosshair, "crosshair"), - ("text", empty, &[], no, CursorIcon::Crosshair, "crosshair"), + ("rectangle", empty, &[], no, CursorIcon::None, "crosshair"), + ("frame", on, &[], no, CursorIcon::None, "crosshair"), + ("slice", empty, &[], no, CursorIcon::None, "crosshair"), + ("text", empty, &[], no, CursorIcon::None, "crosshair"), ("pen", empty, &[], no, CursorIcon::None, "pen"), ("comment", empty, &[], no, CursorIcon::None, "comment"), ("move", empty, &[Key::Space], no, CursorIcon::Grab, "grab"), diff --git a/crates/ui-egui/src/dev_mode_tests.rs b/crates/ui-egui/src/dev_mode_tests.rs index 4d497585e..b7a9f129d 100644 --- a/crates/ui-egui/src/dev_mode_tests.rs +++ b/crates/ui-egui/src/dev_mode_tests.rs @@ -196,3 +196,47 @@ fn the_playground_swaps_an_instance_in_the_preview_only() { let props = u.app.session.execute("component.properties", &json!({"id": inst})).unwrap(); assert_eq!(props["properties"][0]["value"], json!(heart.0), "{star:?}"); } + +#[test] +fn the_annotation_tool_opens_the_inspect_tab_with_the_note_field_focused() { + let (mut u, _, r) = setup(); + u.app.ui.right_tab = crate::RightTab::Design; + u.frames(2, Vec::new); + u.run("tool.annotation", json!({"id": r})); + u.frames(2, Vec::new); + assert_eq!(u.app.ui.right_tab, crate::RightTab::Inspect, "the request shows the Inspect tab"); + let field = egui::Id::unique(("annot_new", r)).with("te"); + assert!(u.ctx.memory(|m| m.has_focus(field)), "the layer's new-note field has the caret"); + assert_eq!(u.app.ui.dev.focus_new_note, None, "the focus request is spent"); + // Asking again while already on the Inspect tab does not toggle it away. + u.run("tool.annotation", json!({"id": r})); + u.frames(2, Vec::new); + assert_eq!(u.app.ui.right_tab, crate::RightTab::Inspect); + assert!(u.ctx.memory(|m| m.has_focus(field)), "the field has the caret again"); + assert_eq!(u.app.ui.dev.focus_new_note, None, "and the request is spent"); +} + +/// A request for a layer that isn't selected (or is gone) does not wait to take the keyboard later. +#[test] +fn a_note_request_for_a_layer_that_is_not_selected_is_dropped() { + let (mut u, _, r) = setup(); + u.app.session.execute("select.set", &json!({"ids": []})).unwrap(); + u.frames(2, Vec::new); + u.app.session.request_ui("annotation.new", json!({"id": r})); + u.frames(2, Vec::new); + assert_eq!(u.app.ui.dev.focus_new_note, None); +} + +/// Choosing the Annotation tool from the toolbar on the Inspect tab keeps the tab (an editing tool +/// would leave it for Design) and asks for the selected layer's note. +#[test] +fn the_toolbar_keeps_the_inspect_tab_for_the_annotation_tool() { + let (mut u, _, r) = setup(); + u.app.session.execute("select.set", &json!({"ids": [r]})).unwrap(); + crate::toolbar::choose(&mut u.app, figcraft_engine::ToolId::Annotation); + u.frames(2, Vec::new); + assert_eq!(u.app.ui.right_tab, crate::RightTab::Inspect); + assert!(u.ctx.memory(|m| m.has_focus(egui::Id::unique(("annot_new", r)).with("te"))), "the note field has the caret"); + crate::toolbar::choose(&mut u.app, figcraft_engine::ToolId::Rectangle); + assert_eq!(u.app.ui.right_tab, crate::RightTab::Design, "a drawing tool leaves it"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 52170af44..e60928fd1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -246,6 +246,7 @@ pub fn show(app: &mut FigApp, ctx: &Context) { (tr("Show dimensions on objects"), prefs.show_dimensions, "pref.showDimensions"), (tr("Use number keys for opacity"), prefs.number_keys_opacity, "pref.numberKeysOpacity"), (tr("Scroll wheel zoom"), prefs.scroll_wheel_zoom, "pref.scrollWheelZoom"), + (tr("Invert zoom direction"), prefs.invert_zoom, "pref.invertZoom"), (tr("Reduce motion"), prefs.reduce_motion, "pref.reduceMotion"), ] { if crate::widgets::checkbox(ui, val, label) { diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index 3887895bb..067d54ea9 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -59,6 +59,10 @@ pub struct Editor { pub(crate) anchor: Option, /// The variable ids the table shows now, in row order (the range a Shift+click covers). pub(crate) order: Vec, + /// The variables the compact "Edit variables" editor is open on (empty = closed). + bulk_edit: Vec, + /// That editor's tab: 0 Details, 1 Scope. + bulk_tab: usize, } /// A click on row `id`: plain selects only it, Shift extends from the anchor to it through the @@ -113,8 +117,13 @@ fn bulk_run(app: &mut FigApp, label: &str, vars: &[&Variable], step: impl Fn(&Va /// The context menu of a row that is part of a selection of several: delete, move to a group and /// scope act on all of them. -fn bulk_menu(app: &mut FigApp, ui: &mut Ui, coll_groups: &[String], vars: &[&Variable]) { +fn bulk_menu(app: &mut FigApp, ui: &mut Ui, st: &mut Editor, coll_groups: &[String], vars: &[&Variable]) { let n = vars.len(); + if menu_item(ui, tr("Edit variables"), "") { + st.bulk_edit = vars.iter().map(|v| v.id.clone()).collect(); + st.bulk_tab = 0; + ui.close(); + } if menu_item(ui, &trn("Delete {n} variables", n, &[]), "") { bulk_run(app, "Delete variables", vars, |v| Some(("variable.delete", json!({"variable": v.id})))); ui.close(); @@ -277,6 +286,7 @@ pub fn show(app: &mut FigApp, ctx: &Context) { }); }); details(app, ctx, &doc.variables, &mut st); + bulk_details(app, ctx, &doc.variables, &mut st); app.ui.variables = open.then_some(st); } @@ -874,7 +884,7 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va crate::right::context_popup(&resp).show(|ui| { if let Some(vars) = bulk_ids(view, st, v) { let coll_groups = groups(view.in_collection(&coll.id).map(|x| x.name.as_str())); - bulk_menu(app, ui, &coll_groups, &vars); + bulk_menu(app, ui, st, &coll_groups, &vars); return; } if menu_item(ui, tr("Edit variable"), "") { @@ -1204,9 +1214,115 @@ fn details(app: &mut FigApp, ctx: &Context, vars: &Variables, st: &mut Editor) { } } +/// Whether `f` holds for every variable (Some(true)), for none (Some(false)) or only some (None). +/// With no variables nothing is on: Some(false), never a checked box for an empty list. +fn tri(vars: &[&T], f: impl Fn(&T) -> bool) -> Option { + if vars.is_empty() { + return Some(false); + } + let on = vars.iter().filter(|v| f(v)).count(); + if on == vars.len() { + Some(true) + } else if on == 0 { + Some(false) + } else { + None + } +} + +/// The compact editor of several selected variables: Details (only Hide from publishing) and Scope +/// (the scopes every selected variable's type has), each box mixed where the selection differs; a +/// click sets or clears it on all of them in one undo step. +fn bulk_details(app: &mut FigApp, ctx: &Context, vars: &Variables, st: &mut Editor) { + if st.bulk_edit.is_empty() { + return; + } + let list: Vec<&Variable> = st.bulk_edit.iter().filter_map(|id| vars.get_by_id(id)).filter(|v| v.extends.is_none()).collect(); + // The menu offers Edit variables only for two or more editable, non-inherited variables of a + // file collection (`bulk_ids`), so this closes only when they have since gone (deleted, + // undone) or a library was opened: there is nothing left to edit. + if list.is_empty() || st.library.is_some() { + st.bulk_edit.clear(); + return; + } + let t = Tokens::get(ctx); + let mut open = true; + egui::Window::new(tr("Edit variables")) + .id(Id::unique("variables_bulk_details")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .default_width(280.0) + .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(16))) + .show(ctx, |ui| { + ui.set_width(260.0); + if let Some(i) = widgets::segmented_text(ui, &[tr("Details"), tr("Scope")], st.bulk_tab) { + st.bulk_tab = i; + } + ui.add_space(8.0); + if st.bulk_tab == 0 { + let hidden = tri(&list, |v| v.hidden_from_publishing); + if widgets::checkbox_tri(ui, hidden, tr("Hide from publishing")) { + let to = hidden != Some(true); + bulk_run(app, "Edit variables", &list, |v| Some(("variable.update", json!({"variable": v.id, "hiddenFromPublishing": to})))); + } + return; + } + // The scopes every selected variable's type has. + let first = list.first().map_or(&[][..], |v| scopes_for(v.kind)); + let common: Vec<(&'static str, &'static str)> = + first.iter().filter(|(id, _)| list.iter().all(|v| scopes_for(v.kind).iter().any(|(k, _)| k == id))).copied().collect(); + if common.is_empty() { + widgets::label(ui, tr("No scope is shared by all the selected variables"), t.text_secondary); + return; + } + let all = tri(&list, |v| v.scopes.is_none()); + if widgets::checkbox_tri(ui, all, tr("All supported properties")) { + let to_all = all != Some(true); + bulk_run(app, "Edit variables", &list, |v| { + Some(("variable.update", json!({"variable": v.id, "scopes": if to_all { Value::Null } else { json!([]) }}))) + }); + } + for (sid, label) in common { + let state = tri(&list, |v| v.in_scope(sid)); + let clicked = ui + .horizontal(|ui| { + ui.add_space(16.0); + widgets::checkbox_tri(ui, state, tr(label)) + }) + .inner; + if clicked { + let to = state != Some(true); + bulk_run(app, "Edit variables", &list, |v| { + let next: Vec<&str> = + scopes_for(v.kind).iter().map(|(id, _)| *id).filter(|id| if *id == sid { to } else { v.in_scope(id) }).collect(); + Some(("variable.update", json!({"variable": v.id, "scopes": next}))) + }); + } + } + }); + if !open { + st.bulk_edit.clear(); + } +} + #[cfg(test)] mod tests { - use super::groups; + use super::{groups, tri}; + + #[test] + fn tri_is_checked_empty_or_mixed() { + let (a, b) = (true, false); + assert_eq!(tri(&[&a, &a], |v| *v), Some(true)); + assert_eq!(tri(&[&b, &b], |v| *v), Some(false)); + assert_eq!(tri(&[&a, &b], |v| *v), None); + } + + #[test] + fn tri_of_no_variables_is_not_checked() { + let none: [&bool; 0] = []; + assert_eq!(tri(&none, |v| *v), Some(false)); + } #[test] fn groups_include_parents_once_and_sorted() { diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 718d681f6..b9620f177 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -189,7 +189,7 @@ fn setup() -> (Ui, NodeId, NodeId) { /// The topmost field named `name` in the Design panel: its value centre and displayed text. /// Layer opacity precedes the equally named opacity fields in paint rows. -fn field(u: &mut Ui, name: &str) -> (Pos2, String) { +pub(crate) fn field(u: &mut Ui, name: &str) -> (Pos2, String) { u.frame(vec![]); let out = u.frame_output(vec![]); let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; @@ -234,7 +234,7 @@ fn geom(u: &Ui, n: NodeId) -> (f64, f64, f64, f64) { (b.x0, b.y0, b.width(), b.height()) } -fn undo_steps(u: &Ui) -> usize { +pub(crate) fn undo_steps(u: &Ui) -> usize { u.app.session.ds().unwrap().history.undo.len() } @@ -252,7 +252,7 @@ fn click(u: &mut Ui, p: Pos2) { } /// Click into field `name`, type `text` over what it shows and press `end`. -fn type_into(u: &mut Ui, name: &str, text: &str, end: Key) { +pub(crate) fn type_into(u: &mut Ui, name: &str, text: &str, end: Key) { let (p, _) = field(u, name); click(u, p); u.frame(vec![Event::Text(text.into())]); @@ -261,7 +261,7 @@ fn type_into(u: &mut Ui, name: &str, text: &str, end: Key) { } /// Scrub field `name` by its label: `dx` points with `modifiers` held, then let go. -fn scrub(u: &mut Ui, name: &str, dx: f32, modifiers: Modifiers) { +pub(crate) fn scrub(u: &mut Ui, name: &str, dx: f32, modifiers: Modifiers) { let from = label(u, name); drag(u, from, dx, modifiers); } @@ -441,6 +441,68 @@ fn the_arrow_keys_step_by_the_nudge_amounts_and_fractional_fields_by_their_own() assert!((rot.abs() - 11.0).abs() < 1e-6, "rotation {rot}: the steps stay after Escape"); } +#[test] +fn the_rotation_field_shows_and_sets_the_rotation_on_the_page() { + let mut s = Session::new(); + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 100, "width": 400, "height": 400})).unwrap()); + s.execute("node.set", &json!({"ids": [f], "props": {"rotation": 10}})).unwrap(); + let r = id(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 120, "height": 80, "parent": f})).unwrap()); + s.execute("node.set", &json!({"ids": [r], "props": {"rotation": -10}})).unwrap(); + let b = id(s.execute("shape.rectangle", &json!({"x": 600, "y": 0, "width": 50, "height": 50})).unwrap()); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + let page = |u: &Ui, n: NodeId| figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().world_transform(n)); + let local = |u: &Ui, n: NodeId| figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().node(n).unwrap().transform); + assert_eq!(field(&mut u, "Rotation").1, "0°"); + type_into(&mut u, "Rotation", "7", Key::Enter); + assert!((page(&u, r) - 7.0).abs() < 1e-6 && (local(&u, r) + 3.0).abs() < 1e-6, "{} {}", page(&u, r), local(&u, r)); + assert_eq!(field(&mut u, "Rotation").1, "7°"); + // Arrows step the shown value. + let shift = Modifiers { shift: true, ..Modifiers::NONE }; + let (p, _) = field(&mut u, "Rotation"); + click(&mut u, p); + key(&mut u, Key::ArrowUp, Modifiers::NONE); + key(&mut u, Key::ArrowUp, shift); + key(&mut u, Key::Escape, Modifiers::NONE); + assert!((page(&u, r) - 18.0).abs() < 1e-6, "{}", page(&u, r)); + 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); + 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. + u.app.session.execute("node.set", &json!({"ids": [b], "props": {"rotation": 33}})).unwrap(); + u.app.session.execute("select.set", &json!({"ids": [r, b]})).unwrap(); + assert_eq!(field(&mut u, "Rotation").1, "33°"); + u.app.session.execute("node.set", &json!({"ids": [b], "props": {"rotation": 20}})).unwrap(); + assert_eq!(field(&mut u, "Rotation").1, "Mixed"); + let steps = undo_steps(&u); + type_into(&mut u, "Rotation", "+10", Key::Enter); + assert!((page(&u, r) - 43.0).abs() < 1e-6 && (page(&u, b) - 30.0).abs() < 1e-6, "{} {}", page(&u, r), page(&u, b)); + assert_eq!(undo_steps(&u), steps + 1); +} + +#[test] +fn a_relative_rotation_edit_turns_a_selected_parent_before_its_child_whatever_the_selection_order() { + let mut s = Session::new(); + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 400, "height": 400})).unwrap()); + let c = id(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 120, "height": 80, "parent": f})).unwrap()); + s.execute("node.set", &json!({"ids": [f], "props": {"rotation": 10}})).unwrap(); + s.execute("node.set", &json!({"ids": [c], "props": {"absoluteRotation": 30}})).unwrap(); + // The child first, then its parent. + s.execute("select.set", &json!({"ids": [c, f]})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + let page = |u: &Ui, n: NodeId| figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().world_transform(n)); + assert_eq!(field(&mut u, "Rotation").1, "Mixed"); + type_into(&mut u, "Rotation", "+10", Key::Enter); + assert!((page(&u, f) - 20.0).abs() < 1e-6 && (page(&u, c) - 40.0).abs() < 1e-6, "{} {}", page(&u, f), page(&u, c)); +} + #[test] fn arithmetic_commits_tab_moves_on_and_escape_restores() { let (mut u, a, _) = setup(); @@ -1485,6 +1547,80 @@ fn sidebar_field_text_stays_in_place_on_focus() { } } +/// The shared paint control shows the same precision as Fill and keeps the picker toggle. +#[test] +fn page_background_shows_fractional_opacity_like_fill_and_keeps_it_when_opening_the_picker() { + let mut u = Ui::new(Session::new()); + u.ctx.enable_accesskit(); + u.app.run("page.setBackground", json!({"color": "#FF000080"})); + u.frame(vec![]); + assert_eq!(field(&mut u, "Opacity").1, "50.2%"); + let page = u.app.session.page().unwrap(); + let background = |u: &Ui| match u.app.session.doc().unwrap().node(page).unwrap().kind { + figcraft_doc::NodeKind::Page { background, .. } => background, + _ => panic!("the page"), + }; + let original = background(&u); + let steps = undo_steps(&u); + let swatch = u.ctx.read_response(Id::unique("pagebg_swatch")).expect("shared page swatch").rect.center(); + click(&mut u, swatch); + assert!(matches!(u.app.ui.picker, Some(crate::colorpicker::PickerTarget::PageBackground))); + assert_eq!(undo_steps(&u), steps, "opening the picker does not edit the colour"); + assert_eq!(background(&u), original, "opening preserves the stored alpha"); + assert_eq!(field(&mut u, "Opacity").1, "50.2%"); + click(&mut u, swatch); + assert!(u.app.ui.picker.is_none(), "the swatch toggles the picker closed"); + assert_eq!(background(&u), original, "closing preserves the stored alpha"); + assert_eq!(field(&mut u, "Opacity").1, "50.2%"); + assert_eq!(undo_steps(&u), steps, "neither toggle creates an edit"); +} + +/// The shared page colour row uses the sidebar's width without hiding either field. +#[test] +fn page_background_colour_and_opacity_fit_a_resized_sidebar() { + // Find the whole galley, rather than its already-clipped bounding box. + fn hex_text(shape: &egui::Shape) -> Option<&egui::epaint::TextShape> { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().find_map(hex_text), + egui::Shape::Text(text) if text.galley.text() == "123ABC" => Some(text), + _ => None, + } + } + let mut widths = Vec::new(); + for width in [240.0, 500.0] { + let mut session = Session::new(); + session.prefs.panel_widths.1 = width; + session.execute("page.setBackground", &json!({"color": "#123ABC80"})).unwrap(); + let mut u = Ui::new(session); + let mut previous = None; + let mut settled = None; + // Stop at stable geometry, with a bound so a layout regression cannot hang the test. + for _ in 0..16 { + let out = u.frame_output(vec![]); + let hex = u.ctx.read_response(Id::unique("pagebg").with("click")).unwrap().rect; + let alpha = u.ctx.read_response(Id::unique("pagebg_a").with("field")).unwrap().rect; + let panel = u.app.ui.right_panel_rect.unwrap(); + if previous == Some((hex, alpha, panel)) { + settled = Some((out, hex, alpha, panel)); + break; + } + previous = Some((hex, alpha, panel)); + } + let (out, hex, alpha, panel) = settled.expect("the page row settles"); + assert!(hex.left() >= u.app.canvas.rect.right(), "the colour stays in the sidebar"); + assert!(hex.right() < alpha.left(), "the colour and opacity never overlap"); + // Half a point permits device-pixel rounding, not an arbitrary gap from the panel edge. + assert!((alpha.right() - (panel.right() - crate::widgets::PAD_RIGHT)).abs() <= 0.5, "opacity stays at the right edge"); + assert!((hex.center().y - alpha.center().y).abs() <= 0.5, "both fields stay on the same row"); + let (text, clip) = out.shapes.iter().find_map(|s| hex_text(&s.shape).map(|text| (text, s.clip_rect))).expect("the HEX text"); + assert!(!text.galley.elided, "the whole HEX value fits at {width} pt"); + assert!(hex.expand(0.5).contains_rect(text.visual_bounding_rect()), "the HEX text fits its field"); + assert!(clip.expand(0.5).contains_rect(text.visual_bounding_rect()), "the HEX text is not clipped"); + widths.push(hex.width()); + } + assert!(widths[1] > widths[0], "a wider sidebar gives the colour field more room"); +} + /// The Page section's opacity field edits the page background's alpha (#1748; it was a label), /// one undo step per commit, and the hex field keeps that opacity unless the typed colour /// carries its own. @@ -1596,3 +1732,35 @@ fn alt_held_over_a_field_scrubs_it() { u.frame(vec![]); assert_eq!(geom(&u, a).0, 65.0, "ten more"); } + +#[test] +fn a_boolean_group_has_one_corner_radius_field_and_a_mixed_selection_reads_mixed() { + let (mut u, a, b) = setup(); + let g = id(u.app.session.execute("bool.union", &json!({"ids": [a, b]})).unwrap()); + let r = id(u.app.session.execute("shape.rectangle", &json!({"x": 400, "y": 0, "width": 50, "height": 50})).unwrap()); + u.app.run("select.set", json!({"ids": [g]})); + assert_eq!(field(&mut u, "Corner radius").1, "0"); + let steps = undo_steps(&u); + type_into(&mut u, "Corner radius", "20", Key::Enter); + let radii = |u: &Ui, n: NodeId| u.app.session.doc().unwrap().node(n).unwrap().corners.radii; + assert_eq!(radii(&u, g), [20.0; 4]); + assert_eq!(undo_steps(&u), steps + 1, "one undo step"); + u.app.run("select.set", json!({"ids": [g, r]})); + assert_eq!(field(&mut u, "Corner radius").1, "Mixed"); + type_into(&mut u, "Corner radius", "8", Key::Enter); + assert_eq!((radii(&u, g), radii(&u, r)), ([8.0; 4], [8.0; 4])); +} + +/// A boolean group draws its first radius; per-corner values a script or a file left behind don't +/// make its field read Mixed, and a relative edit starts from the radius it draws. +#[test] +fn a_boolean_groups_field_shows_the_radius_it_draws() { + let (mut u, a, b) = setup(); + let g = id(u.app.session.execute("bool.union", &json!({"ids": [a, b]})).unwrap()); + let corners = json!({"topRightRadius": 30, "bottomRightRadius": 30, "bottomLeftRadius": 30}); + u.app.session.execute("node.set", &json!({"ids": [g], "props": corners})).unwrap(); + u.app.run("select.set", json!({"ids": [g]})); + assert_eq!(field(&mut u, "Corner radius").1, "0", "the radius it draws"); + type_into(&mut u, "Corner radius", "+10", Key::Enter); + assert_eq!(u.app.session.doc().unwrap().node(g).unwrap().corners.radii, [10.0; 4], "0 + 10, not 30 + 10"); +} diff --git a/crates/ui-egui/src/header_icon_size_tests.rs b/crates/ui-egui/src/header_icon_size_tests.rs new file mode 100644 index 000000000..917276c2a --- /dev/null +++ b/crates/ui-egui/src/header_icon_size_tests.rs @@ -0,0 +1,52 @@ +//! A section header's icon buttons (Appearance, Fill, Stroke, Effects...) draw their glyphs at the +//! same size as the panel's other 24 pt icon buttons (#2227). + +use egui::{Context, Rect, pos2, vec2}; + +use crate::icons::{self, Icon}; +use crate::widgets::{icon_button_at, icon_glyph_rect, section_header}; + +/// Bounding box of everything painted in one frame of `add`. +fn painted_box(add: impl FnOnce(&mut egui::Ui)) -> Rect { + let ctx = Context::default(); + let mut add = Some(add); + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 200.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(f) = add.take() { + f(ui); + } + }); + out.textures_delta.clear(); + out.shapes + .iter() + .filter(|s| matches!(s.shape, egui::Shape::Path(_) | egui::Shape::Mesh(_) | egui::Shape::LineSegment { .. } | egui::Shape::Circle(_))) + .map(|s| s.shape.visual_bounding_rect()) + .fold(Rect::NOTHING, |a, b| a.union(b)) +} + +/// The header's eye, `icon_button_at`'s and a fill row's (`icons::button`, the reporter's +/// reference) are drawn at one size. +#[test] +fn header_eye_draws_as_large_as_a_fill_rows_eye() { + let header = painted_box(|ui| { + section_header(ui, "Appearance", &[(Icon::Eye, "Hide")], false); + }); + let at = painted_box(|ui| { + let r = Rect::from_min_size(pos2(20.0, 20.0), vec2(24.0, 24.0)); + icon_button_at(ui, ui.scope_id().with("b"), r, Icon::Eye, "Hide"); + }); + let row = painted_box(|ui| { + icons::button(ui, Icon::Eye, 24.0, false, "Toggle visibility"); + }); + for (name, b) in [("icon_button_at", at), ("icons::button", row)] { + assert!(header.is_finite() && b.is_finite(), "{header:?} {b:?}"); + assert!((header.width() - b.width()).abs() < 0.5, "{name}: widths {} vs {}", header.width(), b.width()); + assert!((header.height() - b.height()).abs() < 0.5, "{name}: heights {} vs {}", header.height(), b.height()); + } +} + +#[test] +fn glyph_rect_is_the_shared_inset_of_the_button() { + let b = Rect::from_min_size(pos2(0.0, 0.0), vec2(24.0, 24.0)); + assert_eq!(icon_glyph_rect(b).size(), vec2(16.0, 16.0)); +} diff --git a/crates/ui-egui/src/inspect_fields_tests.rs b/crates/ui-egui/src/inspect_fields_tests.rs index bdd0abcd8..9164f02b8 100644 --- a/crates/ui-egui/src/inspect_fields_tests.rs +++ b/crates/ui-egui/src/inspect_fields_tests.rs @@ -62,12 +62,12 @@ fn control_key_arrows_pan_with_nothing_selected() { (v.cx, v.cy) }; call(&mut u, "ui.key", json!({"key": "ArrowRight"})).unwrap(); - assert_eq!(view(&u), (10.0, 0.0), "20 screen pixels at 200%"); + assert_eq!(view(&u), (32.0, 0.0), "64 screen pixels at 200% are 32 document pixels"); call(&mut u, "ui.key", json!({"key": "ArrowUp", "shift": true})).unwrap(); - assert_eq!(view(&u), (10.0, -100.0), "Shift: ten times as far"); + assert_eq!(view(&u), (32.0, -160.0), "Shift: 320 screen pixels, 160 document pixels"); u.app.run("select.set", json!({"ids": [r]})); call(&mut u, "ui.key", json!({"key": "ArrowRight"})).unwrap(); - assert_eq!(view(&u), (10.0, -100.0), "with a selection the view stays"); + assert_eq!(view(&u), (32.0, -160.0), "with a selection the view stays"); let id = figcraft_engine::params::id_of(&r).unwrap(); assert_eq!(u.app.session.doc().unwrap().world_bounds(id).unwrap().x0, 1.0, "the selection moved instead"); // With a shape tool chosen and nothing selected the arrows move the placement crosshair diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a4db9fa3f..01cfe8e88 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -124,6 +124,8 @@ mod guide_release_tests; #[cfg(test)] mod guide_snap_tests; #[cfg(test)] +mod header_icon_size_tests; +#[cfg(test)] mod home_recents_tests; #[cfg(test)] mod home_tests; @@ -230,6 +232,9 @@ mod present_tests; mod present_view_tests; #[cfg(test)] mod property_menu_tests; +mod property_rows; +#[cfg(test)] +mod property_rows_tests; #[cfg(test)] mod proto_editor_tests; #[cfg(test)] @@ -249,6 +254,8 @@ mod save_as_tests; #[cfg(test)] mod select_all_tests; #[cfg(test)] +mod selection_colors_tests; +#[cfg(test)] mod shortcut_keys_tests; #[cfg(test)] mod shortcuts_tests; @@ -287,6 +294,8 @@ mod vector_keys_tests; #[cfg(test)] mod vector_panel_tests; #[cfg(test)] +mod vector_point_xy_tests; +#[cfg(test)] mod vector_tail_ui_tests; #[cfg(test)] mod vote_history_ui_tests; @@ -595,6 +604,10 @@ pub struct UiState { /// copy changes the engine clipboard without writing the OS clipboard; the generation then /// no longer matches, so the stale mirror is not mistaken for the user's own copy. pub last_copy_generation: u64, + /// The fill, stroke or effect row highlighted in the Design panel: Cmd/Ctrl+C copies it. + pub property_row: Option, + /// A paint or effect copied from its row: Cmd/Ctrl+V pastes it while it's the last copy. + pub property_copy: Option, /// A save shortcut pressed while a panel field had the keyboard: the field lets go (which /// commits what was typed) and the command runs next frame for that document/window. pub after_field: Option, @@ -738,6 +751,8 @@ impl Default for UiState { last_copy: None, last_copy_generation: 0, + property_row: None, + property_copy: None, after_field: None, held: egui::Modifiers::NONE, next_autosave: 0.0, diff --git a/crates/ui-egui/src/menu_aim_tests.rs b/crates/ui-egui/src/menu_aim_tests.rs index 6f7c4b8af..f5af573db 100644 --- a/crates/ui-egui/src/menu_aim_tests.rs +++ b/crates/ui-egui/src/menu_aim_tests.rs @@ -1,7 +1,7 @@ //! Which submenu the main and context menus show, driven through egui headless: a closed menu //! reopens with no submenu open (also one level down), hovering another row closes the open -//! submenu at once while a submenu opens only once the pointer stays on its row a moment -//! (sweeping across rows doesn't flash each one), and on the way from a +//! submenu at once and a submenu opens on the first frame its row is hovered (as Figma's does), +//! and on the way from a //! submenu's row to its submenu the rows the pointer crosses don't take over (the safe triangle), //! unless it rests on one or turns away. @@ -214,7 +214,7 @@ fn resting_on_a_crossed_row_hands_over_to_it() { } #[test] -fn moving_straight_down_switches_after_a_short_hover() { +fn moving_straight_down_switches_at_once() { let mut u = Ui::new(); u.open_main_menu(); let file = u.top_row(0); @@ -227,24 +227,21 @@ fn moving_straight_down_switches_after_a_short_hover() { p.y = (p.y + 4.0).min(edit.y); u.hover(p); } - assert!(u.tops_shown().is_empty(), "File closes at once, Edit waits: {:?}", u.tops_shown()); - u.wait(HOVER_DELAY + 0.05); - assert_eq!(u.tops_shown(), ["Edit"]); + u.frame(vec![]); + assert_eq!(u.tops_shown(), ["Edit"], "File closes at once, Edit opens on its first frame"); } #[test] -fn the_first_submenu_opens_after_a_short_hover() { +fn the_first_submenu_opens_on_the_next_frame() { let mut u = Ui::new(); u.open_main_menu(); u.hover(u.top_row(0).center()); u.frame(vec![]); - assert!(u.tops_shown().is_empty(), "opened at once"); - u.wait(HOVER_DELAY + 0.05); - assert_eq!(u.tops_shown(), ["File"]); + assert_eq!(u.tops_shown(), ["File"], "Figma opens it on the first frame (median 11 ms)"); } #[test] -fn sweeping_across_rows_opens_only_where_the_pointer_stops() { +fn sweeping_across_rows_shows_only_the_row_under_the_pointer() { let mut u = Ui::new(); u.open_main_menu(); u.settle(u.top_row(0).center()); @@ -254,9 +251,8 @@ fn sweeping_across_rows_opens_only_where_the_pointer_stops() { u.hover(pos2(r.min.x + 20.0, r.center().y)); // (A panel drawn above the row the pointer is on goes the next frame.) u.frame(vec![]); - assert!(u.tops_shown().is_empty(), "{:?} open on row {i}", u.tops_shown()); + assert_eq!(u.tops_shown(), [TOPS[i]], "wrong submenu open on row {i}"); } - u.wait(HOVER_DELAY + 0.05); assert_eq!(u.tops_shown(), ["Arrange"]); } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index e2d92eff1..b0a7dfaf1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -193,6 +193,10 @@ pub fn invoke(app: &mut FigApp, id: &str) { app.toast(tr("Properties copied")); } } + // A fill, stroke or effect row highlighted in the Design panel: that paint or effect. + "edit.copy" if crate::property_rows::current(app).is_some() => { + crate::property_rows::copy_highlighted(app); + } "edit.copy" | "edit.cut" => { let ids = app.session.selection(); // For other apps: text layers' text, other layers as SVG; taken before a cut removes them. diff --git a/crates/ui-egui/src/menus/clipboard.rs b/crates/ui-egui/src/menus/clipboard.rs index bd7020150..886f56bc4 100644 --- a/crates/ui-egui/src/menus/clipboard.rs +++ b/crates/ui-egui/src/menus/clipboard.rs @@ -16,7 +16,7 @@ pub fn paste(app: &mut FigApp, event_text: Option<&str>, at: Option<(f64, f64)>) if app.control_synthetic { // Synthetic input is user-like: Dev Mode refuses the paste here too, and only the engine's // own copied layers are pasted (the system clipboard is never read). - if !dev_mode_refuses(app, "edit.paste") { + if !(at.is_none() && crate::property_rows::paste(app)) && !dev_mode_refuses(app, "edit.paste") { app.run("edit.paste", at.map_or(json!({}), |(x, y)| json!({"x": x, "y": y}))); } return; @@ -89,6 +89,11 @@ pub fn paste(app: &mut FigApp, event_text: Option<&str>, at: Option<(f64, f64)>) return paste_text(app, &text, (cx, cy), at.is_none()); } } + // Nothing newer from another app: a fill, stroke or effect copied from its row, when that was + // the last copy, else our copied layers. + if at.is_none() && crate::property_rows::paste(app) { + return; + } if !dev_mode_refuses(app, "edit.paste") { app.run("edit.paste", at.map_or(json!({}), |(x, y)| json!({"x": x, "y": y}))); } diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 17ab9eb76..ac4e7059d 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -11,8 +11,8 @@ pub(crate) fn submenu(ui: &mut Ui, key: &str, label: &str, t: &Tokens, add: i // Which submenu is open: hover intent with a safe triangle. // // Every menu tree (the main menu, the context menu) keeps, per level, which of its submenus is -// open. Hovering another row closes the open submenu at once; resting on a submenu row for -// `HOVER_DELAY` opens it (sweeping across rows doesn't flash every submenu on the way). Except while the +// open. Hovering a row closes the open submenu at once and opens the row's own submenu on the +// same frame (as Figma's main menu does, measured; `HOVER_DELAY` is zero). Except while the // pointer is on its way from the open submenu's row to the submenu: while each move lands inside // the triangle between where it was and the submenu's near edge (it keeps getting nearer), rows // it crosses don't take over and the submenu's row stays highlighted. Resting (`AIM_REST`) or @@ -20,8 +20,10 @@ pub(crate) fn submenu(ui: &mut Ui, key: &str, label: &str, t: &Tokens, add: i // last submenu open. // Closing a menu tree forgets all of it, so it reopens with no submenu open. -/// How long the pointer stays on a submenu row before its submenu opens. -pub(crate) const HOVER_DELAY: f64 = 0.15; +/// How long the pointer stays on a submenu row before its submenu opens. None: Figma's main menu +/// opens it on the first frame (median 11 ms measured), so the delay is zero; kept as a constant so +/// the pending-row bookkeeping the aim relies on stays as it was. +pub(crate) const HOVER_DELAY: f64 = 0.0; /// How long the pointer may rest inside the safe triangle before the row under it takes over. pub(crate) const AIM_REST: f64 = 0.3; diff --git a/crates/ui-egui/src/panel_width_tests.rs b/crates/ui-egui/src/panel_width_tests.rs index 8c6da05c9..dd8906311 100644 --- a/crates/ui-egui/src/panel_width_tests.rs +++ b/crates/ui-egui/src/panel_width_tests.rs @@ -78,7 +78,15 @@ fn panels_fit_the_window() { ((744.0, None, Some(480.0)), (0.0, 480.0), "with the left panel closed the right one has room"), ((300.0, Some(240.0), Some(240.0)), (l0, r0), "a window smaller than any layout: the least widths"), ((1384.0, Some(f32::NAN), Some(f32::INFINITY)), (PANEL_DEFAULT, PANEL_DEFAULT), "junk widths: the default"), - ((744.0, Some(480.0), None), (480.0, 0.0), "the right panel closed (a board's): the left one keeps its width"), + ((744.0, Some(480.0), None), (l1, 0.0), "the right panel closed (a board's): the left one keeps as much of its width as it may"), + ((744.0, Some(450.0), None), (450.0, 0.0), "the right panel closed: the left one at its most"), + ((1384.0, Some(200.0), Some(480.0)), (l0, 480.0), "a stored left width under 240 (the old limit was 200) is brought up to 240"), + ((1384.0, Some(470.0), Some(520.0)), (l1, r1), "stored widths over the limits (the old ones were 480) are brought down to 450 and 500"), + ( + (744.0, Some(300.0), Some(500.0)), + (240.0, 344.0), + "the smallest window with the right panel at its most: the right gives way last, the left to its 240 floor", + ), ]; for ((avail, left, right), want, why) in rows { assert_eq!(fit_panels(avail, left, right), want, "{why}"); @@ -122,14 +130,17 @@ fn dragging_an_edge_sizes_its_panel_within_its_limits_and_keeps_the_views_centre let (left, right) = edges(&u); drag(&mut u, pos2(left, 300.0), pos2(left + 700.0, 300.0)); assert_eq!(widths(&u).0, *LEFT_PANEL.end()); + assert_eq!(widths(&u).0, 450.0, "Figma's left sidebar stops at 450"); let (left, _) = edges(&u); drag(&mut u, pos2(left, 300.0), pos2(20.0, 300.0)); assert_eq!(widths(&u).0, *LEFT_PANEL.start()); + assert_eq!(widths(&u).0, 240.0, "and at 240 the other way"); drag(&mut u, pos2(right, 300.0), pos2(right + 500.0, 300.0)); assert_eq!(widths(&u).1, *RIGHT_PANEL.start()); let (_, right) = edges(&u); u.drag_to(pos2(right, 300.0), pos2(right - 900.0, 300.0)); assert_eq!(widths(&u).1, *RIGHT_PANEL.end(), "at its most while the pointer is past it"); + assert_eq!(widths(&u).1, 500.0, "Figma's right sidebar stops at 500"); u.frame(vec![Event::PointerMoved(pos2(right - 100.0, 300.0))]); assert_eq!(widths(&u).1, *RIGHT_PANEL.start() + 100.0, "back with the pointer"); u.button(pos2(right - 100.0, 300.0), false); @@ -187,6 +198,17 @@ fn the_widths_come_back_with_the_preferences() { u.frame(vec![]); let (left, right) = edges(&u); assert_eq!((left, 1440.0 - right), (56.0 + *LEFT_PANEL.start(), PANEL_DEFAULT)); + // Widths saved under the old limits (left 200 to 480, right up to 480) or over the new ones + // are clamped when loaded, not rejected. + for (stored, want) in + [((200.0, 240.0), (240.0, 240.0)), ((239.0, 500.0), (240.0, 500.0)), ((451.0, 480.0), (450.0, 480.0)), ((480.0, 600.0), (450.0, 500.0))] + { + let mut s = Session::new(); + s.prefs.panel_widths = stored; + let mut u = Ui::new(s); + u.frame(vec![]); + assert_eq!(widths(&u), want, "stored {stored:?}"); + } } #[test] @@ -264,7 +286,7 @@ fn minimize_collapses_the_rail_and_both_sidebars_and_the_right_one_follows_the_s #[test] fn the_smallest_window_keeps_its_canvas_whatever_the_widths() { - for asked in [(240.0, 240.0), (480.0, 480.0), (480.0, 240.0), (200.0, 480.0)] { + for asked in [(240.0, 240.0), (450.0, 500.0), (450.0, 240.0), (240.0, 500.0)] { let mut s = Session::new(); s.prefs.panel_widths = asked; let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index a63c10c9a..0da5a9bee 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -1157,7 +1157,7 @@ fn enabled_libraries(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) { if xr.hovered() { ui.painter().rect_filled(x, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), x.shrink(6.0), Icon::Close, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(x), Icon::Close, t.icon); if xr.clicked() { remove = Some(l.id.clone()); } @@ -1169,7 +1169,7 @@ fn enabled_libraries(app: &mut FigApp, ui: &mut Ui, w: f32, doc: &Document) { if sr.hovered() { ui.painter().rect_filled(sw, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), sw.shrink(6.0), Icon::Swap, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(sw), Icon::Swap, t.icon); crate::right::menu_popup(&sr).show(|ui| { for other in doc.libraries.enabled.iter().filter(|o| o.id != l.id) { if crate::right::menu_item(ui, &trf("Swap to {name}", &[("name", &other.name)]), "") { diff --git a/crates/ui-egui/src/panels/dev_mode.rs b/crates/ui-egui/src/panels/dev_mode.rs index bcb97edbb..09c3b9732 100644 --- a/crates/ui-egui/src/panels/dev_mode.rs +++ b/crates/ui-egui/src/panels/dev_mode.rs @@ -92,6 +92,9 @@ impl CategoryFilter { /// revision), the page or the choice change. #[derive(Default)] pub struct DevUi { + /// The layer whose new-note field takes the keyboard focus once its section draws (the + /// Annotation tool asked for that layer's note). + pub focus_new_note: Option, pub filter: usize, pub categories: CategoryFilter, pub compare: Option, @@ -618,6 +621,11 @@ pub fn annotations_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: No } ui.add_space(6.0); } + // The Annotation tool asked for this layer's note: put the caret in the new-note field, once. + if app.ui.dev.focus_new_note == Some(id) { + app.ui.dev.focus_new_note = None; + ui.memory_mut(|m| m.request_focus(Id::unique(("annot_new", id)).with("te"))); + } // A new annotation starts as a note; properties are pinned to it afterwards. if n.annotations.len() < annotations::MAX_PER_LAYER && let Some(label) = widgets::multiline_field(ui, Id::unique(("annot_new", id)), "", tr("Add an annotation for developers"), 1) diff --git a/crates/ui-egui/src/panels/list_drag.rs b/crates/ui-egui/src/panels/list_drag.rs index 08a391aeb..4fa614d4e 100644 --- a/crates/ui-egui/src/panels/list_drag.rs +++ b/crates/ui-egui/src/panels/list_drag.rs @@ -75,8 +75,19 @@ impl ListDrag { /// Item `index` (model order) was laid out with its main row at `header`, covering `extent` /// (the header plus anything open under it). Its grip starts a drag carrying `label`. pub fn row(&mut self, ui: &mut Ui, index: usize, header: Rect, extent: Rect, label: impl FnOnce() -> String) { + self.grip_row(ui, index, header, extent, Sense::drag(), label); + } + + /// [`Self::row`] whose grip also takes a click, the way a click beside the row's fields + /// highlights a fill, stroke or effect row: `true` when it was clicked. The grip senses the + /// click without being focusable, so Tab doesn't stop on it. + pub fn row_clicked(&mut self, ui: &mut Ui, index: usize, header: Rect, extent: Rect, label: impl FnOnce() -> String) -> bool { + self.grip_row(ui, index, header, extent, Sense::DRAG | Sense::CLICK, label) + } + + fn grip_row(&mut self, ui: &mut Ui, index: usize, header: Rect, extent: Rect, sense: Sense, label: impl FnOnce() -> String) -> bool { let grip = Rect::from_min_max(header.min, pos2(header.min.x + PAD, header.max.y)); - let resp = ui.interact(grip, grip_of(self.list, index), Sense::drag()); + let resp = ui.interact(grip, grip_of(self.list, index), sense); // The handle shows while the pointer is over the row (or the row is being dragged). let shown = match self.dragging { Some(d) => d == index, @@ -93,6 +104,7 @@ impl ListDrag { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); } self.row_by(&resp, index, extent, label); + resp.clicked() } /// Item `index` laid out over `extent`, dragged by the whole row (`resp` senses drags; the diff --git a/crates/ui-egui/src/panels/proto_panel.rs b/crates/ui-egui/src/panels/proto_panel.rs index d7728cbdc..fa9f2585c 100644 --- a/crates/ui-egui/src/panels/proto_panel.rs +++ b/crates/ui-egui/src/panels/proto_panel.rs @@ -684,7 +684,7 @@ fn editor_popover(app: &mut FigApp, ctx: &egui::Context, popover: InteractionPop if xr.hovered() { ui.painter().rect_filled(x, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), x.shrink(6.0), Icon::Close, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(x), Icon::Close, t.icon); if xr.clicked() { close = true; } diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index b30d323a7..3c64f665c 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -75,7 +75,12 @@ impl FigApp { None => return, }; let Ok(doc) = self.session.doc() else { return }; - let values: Vec<(NodeId, f64)> = ids.iter().filter_map(|i| Some((*i, rel.apply(shown(doc.node(*i)?))?))).collect(); + let mut values: Vec<(NodeId, f64)> = ids.iter().filter_map(|i| Some((*i, rel.apply(shown(doc.node(*i)?))?))).collect(); + if key == "absoluteRotation" { + // A page angle depends on the parents': turn a selected parent before the layers in it + // (as `node.set` orders a multi-id call), whatever order the selection is in. + values.sort_by_key(|(i, _)| doc.ancestors(*i).len()); + } if values.is_empty() || self.session.begin_interaction("Edit").is_err() { return; } @@ -332,21 +337,22 @@ fn page_section(app: &mut FigApp, ui: &mut Ui, doc: &Document) { let mut new_color: Option<(figcraft_color::Color, Option)> = None; row(ui, 32.0, |ui| { let p = Paint::solid(bg); - let sw = widgets::swatch(ui, &p, 16.0); + let (sw, opacity) = + widgets::paint_field(ui, Id::unique("pagebg_swatch"), Id::unique("pagebg_a"), &p, ui.available_width(), |child, text_r| { + // A typed colour keeps the page's opacity unless it carries one: 4 or 8 hex digits + // (`FF000080`; `FF0000FF` asks for opaque). + if let Some(h) = widgets::text_field_inline(child, Id::unique("pagebg"), &bg.to_hex(), text_r.shrink2(vec2(0.0, 4.0)), regular(11.0)) + && let Some(c) = figcraft_color::Color::from_hex_or_name(&h) + { + let digits = h.trim().trim_start_matches('#'); + let carries_alpha = matches!(digits.len(), 4 | 8) && digits.chars().all(|ch| ch.is_ascii_hexdigit()); + new_color = Some((if carries_alpha { c } else { c.with_alpha(bg.a) }, None)); + } + }); app.picker_control(crate::colorpicker::PickerTarget::PageBackground, &sw); - // A typed colour keeps the page's opacity unless it carries one: 4 or 8 hex digits - // (`FF000080`; `FF0000FF` asks for opaque). - if let Some(h) = widgets::text_field(ui, Id::unique("pagebg"), &bg.to_hex(), 96.0, "") - && let Some(c) = figcraft_color::Color::from_hex_or_name(&h) - { - let digits = h.trim().trim_start_matches('#'); - let carries_alpha = matches!(digits.len(), 4 | 8) && digits.chars().all(|ch| ch.is_ascii_hexdigit()); - new_color = Some((if carries_alpha { c } else { c.with_alpha(bg.a) }, None)); - } // The opacity: a field like every other opacity field, not a label (#1748). let alpha = |v: f64| bg.with_alpha((v / 100.0).clamp(0.0, 1.0) as f32); - let shown = Some(f64::from((bg.a * 100.0).round())); - match widgets::number_field(ui, Id::unique("pagebg_a"), Lead::Named(tr("Opacity")), shown, "%", 56.0, 1.0) { + match opacity { Some(FieldEdit::Set(v)) => new_color = Some((alpha(v), None)), Some(FieldEdit::Scrub(v, done)) => new_color = Some((alpha(v), Some(done))), None => {} @@ -456,7 +462,7 @@ fn header(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) { if sresp.hovered() { ui.painter().rect_filled(sr, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), sr.shrink(5.0), Icon::Rotate, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(sr), Icon::Rotate, t.icon); if sresp.clicked() { app.run("frame.swapOrientation", json!({"ids": sel})); } @@ -511,8 +517,7 @@ fn header(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) { ("bool.union", Some(op)) => crate::layers::op_icon(op), _ => icon, }; - let icon_rect = Rect::from_min_size(br.min, vec2(24.0, 24.0)).shrink(5.0); - icons::paint(ui.painter(), icon_rect, icon, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(br), icon, t.icon); if dropdown { icons::paint(ui.painter(), Rect::from_center_size(pos2(br.max.x - 6.0, br.center().y), vec2(8.0, 8.0)), Icon::Chevron, t.icon_secondary); } @@ -627,8 +632,9 @@ fn y_of(doc: &Document, n: &Node) -> f64 { (doc.frame_relative(n.id).as_coeffs()[5] * 100.0).round() / 100.0 } -fn rot_of(n: &Node) -> f64 { - (figcraft_geom::rotation_degrees(n.transform) * 100.0).round() / 100.0 +/// The layer's rotation on the page (its own angle plus its parents'), what the field shows. +fn rot_of(doc: &Document, n: &Node) -> f64 { + (figcraft_geom::rotation_degrees(doc.world_transform(n.id)) * 100.0).round() / 100.0 } pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc, sel: &[NodeId]) -> PositionValues { @@ -637,7 +643,7 @@ pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc, sel: &[N can_align: figcraft_engine::cmd::arrange::can_align(doc, sel), x: common(doc, sel, |n| x_of(doc, n)), y: common(doc, sel, |n| y_of(doc, n)), - rot: common(doc, sel, rot_of), + rot: common(doc, sel, |n| rot_of(doc, n)), parent_al: sel.iter().all(|i| doc.node(*i).and_then(parent).is_some_and(|p| p.layout.is_some())), absolute: common(doc, sel, |n| n.child_layout.absolute), // Constraints: children of frames without auto layout, or ignoring it. @@ -655,7 +661,7 @@ fn position_fields(app: &mut FigApp, ui: &mut Ui, doc: &Arc, sel: &[No let col = widgets::col_width(ui.available_width()); align_row(app, ui, sel, pv.can_align, col); position_row(app, ui, doc, sel, &pv, col); - rotation_row(app, ui, sel, pv.rot, col); + rotation_row(app, ui, doc, sel, pv.rot, col); if pv.in_frame { constraints_row(app, ui, sel, pv.constraints, col); } @@ -732,12 +738,12 @@ fn position_row(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], p } /// Rotation, with the rotate and flip buttons. -fn rotation_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], rot: Option, col: f32) { +fn rotation_row(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], rot: Option, col: f32) { let ids = sel.to_vec(); widgets::sublabels(ui, tr("Rotation"), None); row(ui, 32.0, |ui| { let e = widgets::number_field_mixed(ui, Id::unique("pos_rot"), Lead::Icon(Icon::Angle, tr("Rotation")), rot, "°", col, 1.0); - app.field_of(&ids, "rotation", e, rot_of, |v| json!(v)); + app.field_of(&ids, "absoluteRotation", e, |n| rot_of(doc, n), |v| json!(v)); let items = [ (Icon::Rotate, tr("Rotate 90° right")), (Icon::FlipH, crate::shortcuts::tip(tr("Flip horizontal"), "object.flipH")), diff --git a/crates/ui-egui/src/panels/right/effects.rs b/crates/ui-egui/src/panels/right/effects.rs index b25990db7..5590a5219 100644 --- a/crates/ui-egui/src/panels/right/effects.rs +++ b/crates/ui-egui/src/panels/right/effects.rs @@ -1,9 +1,10 @@ -use super::menu::{context_popup, menu_check, menu_item, menu_popup, row, row_context_menu, row_rect}; +use super::menu::{context_popup, menu_check, menu_item, menu_popup, row, row_context_menu, row_rect, row_target}; use super::{ Blur, BlurType, Document, Effect, EffectKind, FieldEdit, FigApp, Glass, GridAlign, GridKind, Icon, Id, LayoutGrid, Lead, ListDrag, MAX_BLUR_RADIUS, NodeId, Noise, NoiseMode, Paint, Sense, Shadow, StyleSlot, Texture, Ui, VariableType, common, icons, json, move_flags, moved_index, remove_flags, removed_index, style_picker, tr, trf, trn, vec2, widgets, }; +use crate::property_rows::PropertyKind; /// Draw the effect list with add/style/type/toggle/remove/reorder, open settings, and keep an /// open picker and settings flags aligned when rows move or are removed. @@ -29,9 +30,12 @@ pub(super) fn effects(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[Node let Some(list) = list else { return }; let mut drag = ListDrag::new(ui, "effects"); let mut removed = None; + let selected_row = crate::theme::Tokens::get(ui.ctx()).selected_row; for (i, e) in list.iter().enumerate().rev() { let mut open = effect_open(ui.ctx(), i); - let header = row_rect(ui, 32.0, |ui| { + // A click on the row's background highlights it for Cmd/Ctrl+C (`property_rows`). + let highlight = crate::property_rows::fill(app, PropertyKind::Effect, i, selected_row); + let header = row_target(ui, 32.0, highlight, |ui| { if icons::button(ui, Icon::Effects, 24.0, open, tr("Effect settings")).clicked() { open = !open; ui.data_mut(|d| d.insert_temp(Id::unique((FX_OPEN, i)), open)); @@ -63,10 +67,12 @@ pub(super) fn effects(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[Node removed = Some(i); } }); + crate::property_rows::row(app, &header, PropertyKind::Effect, i, &ids); + let header = header.rect; let can_paste = app.session.clipboard.effect.is_some(); row_context_menu(ui, header, Id::unique(("effect_menu", i))).show(|ui| { if menu_item(ui, tr("Copy effect"), "") { - app.run("effect.copy", json!({"ids": ids, "index": i})); + crate::property_rows::copy(app, PropertyKind::Effect, i, &ids); ui.close(); } if can_paste && menu_item(ui, tr("Paste effect"), "") { @@ -77,10 +83,13 @@ pub(super) fn effects(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[Node if open { effect_settings(app, ui, &ids, i, e); } - drag.row(ui, i, header, header.with_max_y(ui.cursor().min.y.max(header.max.y)), || tr(e.label()).to_string()); + if drag.row_clicked(ui, i, header, header.with_max_y(ui.cursor().min.y.max(header.max.y)), || tr(e.label()).to_string()) { + crate::property_rows::click(app, PropertyKind::Effect, i, &ids, header); + } } if let Some((from, to)) = drag.finish(ui) { app.run("effect.move", json!({"ids": ids, "from": from, "to": to})); + crate::property_rows::follow(app, PropertyKind::Effect, from, Some(to)); move_flags(ui, FX_OPEN, list.len(), from, to); if let Some(crate::colorpicker::PickerTarget::Effect { index, .. }) = &mut app.ui.picker { *index = moved_index(*index, from, to); @@ -88,6 +97,7 @@ pub(super) fn effects(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[Node } // Open settings and an open colour picker stay with their effects, or go with theirs. if let Some(i) = removed { + crate::property_rows::follow(app, PropertyKind::Effect, i, None); remove_flags(ui, FX_OPEN, list.len(), i); if let Some(crate::colorpicker::PickerTarget::Effect { index, .. }) = &mut app.ui.picker { match removed_index(*index, i) { diff --git a/crates/ui-egui/src/panels/right/menu.rs b/crates/ui-egui/src/panels/right/menu.rs index 9b80ab8d8..40215a8a5 100644 --- a/crates/ui-egui/src/panels/right/menu.rs +++ b/crates/ui-egui/src/panels/right/menu.rs @@ -155,12 +155,31 @@ pub(crate) fn row_rect(ui: &mut Ui, h: f32, add: impl FnOnce(&mut Ui)) -> Rect { pub(crate) fn block(ui: &mut Ui, h: f32, inset_y: f32, add: impl FnOnce(&mut Ui)) -> Rect { let w = ui.available_width(); let (r, _) = ui.allocate_exact_size(vec2(w, h), Sense::hover()); + lay_out(ui, r, inset_y, add); + r +} + +/// A [`row_rect`] that is a pointer target itself: a click on its background (beside and between +/// its controls, which are on top of it) comes back in the response. It senses clicks without +/// being focusable, so Tab and F6 still go from control to control. `fill` is drawn under the +/// controls (a highlighted fill, stroke or effect row). +pub(crate) fn row_target(ui: &mut Ui, h: f32, fill: Option, add: impl FnOnce(&mut Ui)) -> egui::Response { + let w = ui.available_width(); + let (r, resp) = ui.allocate_exact_size(vec2(w, h), Sense::CLICK); + if let Some(fill) = fill { + ui.painter().rect_filled(r, CornerRadius::ZERO, fill); + } + lay_out(ui, r, (h - FIELD_H) / 2.0, add); + resp +} + +/// Add a row's controls in `r`, on the section's grid, inset `inset_y` from its top and bottom. +fn lay_out(ui: &mut Ui, r: Rect, inset_y: f32, add: impl FnOnce(&mut Ui)) { // The section's grid: 16 in from the left, 8 from the right (not 16 on both sides). let inner = Rect::from_min_max(pos2(r.min.x + PAD, r.min.y + inset_y), pos2(r.max.x - crate::widgets::PAD_RIGHT, r.max.y - inset_y)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(egui::Layout::left_to_right(egui::Align::Center))); child.spacing_mut().item_spacing = vec2(crate::widgets::GUTTER, 0.0); add(&mut child); - r } /// Width of the check column of [`menu_icon_item`] (the mark, or nothing, so labels line up). diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 967ae266b..df1ca5ee0 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -1,10 +1,11 @@ -use super::menu::{blend_menu, context_popup, menu_check, menu_item, menu_popup, preview_blend, row, row_context_menu, row_rect}; +use super::menu::{blend_menu, context_popup, menu_check, menu_item, menu_popup, preview_blend, row, row_context_menu, row_target}; use super::stroke::stroke_settings; use super::{ Align2, BlendMode, CornerRadius, Document, FIELD_H, FieldEdit, FigApp, Icon, Id, Lead, ListDrag, MaskType, Node, NodeId, NodeKind, Paint, PaintKind, Rect, Sense, Stroke, StrokeAlign, StyleSlot, Tip, Tokens, Ui, Value, VariableType, common, icons, json, moved_index, pos2, regular, removed_index, style_picker, tr, trf, vec2, widgets, }; +use crate::property_rows::PropertyKind; /// Draw visibility/blend/mask, opacity, uniform or per-corner radius, corner smoothing and /// the blend-mode row. @@ -51,11 +52,16 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N let op_of = |n: &Node| (f64::from(n.opacity) * 100.0).round(); let op = common(doc, sel, op_of); let radius_ok = crate::selection_cache::every(doc, sel, |n| n.kind.has_corner_radius()); - // Only rectangles and frames round each corner on its own. + // Only rectangles and frames round each corner on its own; a boolean group has one radius for + // every sharp corner of its result. let indep_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_independent_corners()); - // For polygons, stars and closed vectors the same panel holds only the Corner smoothing row. + // For polygons, stars, boolean groups and closed vectors the same panel holds only the Corner + // smoothing row. let smooth_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_corner_smoothing()); - let r = common(doc, sel, |n| n.corners.uniform().map(|r| (r * 100.0).round() / 100.0)); + // A layer with one radius (polygon, star, boolean group, vector) draws its first one, whatever + // the other three hold; a rectangle or frame shows a value only when its four corners agree. + let shown = |n: &Node| if n.kind.has_independent_corners() { n.corners.uniform() } else { n.corners.radii.first().copied() }; + let r = common(doc, sel, |n| shown(n).map(|r| (r * 100.0).round() / 100.0)); widgets::sublabels(ui, tr("Opacity"), radius_ok.then_some(tr("Corner radius"))); row(ui, 32.0, |ui| { let lead = Lead::Icon(Icon::Opacity, tr("Opacity")); @@ -73,11 +79,13 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N "", col, ); - // A layer with corners of its own starts from its largest. - let radius_of = |n: &Node| n.corners.uniform().unwrap_or_else(|| n.corners.radii.iter().copied().fold(0.0, f64::max)); + // A relative edit starts from the radius shown; a rectangle with differing corners + // starts from its largest. + let radius_of = |n: &Node| shown(n).unwrap_or_else(|| n.corners.radii.iter().copied().fold(0.0, f64::max)); app.field_of(&ids, "cornerRadius", e, radius_of, |v| json!(v.max(0.0))); let open = ui.data(|d| d.get_temp::(Id::unique("indep_corners"))).unwrap_or(false); - // Polygons and stars have no corners of their own: the button opens only Corner smoothing. + // Polygons, stars and boolean groups have no corners of their own: the button opens only + // Corner smoothing. let tip = if indep_ok { tr("Individual corners") } else { tr("Corner smoothing") }; if smooth_ok && icons::button(ui, Icon::IndependentCorners, 24.0, open, tip).clicked() { ui.data_mut(|d| d.insert_temp(Id::unique("indep_corners"), !open)); @@ -341,10 +349,13 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI let mut drag = ListDrag::new(ui, if fills { "fills" } else { "strokes" }); for (i, p) in l.iter().enumerate().rev() { let r = paint_row(app, ui, &ids, i, p, fills, region); - drag.row(ui, i, r, r, || paint_label(p)); + if drag.row_clicked(ui, i, r, r, || paint_label(p)) { + crate::property_rows::click(app, if fills { PropertyKind::Fill } else { PropertyKind::Stroke }, i, &ids, r); + } } if let Some((from, to)) = drag.finish(ui) { app.run(if fills { "fill.move" } else { "stroke.move" }, json!({"ids": ids, "from": from, "to": to})); + crate::property_rows::follow(app, if fills { PropertyKind::Fill } else { PropertyKind::Stroke }, from, Some(to)); // An open colour picker keeps editing the paint it was on. if let Some(crate::colorpicker::PickerTarget::Paint { fills: f, index, .. }) = &mut app.ui.picker && *f == fills @@ -451,12 +462,15 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI /// Paint `i`'s row (swatch, colour or kind, opacity, visibility, remove); returns its area. /// One paint's row; `region`: a row of the regions selected in vector edit mode (#1875), which -/// leaves out what belongs to the layer (its variable binding, the image crop). +/// leaves out what belongs to the layer (its variable binding, the image crop). A click on its +/// background highlights it for Cmd/Ctrl+C ([`crate::property_rows`]). fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint, fills: bool, region: bool) -> Rect { let t = Tokens::get(ui.ctx()); let ids = ids.to_vec(); let cmd = if fills { "fill.set" } else { "stroke.set" }; - let r = row_rect(ui, 32.0, |ui| { + let kind = if fills { PropertyKind::Fill } else { PropertyKind::Stroke }; + let highlight = crate::property_rows::fill(app, kind, i, t.selected_row); + let resp = row_target(ui, 32.0, highlight, |ui| { let w = ui.available_width() - 60.0; let (sresp, e) = widgets::paint_field(ui, Id::unique(("swatch", fills, i)), Id::unique(("pop", fills, i)), p, w, |child, text_r| { let r = child.max_rect(); @@ -537,24 +551,28 @@ fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint, if toggle { app.run(cmd, json!({"ids": ids, "index": i, "visible": !p.visible})); } - if remove - && app.run(if fills { "fill.remove" } else { "stroke.remove" }, json!({"ids": ids, "index": i})).is_some() - && let Some(crate::colorpicker::PickerTarget::Paint { fills: f, index, .. }) = &mut app.ui.picker - && *f == fills - { + if remove && app.run(if fills { "fill.remove" } else { "stroke.remove" }, json!({"ids": ids, "index": i})).is_some() { + // A highlighted row stays on its paint, or goes with it. + crate::property_rows::follow(app, kind, i, None); // An open colour picker keeps editing the paint it was on, or closes with it. - match removed_index(*index, i) { - Some(k) => *index = k, - None => app.ui.picker = None, + if let Some(crate::colorpicker::PickerTarget::Paint { fills: f, index, .. }) = &mut app.ui.picker + && *f == fills + { + match removed_index(*index, i) { + Some(k) => *index = k, + None => app.ui.picker = None, + } } } }); + crate::property_rows::row(app, &resp, kind, i, &ids); + let r = resp.rect; let copy = if fills { tr("Copy fill") } else { tr("Copy stroke") }; let paste = if fills { tr("Paste fill") } else { tr("Paste stroke") }; let can_paste = app.session.clipboard.paint.as_ref().is_some_and(|(f, _)| *f == fills); row_context_menu(ui, r, Id::unique(("paint_menu", fills, i))).show(|ui| { if menu_item(ui, copy, "") { - app.run(if fills { "fill.copy" } else { "stroke.copy" }, json!({"ids": ids, "index": i})); + crate::property_rows::copy(app, kind, i, &ids); ui.close(); } if can_paste && menu_item(ui, paste, "") { diff --git a/crates/ui-egui/src/panels/selection_colors.rs b/crates/ui-egui/src/panels/selection_colors.rs index dbb6f16e4..09c831400 100644 --- a/crates/ui-egui/src/panels/selection_colors.rs +++ b/crates/ui-egui/src/panels/selection_colors.rs @@ -65,7 +65,7 @@ pub(crate) fn toggle(app: &mut FigApp, targets: Vec, response: Opti } } -/// Draw the selection-colour groups (at least two): swatch opens the picker, hex and opacity +/// Draw the selection-colour groups (two, or one when a selected layer has children): swatch opens the picker, hex and opacity /// edits, style/variable detach/apply/bind, a style from this file or an enabled library, Create /// style, and “select layers with this color”; disabled during an interaction. pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId]) { @@ -73,7 +73,10 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId let interacting = ds.interaction.is_some(); let uid = ds.uid; let colors = colors(ui, uid, doc, ids, interacting); - if colors.len() < 2 { + // Measured in Figma: two distinct colours show the section; one colour does too when a selected + // layer has children (frame, group, component, instance). + let has_children = ids.iter().any(|id| doc.node(*id).is_some_and(|n| !n.children.is_empty())); + if colors.len() < 2 && !(colors.len() == 1 && has_children) { ui.data_mut(|d| d.remove::(create_form_id())); return; } diff --git a/crates/ui-egui/src/panels/typography.rs b/crates/ui-egui/src/panels/typography.rs index a3a5bd66a..ccd970bea 100644 --- a/crates/ui-egui/src/panels/typography.rs +++ b/crates/ui-egui/src/panels/typography.rs @@ -210,6 +210,7 @@ pub(crate) fn field_row(ui: &mut Ui, label: &str, add: impl FnOnce(&mut Ui, f #[cfg(test)] mod variable_tests { use egui::{Event, Modifiers, PointerButton, Pos2, RawInput}; + use figcraft_doc::WrapStyle; use figcraft_engine::Session; use super::*; @@ -223,6 +224,8 @@ mod variable_tests { ctx: egui::Context, time: f64, text: NodeId, + /// The AccessKit nodes of the last frame. + nodes: Vec, } impl Panel { @@ -236,7 +239,8 @@ mod variable_tests { s.execute("variable.create", &json!({"collection": "Type", "name": name, "type": ty, "values": {"Base": value}})).unwrap(); } s.execute("select.set", &json!({ "ids": [text] })).unwrap(); - let mut p = Self { app: FigApp::new(s, Box::new(NoServices)), ctx: egui::Context::default(), time: 0.0, text }; + let mut p = Self { app: FigApp::new(s, Box::new(NoServices)), ctx: egui::Context::default(), time: 0.0, text, nodes: Vec::new() }; + p.ctx.enable_accesskit(); crate::theme::install_fonts(&p.ctx, false, 0); crate::theme::apply(&p.ctx, Tokens::light()); for _ in 0..3 { @@ -269,6 +273,9 @@ mod variable_tests { crate::variable_ui::picker(&mut self.app, ui.ctx()); }); out.textures_delta.clear(); + if let Some(update) = out.platform_output.accesskit_update.take() { + self.nodes = update.nodes.into_iter().map(|(_, n)| n).collect(); + } let mut texts = Vec::new(); for c in out.shapes { walk(&c.shape, &mut texts); @@ -351,4 +358,75 @@ mod variable_tests { assert!(shows(&texts, "Inter") && shows(&texts, "Bold"), "the dropdowns show the last values"); assert!(p.app.ui.last_error.is_none(), "{:?}", p.app.ui.last_error); } + + /// The centre of the AccessKit node labelled `label` (a button, say). + fn node_center(p: &Panel, label: &str) -> Pos2 { + let n = p.nodes.iter().find(|n| n.label() == Some(label)).unwrap_or_else(|| panic!("no node {label:?}")); + let r = n.bounds().expect("bounds"); + Pos2::new(((r.x0 + r.x1) / 2.0) as f32, ((r.y0 + r.y1) / 2.0) as f32) + } + + const WRAP: [&str; 3] = [ + "Auto: as many words as fit on each line", + "Balance: every line close to the same length", + "Pretty: full lines, no one word alone on the last", + ]; + + /// The Wrap style buttons that are on, by short name. + fn wrap_on(p: &Panel) -> Vec<&'static str> { + let on = |label: &str| p.nodes.iter().find(|n| n.label() == Some(label)).unwrap_or_else(|| panic!("no node {label:?}")).toggled(); + ["Auto", "Balance", "Pretty"].into_iter().zip(WRAP).filter(|(_, l)| on(l) == Some(egui::accesskit::Toggled::True)).map(|(n, _)| n).collect() + } + + /// The panel with the Type settings popover open, over two paragraphs. + fn settings_panel() -> Panel { + let mut p = Panel::new(); + p.app.session.execute("node.set", &json!({"id": p.text, "props": {"characters": "one\ntwo"}})).unwrap(); + p.frame(vec![]); + let at = node_center(&p, "Type settings"); + p.click(at); + p.frame(vec![]); + p + } + + #[test] + fn wrap_style_control_follows_the_caret_paragraph() { + // #1827: with the caret in one paragraph the control shows and sets that paragraph's style. + let mut p = settings_panel(); + assert_eq!(wrap_on(&p), ["Auto"], "the layer's style when not editing"); + figcraft_engine::textedit::begin(&mut p.app.session, p.text, Some(5), false).unwrap(); + p.frame(vec![]); + assert_eq!(wrap_on(&p), ["Auto"]); + let at = node_center(&p, WRAP[1]); + p.click(at); + let td = |p: &Panel| p.app.session.doc().unwrap().node(p.text).unwrap().kind.text().unwrap().clone(); + assert_eq!((td(&p).para_wrap_style(0), td(&p).para_wrap_style(1)), (WrapStyle::Auto, WrapStyle::Balance), "only the caret's paragraph"); + assert_eq!(td(&p).wrap_style, WrapStyle::Auto); + assert_eq!(wrap_on(&p), ["Balance"], "the control shows the paragraph's value"); + figcraft_engine::textedit::set_caret(&mut p.app.session, 1, false).unwrap(); + p.frame(vec![]); + assert_eq!(wrap_on(&p), ["Auto"], "another paragraph shows its own"); + assert!(p.app.ui.last_error.is_none(), "{:?}", p.app.ui.last_error); + } + + #[test] + fn wrap_style_control_has_nothing_active_for_mixed_paragraphs() { + let mut p = settings_panel(); + figcraft_engine::textedit::begin(&mut p.app.session, p.text, Some(5), false).unwrap(); + p.frame(vec![]); + let at = node_center(&p, WRAP[2]); + p.click(at); + assert_eq!(wrap_on(&p), ["Pretty"]); + // A selection across both paragraphs, which differ: none is on. + figcraft_engine::textedit::set_caret(&mut p.app.session, 1, false).unwrap(); + figcraft_engine::textedit::set_caret(&mut p.app.session, 6, true).unwrap(); + p.frame(vec![]); + assert!(wrap_on(&p).is_empty(), "{:?}", wrap_on(&p)); + // Choosing one sets both paragraphs. + let at = node_center(&p, WRAP[1]); + p.click(at); + assert_eq!(wrap_on(&p), ["Balance"]); + let t = p.app.session.doc().unwrap().node(p.text).unwrap().kind.text().unwrap().clone(); + assert_eq!((t.para_wrap_style(0), t.para_wrap_style(1)), (WrapStyle::Balance, WrapStyle::Balance)); + } } diff --git a/crates/ui-egui/src/panels/typography/fields.rs b/crates/ui-egui/src/panels/typography/fields.rs index c290e9893..3c867e6f9 100644 --- a/crates/ui-egui/src/panels/typography/fields.rs +++ b/crates/ui-egui/src/panels/typography/fields.rs @@ -388,7 +388,14 @@ fn type_settings( } // Where lines break when the text wraps (Explore text properties). caption(ui, tr("Wrap style")); - let wrap = common(doc, ids, |n| n.kind.text().map(|t| t.wrap_style as usize)).flatten(); + // Per paragraph, as the text direction: while editing, the selected paragraphs. + let wrap = common(doc, ids, |n| { + n.kind.text().and_then(|t| { + let (a, b) = range.filter(|r| r.0 == n.id).map_or((0, t.char_count()), |(_, a, b)| (a, b)); + t.common_wrap_style(a, b).map(|w| w as usize) + }) + }) + .flatten(); let items = [ (tr("Auto"), tr_noop("Auto: as many words as fit on each line")), (tr("Balance"), tr_noop("Balance: every line close to the same length")), @@ -396,7 +403,7 @@ fn type_settings( ]; if let Some(i) = text_seg(ui, "wrap", &items, wrap, w) { let style = ["auto", "balance", "pretty"].get(i).copied().unwrap_or("auto"); - app.set_props(ids, json!({"wrapStyle": style})); + app.run("text.wrapStyle", json!({"ids": ids, "style": style})); } // The paragraphs' base direction, once a right-to-left script is in the text or a direction // is forced ("controls are available to override text direction per paragraph", Add diff --git a/crates/ui-egui/src/panels/variable_ui.rs b/crates/ui-egui/src/panels/variable_ui.rs index 53327440f..11345d13f 100644 --- a/crates/ui-egui/src/panels/variable_ui.rs +++ b/crates/ui-egui/src/panels/variable_ui.rs @@ -30,6 +30,9 @@ enum Target { Proto(crate::proto_editor::VarSlot), /// Bind it to `field` of the shared style `style`. Style { style: String, field: String }, + /// Bind it to the weight of the shared text style `style`: a string variable names the face + /// (`fontStyle`), a number one sets the weight (`fontWeight`). + StyleWeight { style: String }, } /// The open variable picker: what it does, the variable type (None: any), where it opens. @@ -197,6 +200,13 @@ pub fn open_style(ui: &Ui, style: &str, field: &str, kind: VariableType, at: Pos ui.data_mut(|d| d.insert_temp(picker_id(), Picker { target, kind: Some(kind), at })); } +/// Open the picker at `at` to bind a string (face name) or number (weight) variable to the weight of +/// the shared text style `style`. +pub fn open_style_weight(ui: &Ui, style: &str, at: Pos2) { + let target = Target::StyleWeight { style: style.to_string() }; + ui.data_mut(|d| d.insert_temp(picker_id(), Picker { target, kind: None, at })); +} + /// Where the open picker is on screen (clicks in it don't close what opened it). pub fn picker_rect(ctx: &egui::Context) -> Option { picker_open(ctx).then(|| ctx.memory(|m| m.area_rect(Id::unique("variable_picker_area")))).flatten() @@ -398,7 +408,7 @@ pub fn picker(app: &mut FigApp, ctx: &egui::Context) { let (scope, own) = match &p.target { Target::Bind { ids, field } => (ids.first().and_then(|id| figcraft_engine::cmd::variables::field_scope(&doc, *id, field)), None), Target::Alias { variable, .. } => (None, doc.variables.get_by_id(variable)), - Target::Proto(_) | Target::Style { .. } => (None, None), + Target::Proto(_) | Target::Style { .. } | Target::StyleWeight { .. } => (None, None), }; // A style's fields offer variables scoped to one of the properties the field sets. let style_scopes = match &p.target { @@ -406,7 +416,8 @@ pub fn picker(app: &mut FigApp, ctx: &egui::Context) { _ => None, }; // Prototypes and styles use this file's variables. - let local_only = matches!(p.target, Target::Proto(_) | Target::Style { .. }); + let local_only = matches!(p.target, Target::Proto(_) | Target::Style { .. } | Target::StyleWeight { .. }); + let weight_target = matches!(p.target, Target::StyleWeight { .. }); let field = match &p.target { Target::Bind { field, .. } => Some(field.as_str()), _ => None, @@ -417,6 +428,12 @@ pub fn picker(app: &mut FigApp, ctx: &egui::Context) { && (q.is_empty() || v.name.to_lowercase().contains(&q)) && scope.is_none_or(|s| v.in_scope(s)) && style_scopes.is_none_or(|list| list.iter().any(|s| v.in_scope(s))) + && (!weight_target + || match v.kind { + VariableType::String => v.in_scope("FONT_STYLE"), + VariableType::Number => v.in_scope("FONT_WEIGHT"), + _ => false, + }) && (lib.is_some() || own.is_none_or(|o| figcraft_engine::cmd::variables::alias_target(&doc.variables, o, &v.id).is_ok())) }; let groups = groups(&doc, &libs, keep); @@ -495,6 +512,11 @@ pub fn picker(app: &mut FigApp, ctx: &egui::Context) { (Target::Style { style, field }, _) => { app.run("style.bind", json!({"style": style, "field": field, "variable": pick.id})); } + (Target::StyleWeight { style }, _) => { + let number = app.session.ds().is_ok_and(|d| d.doc.variables.get_by_id(&pick.id).is_some_and(|v| v.kind == VariableType::Number)); + let field = if number { "fontWeight" } else { "fontStyle" }; + app.run("style.bind", json!({"style": style, "field": field, "variable": pick.id})); + } } close = true; } diff --git a/crates/ui-egui/src/panels/vector_panel.rs b/crates/ui-egui/src/panels/vector_panel.rs index 07dda3ff4..3b91c9ffc 100644 --- a/crates/ui-egui/src/panels/vector_panel.rs +++ b/crates/ui-egui/src/panels/vector_panel.rs @@ -12,7 +12,7 @@ use crate::FigApp; use crate::i18n::tr; use crate::icons::Icon; use crate::right::{CAP_ART_W, cap_art, join_label, menu_item, menu_item_with, menu_popup, row}; -use crate::widgets::{self, FieldEdit, Lead}; +use crate::widgets::{self, Edit, FieldEdit, Lead, Rel}; /// Run a point command from a field: typed values are one step, scrubs one step when released. fn point_field(app: &mut FigApp, cmd: &str, edit: Option, params: impl Fn(f64) -> Value) { @@ -31,6 +31,23 @@ fn point_field(app: &mut FigApp, cmd: &str, edit: Option, params: imp } } +/// A point position field's edit: a value (typed or scrubbed) sets every selected point's own +/// coordinate; a relative edit of a Mixed field (`+10`, `*2`) applies to each point's own. +fn point_edit(app: &mut FigApp, axis: &'static str, edit: Option) { + match edit { + Some(Edit::All(e)) => point_field(app, "vector.edit.position", Some(e), |v| json!({ axis: v })), + Some(Edit::Each(rel)) => { + let op = match rel { + Rel::Add(n) => json!({"add": n}), + Rel::Mul(n) => json!({"mul": n}), + Rel::Div(n) => json!({"div": n}), + }; + app.run("vector.edit.position", json!({ axis: op })); + } + None => {} + } +} + /// The Variable width tool's selected width point: where it is along the path and its width. fn width_point(app: &mut FigApp, ui: &mut Ui, doc: &Document, ve: &VectorEdit) { widgets::section_header(ui, tr("Width point"), &[], false); @@ -88,14 +105,19 @@ pub fn points(app: &mut FigApp, ui: &mut Ui, doc: &Document, ve: &VectorEdit) { return; } let col = widgets::col_width(ui.available_width()); - let pos = vectoredit::selection_position(doc, ve); 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. + let shared = |axis: fn(&figcraft_geom::Point) -> f64| { + let first = parent_pts.first().map(axis)?; + parent_pts.iter().all(|p| (axis(p) - first).abs() < 1e-6).then(|| round(first)) + }; widgets::sublabels(ui, tr("Position"), None); row(ui, 32.0, |ui| { - let e = widgets::number_field(ui, Id::unique("vpt_x"), Lead::Text("X"), pos.map(|p| round(p.x)), "", col, 1.0); - point_field(app, "vector.edit.position", e, |v| json!({"x": v})); - let e = widgets::number_field(ui, Id::unique("vpt_y"), Lead::Text("Y"), pos.map(|p| round(p.y)), "", col, 1.0); - point_field(app, "vector.edit.position", e, |v| json!({"y": v})); + let e = widgets::number_field_mixed(ui, Id::unique("vpt_x"), Lead::Text("X"), shared(|p| p.x), "", col, 1.0); + point_edit(app, "x", e); + let e = widgets::number_field_mixed(ui, Id::unique("vpt_y"), Lead::Text("Y"), shared(|p| p.y), "", col, 1.0); + point_edit(app, "y", e); }); if let Some(b) = vectoredit::transform::point_box(doc, ve).filter(|b| b.points.len() > 1) { widgets::sublabels(ui, tr("Dimensions"), None); diff --git a/crates/ui-egui/src/property_rows.rs b/crates/ui-egui/src/property_rows.rs new file mode 100644 index 000000000..c5c89485c --- /dev/null +++ b/crates/ui-egui/src/property_rows.rs @@ -0,0 +1,254 @@ +//! Fill, stroke and effect rows of the Design panel as things to copy, as the help center's "Copy +//! and paste properties between layers" describes: click to highlight the property in the right +//! sidebar, press Cmd/Ctrl+C, select another layer, press Cmd/Ctrl+V. +//! +//! A click on a row's background (beside and between its controls, or on its reorder grip) +//! highlights it, one row at a time. The highlight belongs to the selection it was made on, and +//! goes with Escape or a press on the canvas or elsewhere in the Design panel. Cmd/Ctrl+C then +//! copies that one paint or effect (`fill.copy`, `stroke.copy`, `effect.copy`, as the row's menu +//! does) instead of the layers, and Cmd/Ctrl+V pastes it onto every selected layer (`fill.paste`, +//! `stroke.paste`, `effect.paste`) while it is still the last thing copied: on top of their list, +//! or in place of their highlighted row when it is of the same kind. A copy keeps its kind: a +//! stroke never lands in the fills, whatever row is highlighted. +//! +//! A programmatic copy (the control channel) never writes the system clipboard, so it has no +//! mirror there: a programmatic paste takes it from the engine clipboard, while a user's paste +//! goes by what the system clipboard holds, as it does for copied layers. + +use egui::{Color32, Context, Rect, Response}; +use figcraft_doc::NodeId; +use serde_json::json; + +use crate::{FigApp, RightTab}; + +/// Which list of the Design panel a row belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PropertyKind { + Fill, + Stroke, + Effect, +} + +impl PropertyKind { + /// The command that copies row `index` of this list. + fn copy_command(self) -> &'static str { + match self { + PropertyKind::Fill => "fill.copy", + PropertyKind::Stroke => "stroke.copy", + PropertyKind::Effect => "effect.copy", + } + } + + /// The command that pastes the copied paint or effect. + fn paste_command(self) -> &'static str { + match self { + PropertyKind::Fill => "fill.paste", + PropertyKind::Stroke => "stroke.paste", + PropertyKind::Effect => "effect.paste", + } + } + + /// What the system clipboard gets when the copy has no text of its own: the marker that also + /// stands for copied layers, so a paste never makes a text layer of it. + fn marker(self) -> &'static str { + match self { + PropertyKind::Fill => "figcraft://clipboard/fill", + PropertyKind::Stroke => "figcraft://clipboard/stroke", + PropertyKind::Effect => "figcraft://clipboard/effect", + } + } + + /// Whether the engine clipboard still holds a copy of this kind. + fn on_clipboard(self, app: &FigApp) -> bool { + let clip = &app.session.clipboard; + match self { + PropertyKind::Fill => clip.paint.as_ref().is_some_and(|(fills, _)| *fills), + PropertyKind::Stroke => clip.paint.as_ref().is_some_and(|(fills, _)| !*fills), + PropertyKind::Effect => clip.effect.is_some(), + } + } +} + +/// The row highlighted in the Design panel. It belongs to the layers selected when it was clicked +/// and goes when they are no longer the selection. +#[derive(Clone, Debug, PartialEq)] +pub struct Highlight { + pub kind: PropertyKind, + /// The paint's or effect's index in its list (model order: the top one is the last). + pub index: usize, + /// The selection the row was highlighted on. + pub ids: Vec, + /// The file it was highlighted in. + pub doc: u64, + /// Where the row was drawn this frame (`None` until it draws): a press elsewhere lets it go, + /// and so does a frame it isn't drawn in. + pub rect: Option, +} + +/// A paint or effect copied from its row: Cmd/Ctrl+V pastes it rather than the copied layers while +/// it is the last thing copied. +#[derive(Clone, Debug, PartialEq)] +pub struct Copied { + pub kind: PropertyKind, + /// The engine clipboard's layers generation at the copy: a layer copy since moves it on. + pub layers_generation: u64, + /// What the copy put on the system clipboard (`None`: a programmatic copy, which never writes + /// it). A user's paste takes the property only while the system clipboard is still that. + pub mirror: Option, +} + +/// The highlighted row, when it still belongs to the selection in the Design panel. +pub(crate) fn current(app: &FigApp) -> Option<&Highlight> { + let h = app.ui.property_row.as_ref()?; + let ds = app.session.ds().ok()?; + (app.ui.right_tab == RightTab::Design && ds.uid == h.doc && ds.selection == h.ids).then_some(h) +} + +/// Let the highlight go once it no longer belongs to what the Design panel shows (another file or +/// tab, another selection, the panel not `shown`), or when the pointer is pressed on the canvas or +/// elsewhere in the Design panel. A press on its own row keeps it; so does one on a menu, a popup +/// or the toolbar, so Edit ▸ Copy still copies the highlighted property. Called each frame before +/// the right panel draws its rows. +pub(crate) fn reconcile(app: &mut FigApp, ctx: &Context, shown: bool) { + if app.ui.property_row.is_none() { + return; + } + let pressed = ctx.input(|i| if i.pointer.any_pressed() { i.pointer.press_origin() } else { None }); + // A menu or popup is a foreground area over whatever is under it. + let lets_go = pressed.filter(|p| ctx.layer_id_at(*p).is_none_or(|l| l.order != egui::Order::Foreground)).is_some_and(|p| { + let on_row = app.ui.property_row.as_ref().and_then(|h| h.rect).is_some_and(|r| r.contains(p)); + let in_panel = app.ui.right_panel_rect.is_some_and(|r| r.contains(p)); + !on_row && (in_panel || app.canvas.rect.contains(p)) + }); + // The row draws itself each frame (`row`): one that wasn't drawn last frame is gone (an undo + // took its paint away, say), and its index may now name another row or none. + let drawn = app.ui.property_row.as_ref().is_some_and(|h| h.rect.is_some()); + if lets_go || !shown || !drawn || current(app).is_none() { + app.ui.property_row = None; + } else if let Some(h) = app.ui.property_row.as_mut() { + h.rect = None; + } +} + +/// Escape with a highlighted row: the highlight goes and the selection stays. `false` when no row +/// is highlighted (Escape does what it does otherwise). +pub(crate) fn escape(app: &mut FigApp) -> bool { + let highlighted = current(app).is_some(); + app.ui.property_row = None; + highlighted +} + +/// Row `index` of the `kind` list, drawn as `resp` (a row target, see [`fill`]) for the selection +/// `ids`: a click on its background highlights it; the highlighted row keeps where it was drawn. +pub(crate) fn row(app: &mut FigApp, resp: &Response, kind: PropertyKind, index: usize, ids: &[NodeId]) { + if resp.clicked() { + click(app, kind, index, ids, resp.rect); + } else if let Some(h) = app.ui.property_row.as_mut() + && h.kind == kind + && h.index == index + { + h.rect = Some(resp.rect); + } +} + +/// A click on row `index` of the `kind` list (drawn at `rect`) for the selection `ids`, on its +/// background or on its reorder grip, the strip left of its fields: it is the highlighted row now. +pub(crate) fn click(app: &mut FigApp, kind: PropertyKind, index: usize, ids: &[NodeId], rect: Rect) { + let Some(doc) = app.session.ds().ok().map(|d| d.uid) else { return }; + app.ui.property_row = Some(Highlight { kind, index, ids: ids.to_vec(), doc, rect: Some(rect) }); +} + +/// The background of row `index` of the `kind` list: the selected-row colour when it is the +/// highlighted one. +pub(crate) fn fill(app: &FigApp, kind: PropertyKind, index: usize, selected: Color32) -> Option { + current(app).is_some_and(|h| h.kind == kind && h.index == index).then_some(selected) +} + +/// The highlight follows its paint or effect when the rows of `kind` are reordered (`from` moved +/// to `to`) or one is removed (`to` is `None`); it goes with a removed one. +pub(crate) fn follow(app: &mut FigApp, kind: PropertyKind, from: usize, to: Option) { + let Some(h) = app.ui.property_row.as_mut().filter(|h| h.kind == kind) else { return }; + let moved = match to { + Some(to) => Some(figcraft_engine::cmd::lists::moved_index(h.index, from, to)), + None => figcraft_engine::cmd::lists::removed_index(h.index, from), + }; + match moved { + Some(i) => h.index = i, + None => app.ui.property_row = None, + } +} + +/// Cmd/Ctrl+C with a highlighted row: copy its paint or effect. `false` when no row is +/// highlighted (the layers are copied as usual). +pub(crate) fn copy_highlighted(app: &mut FigApp) -> bool { + let Some(h) = current(app).cloned() else { return false }; + copy(app, h.kind, h.index, &h.ids); + true +} + +/// Copy paint or effect `index` of the `kind` list of `ids` (a highlighted row, or the row's menu) +/// and remember it as the last thing copied. A solid colour goes to the system clipboard as its +/// hex code, as other apps read colours; anything else as a marker of the copy. +pub(crate) fn copy(app: &mut FigApp, kind: PropertyKind, index: usize, ids: &[NodeId]) { + let Some(copied) = app.run(kind.copy_command(), json!({"ids": ids, "index": index})) else { return }; + let layers_generation = app.session.clipboard.layers_generation; + let mirror = if app.control_synthetic { + // The engine's copy is no longer what the system clipboard mirrors: a user's paste must + // not take that text for this copy (`menus::paste` would paste stale layers). + if app.ui.property_copy.as_ref().is_some_and(|c| c.mirror.is_some() && c.mirror == app.ui.last_copy) { + app.ui.last_copy = None; + } + None + } else { + let text = match kind { + PropertyKind::Effect => None, + PropertyKind::Fill | PropertyKind::Stroke => { + serde_json::from_value::(copied).ok().and_then(|p| p.solid_color()).map(figcraft_color::Color::to_css_hex) + } + } + .unwrap_or_else(|| kind.marker().to_string()); + app.clipboard_set_text(&text); + // The system clipboard holds our copy now: a paste reads it as ours (`menus::paste`). + app.ui.last_copy = Some(text.clone()); + app.ui.last_copy_generation = layers_generation; + Some(text) + }; + app.ui.property_copy = Some(Copied { kind, layers_generation, mirror }); +} + +/// Cmd/Ctrl+V when nothing newer than our own copy is on the system clipboard: when a paint or +/// effect copied from its row is the last thing copied, paste it onto the selected layers (in +/// place of their highlighted row of that kind, else on top) and return `true`; `false` leaves +/// the paste to the copied layers. +pub(crate) fn paste(app: &mut FigApp) -> bool { + let Some(c) = app.ui.property_copy.clone() else { return false }; + let still_last = c.layers_generation == app.session.clipboard.layers_generation + && c.kind.on_clipboard(app) + // A user's paste: the system clipboard must still be what this copy put there. A + // programmatic paste reads only the engine clipboard. + && (app.control_synthetic || (c.mirror.is_some() && app.ui.last_copy == c.mirror)); + if !still_last { + // No layers were copied since this copy, but the engine's copy of it is gone (a command + // copied a paint or effect of another kind since): nothing to paste, rather than the + // layers copied before it. For a user's paste, only while the system clipboard still + // holds this copy's mirror; a programmatic paste reads only the engine clipboard. + let ours = app.control_synthetic + || (c.mirror.is_some() && app.ui.last_copy == c.mirror && app.ui.last_copy_generation == app.session.clipboard.layers_generation); + return ours && c.layers_generation == app.session.clipboard.layers_generation; + } + let ids = app.session.selection(); + if ids.is_empty() { + // Nothing to paste onto: a paste of the layers copied before would be surprising. + return true; + } + let cmd = c.kind.paste_command(); + if crate::menus::dev_mode_refuses(app, cmd) { + return true; + } + let mut params = json!({"ids": ids}); + if let Some(h) = current(app).filter(|h| h.kind == c.kind) { + params["index"] = json!(h.index); + } + app.run(cmd, params); + true +} diff --git a/crates/ui-egui/src/property_rows_tests.rs b/crates/ui-egui/src/property_rows_tests.rs new file mode 100644 index 000000000..d997973b7 --- /dev/null +++ b/crates/ui-egui/src/property_rows_tests.rs @@ -0,0 +1,513 @@ +//! A fill, stroke or effect row of the Design panel highlights on a click on its background, and +//! the keyboard copies and pastes it ("Copy and paste properties between layers": click to +//! highlight the property in the right sidebar, Cmd/Ctrl+C, select another layer, Cmd/Ctrl+V). + +use std::cell::RefCell; +use std::rc::Rc; + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::Services; +use crate::layers_drag_tests::Ui; +use crate::live_tests::{flat, text_center}; +use crate::property_rows::{Highlight, PropertyKind}; + +/// The test machine's system clipboard: the text last written, which another app may replace. +struct Clip(Rc>>); + +impl Services for Clip { + fn clipboard_set_text(&mut self, s: &str) { + *self.0.borrow_mut() = Some(s.to_string()); + } + fn clipboard_get_text(&mut self) -> Option { + self.0.borrow().clone() + } +} + +/// A 40 x 40 rectangle filled with `color`; its id. +fn rect(s: &mut Session, x: f64, color: &str) -> NodeId { + let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()); + s.execute("fill.set", &json!({"ids": [id], "color": color})).unwrap(); + id +} + +/// Rectangles A (red, a 3 pt blue stroke and a layer blur) and B (green, a drop shadow), A +/// selected, in a window whose system clipboard the test reads and writes. +fn setup() -> (Ui, NodeId, NodeId, Rc>>) { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, "#FF0000"); + let b = rect(&mut s, 100.0, "#00FF00"); + s.execute("stroke.add", &json!({"ids": [a], "paint": {"type": "solid", "color": "#0000FF"}})).unwrap(); + s.execute("node.set", &json!({"ids": [a], "props": {"strokeWeight": 3.0}})).unwrap(); + s.execute("effect.add", &json!({"ids": [a], "type": "layerBlur"})).unwrap(); + s.execute("effect.add", &json!({"ids": [b], "type": "dropShadow"})).unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let mut u = Ui::new(s); + let clip = Rc::new(RefCell::new(None)); + u.app.services = Box::new(Clip(clip.clone())); + u.frame(vec![]); + (u, a, b, clip) +} + +/// A primary click at `p`, and a few frames after it. +fn click(u: &mut Ui, p: Pos2) { + u.frame(vec![Event::PointerMoved(p)]); + for pressed in [true, false] { + u.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + u.frame(vec![]); +} + +/// Click the background of the Design panel row showing `label`: its left margin, where no +/// control is (the reorder grip shows there on hover). +fn click_row(u: &mut Ui, label: &str) { + let shapes = flat(&u.frame_output(vec![]).shapes); + let y = text_center(&shapes, label).y; + let panel = u.app.ui.right_panel_rect.expect("the Design panel is open"); + click(u, pos2(panel.min.x + 6.0, y)); +} + +/// Cmd/Ctrl+C, as the desktop shell delivers it. +fn copy(u: &mut Ui) { + u.frame(vec![Event::Copy]); +} + +/// Cmd/Ctrl+V with the system clipboard's text, as the desktop shell delivers it. +fn paste(u: &mut Ui, clip: &Rc>>) { + let text = clip.borrow().clone().unwrap_or_default(); + u.frame(vec![Event::Paste(text)]); +} + +/// Select `id` only, and draw the panel for it. +fn select(u: &mut Ui, id: NodeId) { + u.app.run("select.set", json!({"ids": [id]})); + u.frame(vec![]); +} + +/// The hex codes of `id`'s fills, bottom to top. +fn fills(u: &Ui, id: NodeId) -> Vec { + let doc = u.app.session.doc().unwrap(); + doc.node(id).unwrap().fills.iter().map(|p| p.solid_color().unwrap().to_hex()).collect() +} + +#[test] +fn a_click_on_a_fill_rows_background_highlights_it_and_the_keyboard_copies_and_pastes_it() { + let (mut u, a, b, clip) = setup(); + click_row(&mut u, "FF0000"); + assert_eq!( + u.app.ui.property_row.as_ref().map(|h| (h.kind, h.index, h.ids.clone())), + Some((PropertyKind::Fill, 0, vec![a])), + "the row is highlighted for A" + ); + let layers_before = u.app.session.clipboard.layers_generation; + copy(&mut u); + let (fills_flag, paint) = u.app.session.clipboard.paint.clone().expect("the fill is on the clipboard"); + assert!(fills_flag); + assert_eq!(paint, u.app.session.doc().unwrap().node(a).unwrap().fills[0]); + assert_eq!(u.app.session.clipboard.layers_generation, layers_before, "the layers were not copied"); + assert!(u.app.session.clipboard.nodes.is_empty()); + assert_eq!(clip.borrow().as_deref(), Some("#FF0000"), "the colour goes to the system clipboard as its hex code"); + // Another layer selected, the paste puts the fill on top of its own. + select(&mut u, b); + assert!(u.app.ui.property_row.is_none(), "the highlight belonged to A"); + let layers = u.app.session.doc().unwrap().node_count(); + paste(&mut u, &clip); + assert_eq!(fills(&u, b), ["00FF00", "FF0000"]); + assert_eq!(u.app.session.doc().unwrap().node_count(), layers, "no layer was pasted"); + assert_eq!(fills(&u, a), ["FF0000"], "A keeps its fill"); + // One undo step takes it back off. + u.app.run("edit.undo", json!({})); + assert_eq!(fills(&u, b), ["00FF00"]); +} + +#[test] +fn a_paste_replaces_the_highlighted_row_of_the_target() { + let (mut u, _, b, clip) = setup(); + click_row(&mut u, "FF0000"); + copy(&mut u); + select(&mut u, b); + click_row(&mut u, "00FF00"); + assert_eq!(u.app.ui.property_row.as_ref().map(|h| (h.kind, h.index)), Some((PropertyKind::Fill, 0))); + paste(&mut u, &clip); + assert_eq!(fills(&u, b), ["FF0000"], "in place of B's highlighted fill"); +} + +#[test] +fn a_stroke_row_copies_its_paint_and_settings() { + let (mut u, a, b, clip) = setup(); + click_row(&mut u, "0000FF"); + assert_eq!(u.app.ui.property_row.as_ref().map(|h| h.kind), Some(PropertyKind::Stroke)); + copy(&mut u); + select(&mut u, b); + paste(&mut u, &clip); + let doc = u.app.session.doc().unwrap(); + let (na, nb) = (doc.node(a).unwrap(), doc.node(b).unwrap()); + assert_eq!(nb.strokes, na.strokes); + assert_eq!(nb.stroke.weight, 3.0, "the weight comes with the stroke"); + assert_eq!(fills(&u, b), ["00FF00"], "the fills are untouched"); +} + +#[test] +fn an_effect_row_copies_and_pastes_its_effect() { + let (mut u, a, b, clip) = setup(); + click_row(&mut u, "Layer blur"); + assert_eq!(u.app.ui.property_row.as_ref().map(|h| (h.kind, h.index)), Some((PropertyKind::Effect, 0))); + copy(&mut u); + assert_eq!(clip.borrow().as_deref(), Some("figcraft://clipboard/effect"), "an effect has no text: a marker of our copy"); + select(&mut u, b); + paste(&mut u, &clip); + let doc = u.app.session.doc().unwrap(); + let blur = doc.node(a).unwrap().effects[0].clone(); + assert_eq!(doc.node(b).unwrap().effects.len(), 2); + assert_eq!(doc.node(b).unwrap().effects[1], blur, "the blur goes on top of B's shadow"); +} + +#[test] +fn without_a_highlighted_row_the_keyboard_copies_and_pastes_layers() { + let (mut u, _, b, clip) = setup(); + copy(&mut u); + assert!(u.app.session.clipboard.paint.is_none(), "no fill was copied"); + assert_eq!(u.app.session.clipboard.nodes.len(), 1, "A was copied"); + select(&mut u, b); + let layers = u.app.session.doc().unwrap().node_count(); + paste(&mut u, &clip); + assert_eq!(u.app.session.doc().unwrap().node_count(), layers + 1, "a copy of A was pasted"); + assert_eq!(fills(&u, b), ["00FF00"]); +} + +#[test] +fn copying_layers_after_a_fill_pastes_the_layers() { + let (mut u, a, b, clip) = setup(); + click_row(&mut u, "FF0000"); + copy(&mut u); + // Another selection lets the highlight go; the next copy takes the layers. + select(&mut u, b); + select(&mut u, a); + assert!(u.app.ui.property_row.is_none(), "selecting A again doesn't bring the highlight back"); + copy(&mut u); + select(&mut u, b); + let layers = u.app.session.doc().unwrap().node_count(); + paste(&mut u, &clip); + assert_eq!(u.app.session.doc().unwrap().node_count(), layers + 1, "the layers were the last copy"); + assert_eq!(fills(&u, b), ["00FF00"]); +} + +#[test] +fn text_copied_in_another_app_afterwards_pastes_as_text() { + let (mut u, _, b, clip) = setup(); + click_row(&mut u, "FF0000"); + copy(&mut u); + select(&mut u, b); + *clip.borrow_mut() = Some("Hello".into()); + let layers = u.app.session.doc().unwrap().node_count(); + paste(&mut u, &clip); + assert_eq!(fills(&u, b), ["00FF00"], "the fill isn't what the clipboard holds now"); + assert_eq!(u.app.session.doc().unwrap().node_count(), layers + 1, "the text became a text layer"); +} + +#[test] +fn a_press_elsewhere_lets_the_highlight_go() { + let (mut u, a, _, _) = setup(); + click_row(&mut u, "FF0000"); + assert!(u.app.ui.property_row.is_some()); + // A press on the row's own background keeps it. + click_row(&mut u, "FF0000"); + assert!(u.app.ui.property_row.is_some()); + // One anywhere else in the panel lets it go, the selection staying as it is. + let shapes = flat(&u.frame_output(vec![]).shapes); + click(&mut u, text_center(&shapes, "Effects")); + assert_eq!(u.app.session.selection(), [a]); + assert!(u.app.ui.property_row.is_none()); + // With nothing highlighted Cmd/Ctrl+C copies the layer again. + copy(&mut u); + assert!(u.app.session.clipboard.paint.is_none()); +} + +#[test] +fn the_highlight_follows_its_row_when_rows_move_or_go() { + let (mut u, a, _, _) = setup(); + let doc = u.app.session.ds().unwrap().uid; + let at = |u: &Ui| u.app.ui.property_row.as_ref().map(|h| h.index); + u.app.ui.property_row = Some(Highlight { kind: PropertyKind::Fill, index: 1, ids: vec![a], doc, rect: None }); + crate::property_rows::follow(&mut u.app, PropertyKind::Fill, 1, Some(3)); + assert_eq!(at(&u), Some(3), "moved with its paint"); + crate::property_rows::follow(&mut u.app, PropertyKind::Stroke, 3, None); + assert_eq!(at(&u), Some(3), "another list's change leaves it"); + crate::property_rows::follow(&mut u.app, PropertyKind::Fill, 0, None); + assert_eq!(at(&u), Some(2), "a paint under it went"); + crate::property_rows::follow(&mut u.app, PropertyKind::Fill, 2, None); + assert_eq!(at(&u), None, "its paint went"); +} + +/// A key press with no modifiers, as the desktop shell delivers it. +fn key(u: &mut Ui, key: egui::Key) { + u.frame(vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + u.frame(vec![Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }]); +} + +#[test] +fn escape_lets_the_highlight_go_and_keeps_the_selection() { + let (mut u, a, _, _) = setup(); + click_row(&mut u, "FF0000"); + assert!(u.app.ui.property_row.is_some()); + key(&mut u, egui::Key::Escape); + assert!(u.app.ui.property_row.is_none(), "Escape let the highlight go"); + assert_eq!(u.app.session.selection(), [a], "and only that: A is still selected"); + // The next Escape deselects, as it does with no row highlighted. + key(&mut u, egui::Key::Escape); + assert!(u.app.session.selection().is_empty()); +} + +#[test] +fn a_click_on_the_canvas_lets_the_highlight_go() { + let (mut u, a, _, _) = setup(); + u.app.run("view.zoomFit", json!({})); + u.frame(vec![]); + click_row(&mut u, "FF0000"); + assert!(u.app.ui.property_row.is_some()); + // A click on A itself: the selection stays as it is, the highlight goes. + let on_a = u.app.to_screen(20.0, 20.0); + assert!(u.app.canvas.rect.contains(on_a), "A is in view"); + click(&mut u, on_a); + assert_eq!(u.app.session.selection(), [a]); + assert!(u.app.ui.property_row.is_none()); +} + +#[test] +fn edit_copy_from_the_menu_copies_the_highlighted_row() { + let (mut u, _, _, _) = setup(); + click_row(&mut u, "FF0000"); + crate::menus::invoke(&mut u.app, "edit.copy"); + assert!(u.app.session.clipboard.paint.as_ref().is_some_and(|(fills, _)| *fills), "the fill was copied"); + assert!(u.app.session.clipboard.nodes.is_empty(), "not the layer"); +} + +#[test] +fn a_paste_onto_several_layers_adds_the_fill_to_each_in_one_undo_step() { + let (mut u, a, b, clip) = setup(); + let c = rect(&mut u.app.session, 200.0, "#0000FF"); + // A new rectangle is selected: A again. + select(&mut u, a); + click_row(&mut u, "FF0000"); + copy(&mut u); + // B and C have different fills: the panel shows mixed content, no row to highlight. + u.app.run("select.set", json!({"ids": [b, c]})); + u.frame(vec![]); + paste(&mut u, &clip); + assert_eq!(fills(&u, b), ["00FF00", "FF0000"]); + assert_eq!(fills(&u, c), ["0000FF", "FF0000"]); + u.app.run("edit.undo", json!({})); + assert_eq!((fills(&u, b), fills(&u, c)), (vec!["00FF00".to_string()], vec!["0000FF".to_string()])); +} + +#[test] +fn a_paste_replaces_the_highlighted_row_on_every_selected_layer() { + let (mut u, a, b, clip) = setup(); + let c = rect(&mut u.app.session, 200.0, "#00FF00"); + // A new rectangle is selected: A again. + select(&mut u, a); + click_row(&mut u, "FF0000"); + copy(&mut u); + // B and C share their fill: its row shows for both. + u.app.run("select.set", json!({"ids": [b, c]})); + u.frame(vec![]); + click_row(&mut u, "00FF00"); + assert_eq!(u.app.ui.property_row.as_ref().map(|h| h.ids.clone()), Some(vec![b, c])); + paste(&mut u, &clip); + assert_eq!((fills(&u, b), fills(&u, c)), (vec!["FF0000".to_string()], vec!["FF0000".to_string()])); + u.app.run("edit.undo", json!({})); + assert_eq!((fills(&u, b), fills(&u, c)), (vec!["00FF00".to_string()], vec!["00FF00".to_string()])); +} + +#[test] +fn a_copied_stroke_goes_to_the_strokes_with_a_fill_row_highlighted() { + let (mut u, a, b, clip) = setup(); + click_row(&mut u, "0000FF"); + copy(&mut u); + select(&mut u, b); + click_row(&mut u, "00FF00"); + assert_eq!(u.app.ui.property_row.as_ref().map(|h| h.kind), Some(PropertyKind::Fill)); + paste(&mut u, &clip); + let doc = u.app.session.doc().unwrap(); + assert_eq!(doc.node(b).unwrap().strokes, doc.node(a).unwrap().strokes, "the stroke went to the strokes"); + assert_eq!(fills(&u, b), ["00FF00"], "the highlighted fill wasn't replaced"); +} + +#[test] +fn an_effect_copied_after_a_fill_is_what_pastes() { + let (mut u, a, b, clip) = setup(); + click_row(&mut u, "FF0000"); + copy(&mut u); + click_row(&mut u, "Layer blur"); + copy(&mut u); + select(&mut u, b); + paste(&mut u, &clip); + assert_eq!(fills(&u, b), ["00FF00"], "the fill was copied first: not pasted"); + let doc = u.app.session.doc().unwrap(); + assert_eq!(doc.node(b).unwrap().effects.get(1), doc.node(a).unwrap().effects.first(), "the blur went on top of B's shadow"); +} + +#[test] +fn a_row_menu_copy_is_pasted_by_the_keyboard() { + let (mut u, _, b, clip) = setup(); + let shapes = flat(&u.frame_output(vec![]).shapes); + let p = text_center(&shapes, "FF0000"); + for pressed in [true, false] { + u.frame(vec![Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }]); + } + let menu = flat(&u.frame_output(vec![]).shapes); + click(&mut u, text_center(&menu, crate::i18n::tr("Copy fill"))); + assert_eq!(clip.borrow().as_deref(), Some("#FF0000")); + select(&mut u, b); + paste(&mut u, &clip); + assert_eq!(fills(&u, b), ["00FF00", "FF0000"]); +} + +#[test] +fn programmatic_copy_and_paste_of_a_row_leave_the_system_clipboard_alone() { + let (mut u, a, b, clip) = setup(); + *clip.borrow_mut() = Some("the user's text".into()); + let doc = u.app.session.ds().unwrap().uid; + u.app.ui.property_row = Some(Highlight { kind: PropertyKind::Fill, index: 0, ids: vec![a], doc, rect: None }); + u.app.control_synthetic = true; + crate::menus::invoke(&mut u.app, "edit.copy"); + assert_eq!(clip.borrow().as_deref(), Some("the user's text"), "never written"); + u.app.run("select.set", json!({"ids": [b]})); + crate::menus::paste(&mut u.app, None, None); + assert_eq!(fills(&u, b), ["00FF00", "FF0000"]); +} + +#[test] +fn a_property_copy_whose_engine_copy_is_gone_pastes_no_stale_layers() { + let (mut u, a, b, clip) = setup(); + // A layer copy first, then the fill row's. + copy(&mut u); + click_row(&mut u, "FF0000"); + copy(&mut u); + // A stroke copied without its row (the Actions palette): the fill is no longer on the clipboard. + u.app.run("stroke.copy", json!({"id": a})); + select(&mut u, b); + let layers = u.app.session.doc().unwrap().node_count(); + paste(&mut u, &clip); + assert_eq!(u.app.session.doc().unwrap().node_count(), layers, "the layer copied before wasn't pasted"); + assert_eq!(fills(&u, b), ["00FF00"]); +} + +#[test] +fn a_highlighted_row_whose_paint_an_undo_took_away_goes() { + let (mut u, a, _, _) = setup(); + u.app.run("fill.add", json!({"ids": [a], "paint": {"type": "solid", "color": "#123456"}})); + u.frame(vec![]); + click_row(&mut u, "123456"); + assert_eq!(u.app.ui.property_row.as_ref().map(|h| h.index), Some(1)); + u.app.run("edit.undo", json!({})); + u.frame(vec![]); + u.frame(vec![]); + assert!(u.app.ui.property_row.is_none(), "its row isn't drawn any more"); + assert_eq!(u.app.session.selection(), [a]); +} + +#[test] +fn a_click_beside_the_rows_controls_highlights_it_too() { + let (mut u, _, _, _) = setup(); + // The row's grip, left of the swatch, highlights it (`click_row`); so does the gap between its + // colour field and its visibility button (the grid's 8 pt gutter, 60 pt from the row's right). + click_row(&mut u, "FF0000"); + let row = u.app.ui.property_row.as_ref().and_then(|h| h.rect).expect("the highlighted row was drawn"); + key(&mut u, egui::Key::Escape); + assert!(u.app.ui.property_row.is_none()); + click(&mut u, pos2(row.max.x - 64.0, row.center().y)); + assert_eq!(u.app.ui.property_row.as_ref().map(|h| (h.kind, h.index)), Some((PropertyKind::Fill, 0))); +} + +#[test] +fn a_click_on_a_rows_grip_highlights_that_row_for_the_selection() { + let (mut u, a, b, _) = setup(); + for (label, kind) in [("FF0000", PropertyKind::Fill), ("0000FF", PropertyKind::Stroke), ("Layer blur", PropertyKind::Effect)] { + click_row(&mut u, label); + assert_eq!( + u.app.ui.property_row.as_ref().map(|h| (h.kind, h.index, h.ids.clone())), + Some((kind, 0, vec![a])), + "{label}: one row highlighted, for A" + ); + } + // The row is drawn in the selected-row colour. + let t = crate::theme::Tokens::get(&u.ctx); + assert_eq!(crate::property_rows::fill(&u.app, PropertyKind::Effect, 0, t.selected_row), Some(t.selected_row)); + assert_eq!(crate::property_rows::fill(&u.app, PropertyKind::Fill, 0, t.selected_row), None); + // It belonged to A: another selection lets it go, and A selected again doesn't bring it back. + select(&mut u, b); + assert!(u.app.ui.property_row.is_none()); + select(&mut u, a); + assert!(u.app.ui.property_row.is_none()); +} + +#[test] +fn a_programmatic_paste_after_a_property_copy_whose_engine_copy_is_gone_pastes_no_stale_layers() { + let (mut u, a, b, _) = setup(); + u.app.control_synthetic = true; + // A layer copy first, then the fill row's, both programmatic. + crate::menus::invoke(&mut u.app, "edit.copy"); + assert_eq!(u.app.session.clipboard.nodes.len(), 1, "A was copied"); + crate::property_rows::copy(&mut u.app, PropertyKind::Fill, 0, &[a]); + // A stroke copied without its row: the fill is no longer on the clipboard. + u.app.run("stroke.copy", json!({"id": a})); + u.app.run("select.set", json!({"ids": [b]})); + let layers = u.app.session.doc().unwrap().node_count(); + crate::menus::paste(&mut u.app, None, None); + assert_eq!(u.app.session.doc().unwrap().node_count(), layers, "the layer copied before wasn't pasted"); + assert_eq!(fills(&u, b), ["00FF00"]); + assert!(u.app.session.doc().unwrap().node(b).unwrap().strokes.is_empty()); +} + +#[test] +fn an_effect_paste_replaces_the_highlighted_effect_above_the_bottom_one() { + let (mut u, a, b, clip) = setup(); + u.app.run("effect.add", json!({"ids": [b], "type": "innerShadow"})); + click_row(&mut u, "Layer blur"); + copy(&mut u); + select(&mut u, b); + // B's effects, bottom to top: a drop shadow, an inner shadow (drawn first, at the top). + click_row(&mut u, "Inner shadow"); + assert_eq!(u.app.ui.property_row.as_ref().map(|h| (h.kind, h.index)), Some((PropertyKind::Effect, 1))); + paste(&mut u, &clip); + let doc = u.app.session.doc().unwrap(); + let (blur, effects) = (&doc.node(a).unwrap().effects[0], &doc.node(b).unwrap().effects); + assert_eq!(effects.len(), 2, "replaced, not added"); + assert_eq!(effects[1], *blur, "the blur took the inner shadow's place"); + assert_eq!(effects[0].label(), "Drop shadow", "the drop shadow under it stays"); +} + +#[test] +fn a_property_copied_in_one_window_pastes_in_another_and_the_highlight_stays_in_its_window() { + let mut s = Session::empty(); + s.execute("file.new", &json!({"name": "A"})).unwrap(); + let a = rect(&mut s, 0.0, "#FF0000"); + s.execute("file.new", &json!({"name": "B"})).unwrap(); + let b = rect(&mut s, 0.0, "#00FF00"); + let clip = Rc::new(RefCell::new(None)); + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let mut app = crate::FigApp::new(s, Box::new(Clip(clip.clone()))); + ctx.run_ui(egui::RawInput::default(), |ui| app.ui(ui)).textures_delta.clear(); + // File A goes to a window of its own; the main window shows B. + let w = crate::control::handle(&mut app, &ctx, "window.new", &json!({"index": 0})).unwrap()["window"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [b]})); + let doc = app.session.ds().unwrap().uid; + app.ui.property_row = Some(Highlight { kind: PropertyKind::Fill, index: 0, ids: vec![b], doc, rect: None }); + crate::menus::invoke(&mut app, "edit.copy"); + assert_eq!(clip.borrow().as_deref(), Some("#00FF00")); + let text = clip.borrow().clone(); + let pasted = crate::windows::as_window(&mut app, w, |app| { + assert!(app.ui.property_row.is_none(), "the highlight belongs to the main window"); + app.run("select.set", json!({"ids": [a]})); + crate::menus::paste(app, text.as_deref(), None); + app.session.doc().unwrap().node(a).unwrap().fills.iter().map(|p| p.solid_color().unwrap().to_hex()).collect::>() + }); + let fills = pasted.expect("the window exists"); + assert_eq!(fills, ["FF0000", "00FF00"], "B's fill went on top of A's"); + assert!(app.ui.property_row.is_some(), "the main window keeps its highlight"); +} diff --git a/crates/ui-egui/src/selection_colors_tests.rs b/crates/ui-egui/src/selection_colors_tests.rs new file mode 100644 index 000000000..2164d3a6e --- /dev/null +++ b/crates/ui-egui/src/selection_colors_tests.rs @@ -0,0 +1,96 @@ +//! When the Design panel shows Selection colors (#2188): measured in Figma's web app, a layer with +//! children shows the section from one distinct colour, while layers without children need two. +//! Driven through egui headless; each row has a "Select layers with this color" button. + +use egui::accesskit::Role; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::{Value, json}; + +use crate::layers_drag_tests::Ui; + +const ROW_BUTTON: &str = "Select layers with this color"; + +fn id(v: Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: i32, color: &str, parent: Option) -> NodeId { + let mut p = json!({"x": x, "y": 0, "width": 40, "height": 40}); + if let Some(parent) = parent { + p["parent"] = json!(parent); + } + let r = id(s.execute("shape.rectangle", &p).unwrap()); + s.execute("fill.set", &json!({"ids": [r], "color": color})).unwrap(); + r +} + +fn frame(s: &mut Session, fill: Option<&str>) -> NodeId { + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()); + match fill { + Some(c) => s.execute("fill.set", &json!({"ids": [f], "color": c})).unwrap(), + None => s.execute("fill.remove", &json!({"ids": [f], "index": 0})).unwrap(), + }; + f +} + +/// How many Selection colors rows the Design panel shows with `ids` selected. +fn rows(mut s: Session, ids: &[NodeId]) -> usize { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + let out = u.frame_output(vec![]); + let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; + nodes.iter().filter(|(_, n)| n.role() == Role::Button && n.label() == Some(ROW_BUTTON)).count() +} + +#[test] +fn a_frame_holding_one_red_layer_shows_selection_colors_with_one_row() { + let mut s = Session::new(); + let f = frame(&mut s, None); + rect(&mut s, 10, "#FF0000", Some(f)); + assert_eq!(rows(s, &[f]), 1); +} + +#[test] +fn a_group_of_two_red_layers_shows_one_row() { + let mut s = Session::new(); + let a = rect(&mut s, 0, "#FF0000", None); + let b = rect(&mut s, 60, "#FF0000", None); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + assert_eq!(rows(s, &[g]), 1); +} + +#[test] +fn an_instance_whose_child_has_one_fill_shows_selection_colors() { + let mut s = Session::new(); + let f = frame(&mut s, None); + rect(&mut s, 10, "#FF0000", Some(f)); + let c = id(s.execute("component.create", &json!({"ids": [f]})).unwrap()); + let i = id(s.execute("instance.create", &json!({"component": c, "x": 400, "y": 0})).unwrap()); + assert_eq!(rows(s, &[i]), 1); +} + +#[test] +fn one_layer_or_two_of_the_same_colour_without_children_hide_it() { + let mut s = Session::new(); + let a = rect(&mut s, 0, "#FF0000", None); + assert_eq!(rows(s, &[a]), 0, "one red rectangle"); + let mut s = Session::new(); + let a = rect(&mut s, 0, "#FF0000", None); + let b = rect(&mut s, 60, "#FF0000", None); + assert_eq!(rows(s, &[a, b]), 0, "two red rectangles"); + let mut s = Session::new(); + let g = frame(&mut s, Some("#00FF00")); + assert_eq!(rows(s, &[g]), 0, "a childless green frame"); +} + +#[test] +fn two_loose_layers_of_different_colours_show_two_rows() { + let mut s = Session::new(); + let a = rect(&mut s, 0, "#FF0000", None); + let b = rect(&mut s, 60, "#0000FF", None); + assert_eq!(rows(s, &[a, b]), 2); +} diff --git a/crates/ui-egui/src/shortcut_keys_tests.rs b/crates/ui-egui/src/shortcut_keys_tests.rs index dbe6ab3b9..e48a3d0bb 100644 --- a/crates/ui-egui/src/shortcut_keys_tests.rs +++ b/crates/ui-egui/src/shortcut_keys_tests.rs @@ -44,13 +44,13 @@ fn arrows_pan_the_view_when_nothing_is_selected() { u.app.run("select.set", json!({"ids": []})); u.app.run("view.set", json!({"zoom": 2.0, "cx": 0, "cy": 0})); press(&mut u, Key::ArrowRight, Modifiers::NONE); - assert_eq!(view(&u), (10.0, 0.0, 2.0), "20 screen pixels at 200%"); + assert_eq!(view(&u), (32.0, 0.0, 2.0), "64 screen pixels at 200% are 32 document pixels"); press(&mut u, Key::ArrowUp, Modifiers::SHIFT); - assert_eq!(view(&u), (10.0, -100.0, 2.0), "Shift: ten times as far"); + assert_eq!(view(&u), (32.0, -160.0, 2.0), "Shift: 320 screen pixels, 160 document pixels"); // With a selection the arrows nudge it and the view stays. u.app.run("select.set", json!({"ids": [r]})); press(&mut u, Key::ArrowRight, Modifiers::NONE); - assert_eq!(view(&u), (10.0, -100.0, 2.0)); + assert_eq!(view(&u), (32.0, -160.0, 2.0)); assert_eq!(u.app.session.doc().unwrap().world_bounds(r).unwrap().x0, 1.0); } diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 48b61c39c..3d312387b 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -433,6 +433,11 @@ fn key_event(app: &mut FigApp, key: Key, physical: Option, m: Modifiers, re if key == Key::Escape && !egui::Popup::is_any_open(ctx) && crate::colorpicker::close_if_open(app) { return true; } + // A fill, stroke or effect row highlighted in the Design panel: Escape lets it go, before the + // binding deselects the layers. + if key == Key::Escape && m.is_none() && !egui::Popup::is_any_open(ctx) && crate::property_rows::escape(app) { + return true; + } if key_pick(app, key, m) || key_box(app, key, m) { return true; } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6480983f5..7e6b9aa3f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -27,10 +27,11 @@ pub enum TitleBar { pub type AutoSaveEncoding = std::thread::JoinHandle<(figcraft_engine::cmd::file::FileSnapshot, figcraft_engine::Result>)>; /// The side panels' widths: the least and most a drag of their edge gives, what a double-click on -/// the edge puts back, and how much of the window they leave the canvas. -pub const LEFT_PANEL: std::ops::RangeInclusive = 200.0..=480.0; +/// the edge puts back, and how much of the window they leave the canvas. The limits are Figma's, +/// measured in the web app: left 240 to 450, right 240 to 500, both 240 by default. +pub const LEFT_PANEL: std::ops::RangeInclusive = 240.0..=450.0; -pub const RIGHT_PANEL: std::ops::RangeInclusive = 240.0..=480.0; +pub const RIGHT_PANEL: std::ops::RangeInclusive = 240.0..=500.0; pub const PANEL_DEFAULT: f32 = 240.0; diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 7aff24993..d57f2019b 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -626,8 +626,8 @@ fn flyout(app: &mut FigApp, ui: &mut Ui, g: &Group, bottom_left: egui::Pos2) { /// Choose `tool` from the toolbar. Dev Mode only inspects: a tool that edits leaves it for the /// design. -fn choose(app: &mut FigApp, tool: ToolId) { - if app.ui.right_tab == crate::RightTab::Inspect && !matches!(tool, ToolId::Move | ToolId::Hand | ToolId::Comment) { +pub(crate) fn choose(app: &mut FigApp, tool: ToolId) { + if app.ui.right_tab == crate::RightTab::Inspect && !tool.works_in_dev_mode() { app.ui.right_tab = crate::RightTab::Design; } app.run("tool.set", json!({"tool": tool.id()})); diff --git a/crates/ui-egui/src/variables_select_tests.rs b/crates/ui-egui/src/variables_select_tests.rs index cfb93efd6..3b32dc49d 100644 --- a/crates/ui-egui/src/variables_select_tests.rs +++ b/crates/ui-egui/src/variables_select_tests.rs @@ -268,6 +268,24 @@ fn grouped_window() -> Ui { u } +/// Three colour variables: bravo and charlie also have Stroke in their scopes, delta does not. +fn colour_window() -> Ui { + let mut s = Session::new(); + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + for (n, scopes) in + [("bravo", json!(["FRAME_FILL", "STROKE_COLOR"])), ("charlie", json!(["FRAME_FILL", "STROKE_COLOR"])), ("delta", json!(["FRAME_FILL"]))] + { + s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": "color", "value": "#ff0000"})).unwrap(); + s.execute("variable.update", &json!({"variable": n, "scopes": scopes})).unwrap(); + } + let mut u = Ui::new(s); + u.app.ui.variables = Some(Default::default()); + for _ in 0..10 { + u.frame(vec![]); + } + u +} + /// Right-click the group row `name` and choose Duplicate group. fn duplicate_group(u: &mut Ui, name: &str) { let p = row(u, name); @@ -313,3 +331,157 @@ fn a_second_duplicate_group_takes_the_next_free_name() { assert!(n.contains(&"space 2/sm".to_string()) && n.contains(&"space 3/md".to_string()), "{n:?}"); assert_eq!(n.len(), 6); } + +fn open_edit_variables(u: &mut Ui) -> Vec { + let menu = select_three_and_open_menu(u); + assert!(has_text(&menu, "Edit variables"), "the bulk menu offers Edit variables"); + click(u, text_center(&menu, "Edit variables"), PointerButton::Primary, Modifiers::NONE); + flat(&u.frame_output(vec![]).shapes) +} + +fn flags(u: &Ui) -> Vec<(bool, bool)> { + let doc = u.app.session.doc().unwrap(); + ["bravo", "charlie", "delta"] + .iter() + .map(|n| { + let v = doc.variables.variables.iter().find(|v| v.name == *n).unwrap(); + (v.hidden_from_publishing, v.in_scope("STROKE_COLOR")) + }) + .collect() +} + +#[test] +fn edit_variables_sets_stroke_on_all_selected_in_one_undo_step() { + let mut u = colour_window(); + let shapes = open_edit_variables(&mut u); + assert!(has_text(&shapes, "Hide from publishing") && has_text(&shapes, "Scope")); + click(&mut u, text_center(&shapes, "Scope"), PointerButton::Primary, Modifiers::NONE); + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&shapes, "Stroke")); + assert_eq!(flags(&u), [(false, true), (false, true), (false, false)]); + let before = u.app.session.undo_labels(100).len(); + click(&mut u, text_center(&shapes, "Stroke"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); + assert_eq!(flags(&u), [(false, true), (false, true), (false, true)]); + assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step"); + u.app.session.undo().unwrap(); + assert_eq!(flags(&u), [(false, true), (false, true), (false, false)]); +} + +#[test] +fn edit_variables_hides_all_selected_from_publishing_in_one_undo_step() { + let mut u = colour_window(); + let shapes = open_edit_variables(&mut u); + let before = u.app.session.undo_labels(100).len(); + click(&mut u, text_center(&shapes, "Hide from publishing"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); + assert!(flags(&u).iter().all(|f| f.0), "all hidden"); + assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step"); + u.app.session.undo().unwrap(); + assert!(flags(&u).iter().all(|f| !f.0)); +} + +/// Bravo, charlie and delta of the given types (a value fitting each). +fn typed_window(types: [&str; 3]) -> Ui { + let mut s = Session::new(); + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + for (n, t) in ["bravo", "charlie", "delta"].into_iter().zip(types) { + let value = match t { + "number" => json!(1), + "boolean" => json!(true), + "string" => json!("x"), + _ => json!("#ff0000"), + }; + s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": t, "value": value})).unwrap(); + } + let mut u = Ui::new(s); + u.app.ui.variables = Some(Default::default()); + for _ in 0..10 { + u.frame(vec![]); + } + u +} + +fn scope_tab(u: &mut Ui) -> Vec { + let shapes = open_edit_variables(u); + click(u, text_center(&shapes, "Scope"), PointerButton::Primary, Modifiers::NONE); + flat(&u.frame_output(vec![]).shapes) +} + +fn scopes(u: &Ui) -> Vec>> { + let doc = u.app.session.doc().unwrap(); + ["bravo", "charlie", "delta"].iter().map(|n| doc.variables.variables.iter().find(|v| v.name == *n).unwrap().scopes.clone()).collect() +} + +#[test] +fn all_supported_properties_turns_on_for_every_selected_variable_and_off_again_one_undo_step_each() { + let mut u = colour_window(); + let shapes = scope_tab(&mut u); + assert!(scopes(&u).iter().all(|s| s.is_some()), "each variable starts limited"); + let before = u.app.session.undo_labels(100).len(); + click(&mut u, text_center(&shapes, "All supported properties"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); + assert!(scopes(&u).iter().all(|s| s.is_none()), "on: no variable is limited: {:?}", scopes(&u)); + assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step"); + let shapes = flat(&u.frame_output(vec![]).shapes); + click(&mut u, text_center(&shapes, "All supported properties"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); + assert!(scopes(&u).iter().all(|s| s.as_ref().is_some_and(|l| l.is_empty())), "off: hidden from pickers: {:?}", scopes(&u)); + assert_eq!(u.app.session.undo_labels(100).len(), before + 2, "one undo step each"); +} + +#[test] +fn clicking_a_checked_scope_clears_it_on_every_selected_variable_in_one_undo_step() { + let mut u = colour_window(); + let shapes = scope_tab(&mut u); + let before = u.app.session.undo_labels(100).len(); + // Frame fill is on for all three: checked, so the click clears it. + click(&mut u, text_center(&shapes, "Frame fill"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); + let doc = u.app.session.doc().unwrap(); + assert!(["bravo", "charlie", "delta"].iter().all(|n| !doc.variables.variables.iter().find(|v| v.name == *n).unwrap().in_scope("FRAME_FILL"))); + assert_eq!(flags(&u), [(false, true), (false, true), (false, false)], "the other scopes stay"); + assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step"); + u.app.session.undo().unwrap(); + assert!(scopes(&u).iter().all(|s| s.as_ref().is_some_and(|l| l.iter().any(|x| x == "FRAME_FILL")))); +} + +#[test] +fn booleans_share_no_scope_and_the_scope_tab_says_so() { + let mut u = typed_window(["boolean", "boolean", "boolean"]); + let shapes = scope_tab(&mut u); + assert!(has_text(&shapes, "No scope is shared by all the selected variables")); + assert!(!has_text(&shapes, "All supported properties")); +} + +#[test] +fn mixed_types_list_only_the_scopes_every_type_has() { + // Number and string share only Text content; a colour shares nothing with them. + let mut u = typed_window(["number", "number", "string"]); + let shapes = scope_tab(&mut u); + assert!(has_text(&shapes, "Text content"), "the shared scope is shown"); + for other in ["Corner radius", "Font family", "Font size"] { + assert!(!has_text(&shapes, other), "{other} is not common"); + } + assert!(!has_text(&shapes, "No scope is shared by all the selected variables")); + let mut u = typed_window(["number", "color", "string"]); + let shapes = scope_tab(&mut u); + assert!(has_text(&shapes, "No scope is shared by all the selected variables")); +} + +#[test] +fn edit_variables_is_not_offered_when_every_selected_variable_is_inherited() { + let mut u = window(); + u.app.session.execute("variable.extendCollection", &json!({"collection": "Theme"})).unwrap(); + u.app.ui.variables = Some(crate::dialogs::variables_panel::Editor::on(Some("Theme (extended)".into()))); + for _ in 0..10 { + u.frame(vec![]); + } + click_row(&mut u, "bravo", Modifiers::NONE); + click_row(&mut u, "delta", SHIFT); + assert_eq!(selected(&u), ["bravo", "charlie", "delta"]); + let p = row(&mut u, "delta"); + click(&mut u, p, PointerButton::Secondary, Modifiers::NONE); + let menu = flat(&u.frame_output(vec![]).shapes); + assert!(!has_text(&menu, "Edit variables"), "inherited variables are edited in their own collection"); +} diff --git a/crates/ui-egui/src/vector_point_xy_tests.rs b/crates/ui-egui/src/vector_point_xy_tests.rs new file mode 100644 index 000000000..e93f62873 --- /dev/null +++ b/crates/ui-egui/src/vector_point_xy_tests.rs @@ -0,0 +1,79 @@ +//! The vector edit panel's Point section: X and Y show the value the selected points share, or +//! "Mixed", and a typed value sets every selected point's own coordinate. + +use egui::{Key, Modifiers}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::field_tests::{field, scrub, type_into, undo_steps}; +use crate::layers_drag_tests::Ui; + +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()); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("vector.edit.begin", &json!({"id": id})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + (u, id) +} + +fn xs(u: &Ui, id: NodeId) -> Vec<(f64, f64)> { + let doc = u.app.session.doc().unwrap(); + // In the parent's coordinates: the layer re-fits its box after an edit. + let t = doc.node(id).unwrap().transform; + figcraft_engine::vectoredit::network(doc, id).unwrap().vertices.iter().map(|v| t * v.point()).map(|p| (p.x, p.y)).collect() +} + +#[test] +fn x_reads_mixed_for_points_that_differ_and_typing_sets_every_point() { + let (mut u, id) = setup(); + u.app.session.execute("vector.edit.select", &json!({"vertices": [0, 1]})).unwrap(); + let before = xs(&u, id); + // Points 0 and 1 share their y but not their x. + assert_eq!(field(&mut u, "X").1, "Mixed"); + assert_eq!(field(&mut u, "Y").1, "0"); + type_into(&mut u, "X", "-200", Key::Enter); + let after = xs(&u, id); + assert_eq!((after[0].0, after[1].0), (-200.0, -200.0)); + assert_eq!((after[0].1, after[1].1), (before[0].1, before[1].1)); + assert_eq!(field(&mut u, "X").1, "-200", "the points share an x now"); + // A relative edit of a Mixed field goes to each point from its own value. + u.app.session.execute("vector.edit.select", &json!({"vertices": [1, 2]})).unwrap(); + assert_eq!(field(&mut u, "X").1, "Mixed"); + let b = xs(&u, id); + type_into(&mut u, "X", "+10", Key::Enter); + let a = xs(&u, id); + assert_eq!((a[1].0, a[2].0), (b[1].0 + 10.0, b[2].0 + 10.0)); +} + +#[test] +fn one_point_shows_its_own_value() { + let (mut u, id) = setup(); + u.app.session.execute("vector.edit.select", &json!({"vertices": [2]})).unwrap(); + let p = xs(&u, id)[2]; + assert_eq!(field(&mut u, "X").1, format!("{}", p.0)); + assert_eq!(field(&mut u, "Y").1, format!("{}", p.1)); +} + +#[test] +fn a_shared_value_scrubs_every_point_in_one_step_and_mixed_does_not_scrub() { + let (mut u, id) = setup(); + // Points 0 and 1 share their y: a scrub moves both to the same new y, as one undo step. + u.app.session.execute("vector.edit.select", &json!({"vertices": [0, 1]})).unwrap(); + let (before, steps) = (xs(&u, id), undo_steps(&u)); + scrub(&mut u, "Y", 20.0, Modifiers::NONE); + let after = xs(&u, id); + assert!(after[0].1 > before[0].1, "the scrub moved y: {before:?} -> {after:?}"); + assert_eq!(after[0].1, after[1].1, "both points take the scrubbed value"); + assert_eq!((after[0].0, after[1].0), (before[0].0, before[1].0), "x is untouched"); + assert_eq!(undo_steps(&u), steps + 1, "one undo step for the whole scrub"); + // Their x differs (Mixed): there is no value to scrub from, so nothing moves. + assert_eq!(field(&mut u, "X").1, "Mixed"); + let (before, steps) = (xs(&u, id), undo_steps(&u)); + scrub(&mut u, "X", 20.0, Modifiers::NONE); + assert_eq!((xs(&u, id), undo_steps(&u)), (before, steps)); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 252ae65af..8bd0b47c8 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1024,7 +1024,7 @@ pub fn section_header_resp(ui: &mut Ui, title: &str, buttons: &[(Icon, &str)], d if resp.hovered() { ui.painter().rect_filled(r, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), r.shrink(6.0), *icon, t.icon); + icons::paint(ui.painter(), icon_glyph_rect(r), *icon, t.icon); if resp.clicked() { out = Some(i); } @@ -1056,6 +1056,16 @@ pub fn tight_end_n(ui: &mut Ui, count: usize, add: impl FnOnce(&mut Ui) -> R) add(&mut child) } +/// Inset of the glyph inside a 24 pt icon button: a 16 pt glyph, the icons' native size and what +/// `icons::button` draws (a fill row's eye), so every 24 pt icon button in the panels matches it +/// (section header buttons included). +pub const ICON_BUTTON_INSET: f32 = 4.0; + +/// The rect a 24 pt icon button paints its glyph in. +pub fn icon_glyph_rect(button: Rect) -> Rect { + button.shrink(ICON_BUTTON_INSET) +} + /// An icon button at `rect` (hover highlight, tooltip); true when clicked. pub fn icon_button_at(ui: &mut Ui, id: Id, rect: Rect, icon: Icon, tip: &str) -> bool { let t = Tokens::get(ui.ctx()); @@ -1063,7 +1073,7 @@ pub fn icon_button_at(ui: &mut Ui, id: Id, rect: Rect, icon: Icon, tip: &str) -> if resp.hovered() { ui.painter().rect_filled(rect, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), rect.shrink(5.0), icon, t.icon); + icons::paint(ui.painter(), icon_glyph_rect(rect), icon, t.icon); resp.clicked() } @@ -1141,7 +1151,7 @@ pub fn checker(painter: &egui::Painter, rect: Rect, cell: f32) { } } -/// Shared Fill/Stroke/Selection colors control: one background, a 16 pt swatch, +/// Shared sidebar paint control: one background, a 16 pt swatch, /// caller-provided colour content, and a separated, scrubbable opacity field. /// The caller owns picker routing and commands; this widget only draws and reports edits. pub fn paint_field( @@ -1285,13 +1295,19 @@ pub fn paint_swatch(painter: &egui::Painter, rect: Rect, paint: &figcraft_color: /// A small checkbox with label. pub fn checkbox(ui: &mut Ui, on: bool, label: &str) -> bool { + checkbox_tri(ui, Some(on), label) +} + +/// A checkbox that can show a mixed state (`None`: a dash, for a setting that differs across a +/// selection); returns whether it was clicked. +pub fn checkbox_tri(ui: &mut Ui, state: Option, label: &str) -> bool { let t = Tokens::get(ui.ctx()); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().min(200.0), FIELD_H), Sense::click()); - a11y::checkbox(&resp, label, on); + a11y::checkbox_tri(&resp, label, state); let b = Rect::from_min_size(pos2(rect.min.x, rect.center().y - 7.0), vec2(14.0, 14.0)); - if on { + if state != Some(false) { ui.painter().rect_filled(b, CornerRadius::same(3), t.accent); - icons::paint(ui.painter(), b.shrink(1.5), Icon::Check, t.accent_on); + icons::paint(ui.painter(), b.shrink(1.5), if state.is_some() { Icon::Check } else { Icon::Minus }, t.accent_on); } else { ui.painter().rect_stroke(b, CornerRadius::same(3), Stroke::new(1.0, t.border_strong), StrokeKind::Inside); } diff --git a/crates/ui-egui/src/widgets/style_picker.rs b/crates/ui-egui/src/widgets/style_picker.rs index 7c9254151..cc820ed71 100644 --- a/crates/ui-egui/src/widgets/style_picker.rs +++ b/crates/ui-egui/src/widgets/style_picker.rs @@ -11,7 +11,7 @@ use egui::{Align2, Color32, CornerRadius, Id, Rect, Response, Sense, Stroke, Ui, pos2, vec2}; use figcraft_color::{Paint, PaintKind}; use figcraft_doc::{ - Document, GridKind, ListStyle, Node, NodeId, ParagraphStyle, PublishedLibrary, Style, StyleKind, TextStyle, VariableType, trim_num, + Document, GridKind, ListStyle, Node, NodeId, ParagraphStyle, PublishedLibrary, Style, StyleKind, TextStyle, VariableType, WrapStyle, trim_num, }; use figcraft_engine::library; use serde_json::{Value, json}; @@ -726,6 +726,8 @@ struct TextBinding<'a> { fn text_binding(ui: &mut Ui, binding: TextBinding<'_>, out: &mut Frame) { let TextBinding { style, field, kind, rect, name, lead } = binding; match widgets::bound_field(ui, Id::unique(("ts_bound", style, field)), lead, rect, name) { + // The weight slot takes a face name or a number, so its chip opens the picker that offers both. + Some(widgets::BindEvent::Open(at)) if matches!(field, "fontWeight" | "fontStyle") => crate::variable_ui::open_style_weight(ui, style, at), Some(widgets::BindEvent::Open(at)) => crate::variable_ui::open_style(ui, style, field, kind, at), Some(widgets::BindEvent::Detach) => out.act = Some(Act::Unbind(style.to_string(), field.to_string())), None => {} @@ -787,15 +789,16 @@ fn font_style_size_row(ui: &mut Ui, doc: &Document, style: &Style, def: &TextSty let id = style.id.as_str(); let mut style_resp = None; ui.horizontal(|ui| { - match bound_name(doc, style, "fontStyle") { + let weight_field = if style.bound.contains_key("fontWeight") { "fontWeight" } else { "fontStyle" }; + match bound_name(doc, style, weight_field) { Some(name) => { let (r, _) = ui.allocate_exact_size(vec2(half, widgets::FIELD_H), Sense::hover()); text_binding( ui, TextBinding { style: id, - field: "fontStyle", - kind: VariableType::String, + field: weight_field, + kind: if weight_field == "fontWeight" { VariableType::Number } else { VariableType::String }, rect: r, name: &name, lead: widgets::Lead::Named(tr("Font style")), @@ -944,7 +947,7 @@ fn font_family_menu(ui: &Ui, id: &str, def: &TextStyle, family_resp: &Response, fn font_style_menu(id: &str, def: &TextStyle, style_resp: &Response, out: &mut Frame) { crate::right::menu_popup(style_resp).width(200.0).show(|ui| { if crate::right::menu_item(ui, tr("Apply variable"), "") { - crate::variable_ui::open_style(ui, id, "fontStyle", VariableType::String, style_resp.rect.left_bottom()); + crate::variable_ui::open_style_weight(ui, id, style_resp.rect.left_bottom()); ui.close(); return; } @@ -999,6 +1002,11 @@ fn paragraph_rows(ui: &mut Ui, ps: &ParagraphStyle) { ListStyle::Bulleted => rows.push(tr("Bulleted list").into()), ListStyle::Numbered => rows.push(tr("Numbered list").into()), } + match ps.wrap_style { + WrapStyle::Auto => {} + WrapStyle::Balance => rows.push(format!("{}: {}", tr("Wrap style"), tr("Balance"))), + WrapStyle::Pretty => rows.push(format!("{}: {}", tr("Wrap style"), tr("Pretty"))), + } if !ps.features.is_empty() { rows.push(ps.features.iter().map(|(tag, on)| format!("{}{tag}", if *on { '+' } else { '-' })).collect::>().join(" ")); } diff --git a/crates/ui-egui/src/widgets/style_picker/tests.rs b/crates/ui-egui/src/widgets/style_picker/tests.rs index 9d14ac44a..984f6c8d4 100644 --- a/crates/ui-egui/src/widgets/style_picker/tests.rs +++ b/crates/ui-egui/src/widgets/style_picker/tests.rs @@ -362,9 +362,19 @@ fn text_variables_session(bind: bool) -> crate::layers_drag_tests::Ui { ("Body tracking", "number", json!(1)), ("Body font", "string", json!("Inter")), ("Body weight", "string", json!("Bold")), + ("Body weight number", "number", json!(700)), ] { s.execute("variable.create", &json!({"collection": "Type", "name": name, "type": ty, "values": {"Base": value}})).unwrap(); } + for (name, scope) in [ + ("Body size", "FONT_SIZE"), + ("Body leading", "LINE_HEIGHT"), + ("Body tracking", "LETTER_SPACING"), + ("Body font", "FONT_FAMILY"), + ("Body weight number", "FONT_WEIGHT"), + ] { + s.execute("variable.update", &json!({"variable": name, "scopes": [scope]})).unwrap(); + } if bind { for (field, var) in [ ("fontSize", "Body size"), @@ -454,6 +464,54 @@ fn text_style_editor_shows_bound_fields_as_variables_and_detaches_them() { assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); } +#[test] +fn the_weight_menu_binds_a_number_variable_as_font_weight() { + let mut u = text_variables_session(false); + let left = editor_left(&mut u); + let in_editor = |u: &mut crate::layers_drag_tests::Ui| -> Vec<(String, Pos2)> { + drawn_texts(u).into_iter().filter(|(_, p)| p.x > left && p.x < left + W).collect() + }; + let texts = in_editor(&mut u); + click(&mut u, text_at(&texts, "Regular")); + let texts = drawn_texts(&mut u); + click(&mut u, text_at(&texts, "Apply variable")); + assert!(crate::variable_ui::picker_open(&u.ctx), "the variable picker opens"); + let texts = drawn_texts(&mut u); + assert!(texts.iter().any(|(t, _)| t == "Body weight"), "string variables are offered"); + assert!(!texts.iter().any(|(t, _)| t == "Body font" || t == "Body leading"), "other fields' variables are not"); + click(&mut u, text_at(&texts, "Body weight number")); + assert_eq!(bound_to(&u, "fontWeight").as_deref(), Some("Body weight number")); + assert_eq!(bound_to(&u, "fontStyle"), None); + let font_style = || { + let doc = u.app.session.doc().unwrap(); + let Some(StyleKind::Text { style: def, .. }) = doc.style("Body").map(|s| s.kind.clone()) else { panic!("a text style") }; + def.font_style + }; + assert_eq!(font_style(), "Bold"); + // The chip shows it in the style slot; clicking it lists the string variable too, and picking that + // replaces the number: fontStyle is bound and fontWeight is not. + for _ in 0..2 { + u.frame(vec![]); + } + let texts = in_editor(&mut u); + click(&mut u, text_at(&texts, "Body weight number")); + assert!(crate::variable_ui::picker_open(&u.ctx), "the chip opens the weight picker"); + let texts = drawn_texts(&mut u); + assert!(texts.iter().any(|(t, _)| t == "Body weight"), "the string variable is offered beside the number one"); + click(&mut u, text_at(&texts, "Body weight")); + assert_eq!(bound_to(&u, "fontStyle").as_deref(), Some("Body weight")); + assert_eq!(bound_to(&u, "fontWeight"), None, "the name replaced the number"); + // The chip's detach button clears the binding. + for _ in 0..2 { + u.frame(vec![]); + } + let texts = in_editor(&mut u); + let chip = text_at(&texts, "Body weight"); + click(&mut u, Pos2::new(left + (W - 8.0) / 2.0 - 11.0, chip.y)); + assert_eq!(bound_to(&u, "fontStyle"), None, "the face name is detached"); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); +} + #[test] fn text_style_editor_binds_variables_from_its_fields() { let mut u = text_variables_session(false); @@ -477,7 +535,7 @@ fn text_style_editor_binds_variables_from_its_fields() { click(&mut u, Pos2::new(x, y)); assert!(crate::variable_ui::picker_open(&u.ctx), "{field}: the variable picker opens"); let texts = drawn_texts(&mut u); - assert!(!texts.iter().any(|(t, _)| t == "Body font"), "{field} offers number variables only"); + assert!(!texts.iter().any(|(t, _)| t == "Body weight"), "{field} offers number variables only"); click(&mut u, text_at(&texts, name)); assert_eq!(bound_to(&u, field).as_deref(), Some(name)); } @@ -491,7 +549,7 @@ fn text_style_editor_binds_variables_from_its_fields() { assert!(crate::variable_ui::picker_open(&u.ctx), "{field}: the variable picker opens"); let texts = drawn_texts(&mut u); // "Body size" shows once, on the size field's chip: the picker doesn't list it. - assert_eq!(texts.iter().filter(|(t, _)| t == "Body size").count(), 1, "{field} offers string variables only"); + assert_eq!(texts.iter().filter(|(t, _)| t == "Body size").count(), 1, "{field} does not offer the size variable"); click(&mut u, text_at(&texts, name)); assert_eq!(bound_to(&u, field).as_deref(), Some(name)); } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 3397e00de..c0e838e4d 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -236,6 +236,8 @@ fn exchange(app: &mut FigApp, p: &mut Pane) { std::mem::swap(&mut app.ui, &mut p.ui); std::mem::swap(&mut app.ui.last_copy, &mut p.ui.last_copy); std::mem::swap(&mut app.ui.last_copy_generation, &mut p.ui.last_copy_generation); + // A paint or effect copied from its row is on the one clipboard every window pastes from. + std::mem::swap(&mut app.ui.property_copy, &mut p.ui.property_copy); std::mem::swap(&mut app.ui.quit, &mut p.ui.quit); std::mem::swap(&mut app.ui.dark, &mut p.ui.dark); std::mem::swap(&mut app.canvas, &mut p.canvas); diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 03b6fd830..b9744a4e4 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,11 +1,11 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (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-09 · **Change:** patch (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%, ready ~74% (estimated)**: every rule of the public documentation is a test case with the sizes and -positions it implies (`crates/layout/src/behaviour_tests.rs`, 64 cases, and +positions it implies (`crates/layout/src/behaviour_tests.rs`, 68 cases, and `crates/engine/src/al_behaviour_tests.rs` through commands), and all pass; nothing yet against real Figma files. Remaining: 3–6 h. @@ -67,7 +67,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Ignore auto layout: out of the flow, kept in the frame; constraints apply only then | pass | `absolute_position_rules` | | Canvas stacking: last on top by default, first on top on request; the layer order stays | **fixed** + **added** | `reverseZ` was stored but never drawn: now the canvas, PNG, SVG and PDF exports and hit testing paint in that order; Design panel control | | Grid: `fr` tracks share by fraction; fixed tracks keep their size; hug tracks fit their content | pass | `grid_rules` | -| Grid `fr` tracks behave like the CSS `fr` unit: a track never gets less than its content | **fixed** | was `minmax(0, 1fr)`: a fixed-size child taller than its share overflowed into the next row | +| Grid `fr` tracks as measured in Figma: on a fixed-size axis they share the space left after gaps and padding by their fractions and a fixed-size child bigger than its share overflows into the next track (`minmax(0, 1fr)` for fixed-size and hug-size children); a Fill child's own minimum width or height still keeps its track at least that big (not measured, kept from before: two 1fr rows in 200 with a 150 minimum resolve to 150 / 50); on a Hug axis they size to their content | **fixed** | 300 x 200 frame, rows 1fr / 1fr, children 100 x 150 and 100 x 20: rows 100 / 100, second child at y 100; row gap 10: rows 95 / 95, y 105; frame height Hug: rows 150 / 20, frame 170; columns the same. Measured in Figma 2026-11-11; was the CSS rule from the documentation (2026-10-11) | | Grid placement left to right, top to bottom; rows grow; anchors; spans; gaps; padding | pass | `grid_rules` | | Grid children align independently in their cells | **added** | `gridAlignH` / `gridAlignV` (Auto follows the frame), Design panel cell alignment | | A hugging grid with `fr` tracks | silent | the file format calls it invalid; `fr` tracks hug their content | @@ -79,7 +79,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Feature | Status | Evidence / notes | |---|---|---| | Horizontal, vertical, wrap (both directions) | done | `crates/layout` | -| Grid auto layout: fixed / hug / `fr` tracks, cells, spans, gaps, cell alignment | done | `fr` like CSS `fr` | +| 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` | @@ -101,6 +101,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 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-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. | diff --git a/docs/boards-parity.md b/docs/boards-parity.md index c424ad801..04cb832bc 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (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 @@ -60,21 +60,23 @@ all end with the same geometry. | Voting results: who voted for what, earlier sessions' results | partial | once a vote ends, its results list who voted for each object and how many times (by name in a live session, kept with the results so someone who has left still shows by name), as the reference app shows how each participant voted; each ended vote's results are kept in the file (the last 20), listed newest first in the Results popover with arrows to earlier ones, and deleted one at a time (`board.vote {action: delete, index}`; Clear results only takes them off the board), as the reference app keeps each session's results until deleted; saved, synced in live sessions, and like the vote not undo steps. Anyone who can edit the board ends or clears a vote, as the reference app's help describes. A vote has no prompt (question) of its own | | Board widgets | missing | design-file widgets exist (`crates/engine/src/extensions/widgets.rs`), not wired to boards | | Templates (retrospective, brainstorm, flow chart…) | partial | five built-in templates drawn up for FigCraft (retrospective, brainstorm, weekly planner, flow chart, kanban board), placed from the toolbar's templates picker (each with a picture of itself) or `board.template {name, x?, y?}` as ordinary sections, stickies, shapes, connectors and text in one undo step; `board.templates` lists them. No community templates, no saving your own | -| Tables | partial | `board.table {rows, columns, cells?, x?, y?}` (at most 50 × 20): an auto layout frame of rows of cells with text, a tinted header row and lines between rows and columns; a cell's row grows with its text; a double-click types in the cell under the pointer; add or remove a row or column from the bar over the selection or `board.tableEdit {id, action, index?}`; cells copied from a spreadsheet (tab-separated text, quoted cells kept whole) paste as a table, up to 50 × 20 with a note when there was more; undoable and synced in live sessions. No column resizing by dragging, no cell colours, no Tab between cells; comma-separated text pastes as text | +| 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 | | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | | Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots stay about a point and a half across on screen (1 to 3 points), scaled by the size setting. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none | -| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies and shapes with text come in as frames with their generated layers and its connectors as vectors, not as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) | +| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies come in as native stickies (their colour, text and author kept; size as saved), its shapes with text as frames with their generated layers and its connectors as vectors, not yet as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) | ## Revision history | Date | Change | Summary | |---|---|---| +| 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` | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. A mind map node is a board object of its own (`BoardItem::MindNode`: text with no box) and a branch is a connector marked `branch`; the map's shape is read from its branches. `board.mindMap` places a first node with three children and `board.mindMapAdd` adds a child or a sibling, each one undo step. The normalize pass lays a touched map out again from its first node (`board::settle_mind_maps`, `figcraft_doc::mind_layout`): 88 between columns, 48 between siblings, each stack centred on its parent, numbers from a FigJam file saved and decoded. Tests: `board_mindmap_tests` in doc (five) and engine (eight). Numbers unchanged (no toolbar entry yet). | | 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. | +| 2026-11-10 | minor | M9, #1808: a `.jam` sticky imports as a native board sticky (`BoardItem::Sticky`): its frame keeps the saved size (240 pt, not FigCraft's 200), place, opacity and shadows, the saved colour is kept as it is (not snapped to the board colours), the note and the author line are its text layers, and it lays out like one made here (vertical, space between, hugging the height down to the saved size, the saved inset as padding). The importer reads a `board` field on the REST JSON (a FigCraft extension) for this; a sticky whose generated records are damaged, or the same sticky in a `.fig`, keeps the generated layers as before. Shapes, connectors, stamps and tables are unchanged; the note's text keeps the file's size until it is edited. Tests: `board_import_tests.rs` (native sticky, no author, damaged records, `.fig` unchanged), `import_regression_tests.rs` (the `board` field and junk values). Numbers unchanged. | | 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. | | 2026-11-04 | patch | M6, #1910: a `.jam` elbowed connector saved with its path (FigJam's `connectorControlPoints`) keeps it on import: the points become the `ConnectorPath::Runs` a connector reshaped by hand has and the line is walked along them, so a connector drawn around a layer stays around it; one whose points don't make a path from its ends' sides is routed as before. Still a vector, not a native board object. Details in [`file-format-parity.md`](file-format-parity.md). | | 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged | diff --git a/docs/components-parity.md b/docs/components-parity.md index 7e336c42f..af92de6d2 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-07 · **Change:** minor (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); 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-07 · **Change:** minor (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); 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 @@ -62,10 +62,10 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Feature | Status | Notes | |---|---|---| -| Paint, text, effect, grid styles; style picker; text styles on character ranges | done | behaviour suite: `styles_behaviour_tests.rs`; a text style carries paragraph spacing and indent, the list style and the OpenType features beside the character properties (`paragraph` next to `style` in `style.list`): applied with it, moved by `style.update`, unlinking when edited, kept by `.fig` files (#1829) | +| Paint, text, effect, grid styles; style picker; text styles on character ranges | done | behaviour suite: `styles_behaviour_tests.rs`; a text style carries paragraph spacing and indent, the list style, the wrap style and the OpenType features beside the character properties (`paragraph` next to `style` in `style.list`): applied with it, moved by `style.update`, unlinking when edited, kept by `.fig` files (#1829; not the wrap style yet: its `.fig` field is unknown, #1827) | | 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, size, line height and letter spacing, the rest through the command | +| 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) | | 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 | @@ -82,9 +82,12 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| | 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-10 | minor | M7, #2174: a text style binds a number variable to its weight (`style.bind {field: "fontWeight"}`): the style takes the face nearest the number and sets the `wght` axis, so static and variable fonts both follow; a face-name (string) binding and a weight binding replace each other, and the weight wins in a file carrying both. The style editor's weight menu offers number variables beside string ones. A number bound to a line height is applied in pixels, as the reference tool does, which a test now pins. Numbers unchanged. Tests: `style_vars_tests`, `style_picker::tests`. | | 2026-11-07 | patch | M3, #2088: with two or more layers selected the Design panel header's component button opens a menu with Create component, Create multiple components and Create component set (`component.createSet`, naming measured in Figma), as Figma's does; one layer keeps the plain button. Tests: `create_multiple_menu_tests`, `components_behaviour_tests::create_multiple_components_keeps_names_and_places_and_is_one_undo_step`, `components_behaviour_tests::create_set_*`. Grade unchanged. | | 2026-11-05 | minor | M3, #2002: the Local variables window selects several variables, as the Layers panel selects layers. A click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, Escape or a click on the empty space below the rows clears; selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope (all supported properties, hidden from pickers, or only one scope) for the selected local variables, each sent as one `command.batch`, so one undo step; no engine command changed. Renaming and value edits stay single-row. Tests: `variables_select_tests` (headless UI). Grade unchanged | | 2026-11-02 | minor | M3, #1829: text styles carry paragraph spacing and indent, the list style and the OpenType features ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType features", Create and apply text styles) beside the character properties: `style.create` takes them from the layer (or the selected paragraphs' list) or from a `value` (`paragraphSpacing`, `paragraphIndent`, `listStyle`, `features`), `style.apply` sets them (on a range, the list goes to the paragraphs touched; the rest is the layer's, as in Figma), `style.update` moves them on every linked layer, editing one on a styled text unlinks it as editing its font does, the style editor lists them, and a `.fig` file keeps them with the style (its sample layer). Grade unchanged. | +| 2026-11-07 | minor | M4, #1827: text styles carry the wrap style (`wrapStyle` in a style's `paragraph`): applied with the style (on a range, to the paragraphs touched), moved by `style.update`, unlinking when edited; shown read-only in the style editor | | 2026-11-06 | patch | M3: a glass's light angle bound to a number past ±180 turns round to the same direction (270 is -90), as the angle drawn from it does, instead of stopping at 180. Tests: `effects_tests::a_bound_light_angle_turns_round_instead_of_stopping`. Grade unchanged. | | 2026-11-06 | patch | M3: a layer's effect binding (`variable.bind`, `effects//`) takes only a field its effect has, as an effect style's does: `effects/0/refraction` on a drop shadow, or a binding on an effect the layer doesn't have, is refused instead of being kept and doing nothing (a binding an older file has there still does nothing, and unbinds). Tests: `binding_lists_tests::a_layer_binds_only_fields_its_effects_have`. Grade unchanged. | | 2026-11-06 | minor | M3: Go to main component (context menu, Design panel, Ctrl+Alt+Cmd+K) on an instance of a library component opens the library file, as the help center describes for mains kept in another file ("Edit main components"); it used to refuse. The file opens in a tab, or an open tab comes to the front, on the main's page with the main selected and zoomed to: a nested instance goes to its own main, a variant to that variant. A main deleted from the library file since it was published leaves the file open with a note; a library file that moved, a team library on a server and a path off this computer are refused with a message. Test: `library::tests::going_to_a_library_main_opens_the_library_file`. Numbers unchanged | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4835bd1e1..b06d79932 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -67,6 +67,7 @@ state are answered without a frame (about half a second each), while `ui.screens Coordinates are page units, y down. `x`/`y` in `node.set`/`node.create` are relative to the parent frame (groups have no coordinate space of their own). +`rotation` in `node.set` is the layer's angle to its parent; `absoluteRotation` sets its rotation on the page (what the Design panel's field shows); a call takes one of the two. **Windows.** The desktop app can show files in several windows (`window.new`). Every method takes an optional `window` (an id from `window.list`; `0` is the main window) and then runs in that diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index 87dc3739f..66ef3a0ae 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -1,6 +1,6 @@ # Dev Mode parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-07 · **Change:** patch (the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-09 · **Change:** patch (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 Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) **Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect to the code components of a repository (with their imports, also inside generated layer trees), @@ -15,7 +15,7 @@ repository, third-party integrations. Remaining: 1–2 h. | 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, 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) | | 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 | | +| 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) | | Focus view (one frame, previous / next) | done | | | Compare changes (before/after side by side or overlaid, property diffs) | done | against the snapshot taken when a frame was first changed after it was marked ready, or any saved version (`dev.compare {version}`; the view's Compare with menu); a frame that isn't ready for dev compares with versions | @@ -29,6 +29,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Date | Change | Summary | |---|---|---| +| 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 | | 2026-10-26 | minor | Class names from layer names transliterate non-ASCII scripts (#1235): `class_name` runs names through `deunicode` (new dependency: pure Rust tables, zero deps, BSD-3-Clause), so Korean, Cyrillic, Latin-diacritic and CJK names become readable ASCII classes in HTML/CSS/React/Leptos output, component roots and `data-*` variant attributes (`rogeuin-hwamyeon`, `knopka`, `uber`, `an-niu`; before, every one of them came out `layer-`); symbols-only names take the node's kind (`.text`, `.frame`) instead of `layer-`, and the 40-character cut lands on a word boundary. ASCII-only names are unchanged. `html_codegen_tests` updated (its diacritics expectation improves from `layer-1-n-code-name` to `layer-1-unicode-name`) and extended. Percentages and hours unchanged | | 2026-10-24 | minor | Dev Mode refuses design edits from files dropped on the canvas (a dropped document still opens as a file of its own, and the drop overlay shows the Dev Mode note for other files), from the Pages list's add, rename, reorder, duplicate and delete, and from the Assets panel's place, drag, Alt-drop swap, style, Hide when publishing, Update, and adding, removing and swapping libraries. Percentages and hours unchanged | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 12bfe5c71..56de5f480 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (`.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (`.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 @@ -17,10 +17,10 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| -| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides; an instance scaled with the Scale tool, which stores `symbolData.uniformScaleFactor`, draws its layers at the main's lengths times that factor, composed through nested instances: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent, except where an override or derived row gives the value, which is already at the instance's scale; per-point vector corner radii also take their vector-data row's factor; the vector outline paths a layer carries (a network's points follow the layer's size), fixed grid tracks, image tile scales and glass effects are not scaled by the factor, #2091), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234), and the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; ZIP image reads have a separate total budget of 4 GiB (1 GiB on 32-bit targets) of decompressed ZIP-member bytes containing encoded images, with the 256 MiB per-image cap kept: a member that cannot fit is skipped before its output buffer is allocated, and the import report names the budget and counts skipped images (#1076). Failed reads and invalid image contents still consume the bytes read; a reference used by several layers is read once. This is not a limit on decoded pixels or total import memory; images carried inside the message are unchanged. The file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Elbowed and curved connectors without a saved path are routed as FigCraft's board connectors are (right angles, or one curve, from the sides of the layers they join); an elbowed one saved with its path (`connectorControlPoints`: a point and an axis per run between the first and the last) keeps that path when it leaves and arrives by the ends' sides (#1910), and a curved one's saved `connectorBezierControlPoints` are not read; a connector routed here takes its line's paint, weight, cap and dashes from the file's generated line record, as one with a saved snapshot does (#1807). A connector's label without a saved snapshot is kept as text centred on its line, without its background. Not read: table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | +| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations (with their corner radius and smoothing, #2222), components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides; an instance scaled with the Scale tool, which stores `symbolData.uniformScaleFactor`, draws its layers at the main's lengths times that factor, composed through nested instances: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent, except where an override or derived row gives the value, which is already at the instance's scale; per-point vector corner radii also take their vector-data row's factor; the vector outline paths a layer carries (a network's points follow the layer's size), fixed grid tracks, image tile scales and glass effects are not scaled by the factor, #2091), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234), and the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; ZIP image reads have a separate total budget of 4 GiB (1 GiB on 32-bit targets) of decompressed ZIP-member bytes containing encoded images, with the 256 MiB per-image cap kept: a member that cannot fit is skipped before its output buffer is allocated, and the import report names the budget and counts skipped images (#1076). Failed reads and invalid image contents still consume the bytes read; a reference used by several layers is read once. This is not a limit on decoded pixels or total import memory; images carried inside the message are unchanged. The file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Elbowed and curved connectors without a saved path are routed as FigCraft's board connectors are (right angles, or one curve, from the sides of the layers they join); an elbowed one saved with its path (`connectorControlPoints`: a point and an axis per run between the first and the last) keeps that path when it leaves and arrives by the ends' sides (#1910), and a curved one's saved `connectorBezierControlPoints` are not read; a connector routed here takes its line's paint, weight, cap and dashes from the file's generated line record, as one with a saved snapshot does (#1807). A connector's label without a saved snapshot is kept as text centred on its line, without its background. Not read: table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | | `.penpot` (Penpot 2.x ZIP export) | — | **yes, offline** (open, import, drop, CLI, MCP) | **yes, offline** (export, CLI convert) | Editable layers, supported flex/grid layout, components, tokens and prototypes using the existing model. Unsupported layouts retain saved positions and bounded metadata; toggle-overlay and embedded font binaries are reported. Font references remain editable; no downloads. Synthetic regression coverage; live Penpot and cross-platform QA remain open. See [Penpot reference](penpot.md). | further live Penpot and cross-platform QA | | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | -| `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with generated sticky and shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | +| `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with stickies as native board stickies (their colour, text and author kept, size as saved, #1808) and generated shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | | REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Developer Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — | @@ -196,12 +196,14 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M4, #2222: a boolean group's corner radius and smoothing are read and written by the `.fig` importer and exporter, and by the REST importer | | 2026-11-07 | patch | Fonts, #2092: a font loaded with `text.loadFont` is the counterpart of a font uploaded to the organization, which Figma's help center ("Manage conflicting fonts") ranks first, ahead of installed fonts and the web fonts. FigCraft chose the first face added for a family and style, so the built-in Inter 4.x kept Regular, SemiBold and Bold after Inter 3.19 was loaded and only Medium refitted. A loaded face now wins over the other faces of its family and style, the latest load over earlier ones; style matching and fallbacks are unchanged, and `refitted` lists the text whose size changes. Installed versus built-in order is not changed here. Test: `fontdb::tests::a_loaded_face_wins_over_the_built_in_one_of_its_family_and_style`. Numbers unchanged. | | 2026-11-08 | minor | M6, #2097 follow-up: per-point vector corner radii take the scale of the row supplying `vectorData`, including nested instance rows; override and derived rows are not scaled twice. Network caching distinguishes the instance scale even when resizing gives two vectors the same final box. Synthetic tests cover missing/unit factors, half/double scale, derived size alone, overridden and derived vector data, nested scale and equal-size cache separation. Layer-radius fallback remains the separate #2115 change. Numbers unchanged. | | 2026-11-08 | patch | #2097 / #2100: scaled-instance lengths reset to the unscaled main value survive export/import as explicit overrides. Dimensionless values and zero do not gain scale overrides. Exported factors stay within the importer's 0.001–1000 range; larger or smaller ratios use explicit values instead. Effect/grid payload rows above an inherited style link take precedence at their own scale, including nested instances and empty-list clears, without detaching styles. Synthetic regressions cover corners, dashes/shadows, layout/grids and bounds, typography and styled runs, linked text and nested styles. Numbers unchanged. | | 2026-11-07 | minor | `.fig` import, #2091 item 1: an instance scaled with the Scale tool stores `symbolData.uniformScaleFactor`, which the import never read, so the layers of a 128 px instance of a 256 px component came in at 256 px with the main's radii, strokes and spacing. The layers of an instance now take the main's lengths times the factor (composed through nested instances, so 0.5 inside 0.5 is 0.25 for the inner layers), the lengths the Scale tool scales: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent. A value an override or derived row gives is taken as written, already at the instance's scale; the instance's own size is the file's; a missing, non-finite, non-positive or out-of-range factor (outside 0.001 to 1000) changes nothing. Not scaled: vector outline paths (a network's points follow the layer's size), per-point corner radii, fixed grid tracks, image tile scales and glass effects. Tests: `fig::tests::a_scaled_instance_draws_its_layers_at_the_factor` and `fig::scale_factor_tests`. Numbers unchanged | | 2026-11-03 | patch | M6, #1909: `.jam` import: a connector end whose magnet is `AUTO` (FigJam picks the side when it draws) or `CENTER` (the end aims at the layer's middle) left the side its stale `relativePosition` named, the left one in the reporter's file, so the connectors looped behind their shape or crossed it. It now leaves the side facing the other end, as a board connector drawn here does (`Side::Auto`), for straight, elbowed and curved connectors alike; a named magnet (`TOP`, `RIGHT`, `BOTTOM`, `LEFT`) is unchanged, and an end without a magnet still takes the edge its point lies on. The Plugin API lists the magnets (`ConnectorEndpoint.magnet`: "Which side of the node it attaches to"; NONE, AUTO, TOP, LEFT, BOTTOM, RIGHT, CENTER; "Straight connectors may use only CENTER or NONE magnets"). Test: `connectors_with_an_automatic_side_leave_the_side_facing_the_target`. Numbers unchanged. | | 2026-11-04 | minor | JPG export: `quality` (1 to 100, default 90) on `file.export`, `export.add` / `export.update` and MCP `export`, kept in the export setting; an sRGB file's JPGs embed the sRGB ICC profile, as Display P3 files' JPGs already embedded theirs, since an untagged JPG is only assumed to be sRGB (#2004). | +| 2026-11-10 | minor | M9, #1808: `.jam` import: a FigJam sticky comes in as a native board sticky. The mapper knows the canvas header (`fig-jam.`) and, for a whiteboard only, writes a `board` field (`{"type": "sticky", "author": ..}`, a FigCraft extension of the REST JSON) on a sticky whose generated records are complete (layout version 1, one visible solid background paint without strokes, a non-blank note), with the background's colour and corner radius, the file's size, place, opacity and shadows, the note and the author line as text layers and no background vector; the REST importer sets it as the layer's board item and ignores a junk `board` value with a warning. A sticky that isn't complete, or any sticky in a `.fig`, keeps the generated layers and the old note. Shapes with text, connectors, stamps and tables are unchanged. Tests: `fig::tests::board` (four), `rest::import_regression_tests` (two). | | 2026-11-04 | minor | `.fig` and `.jam` import, #1910: an elbowed connector saved with its path keeps it. FigJam stores `connectorControlPoints`, one per run between the first and the last, each a point on its run (in the connector's parent's coordinates) with the run's axis; the first run leaves the start's side and the last arrives at the end's. They become the `ConnectorPath::Runs` a board connector reshaped by hand has (`figcraft_doc::route_along`), so a connector drawn around a layer in FigJam stays around it instead of being routed through it. Points that don't make such a path (off both axes, two runs in a row the same way, a first or last run sideways to its side or going back into its object, more runs than a hand could make) leave the connector to the router as before, and only connectors routed here count in the "follow FigCraft's own routing" note. A curved connector's `connectorBezierControlPoints` are still not read. Tests: `tail_tests::an_elbow_connector_saved_with_its_path_keeps_it`, `tail_tests::an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here`. | | 2026-11-01 | patch | `.fig` and `.jam` import: a connector without a saved snapshot (elbowed and curved ones are routed here) took no stroke, so it was invisible (#1807); its line's paint, weight, cap and dashes now come from the file's generated line record, as a saved snapshot's do, and the connector's own values, when it has any, win. Test: `fig::connector_label_tests::a_routed_connector_takes_its_line_style_from_the_generated_record`. Numbers unchanged | | 2026-10-31 | minor | Export settings: each PNG, JPG and WebP setting has a color profile, Same as file (the default; the document's profile when it exports), sRGB or Display P3, in its advanced settings and as `colorProfile` on `export.add`, `export.update`, `file.export`, `file.exportLayers` and MCP `export`. The pixels convert to the chosen profile (out-of-gamut colors clip) and the file is tagged as before: sRGB PNG with an `sRGB` chunk, Display P3 with the generated ICC profile (and `cICP` in PNG); sRGB JPG and WebP stay untagged (builds before 2026-11-04; from that date sRGB JPGs embed the sRGB ICC profile, see the 2026-11-04 JPG export entry). A setting keeps its choice when its format changes; settings saved without one read as Same as file. SVG, PDF and XML show no choice and stay sRGB (PDF has no output intent yet). Numbers unchanged | diff --git a/docs/gaps.md b/docs/gaps.md index ee855922c..e7cbdb76a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (gap 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 @@ -383,14 +383,16 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Estimate:** 5–10 h (video playback in the presenter is most of it; it can reuse the GIF clock). ### 13. Vector tail: none left +- **Landed (2026-11-10):** a boolean group takes a corner radius (and smoothing) that rounds every sharp + corner of its result, convex and concave, with the children's own radii kept and a radius larger + than the edges allow shrinking to fit (#2222; `crates/pathops/src/round_tests.rs`). - **Landed (2026-10-22):** the transform box around points selected in several layers at once, in the page's axes: its corners and edges scale them, outside a corner rotates them and inside drags them, each in its own layer and one undo step for all (`transform_tests`). - **Landed (2026-10-12):** several Bezier handles selected with Shift-click and dragged together, sharp points beside curved segments rounded, a stroke cap and join per point (canvas, PNG, SVG, PDF, outline stroke), the Pen outside edit mode connecting to its own points and continuing a - selected open path. Left: corner radius and smoothing on boolean groups that contain - rectangles, per-point caps and joins on dashed, variable-width and brush + selected open path. Left: per-point caps and joins on dashed, variable-width and brush strokes. - **Landed (2026-10-11):** boolean groups are clicked where their result is (a click in a subtracted hole reaches what's behind; with the group or an operand selected its operands are @@ -593,6 +595,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 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. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | | 2026-10-31 | minor | Gap 10: library analytics list the layers and files using each style and variable; their insertions, detachments and modes stay on the missing list. | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index b827a887c..fec7dae37 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:** patch (Windows: the custom title bar's windows stay borderless, so the content is no longer drawn about 30 px low with clicks landing above it (#1343); 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-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) 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 @@ -12,7 +12,7 @@ since 2025). FigCraft renders the canvas on the CPU and presents it through wgpu | Feature | Figma | FigCraft (macOS / Windows / Linux / web) | Hours | |---|---|---|---| -| Canvas rendering | GPU | CPU (tiny-skia), banded across cores, retained (re-renders only what an edit or pan touches), levels of detail below 50% zoom, large images drawn from a copy no larger than they show (#1483); when renders from scratch are slow, a new zoom shows the whole view coarsely first, then refines it (#312); shown through wgpu (WebGPU or WebGL2 in the browser) | 30–60 for a GPU path | +| Canvas rendering | GPU | CPU (tiny-skia), banded across cores, retained (re-renders only what an edit or pan touches), levels of detail below 50% zoom, images drawn from the smallest copy that holds the size they show, down to 256 px (#1483); when renders from scratch are slow, a new zoom shows the whole view coarsely first, then refines it (#312); shown through wgpu (WebGPU or WebGL2 in the browser) | 30–60 for a GPU path | | Effects (blurs, glass, noise) | GPU | CPU | in the above | | HiDPI / Retina | yes | yes (all); a canvas image rendered at the screen's density is placed on whole device pixels, so fractional pans, zooms and display scales don't blur it (#359; geometry tests, the snapping not judged by eye) | — | | Wide-gamut display (Display P3) | yes, on capable displays | colours stored and exported in P3; the screen shows sRGB: eframe/egui-wgpu 0.37 configure an 8-bit sRGB surface with no colour space option, although wgpu 30 can present Display P3 or extended sRGB on Metal, DX12, Vulkan and WebGPU (see gaps #18). The colour picker warns about colours outside sRGB and View ▸ Soft-proof sRGB stripes them on the canvas | 2–5 | @@ -50,6 +50,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import). | Date | Change | Summary | |---|---|---| +| 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` | | 2026-10-31 | minor | M1, #492: Web row: the browser pastes images copied in other apps, read from the paste event under the same limits as the desktop. Numbers unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 23a7c77d3..a6c04af07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -172,6 +172,7 @@ Or in a project's `.mcp.json`: - `create_node` and `set_properties` take `x`/`y` **relative to the parent frame** (the page when there is none, so they are page coordinates then). Groups and boolean groups have no coordinate space of their own: a layer in a group is placed in the frame (or on the page) the group is in. + `rotation` is the layer's angle to its parent (Figma's plugin API `rotation` is the same); `absoluteRotation` sets its rotation on the page, what the Design panel's field shows; a call takes one of the two. `inspect_document` reports `x`/`y` the same way, plus `absoluteBounds` in page coordinates. In `props`, `fill` and `stroke` also accept `"none"` (either case) or `null` as no paint, the same as an empty `fills`/`strokes` list, so an outline-only shape can be made in one call. @@ -298,6 +299,11 @@ Or in a project's `.mcp.json`: `textDecorationOffset` (`auto`, px, or `"10%"` of the font size; the offset runs from the baseline down to an underline's top edge), `textDecorationSkipInk` (underlines break around descenders) and `textDecorationColor` (a colour, or `auto` for the text's) are character props too. +- **Wrap style** (`auto`, `balance`, `pretty`) works at three levels: `wrapStyle` on `node.set` + sets the layer (every paragraph); with `start`/`end` it sets the paragraphs those chars touch, + and a paragraph's own style beats the layer's. `text.wrapStyle` sets the selected paragraphs while + text is edited. `get_node` reports one `wrapStyle`, or `lineWrapStyles` per paragraph when they + differ. - **Lists** are per paragraph: `listStyle` (`none`, `bulleted`, `numbered`) and `indentation` (the nesting level, 0–8) apply to the paragraphs chars `start`..`end` touch (all of them without a range); `get_node` reports one `listStyle` for the layer, or `lineTypes` and `lineIndentations` @@ -313,10 +319,11 @@ Or in a project's `.mcp.json`: `style.detach {which: "text", start?, end?}` unlinks them (values stay). A layer's `styles.text` is the style all its chars share (none when they differ); `get_node` lists the linked chars as `textStyleRanges` (`[start, end, style id]`). - A text style also carries paragraph spacing and indent, the list style and the OpenType features - (`paragraph` beside `style` in `style.list`): applying it sets them (on a range, the list goes to - the paragraphs touched; the rest is the layer's), `style.update` moves them too, and a `.fig` - file keeps them with the style. + A text style also carries paragraph spacing and indent, the list style, the wrap style and the + OpenType features (`paragraph` beside `style` in `style.list`; a `value` takes `wrapStyle`): + applying it sets them (on a range, the list and wrap style go to the paragraphs touched; the rest + is the layer's), `style.update` moves them too, and a `.fig` file keeps them with the style + (not the wrap style yet). Changing what a text style sets (font, size, line height, letter spacing, decoration, case, axis values; at the paragraph level the spacing, indent, list and features) on linked chars unlinks them; `style.update` moves every linked char. `style.create {type: "text", name}` takes the @@ -638,7 +645,7 @@ on; `key` resolves keys the way the canvas does. Commands behind keys: `board.nextSticky` (`Shift+Cmd/Ctrl+Enter`, also while typing in a sticky). Keys no design-file shortcut uses; on a design file they refuse. - `view.pan {dx, dy, big?}`: the arrow keys with nothing selected (`key ArrowRight` does the same) - pan the view by 20 screen pixels a step, 200 with `big` (Shift). + pan the view by 64 screen pixels a step, 320 with `big` (Shift). - `view.multiplayerCursors {on?}` (`Alt+Cmd+\`): show or hide others' cursors in a live session. - `view.outlinesHiddenLayers {on?}` and `view.outlinesObjectBounds {on?}`: what outline mode (`view.outlines`, `view.outlinesSelection`) draws besides the shapes: hidden layers, and the box @@ -761,7 +768,7 @@ page line crosses; parts that come apart move to layers of their own above, list `vector.deleteHeal`, `vector.join` / `vector.smoothJoin` (join the selected points while editing), `vector.edit.cornerRadius` (rounds the selected sharp points, next to straight or curved segments: a curve is cut where the arc meets it and keeps the rest of its shape; drawn and exported; -`node.set {cornerRadius}` on a vector rounds every point), `vector.edit.strokeCap {cap, vertices?}` +`node.set {cornerRadius}` on a vector rounds every point, and on a boolean group every sharp corner of its result, while its layers keep their own radius), `vector.edit.strokeCap {cap, vertices?}` and `vector.edit.strokeJoin {join, vertices?}` (the stroke's cap where it ends at these points and its join where it turns there, `null` for the layer's; drawn, exported and outlined), `vector.edit.moveHandles {dx, dy, handles?}` (moves the selected handles by a page offset), @@ -1886,7 +1893,9 @@ properties with their values, its code and, with `path`, a PNG of it. The docume unbinds): `fill` or `fills//color` and `fills//stops//color` on a paint style, `effects//` on an effect style, `layoutGrids//` on a grid style, `fontSize`, `lineHeight`, -`letterSpacing`, `fontFamily`, `fontStyle` on a text style. Each layer using the style shows the +`letterSpacing`, `fontWeight` (numbers; a weight picks the family's face nearest it and sets the +`wght` axis of a variable font), `fontFamily`, `fontStyle` (strings; a bound weight and a bound style +name replace each other) on a text style. Each layer using the style shows the field in its own modes and stays linked; `style.list` gives a style's `bound` map. `effect.add {ids?, type? | effect?}` adds an effect (`dropShadow`, `innerShadow`, `layerBlur`, diff --git a/docs/roadmap.md b/docs/roadmap.md index 0e12d327c..1ba946bb2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (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-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 | | 2026-11-03 | patch | M4, #1747: a text layer still carrying the name its characters gave it is renamed as they are typed, so the Layers panel no longer shows the word a layer started with while the canvas shows another (`hello` typed into `hello there` read as `hello` in the panel). A name the author typed is kept, and only the editor follows the characters: commands leave the name alone, so the layer names `data.fill`, component property bindings and templates use as field keys stay put. Tests: `text_behaviour_tests::typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it`, `setting_characters_as_a_command_never_renames_the_layer`. Grade unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ccc133c51..031ef0726 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-11 · **Change:** minor (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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **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) 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 @@ -99,12 +99,12 @@ Breadth: does it exist. Ready: depth, correctness and fidelity for real projects | 1 | Canvas & navigation | 6 | 98% | 74% | Display P3 on screen, QA at extreme zooms (behaviour suite for navigation, rulers, guides, layout grids and outline mode landed: guide selection, Auto grid counts, outline-mode clicks; outline mode's Include hidden layers and Include object bounds landed) | 1–4 | | 2 | Selection & transform | 8 | 97% | 72% | Handles, measuring and snapping checked tool by tool against Figma and real files (snap distance, handle reach, cursors); children turned off a right angle scale without skew, approximately (behaviour suite from the documentation, rotated groups and mixed selections, equal spacing snapping, Cmd/Ctrl to ignore constraints and marquees inside frames landed) | 3–5 | | 3 | Layers panel | 5 | 99% | 85% | QA with long real files (behaviour suite from the documentation, Rename layers dialog, sweeping eyes and padlocks, page dragging and dividers, several layers dropped together, keyboard box selection, F2 rename, Shift+F10 context menu and 10k-layer timings landed) | 1–2 | -| 4 | Shapes & vector | 8 | 99% | 73% | Corner radius and smoothing on boolean groups that contain rectangles; per-point caps and joins on dashed, variable-width and brush strokes; vector QA with real files (behaviour suites from the documentation, corner radius and star ratio handles, corner smoothing on polygons, stars and closed vectors, rounded vector points drawn, also beside curved segments, a cap and join per point, several handles dragged together, cut and paint bucket drags, delete and heal along the curve, a boolean group's look by operation and the miter angle landed) | 1–3 | +| 4 | Shapes & vector | 8 | 99% | 73% | per-point caps and joins on dashed, variable-width and brush strokes; vector QA with real files (behaviour suites from the documentation, corner radius and star ratio handles, corner smoothing on polygons, stars and closed vectors, rounded vector points drawn, also beside curved segments, a cap and join per point, several handles dragged together, cut and paint bucket drags, delete and heal along the curve, a boolean group's look by operation, a boolean group's corner radius and the miter angle landed) | 1–3 | | 5 | Paint | 7 | 90% | 71% | Video fills, wide-gamut canvas, HEIC images; plus darker in PDF (behaviour suite from the documentation, pass-through and isolating groups, clipping frames that don't isolate, plus darker, animated GIF fills, TIFF images and embedded image colour profiles landed) | 2–5 | | 6 | Strokes | 3 | 95% | 75% | Stroke QA with real files (colour styles on strokes, stroke weight and per-side weight variables, brush strokes landed, see 20) | 1–2 | -| 7 | Effects | 4 | 100% | 75% | Glass and progressive blur tuned side by side (behaviour suite from the documentation, inner shadows and background blur on groups, shadows hidden behind translucent layers on the canvas and in every export landed) | 2–5 | +| 7 | Effects | 4 | 100% | 75% | Glass and progressive blur tuned side by side (behaviour suite from the documentation, inner shadows and background blur on groups, shadows hidden behind translucent layers on the canvas and in every export landed; a background blur or glass exported on its own keeps the content behind it within its bounds, measured 2026-11-10, #2213) | 2–5 | | 8 | Frames, groups, sections, masks | 5 | 97% | 80% | Visual QA with real files (a one-step frame/group convert, and a behaviour suite from the documentation landed: masked-out areas don't take clicks, mask group bounds and exports follow the mask, sections kept out of frames and groups, frames and sections drawn around layers take them, section resizing leaves contents in place, X/Y measured in the frame) | 1–3 | -| 9 | Auto layout & constraints | 9 | 98% | 74% | Behaviour against real Figma files (behaviour suite from the documentation, `fr` tracks like CSS, vertical wrap, auto gaps evenly/around, cell alignment and wrapped-line alignment landed) ([auto-layout-parity](auto-layout-parity.md)) | 3–6 | +| 9 | Auto layout & constraints | 9 | 98% | 74% | Behaviour against real Figma files (behaviour suite from the documentation, `fr` tracks as measured, vertical wrap, auto gaps evenly/around, cell alignment and wrapped-line alignment landed) ([auto-layout-parity](auto-layout-parity.md)) | 3–6 | | 10 | Text | 8 | 90% | 70% | Spell check, text metrics on real files and in other fonts (text box sizes measured against documents re-saved by other software: all 230 self-sizing boxes in 7 documents come out to the pixel, one font family; behaviour suite with CJK line breaking, Thai, Lao, Khmer and Burmese breaks between words, vertical trim and carets by grapheme cluster landed; lists per paragraph with nesting and list spacing (typing `-`, `*`, `1.` or `1)` and a space starts one), hanging punctuation and lists, decoration style, thickness, offset, skip ink and colour landed) | 3–7 | | 11 | Components & variants | 9 | 96% | 72% | Real (not synthetic) libraries, `.fig` libraries (a component playground for variant, boolean, text and instance-swap properties, a behaviour suite from the documentation, overrides of padding, gap, grids, exports and interactions, refused geometry overrides, variant-switch and Assets-swap override rules, top-left default variant landed) ([components-parity](components-parity.md)) | 4–9 | | 12 | Styles & variables | 5 | 95% | 76% | Real-library QA (variables inside styles, behaviour suite from the documentation, style folders and order, mode order, code syntax, extended collections with their tail (new library variables as updates, chains through libraries) and variables import/export landed) ([components-parity](components-parity.md)) | 2–4 | @@ -246,7 +246,7 @@ Hours in this narrative are the builders' estimates; the tables above supersede closed area (faces with holes), point/segment selection, handle mirroring (none/angle/angle and length) with a Point panel (position, corner radius, mirroring), smooth/sharp points, join and merge (joining the two ends of a path broken open by a deleted point closes it again, so its - fill follows the new segment, #1951), delete vs delete-and-heal, nudging, one undo step per gesture, eraser (⇧E), shape builder + fill follows the new segment, and a rounded loop left open where a segment joins its ends is cut by arcs at them too, and Delete closes such a loop through that segment, #1951), delete vs delete-and-heal, nudging, one undo step per gesture, eraser (⇧E), shape builder (⇧M: the regions of overlapping shapes, click or drag to merge, Alt to remove, curves kept), variable width strokes (width profile presets with previews in the stroke settings, the Variable width tool ⇧W: drag the path to add a width point, slide points, drag their handles, Delete; @@ -330,8 +330,7 @@ Hours in this narrative are the builders' estimates; the tables above supersede "Navigate to" a section shows its frame shown last, else its first; ready for dev turns "Changed" when the contents are edited, resolved with a reason; Compare changes shows what a changed frame or section looked like when it was marked next to how it is now, with the - changed layers and their property changes. *Left:* whether `fr` rows of a fixed-height grid - should make room for fixed-size children (now `minmax(0, 1fr)`-like). 1–2 h. + changed layers and their property changes. 1–2 h. 4. **Components depth**: *landed:* component properties (edit/delete/bind) with the properties panel, add variant, instance swap UI, per-layer overrides with reset, restore main, instance structure protection; Assets panel with live thumbnails, search and drag-to-canvas (drops into @@ -650,11 +649,17 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 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 | +| 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). Percentages 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). | +| 2026-11-11 | patch | M4, #1951 (reporter's file, v0.17.0): a corner cut off by a segment drawn first, the corner point then deleted with Delete, leaves the region's loop as the open chain of the other segments, the cutting segment (which joins the chain's two ends) in no loop; rounded, the loop's first point was never cut by an arc (rounding only adds arcs at points the loop arrives at) and the closing edge ran straight, so the fill and the selection outline missed corners the stroke rounded. `VectorNetwork::rounded_smoothed` now walks the segment joining an open loop's ends, when no loop holds it, as the loop's last segment (`closing_segment`). Evidence: `doc::tests::a_rounded_loop_left_open_where_a_segment_joins_its_ends_follows_that_segment` (fails on main: fill 1810.85 vs stroke 1818.58); #1991's tests unchanged. | +| 2026-11-11 | patch | M4, #1951: Delete (and removing segments, and the eraser) closes a region's loop through the segment that joins its ends: a bridge drawn between two points of a ring leaves the region alone (`connect` rightly keeps the ring), and deleting the point between them rotated the loop open, the bridge in no loop, so even an unrounded fill ran straight across a curved bridge. `reopen_loops` now pushes the one segment in no loop that joins an open chain's ends onto the loop's end, keeping its winding, as #1991's connect does; `closing_segment` (now public) walks strictly, ignores segments already in loops and gives up when two qualify. The render fix stays as the fallback for files saved in that state. Evidence: `vectoredit::tests::deleting_the_corner_behind_a_pen_bridge_closes_the_loop_through_the_bridge` (fails before: the loop kept 4 of 5 segments), `ops::tests::deleting_a_point_behind_a_curved_bridge_keeps_the_bridge_in_the_loop`, `doc::tests::an_open_loop_follows_the_segment_joining_its_ends_listed_first_or_walked_backwards`. | | 2026-11-06 | patch | M3: glass's docs say which centre `splay` bends away from: the centre of the layer's bounds, as the reference tool's, checked side by side on a ring and an L at Splay 0% and 100% (an inner edge bends towards the hole in both). And where a glass shape gets no core: past 4M px on the desktop and 1M on the web (`MAX_SHAPE_PX`) it bends along its edge normals, so a large glass text or vector can bend differently once zoomed into, in a 2× export, or on the web. Docs only. Grade unchanged. | +| 2026-11-10 | patch | M10, #2213: a layer with a background blur or glass exported on its own includes the blurred content behind it within its bounds, as the reference tool's web app does (measured 2026-11-10: the pane's own bounds, opaque where the backdrop is, nothing outside them; layers above it stay out, "contents only" unchanged for layers without those effects); the export reads the page's layers below the exported one as its backdrop | | 2026-11-02 | minor | M3, #1885: glass bends towards its core, the shape shrunk by `depth` and the bevel, as the reference tool's: round a sharp corner the bend turns smoothly, and a thin part (a capsule, a letter's stroke) bends across itself, checked side by side on a capsule 44 units tall. Rounded rectangles work it out in closed form. A shape too big to keep whole at the zoom bends along its edge normals instead, so no render works out a core over more pixels than a kept shape holds. Tests: `glass::tests::a_sharp_corner_bends_round_towards_the_core`, `glass::tests::a_thin_part_bends_across_itself`, `glass::tests::a_shape_too_big_to_keep_bends_along_its_normals`, `glass_cut_tests::a_cut_through_the_pane_matches_the_whole_render`. Grade unchanged. | | 2026-11-02 | minor | M3, #1885: glass's light is a line on its 1-unit bevel added to the backdrop, as the reference tool's: fully where the edge faces the light, none below 0.35 of facing it, 0.6 as much on the opposite side, with a faint gradient across the curve. `splay` turns the bend from along the edge's normal towards the way away from the layer's centre and no longer widens the light, as in the reference tool. Checked side by side on synthetic files: a splay of 1 bends the backdrop towards the centre in both. Tests: `glass::tests::the_light_lies_on_the_bevel_and_the_gradient_across_the_curve`, `backdrop_tests::splay_turns_the_bend_towards_the_centre`, `glass_cut_tests::the_light_is_a_line_on_the_bevel`. Grade unchanged. | | 2026-11-02 | minor | M3, #1885: glass bends the backdrop with the reference tool's thick-lens profile (most a 1-unit bevel in from the edge, falling off as the 3.5th power of the way out of the curve to nothing `depth` further in) and splits its colours over 8 steps, red and blue 0.16 of the bend apart at 100% dispersion. Measured against the reference tool on synthetic files at 2×: the black band a pane pulls to its edge ends within 3 px of the reference tool's, and red and blue part 2.27 px at 50% dispersion and 4.66 px at 100% (2.38 and 4.69 there). Tests: `glass::tests::the_bend_follows_the_thick_lens_profile`, `glass::tests::dispersion_splits_the_channels_along_the_bend`. Grade unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 021576607..1911dbbcd 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 (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 (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: @@ -20,22 +20,25 @@ interaction feel not yet compared. | 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`) | | 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 200–480, right 240–480, 240 by default; 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 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`). Not compared with Figma's widths; no snap points | +| 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) | | Actions palette (Cmd+K, Cmd+/) | done | tabs: All (every command, grouped by menu, or Other; a command that needs parameters only through its menu item, and none twice under one label, #1574), Assets (components and styles) and Plugins & widgets; results ranked prefix first, then shortest, at most 60 rows; Up/Down move a highlight and Enter runs it; Recents list what was run from the palette (matching translated labels); one open/toggle path from every entry point (`palette_tests`). Ranking and the Assets results not compared with Figma's | | Context menus | done | canvas and layers; submenus as in the main menu below, and a right-click in a new spot starts a fresh menu (Select layer closed); Shift+F10 or the keyboard's Menu key opens them from the keyboard (at the focused layer row or below the canvas selection) and the menu takes the keyboard (`layers_keyboard_tests`) | | Home screen: Recents, Online and Templates | done (ours) | The sidebar switches between the three (`ui.set {homeSection}`). Online: your online files (see the collaboration checklist). Recents: new file, open, join with a code, open files, recent files (cards with the picture each file carries on its page colour, the file's icon, name and "Edited ... ago" or "File not found", full path on hover; or a Name, Last modified and Created table with sortable headers; sorted by name, creation or last change either way; grid or list and the sort kept in the preferences, `ui.set {homeRecentsView, homeRecentsSort, homeRecentsOrder}`; a click selects, a double-click or Enter opens, arrow keys move the selection; Open, Show in folder and Remove from recents on right-click), a Getting started card (six tips with their shortcuts from the keymap; its close button is remembered in the preferences and Help ▸ Getting started brings it back) and, while there are no recent files, four templates to start from. Templates: the eight starter templates as cards (thumbnail rendered from the document, cached per theme; name, description, kind and size), a search field and a kind filter, an empty state; Tab reaches every card and Enter opens it; cards and tabs are named for screen readers. A first run opens here. No Community files or drafts folder | -| Main menu from the logo | done | generated from `catalog.rs`; popups sized to content. Submenus open after 0.15 s on their row (a click or the keyboard opens one at once) and close at once when another row is hovered; while the pointer heads for an open submenu inside the triangle to its near edge, the rows it crosses don't take over, and resting 0.3 s on one hands over; closing the menu, however it closes, clears which submenus were open, so it reopens with none (`menu_aim_tests`, 10 tests; timings tuned by feel, not measured against Figma). A menu or submenu that would run past the window's bottom moves up to fit (never above the top), and one taller than the window scrolls with the wheel, the keyboard's focus kept in view; the context menu's submenus share this (#2217, `menu_overflow_tests`). Menu and palette items that need a value ask for it first: Create link, Offset path and Move to page in a dialog of the shared controls, the language, user name, server and nudge items in Preferences, Open recent on the home screen's Recents; File ▸ Rename edits the file name in place | +| Main menu from the logo | done | generated from `catalog.rs`; popups sized to content. Submenus open on the first frame their row is hovered (a click or the keyboard opens one at once; Figma's main menu measured 2026-11-07 with synthetic pointer events: median 11 ms to open, 13 ms to switch rows) and close at once when another row is hovered; while the pointer heads for an open submenu inside the triangle to its near edge, the rows it crosses don't take over, and resting 0.3 s on one hands over; closing the menu, however it closes, clears which submenus were open, so it reopens with none (`menu_aim_tests`, 10 tests; the open delay is measured; the safe triangle and its 0.3 s rest are still tuned by feel, and Figma's main menu showed no triangle at all in that measurement, so the aim is kept pending the maintainer's decision). A menu or submenu that would run past the window's bottom moves up to fit (never above the top), and one taller than the window scrolls with the wheel, the keyboard's focus kept in view; the context menu's submenus share this (#2217, `menu_overflow_tests`). Menu and palette items that need a value ask for it first: Create link, Offset path and Move to page in a dialog of the shared controls, the language, user name, server and nudge items in Preferences, Open recent on the home screen's Recents; File ▸ Rename edits the file name in place | | Keyboard shortcuts panel | done | closes when the home screen shows (#548); docked, tabbed by group like the documentation, searchable, per-platform keycaps; held keys, gestures and presentation keys listed beside the bindings; a label too long for its column ends with "…" and shows in full on hover | | Several windows | partial | File ▸ New window, Open in new window on a tab, a tab dragged off the strip; screen-reader tree in the main window only; positions not restored | | Multiplayer avatars, Share button | missing | waits for multiplayer | | Colour names in hex fields | done | every hex field (fills, strokes, text ranges, effects, layout grids, colour variables, page and prototype backgrounds, the colour picker's Hex) takes a CSS colour name as well: `red` becomes `FF0000`; case, spaces and hyphens are ignored (`Light Blue`); names are opaque and keep the colour's opacity; hex wins where both could match. The picker's CSS field takes every CSS name too (`Color::from_hex_or_name`, `color::named`) | | Fields select their text on focus | done | Number and text values keep their vertical position when their editor gains focus (including typography spacing; `sidebar_field_text_stays_in_place_on_focus`). a click or Tab into a one-line field selects all of its text, so typing replaces the value: hex and colour fields, number fields, inline fields (a fill's hex, variable values, renames), names, search boxes and dialog fields; a drag from the press selects only what it covers; multi-line fields (descriptions, comments) keep the caret where clicked. The first click into an inline field (a fill's hex) now takes the keyboard; it took a second click. A rename (double-click, F2, File ▸ Rename, a page) selects the whole name before its field first draws, so a key typed in that same frame replaces the name; it was appended (`widgets::select_all_on_focus`, `select_all_tests`, `layers_rename_tests`) | +| Canvas page transparency | done | Transparent or translucent page backgrounds show a checkerboard using the theme’s panel and canvas colours, updated immediately when switching between light and dark. The page background alpha is applied once: a rendered image already contains the page colour, so only uncovered areas receive the fallback colour during zoom and pan. An opaque page hides the checkerboard. Theme changes update the same cached texture. The grid is a repeated four-pixel texture at a fixed screen size, separate from document exports. Tests: `canvas::background::tests` assert strip colour/alpha, gap-free non-overlapping coverage for absent, offscreen, edge-straddling and fully covering renders, checkerboard rect/UV/order, and theme updates through drawing. | +| Page background colour control | done | Uses `widgets::paint_field`, as Fill, Stroke and Selection colors do: one background, inline HEX, accessible swatch toggling the picker and fractional opacity. Typed colours preserve alpha unless 4/8 HEX digits explicitly supply it; opacity scrubs remain live and undo as one step. Tests: `field_tests::the_page_background_opacity_field_sets_the_page_colour_alpha`, `field_tests::page_background_shows_fractional_opacity_like_fill_and_keeps_it_when_opening_the_picker` and `field_tests::page_background_colour_and_opacity_fit_a_resized_sidebar` (240 and 500 pt). | | Colour picker models | done | Hex, RGB, HSL, HSB, LCH, OKLCH and CSS; LCH and OKLCH keep lightness and hue when a colour leaves sRGB (chroma comes down); the values typed stay while the colour is theirs (a hue typed on a grey, a chroma sRGB can't hold); CSS reads `lch()` and `oklch()` with any hue unit and `none` (`figcraft_color::{Lch, Oklch}`). Values are the stored channels read as sRGB | | Colour picker placement and dismissal | done | Opens 8 pt beside the sidebar at the opening control, lifted to fit the screen; outside presses (including the sidebar), Escape and X close it. Reopening resets a dragged position; eyedropper sampling keeps it open, and so does a drag of the open gradient's handles or stops on the canvas (#1852). | | Colour picker image well | partial | the Image tab shows a checkered placeholder and Upload from computer until there is a file (no dialog at once); an image paint shows its asset preview; a file dropped on the open picker replaces the image, keeping the fill mode, crop, position and adjustments (`image.replace`). Layers' fills and strokes only (text ranges, styles and selection colours keep Upload). The Fill and Stroke swatches take no drop: a dragged file's position isn't known, so a drop with none goes to the open picker | | Colour picker on a new fill or stroke | done | + opens the picker on the new paint when the selection shares one paint list; on a mixed selection + adds a paint to each layer and no picker opens (#404) | | Fill section on a text with coloured characters | done | a text's Fill section shows what its characters show: characters coloured differently while editing are mixed content ("Click + to replace mixed content", as a mixed selection; the developer documentation's `fills`: "Text nodes can have multiple sets of fills if some characters are colored differently than others"), and characters that all share fills the layer doesn't have show those. Any layer-level fill edit (a row, its picker, +, reordering, `fill.*`, `node.set`) reaches every character, starting from the list they showed; the characters' own fills go in the same undo step; the canvas gradient and crop handles show and edit the paint the row shows, the characters' own, also when their image is already in Crop mode (`text_mixed_fill_tests`, `canvas::handles::character_fill_tests`, engine `text_fill_tests`; #1856). A range selected while editing keeps its own Fill row | +| Fill, stroke and effect rows: click to highlight, Cmd/Ctrl+C, Cmd/Ctrl+V | done | a click on a row's reorder grip (left of its fields) or its background between its controls highlights it in the selected-row colour, one row at a time; Cmd/Ctrl+C (or Edit ▸ Copy) then copies that paint or effect instead of the layers (`fill.copy`, `stroke.copy`, `effect.copy`, as the row's menu does; a stroke takes its weight and settings along) and Cmd/Ctrl+V pastes it onto every selected layer (`fill.paste`, `stroke.paste`, `effect.paste`), one undo step: on top of each layer's list, or in place of the highlighted row when it is of the same kind. A copy keeps its kind: a stroke goes to the strokes and an effect to the effects whatever row is highlighted, and the last row copied is the one pasted. A solid colour also goes to the system clipboard as its hex code; a programmatic copy never writes it. A later layer copy, or text or an image copied in another app, is pasted instead; every window pastes the same copy. Escape, a press on the canvas or elsewhere in the Design panel, another selection, file or tab let the highlight go (#1494). The help center says only that a property is highlighted with a click; adding on top follows the forum's accepted answer for adding one fill without replacing the others, not an observation. Delete and Cmd/Ctrl+X still act on the layers; the keyboard alone can't highlight a row | | Blend mode menus: the layer's (Design panel) and each paint's (colour picker) | done | Pass through and Normal are distinct (Normal isolates a group's or frame's children); paints have no pass-through; plus darker drawn exactly on the canvas | ## Layers and Assets panels @@ -62,7 +65,8 @@ interaction feel not yet compared. | 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`) | -| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation | +| 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 | | 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) | @@ -79,9 +83,9 @@ interaction feel not yet compared. | 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 | for a mixed selection the Design panel 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`). No library styles or variables from there, and no new style or variable from a row (#403) | +| 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 | for a mixed selection the Design panel 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) | +| 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 | ## Tools @@ -93,15 +97,21 @@ interaction feel not yet compared. | 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); 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). 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; 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). Not yet: areas of other layers edited at once | | 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); 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); 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 | | 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; 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. 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: 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` | -| Eyedropper (I) | done | picks the colour seen under the pointer (opaque) into the selection's fill and the recent colours, one undo step (`fx_behaviour_tests`); with Cmd/Ctrl+Shift held it makes a colour style or variable of it instead, as the reference app's eyedropper does: a Create from color window asks which, its name (the next free "Color n") and a variable's collection (the file's first, or a new one made with it in the same undo step), and leaves the selection's fills alone (`eyedropper_create_tests`, `sampled_color_tests`) | +| Eyedropper (I) | done | picks the colour seen under the pointer (opaque) into the selection's fill and the recent colours, one undo step (`fx_behaviour_tests`): one screen pixel centred on the pointer, sampled as the canvas draws it when zoomed in, so an image magnified past 2x gives the pixel under the pointer, not a blend with its neighbours; zoomed out it samples the full-resolution image (the canvas may show a smaller copy, which the eyedropper does not use), so it can differ slightly from the shown colour (#2189, `eyedropper_image_tests`); with Cmd/Ctrl+Shift held it makes a colour style or variable of it instead, as the reference app's eyedropper does: a Create from color window asks which, its name (the next free "Color n") and a variable's collection (the file's first, or a new one made with it in the same undo step), and leaves the selection's fills alone (`eyedropper_create_tests`, `sampled_color_tests`) | | Comment (C), Shift+C to show/hide | done | local only | +| Annotation tool (Shift+T) | done | picks the layer under the pointer, or the selection (or an `id`) with `tool.annotation`, and opens its note in the Inspect tab with the new-note field focused; it works in Developer Mode and in Design mode, and stays selected until V or Escape (inferred). 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 | | Text on a path (Figma Draw) | done | the Text on a path tool in the Text flyout (`tool.textOnPath`) shows the I-beam over a shape's or vector's path, and a click there puts new text on the path, starting at the click, with the path's effects and its fill when one shows; the path layer is removed, and the path comes back if nothing is typed. Also from the Design panel or `text.onPath`; the path is edited by resizing only | | Stretch and scatter brushes (Figma Draw) | done | eight presets drawn in code; the Pencil's brush is set by `tool.pencilBrush`, not from the toolbar | | Image crop handles; Crop image | done | Object ▸ Crop image, the right-click menu and the crop button on an image fill row (`image.crop`) switch the image to Crop where it already shows and enter crop mode: the whole image shows, dimmed outside the layer; the layer's box carries L-shaped corner brackets and edge bars in the selection colour (in place of the square handles), and its edges and corners crop it with the picture held still (as Cmd/Ctrl-resizing does anywhere), the image drags to move and its corners scale it (Shift: freely); Enter, Escape or a click outside finishes (`image_crop_tests`, `crop_image_tests`). Not compared side by side | @@ -110,7 +120,8 @@ interaction feel not yet compared. | Item | Status | Notes | |---|---|---| -| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`) | +| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); 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`) | +| 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_tests`) | | 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 | @@ -123,7 +134,7 @@ interaction feel not yet compared. | 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) | | 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 | +| 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 | ## Keyboard shortcuts @@ -138,9 +149,9 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | | Count | Notes | |---|---|---| -| Documented shortcuts (rows) | 136 | each with macOS and Windows/Linux keys | -| Bound as documented | 135 (110 before this suite) | 112 keymap bindings, 15 held keys, gestures and presentation keys, 6 vector edit tool keys | -| Bound as documented | 135 (110 before this suite) | 112 keymap bindings, 16 held keys, gestures and presentation keys, 6 vector edit tool keys | +| 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 | | Documented keys a platform keeps | 2 | Ctrl+Space (Windows/Linux keyboard box selection) switches some CJK input methods; F6 goes to a browser's address bar in the web build | @@ -184,15 +195,51 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | WCAG AA contrast of secondary and accent text | done | disabled and dim text at least 3:1 against panels, fields and selected rows, selected text at least 3:1 on its highlight, in both themes (`theme::tests`, #890) | | Tested with VoiceOver, NVDA, Narrator, Orca | missing | human QA | +## Sidebar colour control audit (2026-11-09) + +The Page background, Fill, Stroke and Selection colors reuse `widgets::paint_field`. +The remaining custom controls are: + +| Control | Implementation | Remaining difference | +|---|---|---| +| Effects: drop/inner shadow and noise colours | `panels/right/effects.rs`, `fx_color` | Separate swatch, HEX and rounded opacity; shadow colour also supports variable binding. | +| Layout-grid colour | `panels/right/effects.rs`, `grid_settings` | Separate painted swatch, HEX and rounded opacity; the swatch is not interactive. | +| Prototype overlay background | `panels/proto_panel.rs`, `action_fields` | Separate swatch, HEX and rounded opacity; opacity scrubs apply only on release. | +| Prototype device background | `panels/proto_panel.rs`, `settings` | Swatch and HEX only; no opacity field or picker routing. | +| Prototype Set variable colour value | `panels/proto_editor.rs`, `literal_field` | Swatch and HEX only; no opacity field or picker routing. | +| Selected-text Fill | `panels/right/paints.rs`, `range_fill` | Custom combined swatch/HEX row, with picker routing but no sidebar opacity field. | + +Device-colour presets and Developer Mode inspection swatches are display controls, so they +are not colour/opacity editors. Variable cells and style editing live in separate windows. +This audit records candidates for subsequent fixes; their behaviour is unchanged here. + ## Revision history | Date | Change | Summary | |---|---|---| +| 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) | +| 2026-11-09 | patch | M3, #2189: the eyedropper picks the colour the canvas shows. It sampled a 1x1 render without the canvas's magnified-image pixels, so on an image magnified past 2x it blended a 1 px line with its neighbours (#3D444D picked as #343B44 beside #151B23), and the pixel it sampled began at the pointer instead of being centred on it. It now matches the canvas when zoomed in; zoomed out it still samples the full-resolution image, not the smaller copy the canvas may show. Test: `eyedropper_image_tests` | +| 2026-11-09 | patch | M3, #2188: Selection colors shows for a selection holding a layer with children (a frame, group, component or instance) from one paint group, and for layers without children only from two paint groups (groups are counted by style, variable and paint value, as `collect` does, not by distinct colours); measured in Figma's web app on 2026-11-09 for the examples below only, and instance and component behaviour was not measured: a frame holding one red rectangle, a group of two red rectangles and a frame with a lone black-stroked rectangle show one row; one red rectangle, two red rectangles and a childless green frame show none; a red and a blue loose rectangle show two (two paint groups). A childless rectangle with a red fill and a blue stroke has two paint groups, so the engine shows the section (not measured). Tests: `selection_colors_tests`. Counts unchanged | +| 2026-11-10 | patch | M1, #2198: with a shape, frame, slice or Text tool the pointer was the system's crosshair, white under some pointer styles on Windows and lost on the default white frame; it is now drawn at the pointer in dark lines with a white edge, open at the centre (`Glyph::Crosshair`), so it shows on any canvas colour. | +| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result (measured in Figma's web app), Boolean groups row | +| 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-09 | patch | Preferences ▸ Invert zoom direction (#2145): Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom the other way; pinch and panning unchanged. Numbers unchanged. | +| 2026-11-07 | patch | Transform: Shift while rotating lands on absolute multiples of 15°, measured in Figma (a layer at 7° or -4.27° Shift-rotated by its corner ends at 15°); FigCraft rounded the turn since the drag began, so 7° landed on 7 + k*15. The gesture keeps the selection's shared rotation and rounds base + turn; a selection with different rotations keeps rounding the turn. Test: `shift_rotating_lands_on_multiples_of_15_not_steps_from_the_start` | +| 2026-11-10 | patch | M1 review follow-up: strengthen canvas alpha, clipping/coverage, grid geometry/order and drawn-theme tests; use settled fresh sidebars at each width, check HEX visibility and opacity alignment, and assert picker toggling preserves page alpha. Production behavior unchanged. | +| 2026-11-09 | patch | M1: canvas page transparency uses a checkerboard that follows light/dark themes and applies background alpha once, including partial or missing renders. The page control also fits both sidebar width limits. Tests: `canvas::background::tests`, `field_tests::page_background_colour_and_opacity_fit_a_resized_sidebar`. Numbers unchanged | +| 2026-11-09 | patch | M1: the Page background reuses the shared sidebar paint control; fractional opacity and picker toggling covered alongside alpha-aware HEX and scrub undo. Audited remaining custom sidebar colour controls. Numbers unchanged | +| 2026-11-07 | patch | View: the arrow keys with nothing selected pan 64 px, 320 with Shift (five steps), as measured in Figma's web app at 100% zoom (62–64 px in two trials, about 320 px with Shift, about ±3 px); they panned 20 px (200 with Shift). Test: `cmd::view::start_on_home_tests::the_arrows_pan_64_px_and_320_with_shift_as_measured_in_figma` | +| 2026-11-09 | minor | Shortcuts: Shift+T picks the new Annotation tool (`tool.annotation {id?}`, Accessibility at Figma, Add an annotation): with a layer selected, or an `id`, it asks the UI for that layer's note at once; in the tool a press on a layer selects it and asks, a press on empty canvas does nothing; the Inspect tab opens with the caret in the new-note field and the engine writes nothing itself; documented shortcuts 137, bound 136 (#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-11-11 | patch | M5, gap 4: marquee selection as measured in Figma's web app (Select layers and objects, Selection marquee): a partly covered top-level frame or section gives the layers in it the marquee touches (it was selected only when enclosed, so nothing came), an empty frame is selected on touch, a rotated shape is touched by its outline and not its box, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole), and also takes the top-level layers it touches outside it, and selecting a frame whole keeps the marquee at the top level (a partly covered frame then comes whole, not its layers). Flipped: `marquee_selects_what_it_touches`, `cmd_marquee_selects_nested_layers`, `a_box_selects_like_a_marquee`. Tests: `marquee_behaviour_tests`. Counts unchanged | +| 2026-11-11 | patch | #2195: Flatten on a vector whose points have a corner radius bakes the rounding into the path, as measured in Figma web: each rounded point becomes the arc's end points joined by curves (a 3-point V with radius 60 on the apex gives 4 points), the layer stays a vector, every radius reads 0 afterwards and the box shrinks to the real geometry (245 to 205.09 high). Shapes' own radii were already baked. Numbers unchanged. | | 2026-11-08 | minor | Vector edit mode, #1875, measured in Figma (web, real keys): Copy with segments selected takes only those (with just a point selected, the segments touching it) and a paste outside edit mode is a new vector layer in place; Cut removes them, the path splitting into subpaths in the same layer with edit mode staying on, and a paste outside gives a new layer with the cut segments; Paste while editing a vector adds the clipboard's segments, or a copied layer's outline, to the same network in place, selecting the pasted points, with no new layer and the bounds growing. FigCraft copied the whole layer, Cut left nothing to paste and Paste did nothing. `edit.copy`, `edit.cut` and `edit.paste` act so with no `ids`/`parent` given (Ctrl+X is the real Cut again; Shift+Delete still heals); the copy carries the layer's look (fills, strokes, effects, opacity, blend; the width profile only when every segment is copied); layers with no outline are skipped. Tests: `vector_clipboard_tests` | | 2026-11-08 | patch | Selection: Escape with layers selected clears the selection instead of stepping out to the parent first. Measured in the Figma web app with a rectangle in a group in a frame, selected from the canvas, from the Layers panel and after Tab: one Escape selects nothing. Editing, gestures and the pen still end first | +| 2026-11-08 | patch | Panels: the sidebars' width limits are Figma's, measured in its web app (left 240 to 450, right 240 to 500, both 240 by default, a double-click on the edge resets), where FigCraft had left 200 to 480 and right 240 to 480; widths saved under the old limits are clamped on load | +| 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-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 | | 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`. | @@ -206,12 +253,14 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | 2026-11-06 | patch | M7, #2032: closing a tab whose file has unsaved changes, by its X, a middle click, File ▸ Close tab or its shortcut, only showed a toast ("save first, or close again with Alt to discard") and left the tab open, so closing seemed not to work. It now asks the unsaved-changes question the window asks (`windows::TabClose`): Don't Save closes the tab, Cancel or Escape keeps it, Save saves the file and then closes it (a file without a path, or saved as .fig, asks where with Save as first and stays open if that is cancelled); Alt+close still drops the changes at once, and `file.close`'s `dialog.unsaved` request asks too. The three toasts left the catalogs. Tests: `titlebar_tests::closing_a_tab_with_unsaved_changes_asks`, `titlebar_tests::save_in_the_tab_question_saves_then_closes`. Reordering tabs by dragging, the issue's other half, landed on 2026-10-19 (`dragging_a_tab_along_the_bar_reorders_it_without_detaching`) | | 2026-11-05 | minor | M4, #1830: a paragraph's base direction can be forced (`TextDirection`: Auto, Ltr, Rtl on `ParaList`): Text ▸ Text direction ▸ Auto / Left to right / Right to left (`text.directionAuto` / `Ltr` / `Rtl`) and `text.direction {direction, ids?}` set the edited paragraphs while editing, else the layer's; `node.set textDirection`; the Type settings control once a right-to-left script is in the text; inspect `textDirection` / `lineDirections`; CSS `direction`; `.fig` lines' `sourceDirectionality` in and out. Layout gives each paragraph its base level (`Bidi::of` runs the algorithm per paragraph, as it starts over at each). Before, direction came from the letters only ("controls are available to override text direction per paragraph", Add right-to-left text). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests::a_lines_source_directionality_is_its_paragraphs_direction_both_ways`. | | 2026-11-02 | minor | M1, #1836: pick select. Tab while the keyboard selection box shows, or Alt/Ctrl+Space again, puts 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 as the Layers panel lists them, Enter into a frame's top child, Shift+Enter out to the parent (never the page), Space selects the layer under it, Escape or a press on the canvas ends it; the chord again while the pick cursor shows brings the box back (Accessibility at Figma). The control channel's `ui.key` sends the box's and the pick cursor's keys to them too. One documented row more (135, 134 bound); four gesture rows. Tests: `layers_keyboard_tests::tab_switches_the_selection_box_to_pick_select`. | +| 2026-11-10 | patch | M10, #2227: the Design panel's section header buttons (Appearance, Typography, Fill, Stroke, Effects) draw their icons at the size of the panel's other 24 pt icon buttons, 16 pt (the icons' native size, as a fill row's eye), not 12 pt; `icon_button_at` goes from 14 to 16 pt with them; the Close and Swap buttons of the assets and prototype panels and the Design panel's Swap orientation and quick-action buttons share the inset. Test: `header_icon_size_tests`. Numbers unchanged. | | 2026-11-05 | patch | M1, #2003: the Design panel's boolean operation menu leads Union, Subtract, Intersect and Exclude with original icons drawn in code (two offset squares, the result filled at reduced alpha). Numbers unchanged. | | 2026-11-02 | minor | M8, #1875: a fill per region. With regions of a vector selected in edit mode (a press inside one with the Move tool, `vector.edit.select {regions}`), the Fill section lists the regions' own fills (the layer's for a region that has none; mixed content when they differ) and its rows and the colour picker edit them: `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` on the edited layer go to the selected regions' stacks (`Region.fills`, what the renderer already draws), the layer's fills and fill style untouched; `regions: [index, ...]` names them on any vector layer (Edit vector layers). Tests: `regions_tests::the_fill_commands_edit_the_selected_regions`. Numbers unchanged. | | 2026-11-05 | patch | M1, #1758: a mouse's side buttons (4 and 5) pan the canvas as the middle button does, the pan ending on release over the canvas or off it; the grab cursor shows while they're held. | | 2026-11-04 | patch | M1, #1852: a press on one of the open gradient's handles or stops on the canvas is the colour picker's own, not a press outside it (Figma keeps the picker and the handles up while a handle or stop is dragged; the stops are made to be dragged: "You can click and drag a stop to change its placement on the gradient", Use gradients as a fill or stroke). The canvas took the press and began the drag, then the picker, drawn later in the same frame, saw a press outside its card and closed, committing the drag's interaction at once; the handles vanished with it and the drag went on without an undo step of its own. Now the picker stays while a gradient handle or stop drags, and the drag is one undo step; a press elsewhere on the canvas still closes it. A handle drag whose button goes up off the canvas (over a panel or the picker) ends there too, instead of waiting, uncommitted, to move the handle to the next press on the canvas. Tests: `colorpicker_selection_tests::dragging_a_gradient_handle_on_the_canvas_keeps_the_picker_open`, `colorpicker_selection_tests::a_gradient_drag_released_off_the_canvas_ends_there`. | | 2026-11-02 | patch | M8, #1875: a click with the Bend tool on a sharp point between two segments gives it handles along the line between its neighbours, a third of the way to each ("Click on a point or path where you want to add a curve", Edit vector layers); a click on a curved point still makes it sharp, a drag still sets the handles by hand, an endpoint is left alone. Between a handle's end and a point both within reach of the pointer, the nearer one on the page is hit (the handle on a tie), so a short path's point (its handles a few pixels long) can be clicked again. Before, only a drag curved a point, and a short one left two tiny handles in its direction. Tests: `vectoredit::tests::short_handles_leave_their_point_clickable`, `vectoredit::tests::a_bend_click_curves_a_sharp_point_between_its_neighbours`, `bend_tool_smooths_and_sharpens_points`. Numbers unchanged. | | 2026-11-02 | minor | M4, #1827: wrap style on a text layer (`WrapStyle`: Auto, Balance, Pretty): Balance re-breaks each paragraph at the narrowest width that keeps its line count (bisection over the greedy breaker, as browsers balance), Pretty narrows one of the last four lines just enough so the last line isn't one word; `text.wrapStyle`, `node.set wrapStyle` (`textWrap` too), inspect `wrapStyle`, Developer Mode CSS `text-wrap` (Tailwind `text-balance` / `text-pretty`), the Type settings control under Vertical trim. Per-paragraph settings, text-style support and the `.fig` import/export mapping stay open. Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented`. | +| 2026-11-07 | minor | M4, #1827: wrap style per paragraph and in text styles, overriding the layer's: `ParaList::wrap` (None follows the layer; Enter carries it, an override equal to the layer's is none), `text.wrapStyle` while editing and `node.set wrapStyle` with `start`/`end` set the paragraphs, without them the layer sets every paragraph; `restyle_breaks` takes a style per paragraph; inspect `lineWrapStyles`, CSS `text-wrap` when the paragraphs agree; `ParagraphStyle::wrap_style` (text styles apply, update and unlink on it); the Wrap style control follows the paragraph; the `.fig` mapping stays open | | 2026-11-02 | patch | M4: Backspace or Delete at the start of a list item takes its marker and keeps its level ("Use Backspace or Delete at the beginning of a list item to delete the counter, but keep the same level of indentation", Create bulleted and numbered lists): a plain paragraph may now carry a list level, and the text layout starts it where that level's item text starts (the gutters stay even when no list is left). Backspace used to drop the level too, and Delete at an item's start deleted the next character. Tab on such a paragraph types a tab, as outside a list. Tests: `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests::a_plain_paragraph_at_a_list_level_starts_where_the_items_text_does` | | 2026-11-02 | patch | M4: max lines on an auto-width text keep it auto width: the box hugs up to that many lines and still grows with its longest line ("Max lines is available only if truncate text is enabled, and: Text resizing is set to auto height or auto width", Explore text properties). `text.maxLines` turned such a text into a fixed truncating box with a stale height, so later typing no longer widened it; fixed-size text still becomes a truncating box, auto-height text hugs as before. Test: `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines` | | 2026-11-02 | patch | M4, #1828: superscript and subscript synthesised where the font has no `sups` / `subs` glyphs (the standard glyph shrunk and shifted by the OS/2 metrics, the usual 0.65 em and 0.35 / 0.14 em offsets without them), and a run mixing available and unavailable glyphs synthesised whole, as Explore text properties says. Tests: `text::tests::superscript_native_or_synthesised_and_never_mixed`, `text_behaviour_tests::superscript_and_subscript_are_synthesised_without_glyphs_for_them`. |