From 6b46a9c81a08a8b8c351d63f6884336168f3c12b Mon Sep 17 00:00:00 2001 From: Salah1St <83543012+Salah1St@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:24:53 +0700 Subject: [PATCH 001/326] M7: FIGCRAFT_WEB_FONTS embeds more craft-fonts families in the web build The web build has no system fonts, so it can only draw text in faces compiled into the wasm, and crates/text/build.rs keeps a fixed set: Inter, Noto Sans Georgian, the Archivo wordmark, and Noto Sans CJK with FIGCRAFT_EMBED_CJK. A distribution for users of another script (Thai, Hebrew, Devanagari, ...) had no supported way to add the face they need, so their text was drawn as missing-glyph boxes. FIGCRAFT_WEB_FONTS names extra manifest families, comma-separated, to embed on wasm32. Unset, nothing changes; the variable is declared with rerun-if-env-changed. docs/releasing.md says how to use it. Co-Authored-By: Claude Opus 5.5 --- crates/text/build.rs | 9 +++++++-- docs/releasing.md | 5 ++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index 05dfc6533..624930002 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -2,6 +2,7 @@ //! opt-in Latin presentation fonts in `fonts/latin-manifest.txt` (Inter, Roboto, …). Unset or missing, //! `CRAFT_FONTS` is empty and the app uses system fonts. Recipe: craft-fonts `docs/integration.md`. //! Noto Sans CJK only with `FIGCRAFT_EMBED_CJK` set (the web build's only way to show CJK UI text). +//! `FIGCRAFT_WEB_FONTS` (comma-separated families) adds manifest families to the web build. use std::fmt::Write as _; use std::path::PathBuf; @@ -9,6 +10,7 @@ fn main() { println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR"); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_CJK"); + println!("cargo::rerun-if-env-changed=FIGCRAFT_WEB_FONTS"); let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n"); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from) { let mut ok = false; @@ -54,6 +56,8 @@ fn craft_fonts(dir: &std::path::Path, manifest_rel: &str) -> Result = line.split(" | ").map(str::trim).collect(); @@ -66,9 +70,10 @@ fn craft_fonts(dir: &std::path::Path, manifest_rel: &str) -> Result.txt` +Noto Sans Georgian and the Archivo SemiBold wordmark, when the pin has them. A distribution +whose users write another script names the manifest families it needs, comma-separated, in +`FIGCRAFT_WEB_FONTS` (`FIGCRAFT_WEB_FONTS="Noto Sans Thai" trunk build --release`); each adds +its size to the wasm, which must stay under the 24 MiB gate. Packages carry each embedded font's licence as `OFL-.txt` (`copy_font_licences` in `packaging/env.sh`; `Contents/Resources/Licenses` in the macOS app). ### macOS From a7bb249813bcbbbc3c8991c64da59f8556578dae Mon Sep 17 00:00:00 2001 From: Salah1St <83543012+Salah1St@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:47:16 +0700 Subject: [PATCH 002/326] M7: warn when a FIGCRAFT_WEB_FONTS family isn't embedded A misspelt family name (or a CJK one without FIGCRAFT_EMBED_CJK) used to embed nothing without a word, and the web build then drew that script as missing-glyph boxes. With craft-fonts present, each named family that no manifest entry embedded now gets a cargo warning. Co-Authored-By: Claude Opus 5.5 --- crates/text/build.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/text/build.rs b/crates/text/build.rs index 624930002..2f5017563 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -29,6 +29,12 @@ fn main() { if !ok { println!("cargo::warning=building without craft-fonts (once it is there, `cargo clean -p figcraft-text` makes the next build use it)"); } + // A family named in FIGCRAFT_WEB_FONTS that nothing embedded is most likely misspelt. + for name in std::env::var("FIGCRAFT_WEB_FONTS").unwrap_or_default().split(',').map(str::trim).filter(|n| ok && !n.is_empty()) { + if !src.contains(&format!("family: {name:?},")) { + println!("cargo::warning=FIGCRAFT_WEB_FONTS: no craft-fonts manifest family {name:?} was embedded"); + } + } } src.push_str("];\n"); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs"); From b278d8f541688475393d907e31fac2cd6792a046 Mon Sep 17 00:00:00 2001 From: Salah1St <83543012+Salah1St@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:58:25 +0700 Subject: [PATCH 003/326] M7: the FIGCRAFT_WEB_FONTS example needs a craft-fonts checkout with the family Review: the release pin has no Noto Sans Thai yet, so the example built against it only warns. The docs now say to build with a craft-fonts checkout that has the families named, and that a family the build doesn't embed gets a warning. Co-Authored-By: Claude Opus 5.5 --- docs/releasing.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/releasing.md b/docs/releasing.md index 0631dedfe..079319457 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -107,8 +107,10 @@ Noto Sans Georgian (craft-fonts' main has it but no Latin manifest), so desktop installed font; re-pin when one commit has both (craft-fonts#42). The web build embeds only Inter, Noto Sans Georgian and the Archivo SemiBold wordmark, when the pin has them. A distribution whose users write another script names the manifest families it needs, comma-separated, in -`FIGCRAFT_WEB_FONTS` (`FIGCRAFT_WEB_FONTS="Noto Sans Thai" trunk build --release`); each adds -its size to the wasm, which must stay under the 24 MiB gate. Packages carry each embedded font's licence as `OFL-.txt` +`FIGCRAFT_WEB_FONTS`, building with a craft-fonts checkout that has them (Noto Sans Thai is on +craft-fonts' main, not yet in the release pin): `FIGCRAFT_WEB_FONTS="Noto Sans Thai" trunk build +--release`. A named family the build doesn't embed gets a warning. Each one adds its size to the +wasm, which must stay under the 24 MiB gate. Packages carry each embedded font's licence as `OFL-.txt` (`copy_font_licences` in `packaging/env.sh`; `Contents/Resources/Licenses` in the macOS app). ### macOS From 031714fa95da0a0bc9554a88d6e2f405a73ee165 Mon Sep 17 00:00:00 2001 From: Salah1St <83543012+Salah1St@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:08:53 +0700 Subject: [PATCH 004/326] M7: the FIGCRAFT_WEB_FONTS warning also covers builds without craft-fonts Review: with no craft-fonts the check was skipped, so a named family went missing without a family-specific word. Every named family that nothing embedded now gets a warning that says why: no craft-fonts in the build, or no manifest entry embedded for it (misspelt, or CJK without FIGCRAFT_EMBED_CJK). Co-Authored-By: Claude Opus 5.5 --- crates/text/build.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index 2f5017563..32b8089c0 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -12,8 +12,8 @@ fn main() { println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_CJK"); println!("cargo::rerun-if-env-changed=FIGCRAFT_WEB_FONTS"); let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n"); + let mut ok = false; if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from) { - let mut ok = false; for manifest in ["fonts/latin-manifest.txt", "fonts/manifest.txt"] { match craft_fonts(&dir, manifest) { Ok(entries) => { @@ -29,11 +29,17 @@ fn main() { if !ok { println!("cargo::warning=building without craft-fonts (once it is there, `cargo clean -p figcraft-text` makes the next build use it)"); } - // A family named in FIGCRAFT_WEB_FONTS that nothing embedded is most likely misspelt. - for name in std::env::var("FIGCRAFT_WEB_FONTS").unwrap_or_default().split(',').map(str::trim).filter(|n| ok && !n.is_empty()) { - if !src.contains(&format!("family: {name:?},")) { - println!("cargo::warning=FIGCRAFT_WEB_FONTS: no craft-fonts manifest family {name:?} was embedded"); - } + } + // Say which families named in FIGCRAFT_WEB_FONTS nothing embedded: with craft-fonts there the + // name is most likely misspelt. + for name in std::env::var("FIGCRAFT_WEB_FONTS").unwrap_or_default().split(',').map(str::trim).filter(|n| !n.is_empty()) { + if !src.contains(&format!("family: {name:?},")) { + let why = if ok { + "no craft-fonts manifest entry was embedded for it (misspelt? CJK also needs FIGCRAFT_EMBED_CJK)" + } else { + "this build has no craft-fonts" + }; + println!("cargo::warning=FIGCRAFT_WEB_FONTS: {name:?} isn't embedded: {why}"); } } src.push_str("];\n"); From 0b34cf335bc777f270b893e8f6ce5e850214803d Mon Sep 17 00:00:00 2001 From: Salah1St <83543012+Salah1St@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:50:12 +0700 Subject: [PATCH 005/326] M7: the web size gate is 24.5 MiB Review: packaging/web/package.sh caps the wasm at 25 MiB - 512 KiB since 0.12.1, not 24 MiB. Co-Authored-By: Claude Opus 5.5 --- docs/releasing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/releasing.md b/docs/releasing.md index 03d42adfc..2c7f970af 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -127,7 +127,7 @@ allowlist: Inter, Noto Sans Georgian and Archivo SemiBold when supplied. A distr users write another script adds the manifest families it needs, comma-separated, with `FIGCRAFT_WEB_FONTS` (`FIGCRAFT_WEB_FONTS="Noto Sans Thai" trunk build --release`); a named family the build doesn't embed gets a warning, and each one adds its size to the wasm, which must stay -under the 24 MiB gate. Packages carry each embedded font's licence as `OFL-.txt` +under the 24.5 MiB gate in `packaging/web/package.sh`. Packages carry each embedded font's licence as `OFL-.txt` (`copy_font_licences` in `packaging/env.sh`; `Contents/Resources/Licenses` in the macOS app). ### macOS From 84d9391ba457429a3833333f25c57aea8d6d6f29 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Fri, 30 Oct 2026 11:18:05 +0100 Subject: [PATCH 006/326] M8: align sidebar action icons --- crates/ui-egui/src/icons.rs | 2 ++ crates/ui-egui/src/icons/draw.rs | 19 +++++++++++++++++-- crates/ui-egui/src/panels/selection_colors.rs | 2 +- docs/ui-parity.md | 5 +++-- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index f8480127f..00542babd 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -29,6 +29,8 @@ pub use draw::{paint, paint_outlines}; icons! { Move, + /// Select layers using a colour: selection corners around a colour swatch. + SelectColor, Scale, FitContents, Hand, diff --git a/crates/ui-egui/src/icons/draw.rs b/crates/ui-egui/src/icons/draw.rs index 1d3925507..3c471ea85 100644 --- a/crates/ui-egui/src/icons/draw.rs +++ b/crates/ui-egui/src/icons/draw.rs @@ -280,6 +280,13 @@ fn draw(p: &P, icon: Icon) { use Icon::*; match icon { Move => p.fill(&[(4.0, 2.0), (4.0, 13.6), (6.9, 10.9), (8.8, 14.8), (10.6, 14.0), (8.7, 10.2), (12.6, 10.2)]), + SelectColor => { + p.poly(&[(2.5, 5.5), (2.5, 2.5), (5.5, 2.5)], false); + p.poly(&[(10.5, 2.5), (13.5, 2.5), (13.5, 5.5)], false); + p.poly(&[(2.5, 10.5), (2.5, 13.5), (5.5, 13.5)], false); + p.poly(&[(10.5, 13.5), (13.5, 13.5), (13.5, 10.5)], false); + p.circle(8.0, 8.0, 2.5); + } Scale => { p.rect(2.5, 7.5, 8.5, 13.5, 0.0); p.line(6.0, 10.0, 13.0, 3.0); @@ -387,8 +394,16 @@ fn draw(p: &P, icon: Icon) { ChevronRight => p.poly(&[(6.0, 4.5), (9.5, 8.0), (6.0, 11.5)], false), ChevronLeft => p.poly(&[(10.0, 4.5), (6.5, 8.0), (10.0, 11.5)], false), Plus => { - p.line(7.5, 2.0, 7.5, 13.0); - p.line(2.0, 7.5, 13.0, 7.5); + // Snap the shared centre once, then give every arm the same pixel length. + // Snapping each line's ends separately can offset its midpoint at small sizes. + let c = p.sp(8.0, 8.0); + let half = p.stroke.width / 2.0; + let reach = (5.0 * p.s / p.px).round() * p.px + half; + let mut mesh = Mesh::default(); + mesh.add_colored_rect(Rect::from_min_max(c - vec2(reach, half), c + vec2(reach, half)), p.color); + mesh.add_colored_rect(Rect::from_min_max(c - vec2(half, reach), c + vec2(half, -half)), p.color); + mesh.add_colored_rect(Rect::from_min_max(c + vec2(-half, half), c + vec2(half, reach)), p.color); + p.painter.add(Shape::mesh(mesh)); } Minus => p.line(2.0, 7.5, 13.0, 7.5), Eye | EyeOff => { diff --git a/crates/ui-egui/src/panels/selection_colors.rs b/crates/ui-egui/src/panels/selection_colors.rs index 9d7a058c2..bb4fe3d45 100644 --- a/crates/ui-egui/src/panels/selection_colors.rs +++ b/crates/ui-egui/src/panels/selection_colors.rs @@ -158,7 +158,7 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId } }); } - if icons::button(ui, Icon::Move, 24.0, false, tr("Select layers with this color")).clicked() { + if icons::button(ui, Icon::SelectColor, 24.0, false, tr("Select layers with this color")).clicked() { app.run("selection.selectColor", json!({"targets": group.targets})); } }); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9152466ee..f57b695b5 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-10-30 · **Change:** minor (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; 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; 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; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; 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) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Selection colors uses an original outlined selection icon for selecting layers using a colour; the Plus icon’s bars share one snapped centre and equal arms at every size. 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; 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; 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; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; 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) · **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: @@ -73,7 +73,7 @@ interaction feel not yet compared. | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | 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). No reorder rings for swapping layers; 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 | An outlined selection icon selects layers using the colour. 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) | | 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 @@ -175,6 +175,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | M8: Selection colors uses an original outlined selection icon for selecting layers using a colour; the Plus icon’s bars share one snapped centre and equal arms at every size. Readiness estimates unchanged. | | 2026-10-30 | minor | Pen into vector edit mode (#1430): Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on; Escape keeps the pen. Numbers unchanged. | | 2026-10-30 | minor | M8, #1574: the Actions palette (Ctrl+K) offered engine commands that need parameters it can't give, such as `image.place` ("Place image", needing the image's `data` or `path`), which failed with "Invalid parameters" and sat above the menu's Place image… row with the same label. A search now leaves out a command no menu lists when its params doc names a parameter without `?` (`figcraft_engine::cmd::needs_params`), and a row no menu item gives whose label reads like a menu item's (any case, without the ellipsis). Place image runs File ▸ Place image…, which opens the file dialog. Tests: `palette_tests.rs` (no row needs parameters unless a menu item runs it, no duplicate label across several searches), `unknown_params_tests.rs`. | | 2026-10-30 | minor | Preferences ▸ Scroll wheel zoom (#1390): a mouse wheel zooms about the pointer and Cmd/Ctrl+wheel scrolls; Shift+wheel, trackpads and pinches unchanged. Numbers unchanged. | From 967917dbbda7f3eebb28e23d5c14576c0674abc7 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Fri, 30 Oct 2026 11:18:56 +0100 Subject: [PATCH 007/326] M8: share paint input with Selection colors --- crates/ui-egui/src/field_tests.rs | 28 +- crates/ui-egui/src/panels/right/paints.rs | 118 ++++---- crates/ui-egui/src/panels/selection_colors.rs | 253 ++++++++++++------ crates/ui-egui/src/widgets.rs | 27 ++ docs/ui-parity.md | 5 +- 5 files changed, 283 insertions(+), 148 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index e1d17c271..6168ca5b9 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -187,13 +187,18 @@ fn setup() -> (Ui, NodeId, NodeId) { (u, a, b) } -/// The field named `name` in the Design panel: the middle of its value, and what it shows. +/// 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) { u.frame(vec![]); let out = u.frame_output(vec![]); let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; - let n = - nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::SpinButton && n.label() == Some(name)).unwrap_or_else(|| panic!("no field {name:?}")); + let n = nodes + .iter() + .map(|(_, n)| n) + .filter(|n| n.role() == Role::SpinButton && n.label() == Some(name)) + .min_by(|a, b| a.bounds().map_or(f64::INFINITY, |r| r.y0).total_cmp(&b.bounds().map_or(f64::INFINITY, |r| r.y0))) + .unwrap_or_else(|| panic!("no field {name:?}")); let b = n.bounds().expect("bounds"); (pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32), n.value().unwrap_or_default().to_string()) } @@ -203,11 +208,26 @@ fn label(u: &mut Ui, name: &str) -> Pos2 { u.frame(vec![]); let out = u.frame_output(vec![]); let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; - let n = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::SpinButton && n.label() == Some(name)).unwrap(); + let n = nodes + .iter() + .map(|(_, n)| n) + .filter(|n| n.role() == Role::SpinButton && n.label() == Some(name)) + .min_by(|a, b| a.bounds().map_or(f64::INFINITY, |r| r.y0).total_cmp(&b.bounds().map_or(f64::INFINITY, |r| r.y0))) + .unwrap(); let b = n.bounds().unwrap(); pos2(b.x0 as f32 - 12.0, ((b.y0 + b.y1) / 2.0) as f32) } +/// Layer and fill opacity are both named for assistive technology, even without a visible lead. +#[test] +fn paint_opacity_has_an_accessible_name() { + let (mut u, _, _) = setup(); + let output = u.frame_output(vec![]); + let nodes = output.platform_output.accesskit_update.unwrap().nodes; + let opacity_fields = nodes.iter().filter(|(_, n)| n.role() == Role::SpinButton && n.label() == Some("Opacity")).count(); + assert_eq!(opacity_fields, 2, "both layer and fill opacity must have an accessible name"); +} + fn geom(u: &Ui, n: NodeId) -> (f64, f64, f64, f64) { let doc = u.app.session.doc().unwrap(); let b = doc.world_bounds(n).unwrap(); diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 11b368d1a..6f9e090ff 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -446,78 +446,62 @@ fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint, let cmd = if fills { "fill.set" } else { "stroke.set" }; let r = row_rect(ui, 32.0, |ui| { let w = ui.available_width() - 60.0; - let (r, _) = ui.allocate_exact_size(vec2(w, FIELD_H), Sense::hover()); - ui.painter().rect_filled(r, CornerRadius::same(5), t.field); - let sw = Rect::from_min_size(pos2(r.min.x + 4.0, r.center().y - 8.0), vec2(16.0, 16.0)); - widgets::paint_swatch(ui.painter(), sw, p); - let sresp = ui.interact(sw.expand(2.0), Id::unique(("swatch", fills, i)), Sense::click()); - app.picker_control(crate::colorpicker::PickerTarget::Paint { fills, index: i, ids: ids.clone() }, &sresp); - let text_r = Rect::from_min_max(pos2(sw.max.x + 8.0, r.min.y), pos2(r.max.x - 52.0, r.max.y)); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(text_r)); - // The variable bound to this paint's colour (its key on the layers: `fill` or `fills//color`). - let bound = app.session.doc().ok().and_then(|d| { - let key = ids.first().and_then(|id| d.node(*id)).and_then(|n| figcraft_engine::cmd::lists::paint_binding_key(n, fills, i))?; - Some((key.to_string(), crate::variable_ui::bound_name(d, &ids, key)?)) - }); - match &p.kind { - PaintKind::Solid { .. } if bound.is_some() => { - let (key, name) = bound.clone().unwrap_or_default(); - let chip = Rect::from_min_max(pos2(text_r.min.x - 2.0, r.min.y + 3.0), pos2(text_r.max.x - 20.0, r.max.y - 3.0)); - child.painter().rect_filled(chip, CornerRadius::same(4), t.hover); - child.painter().rect_stroke(chip, CornerRadius::same(4), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - let short = name.rsplit('/').next().unwrap_or(&name).to_string(); - child.painter().with_clip_rect(chip.shrink2(vec2(5.0, 0.0))).text( - pos2(chip.min.x + 5.0, r.center().y), - Align2::LEFT_CENTER, - short, - regular(11.0), - t.text, - ); - let _ = ui.interact(chip, Id::unique(("bound_paint", fills, i)), Sense::hover()).on_hover_text(&name); - let dr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0)); - let dresp = ui.interact(dr, Id::unique(("detach_paint", fills, i)), Sense::click()).tip(tr("Detach variable")); - icons::paint(ui.painter(), dr.shrink(3.0), Icon::Detach, t.icon_secondary); - if dresp.clicked() { - app.run("variable.bind", json!({"ids": ids, "field": key, "variable": null})); + 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(); + // The variable bound to this paint's colour (its key on the layers: `fill` or `fills//color`). + let bound = app.session.doc().ok().and_then(|d| { + let key = ids.first().and_then(|id| d.node(*id)).and_then(|n| figcraft_engine::cmd::lists::paint_binding_key(n, fills, i))?; + Some((key.to_string(), crate::variable_ui::bound_name(d, &ids, key)?)) + }); + match &p.kind { + PaintKind::Solid { .. } if bound.is_some() => { + let (key, name) = bound.clone().unwrap_or_default(); + let chip = Rect::from_min_max(pos2(text_r.min.x - 2.0, r.min.y + 3.0), pos2(text_r.max.x - 20.0, r.max.y - 3.0)); + child.painter().rect_filled(chip, CornerRadius::same(4), t.hover); + child.painter().rect_stroke(chip, CornerRadius::same(4), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + let short = name.rsplit('/').next().unwrap_or(&name).to_string(); + child.painter().with_clip_rect(chip.shrink2(vec2(5.0, 0.0))).text( + pos2(chip.min.x + 5.0, r.center().y), + Align2::LEFT_CENTER, + short, + regular(11.0), + t.text, + ); + let _ = child.interact(chip, Id::unique(("bound_paint", fills, i)), Sense::hover()).on_hover_text(&name); + let dr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0)); + let dresp = child.interact(dr, Id::unique(("detach_paint", fills, i)), Sense::click()).tip(tr("Detach variable")); + icons::paint(child.painter(), dr.shrink(3.0), Icon::Detach, t.icon_secondary); + if dresp.clicked() { + app.run("variable.bind", json!({"ids": ids, "field": key, "variable": null})); + } } - } - PaintKind::Solid { color } => { - if let Some(h) = widgets::text_field_inline( - &mut child, - Id::unique(("hex", fills, i)), - &color.to_hex(), - text_r.shrink2(vec2(0.0, 4.0)), - regular(11.0), - ) && let Some(c) = figcraft_color::Color::from_hex_or_name(&h) - { - app.run(cmd, json!({"ids": ids, "index": i, "color": c.to_css_hex()})); + PaintKind::Solid { color } => { + if let Some(h) = widgets::text_field_inline( + child, + Id::unique(("hex", fills, i)), + &color.to_hex(), + text_r.shrink2(vec2(0.0, 4.0)), + regular(11.0), + ) && let Some(c) = figcraft_color::Color::from_hex_or_name(&h) + { + app.run(cmd, json!({"ids": ids, "index": i, "color": c.to_css_hex()})); + } } - } - _ => { - child.painter().text(pos2(text_r.min.x, r.center().y), Align2::LEFT_CENTER, paint_label(p), regular(11.0), t.text); - // One layer's image fill: crop it on the canvas. - if fills && ids.len() == 1 && matches!(p.kind, PaintKind::Image(_)) { - let cr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0)); - let cresp = ui.interact(cr, Id::unique(("crop_image", i)), Sense::click()).tip(tr("Crop image")); - icons::paint(ui.painter(), cr.shrink(3.0), Icon::Crop, if cresp.hovered() { t.icon } else { t.icon_secondary }); - if cresp.clicked() { - app.run("image.crop", json!({"ids": ids, "index": i})); + _ => { + child.painter().text(pos2(text_r.min.x, r.center().y), Align2::LEFT_CENTER, paint_label(p), regular(11.0), t.text); + // One layer's image fill: crop it on the canvas. + if fills && ids.len() == 1 && matches!(p.kind, PaintKind::Image(_)) { + let cr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0)); + let cresp = child.interact(cr, Id::unique(("crop_image", i)), Sense::click()).tip(tr("Crop image")); + icons::paint(child.painter(), cr.shrink(3.0), Icon::Crop, if cresp.hovered() { t.icon } else { t.icon_secondary }); + if cresp.clicked() { + app.run("image.crop", json!({"ids": ids, "index": i})); + } } } } - } - let op_r = Rect::from_min_max(pos2(r.max.x - 48.0, r.min.y), r.max); - ui.painter().line_segment([pos2(op_r.min.x, r.min.y + 4.0), pos2(op_r.min.x, r.max.y - 4.0)], Stroke::new(1.0, t.panel)); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_r)); - let e = widgets::number_field( - &mut child, - Id::unique(("pop", fills, i)), - Lead::None, - Some((f64::from(p.opacity) * 100.0).round()), - "%", - 48.0, - 1.0, - ); + }); + app.picker_control(crate::colorpicker::PickerTarget::Paint { fills, index: i, ids: ids.clone() }, &sresp); match e { Some(FieldEdit::Set(v)) => { app.run(cmd, json!({"ids": ids, "index": i, "opacity": (v / 100.0).clamp(0.0, 1.0)})); diff --git a/crates/ui-egui/src/panels/selection_colors.rs b/crates/ui-egui/src/panels/selection_colors.rs index bb4fe3d45..f2019ee86 100644 --- a/crates/ui-egui/src/panels/selection_colors.rs +++ b/crates/ui-egui/src/panels/selection_colors.rs @@ -24,6 +24,12 @@ struct Cache { colors: Arc>, } +#[derive(Clone)] +struct OpacityScrub { + targets: Vec, + opacity: f32, +} + /// Return the cached selection colours when the document and selection match. During an /// interaction reuse an existing matching cache, or return an empty list without discovering /// colours; otherwise discover and cache them. @@ -47,6 +53,7 @@ fn colors(ui: &Ui, document: u64, doc: &Arc, ids: &[NodeId], interacti colors } +/// Open or close the picker for frozen paint targets, anchored to the invoking control. pub(crate) fn toggle(app: &mut FigApp, targets: Vec, response: Option<&egui::Response>) { let Ok(ds) = app.session.ds() else { return }; let target = PickerTarget::SelectionColor { targets, selection: ds.selection.clone(), document: ds.uid }; @@ -70,97 +77,147 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId let t = Tokens::get(ui.ctx()); widgets::section_header(ui, tr("Selection colors"), &[], false); // Bound the panel's height; a document with many distinct colors stays scrollable. - ui.add_enabled_ui(!interacting, |ui| { + let scrub_key = Id::unique("selection_color_scrub"); + if !interacting { + ui.data_mut(|d| d.remove::(scrub_key)); + } + let scrubbing = ui.data(|d| d.get_temp::(scrub_key)); + ui.add_enabled_ui(!interacting || scrubbing.is_some(), |ui| { egui::ScrollArea::vertical().id_salt("selection_colors_rows").max_height(240.0).show_rows(ui, 32.0, colors.len(), |ui, range| { for group in &colors[range] { ui.push_id((&group.targets, "selection_color"), |ui| { crate::right::row(ui, 32.0, |ui| { - let swatch = widgets::swatch(ui, &group.paint, 24.0).tip(tr("Edit colour")); - toggle(app, group.targets.clone(), Some(&swatch)); - let width = (ui.available_width() - 116.0).max(40.0); let linked_name = group .style .as_ref() .and_then(|id| doc.style(id).map(|s| s.name.as_str())) .or_else(|| group.variable.as_ref().and_then(|id| doc.variables.get(id).map(|v| v.name.as_str()))); - if let Some(name) = linked_name { - let response = widgets::dropdown(ui, name, width, None); - toggle(app, group.targets.clone(), Some(&response)); - } else if let Some(color) = group.paint.solid_color() { - if let Some(hex) = widgets::text_field_named(ui, ui.scope_id().with("hex"), &color.to_hex(), width, tr("Color")) { - if let Some(color) = Color::from_hex(&hex) { - let mut paint = group.paint.clone(); - paint.kind = figcraft_color::PaintKind::Solid { color: color.with_alpha(1.0) }; - if color.a < 1.0 { - paint.opacity = color.a; - } - app.run("selection.setPaint", json!({"targets": group.targets, "paint": paint})); - } else { - app.toast(tr("Invalid color")); - } - } - } else { - let response = widgets::dropdown(ui, &widgets::paint_name(&group.paint), width, None); - toggle(app, group.targets.clone(), Some(&response)); - } - let alpha = format!("{}%", figcraft_doc::trim_num(f64::from(group.paint.opacity) * 100.0)); - if let Some(value) = widgets::text_field_named(ui, ui.scope_id().with("opacity"), &alpha, 44.0, tr("Opacity")) - && let Ok(value) = value.trim().trim_end_matches('%').parse::() - && value.is_finite() + let width = ui.available_width() - 60.0; + let mut paint = group.paint.clone(); + if let Some(scrub) = &scrubbing + && scrub.targets == group.targets { - let mut paint = group.paint.clone(); - paint.opacity = (value / 100.0).clamp(0.0, 1.0); - app.run("selection.setPaint", json!({"targets": group.targets, "paint": paint})); + paint.opacity = scrub.opacity; } - if linked_name.is_some() { - let detach = if group.style.is_some() { tr("Detach style") } else { tr("Detach variable") }; - if icons::button(ui, Icon::Detach, 24.0, false, detach).clicked() { - app.run("selection.detachColor", json!({"targets": group.targets})); - } - } else { - let styles = icons::button(ui, Icon::Styles, 24.0, false, tr("Color styles")); - crate::right::menu_popup(&styles).show(|ui| { - let mut any = false; - for style in &doc.styles { - if !matches!(style.kind, StyleKind::Paint { .. }) { - continue; - } - any = true; - if crate::right::menu_item(ui, &style.name, "") { - app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id})); - app.ui.picker = None; - ui.close(); + let mut name_response = None; + let (swatch, opacity) = widgets::paint_field( + ui, + ui.scope_id().with("paint_field"), + ui.scope_id().with("opacity"), + &paint, + width, + |child, rect| { + if linked_name.is_some() || group.paint.solid_color().is_none() { + let name = linked_name.map(str::to_owned).unwrap_or_else(|| widgets::paint_name(&group.paint)); + child.painter().with_clip_rect(rect).text( + rect.left_center(), + egui::Align2::LEFT_CENTER, + &name, + crate::theme::regular(11.0), + t.text, + ); + name_response = Some(child.interact(rect, child.scope_id().with("paint_name"), egui::Sense::click()).tip(name)); + } else if let Some(color) = group.paint.solid_color() + && let Some(hex) = widgets::text_field_inline( + child, + child.scope_id().with("hex"), + &color.to_hex(), + rect.shrink2(egui::vec2(0.0, 4.0)), + crate::theme::regular(11.0), + ) + { + if let Some(color) = Color::from_hex_or_name(&hex) { + let mut paint = group.paint.clone(); + paint.kind = figcraft_color::PaintKind::Solid { color: color.with_alpha(1.0) }; + if color.a < 1.0 { + paint.opacity = color.a; + } + app.run("selection.setPaint", json!({"targets": group.targets, "paint": paint})); + } else { + app.toast(tr("Invalid color")); } } - if !any { - widgets::label(ui, tr("No color styles"), t.text_secondary); - } - let variables: Vec<_> = doc - .variables - .variables - .iter() - .filter(|v| { - v.kind == VariableType::Color - && bind_refusal(doc, &group.targets, &v.id).is_none() - && in_scope(doc, &group.targets, &v.id) - }) - .collect(); - if !variables.is_empty() { - ui.separator(); - widgets::label(ui, tr("Color variables"), t.text_secondary); - } - for v in variables { - if crate::right::menu_item(ui, &v.name, "") { - app.run("selection.bindColorVariable", json!({"targets": group.targets, "variable": v.id})); - app.ui.picker = None; - ui.close(); - } + }, + ); + toggle(app, group.targets.clone(), Some(&swatch)); + if let Some(response) = name_response { + toggle(app, group.targets.clone(), Some(&response)); + } + if let Some(edit) = opacity { + let (value, scrub, done) = match edit { + widgets::FieldEdit::Set(value) => (value, false, false), + widgets::FieldEdit::Scrub(value, done) => (value, true, done), + }; + let mut paint = group.paint.clone(); + paint.opacity = (value / 100.0).clamp(0.0, 1.0) as f32; + ui.data_mut(|d| { + if scrub && !done { + d.insert_temp(scrub_key, OpacityScrub { targets: group.targets.clone(), opacity: paint.opacity }); + } else { + d.remove::(scrub_key); } }); + if scrub { + let _ = app.session.begin_interaction("Opacity"); + let _ = app.session.execute("selection.setPaint", &json!({"targets": group.targets, "paint": paint})); + if done { + let _ = app.session.commit_interaction(); + } + } else { + app.run("selection.setPaint", json!({"targets": group.targets, "paint": paint})); + } } - if icons::button(ui, Icon::SelectColor, 24.0, false, tr("Select layers with this color")).clicked() { - app.run("selection.selectColor", json!({"targets": group.targets})); - } + widgets::tight_end(ui, |ui| { + if linked_name.is_some() { + let detach = if group.style.is_some() { tr("Detach style") } else { tr("Detach variable") }; + if icons::button(ui, Icon::Detach, 24.0, false, detach).clicked() { + app.run("selection.detachColor", json!({"targets": group.targets})); + } + } else { + let styles = icons::button(ui, Icon::Styles, 24.0, false, tr("Color styles")); + crate::right::menu_popup(&styles).show(|ui| { + let mut any = false; + for style in &doc.styles { + if !matches!(style.kind, StyleKind::Paint { .. }) { + continue; + } + any = true; + if crate::right::menu_item(ui, &style.name, "") { + app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id})); + app.ui.picker = None; + ui.close(); + } + } + if !any { + widgets::label(ui, tr("No color styles"), t.text_secondary); + } + let variables: Vec<_> = doc + .variables + .variables + .iter() + .filter(|v| { + v.kind == VariableType::Color + && bind_refusal(doc, &group.targets, &v.id).is_none() + && in_scope(doc, &group.targets, &v.id) + }) + .collect(); + if !variables.is_empty() { + ui.separator(); + widgets::label(ui, tr("Color variables"), t.text_secondary); + } + for v in variables { + if crate::right::menu_item(ui, &v.name, "") { + app.run("selection.bindColorVariable", json!({"targets": group.targets, "variable": v.id})); + app.ui.picker = None; + ui.close(); + } + } + }); + } + if icons::button(ui, Icon::SelectColor, 24.0, false, tr("Select layers with this color")).clicked() { + app.run("selection.selectColor", json!({"targets": group.targets})); + } + }); }); }); } @@ -300,6 +357,52 @@ mod tests { assert!(p.app.ui.last_error.is_none()); } + #[test] + fn shared_color_field_edits_hex_and_opacity_and_undoes_each_edit() { + let (mut p, a, _) = Panel::new(); + let red = p.frame(vec![]).into_iter().find(|(s, _)| s == "FF0000").unwrap().1; + p.click(red); + p.frame(vec![Event::Text("00FF00".into())]); + let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + p.frame(vec![enter.clone()]); + assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].solid_color().unwrap().to_hex(), "00FF00"); + p.frame(vec![]); + p.click(Pos2::new(176.0, red.y)); + p.frame(vec![Event::Text("45".into())]); + p.frame(vec![enter]); + assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity, 0.45); + p.app.run("edit.undo", json!({})); + assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity, 1.0); + p.app.run("edit.undo", json!({})); + assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].solid_color().unwrap().to_hex(), "FF0000"); + } + + #[test] + fn shared_opacity_field_keeps_dragging_until_release_as_one_undo_step() { + let (mut p, a, _) = Panel::new(); + let red = p.frame(vec![]).into_iter().find(|(s, _)| s == "FF0000").unwrap().1; + let start = Pos2::new(167.0, red.y); + p.frame(vec![ + Event::PointerMoved(start), + Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + ]); + for dx in [-10.0, -20.0, -30.0] { + p.frame(vec![Event::PointerMoved(start + vec2(dx, 0.0))]); + } + assert!(p.frame(vec![]).iter().any(|(text, _)| text == "70%"), "the live opacity stays visible while scrubbing"); + p.frame(vec![Event::PointerButton { + pos: start - vec2(30.0, 0.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: Default::default(), + }]); + assert!(p.app.session.ds().unwrap().interaction.is_none()); + assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity, 0.7); + p.app.run("edit.undo", json!({})); + assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity, 1.0); + assert_eq!(p.app.session.selection().len(), 2); + } + #[test] fn panel_displays_the_linked_style_name_and_the_other_color() { let (mut p, a, b) = Panel::new(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b6b4b7e88..ee6349b95 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1016,6 +1016,33 @@ pub fn checker(painter: &egui::Painter, rect: Rect, cell: f32) { } } +/// Shared Fill/Stroke/Selection colors 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( + ui: &mut Ui, + id: Id, + opacity_id: Id, + paint: &figcraft_color::Paint, + width: f32, + content: impl FnOnce(&mut Ui, Rect), +) -> (Response, Option) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(width, FIELD_H), Sense::hover()); + ui.painter().rect_filled(r, CornerRadius::same(5), t.field); + let sw = Rect::from_min_size(pos2(r.min.x + 4.0, r.center().y - 8.0), vec2(16.0, 16.0)); + paint_swatch(ui.painter(), sw, paint); + let swatch = ui.interact(sw.expand(2.0), id, Sense::click()).tip(tr("Edit colour")); + let text_r = Rect::from_min_max(pos2(sw.max.x + 8.0, r.min.y), pos2(r.max.x - 52.0, r.max.y)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(text_r)); + content(&mut child, text_r); + let op_r = Rect::from_min_max(pos2(r.max.x - 48.0, r.min.y), r.max); + ui.painter().line_segment([pos2(op_r.min.x, r.min.y + 4.0), pos2(op_r.min.x, r.max.y - 4.0)], Stroke::new(1.0, t.panel)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_r)); + let opacity = number_field(&mut child, opacity_id, Lead::Named(tr("Opacity")), Some((f64::from(paint.opacity) * 100.0).round()), "%", 48.0, 1.0); + (swatch, opacity) +} + /// A paint swatch (with checkerboard under transparent colours). pub fn swatch(ui: &mut Ui, paint: &figcraft_color::Paint, size: f32) -> Response { swatch_named(ui, paint, size, tr("Color")) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f57b695b5..fb0548e1c 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-10-30 · **Change:** minor (Selection colors uses an original outlined selection icon for selecting layers using a colour; the Plus icon’s bars share one snapped centre and equal arms at every size. 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; 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; 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; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; 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) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Selection colors shares Fill and Stroke’s swatch/colour/opacity control, including live opacity scrubbing with one undo step. Selection colors uses an original outlined selection icon for selecting layers using a colour; the Plus icon’s bars share one snapped centre and equal arms at every size; 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; 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; 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; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; 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) · **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: @@ -73,7 +73,7 @@ interaction feel not yet compared. | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | 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). No reorder rings for swapping layers; checked by its author on macOS and in the app on Windows (#402) | -| Selection colors | partial | An outlined selection icon selects layers using the colour. 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 | 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); each row shares Fill and Stroke’s colour control, and an outlined selection icon selects the layers that use its colour. Editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a colour style or colour variable of the document, and a row linked to a style or variable detaches it, keeping the colour (`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) | | 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 @@ -175,6 +175,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | M8: Selection colors shares Fill and Stroke’s swatch/colour/opacity control, including live opacity scrubbing with one undo step. Verified in light and dark themes; colour edits, opacity scrubbing and undo covered by panel tests. Readiness estimates unchanged. | | 2026-10-30 | minor | M8: Selection colors uses an original outlined selection icon for selecting layers using a colour; the Plus icon’s bars share one snapped centre and equal arms at every size. Readiness estimates unchanged. | | 2026-10-30 | minor | Pen into vector edit mode (#1430): Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on; Escape keeps the pen. Numbers unchanged. | | 2026-10-30 | minor | M8, #1574: the Actions palette (Ctrl+K) offered engine commands that need parameters it can't give, such as `image.place` ("Place image", needing the image's `data` or `path`), which failed with "Invalid parameters" and sat above the menu's Place image… row with the same label. A search now leaves out a command no menu lists when its params doc names a parameter without `?` (`figcraft_engine::cmd::needs_params`), and a row no menu item gives whose label reads like a menu item's (any case, without the ellipsis). Place image runs File ▸ Place image…, which opens the file dialog. Tests: `palette_tests.rs` (no row needs parameters unless a menu item runs it, no duplicate label across several searches), `unknown_params_tests.rs`. | From 000d39b0421225e3382b3b6b30b52196990caf24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:33:38 -0700 Subject: [PATCH 008/326] M4: closed vectors take corner smoothing A vector's corner smoothing was stored, imported and exported, but its rounded points were drawn as plain circular arcs, and the Design panel hid the Corner smoothing control for vectors. A vector with a closed region now draws its rounded points with the layer's corner smoothing, on the canvas, in hit testing, in PNG, SVG and PDF exports, and in the fill and stroke geometry of .fig exports. Each point keeps its own radius; a point without one stays sharp. The corner uses the profile of smoothed polygon corners, and smoothing is reduced before the radius when a corner does not fit in half of each segment. FigCraft's own rules for cases the help page does not describe: only a point between two straight segments that both bound a closed region is smoothed; points on open branches and points next to a curved segment keep the plain arc; concave corners are smoothed like convex ones. The Design panel shows Corner smoothing and its iOS (60%) button for vectors with a closed region, and not for open paths. --- crates/doc/src/geometry.rs | 21 ++- crates/doc/src/node.rs | 8 +- crates/doc/src/tests.rs | 122 +++++++++++++ crates/doc/src/vector.rs | 101 ++++++++--- crates/engine/src/canvas/shapebuilder.rs | 4 +- .../engine/src/canvas/vectoredit/regions.rs | 14 +- crates/engine/src/shapes_behaviour_tests.rs | 51 +++++- crates/format/src/fig/export/common.rs | 4 +- crates/format/src/fig/export/shape.rs | 4 +- crates/format/src/fig/export_tests.rs | 43 +++++ crates/geom/src/lib.rs | 168 ++++++++++++------ crates/geom/src/tests.rs | 47 +++++ crates/pdf/src/draw.rs | 4 +- crates/pdf/src/tests.rs | 21 +++ crates/render/src/draw.rs | 14 +- crates/svg/src/lib.rs | 4 +- crates/ui-egui/src/corner_individual_tests.rs | 33 ++++ crates/ui-egui/src/panels/right/paints.rs | 2 +- docs/gaps.md | 4 +- docs/target-app-parity.md | 2 +- 20 files changed, 559 insertions(+), 112 deletions(-) diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs index 0e06d2941..3dbbce6d4 100644 --- a/crates/doc/src/geometry.rs +++ b/crates/doc/src/geometry.rs @@ -28,8 +28,9 @@ pub fn shape_path(n: &Node) -> Option { p } NodeKind::Vector { network } => { - let f = network.fill_path(); - if f.elements().is_empty() { network.stroke_path() } else { f } + let net = drawn_network(network, c.smoothing); + let f = net.fill_path(); + if f.elements().is_empty() { net.stroke_path() } else { f } } NodeKind::Text(_) => figcraft_geom::rounded_rect(w, h, [0.0; 4], 0.0), NodeKind::Page { .. } | NodeKind::Group | NodeKind::BooleanOp { .. } => return None, @@ -39,11 +40,21 @@ pub fn shape_path(n: &Node) -> Option { /// The open/closed path strokes follow (vector networks stroke every segment, filled or not). pub fn stroke_geometry(n: &Node) -> Option { match &n.kind { - NodeKind::Vector { network } => Some(network.stroke_path()), + NodeKind::Vector { network } => Some(drawn_network(network, n.corners.smoothing).stroke_path()), _ => shape_path(n), } } +/// A vector's `network` as the layer draws it: rounded points drawn in with the layer's corner +/// `smoothing` (see [`VectorNetwork::rounded_smoothed`](crate::VectorNetwork::rounded_smoothed)), +/// or the network itself when no point is rounded. +pub fn drawn_network(network: &crate::VectorNetwork, smoothing: f64) -> std::borrow::Cow<'_, crate::VectorNetwork> { + match network.rounded_smoothed(smoothing) { + Some(r) => std::borrow::Cow::Owned(r), + None => std::borrow::Cow::Borrowed(network), + } +} + /// Whether the shape's path is closed (fills apply). pub fn is_closed(n: &Node) -> bool { match &n.kind { @@ -75,8 +86,8 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o n.local_rect().inflate(tol_l, tol_l).contains(lp) } NodeKind::Vector { network } if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) => { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); if !outline { for (i, region) in net.regions.iter().enumerate().rev() { let paints = region.fills.as_deref().unwrap_or(&n.fills); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 6ec7e8245..21241cf0f 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -416,9 +416,13 @@ impl NodeKind { self.has_corner_radius() && !matches!(self, NodeKind::Polygon { .. } | NodeKind::Star { .. } | NodeKind::Vector { .. }) } - /// Kinds whose rounded corners are drawn with corner smoothing (a vector's rounded points are drawn without it). + /// 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). pub fn has_corner_smoothing(&self) -> bool { - self.has_corner_radius() && !matches!(self, NodeKind::Vector { .. }) + match self { + NodeKind::Vector { network } => !network.regions.is_empty(), + _ => self.has_corner_radius(), + } } pub fn text(&self) -> Option<&TextData> { diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a0e3e17b0..2eb912f45 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -665,6 +665,128 @@ fn two_segment_closed_loop_rounded_corners() { assert_eq!(r.regions[0].loops[0].len(), 4, "both arcs are in the loop"); let path = net.fill_path(); assert!(!path.elements().is_empty()); + // Both points sit next to the curved segment, so smoothing keeps their plain arcs. + assert_eq!(net.rounded_smoothed(0.6), net.rounded(), "a corner next to a curve keeps the plain arc"); +} + +/// A closed 100 × 100 square whose corners (top left, top right, bottom right, bottom left) have +/// radii `radii`. +fn rounded_square(radii: [f64; 4]) -> VectorNetwork { + let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + let mut net = VectorNetwork::from_points(&pts, true); + for (v, r) in net.vertices.iter_mut().zip(radii) { + v.radius = r; + } + net +} + +/// The area a closed path encloses, whichever way it runs. +fn area_of(p: &figcraft_geom::BezPath) -> f64 { + use figcraft_geom::Shape; + p.area().abs() +} + +#[test] +fn closed_vectors_smooth_each_rounded_point_with_its_own_radius() { + use figcraft_geom::Shape; + use figcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + // (point radii, smoothing, derivation): a closed square draws the smoothed rectangle's corners, + // each point keeping its own radius and a point without one staying sharp. + let rows: Vec<([f64; 4], f64, &str)> = vec![ + ([20.0; 4], 0.6, "one radius on every point"), + ([30.0, 0.0, 10.0, 0.0], 0.6, "each point keeps its own radius; points without one stay sharp"), + ([12.0; 4], 1.0, "full smoothing"), + ([40.0; 4], 0.6, "a corner too large for its edges loses smoothing first"), + ]; + for (radii, s, why) in rows { + let net = rounded_square(radii); + let smoothed = net.rounded_smoothed(s).unwrap().fill_path(); + // The rectangle's corners take [top left, top right, bottom right, bottom left] radii. + let want = area_of(&figcraft_geom::rounded_rect(100.0, 100.0, radii, s)); + let got = area_of(&smoothed); + assert!((got - want).abs() < 0.1, "{why}: {got} vs the smoothed rectangle's {want}"); + assert!((got - area_of(&net.fill_path())).abs() > 1.0, "{why}: smoothing changes the outline"); + let b = smoothed.bounding_box(); + assert!(b.x0 >= -1e-6 && b.y0 >= -1e-6 && b.x1 <= 100.0 + 1e-6 && b.y1 <= 100.0 + 1e-6, "{why}: {b:?}"); + } + // The sharp points stay on the outline, and the outline has no kinks at the rounded points. + let smoothed = rounded_square([30.0, 0.0, 10.0, 0.0]).rounded_smoothed(0.6).unwrap(); + let path = smoothed.fill_path(); + for p in [Point::new(100.0, 0.0), Point::new(0.0, 100.0)] { + let d = path.segments().map(|seg| seg.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min); + assert!(d < 1e-12, "the sharp point {p:?} stays a corner"); + } + let segs: Vec<_> = path.segments().filter(|seg| seg.arclen(1e-6) > 1e-6).collect(); + let mut kinks = 0; + for (i, seg) in segs.iter().enumerate() { + let next = segs[(i + 1) % segs.len()]; + let out = (seg.eval(1.0) - seg.eval(1.0 - 1e-6)).normalize(); + let into = (next.eval(1e-6) - next.eval(0.0)).normalize(); + if out.dot(into) < 0.999 { + kinks += 1; + } + } + assert_eq!(kinks, 2, "only the two sharp points turn without a curve"); + assert_eq!(smoothed.regions[0].loops[0].len(), smoothed.segments.len(), "the loop walks every curve once"); +} + +#[test] +fn corner_smoothing_leaves_open_paths_and_zero_alone() { + let square = rounded_square([20.0; 4]); + assert_eq!(square.rounded_smoothed(0.0), square.rounded(), "no smoothing draws the plain rounded points"); + assert_eq!(square.rounded_smoothed(f64::NAN), square.rounded(), "an unusable smoothing draws no smoothing"); + // An open path (no closed region) keeps its plain arcs. + let pts = [Point::new(200.0, 0.0), Point::new(250.0, 0.0), Point::new(250.0, 50.0)]; + let mut open = VectorNetwork::from_points(&pts, false); + for v in &mut open.vertices { + v.radius = 20.0; + } + assert!(open.regions.is_empty()); + assert_eq!(open.rounded_smoothed(0.6), open.rounded(), "an open path takes no smoothing"); + // In a network with a closed square and a separate open branch, only the square smooths. + let mut mixed = square.clone(); + let base = mixed.vertices.len(); + mixed.vertices.extend(open.vertices.iter().copied()); + mixed.segments.extend(open.segments.iter().map(|s| Segment { a: s.a + base, b: s.b + base, ..*s })); + let runs = mixed.rounded_smoothed(0.6).unwrap().stroke_runs(); + let open_run = runs.iter().find(|r| !r.closed).expect("the open branch"); + assert_eq!(open_run.path, open.rounded().unwrap().stroke_runs()[0].path, "the open branch keeps its plain arc"); + let closed_run = runs.iter().find(|r| r.closed).expect("the square"); + assert_eq!(closed_run.path, square.rounded_smoothed(0.6).unwrap().stroke_runs()[0].path, "the square smooths"); + assert_ne!(closed_run.path, square.rounded().unwrap().stroke_runs()[0].path, "the square's smoothed corners differ from its arcs"); +} + +#[test] +fn smoothed_vector_corners_stay_finite_on_awkward_networks() { + use figcraft_geom::Shape; + // A concave L, a square with a square hole, points with unusable radii and a loop that names a + // missing segment. + let l = [(0.0, 0.0), (100.0, 0.0), (100.0, 40.0), (40.0, 40.0), (40.0, 100.0), (0.0, 100.0)]; + let mut concave = VectorNetwork::from_points(&l.map(|(x, y)| Point::new(x, y)), true); + for v in &mut concave.vertices { + v.radius = 1000.0; + } + let mut holed = rounded_square([10.0; 4]); + let hole = rounded_square([5.0; 4]); + let (base, seg_base) = (holed.vertices.len(), holed.segments.len()); + holed.vertices.extend(hole.vertices.iter().map(|v| Vertex { x: 25.0 + v.x / 2.0, y: 25.0 + v.y / 2.0, ..*v })); + holed.segments.extend(hole.segments.iter().map(|s| Segment { a: s.a + base, b: s.b + base, ..*s })); + holed.regions[0].loops.push((seg_base..seg_base + hole.segments.len()).collect()); + holed.regions[0].winding = WindingRule::EvenOdd; + let mut odd = rounded_square([f64::INFINITY, 10.0, f64::NAN, 10.0]); + odd.regions[0].loops[0].push(99); + for (net, s, why) in [(&concave, 1.0, "concave"), (&holed, 0.6, "holed"), (&odd, 0.6, "odd radii")] { + let drawn = net.rounded_smoothed(s).unwrap(); + let b = drawn.fill_path().bounding_box(); + assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()), "{why}: {b:?}"); + assert!(b.x0 >= -1e-6 && b.y0 >= -1e-6 && b.x1 <= 100.0 + 1e-6 && b.y1 <= 100.0 + 1e-6, "{why}: {b:?}"); + assert!(!drawn.stroke_path().elements().is_empty(), "{why}"); + } + let concave_path = concave.rounded_smoothed(1.0).unwrap().fill_path(); + assert_ne!(concave_path, concave.fill_path(), "the concave L smooths"); + assert!(concave_path.winding(Point::new(20.0, 60.0)) != 0, "the L stays filled"); + let holed_net = holed.rounded_smoothed(0.6).unwrap(); + assert!(!holed_net.fill_contains(Point::new(50.0, 50.0)) && holed_net.fill_contains(Point::new(12.0, 50.0)), "the hole stays a hole"); } #[test] diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index 5ae01a089..f53ad4408 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -129,9 +129,10 @@ impl Region { } } -/// A rounded point as drawn: point `v` moves to `a` (on segment `s1`), segment `s2` starts again -/// at `b`, and an arc with handles `ta`/`tb` joins them. `cut1`/`cut2`: where each segment is cut, -/// in its own parameter (curved segments keep the rest of their curve). +/// A rounded point as drawn: point `v` moves to `a` (on segment `s1`), and the curves of `chain` +/// lead from there to where segment `s2` starts again (one arc, or a smoothed corner's easing +/// curves and arc). `cut1`/`cut2`: where each segment is cut, in its own parameter (curved +/// segments keep the rest of their curve). struct Corner { v: usize, s1: usize, @@ -139,13 +140,19 @@ struct Corner { s2: usize, s2_at_a: bool, a: Point, - b: Point, - ta: (f64, f64), - tb: (f64, f64), + chain: Vec, cut1: f64, cut2: f64, } +/// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to +/// those ends, and the point it ends at. +struct CornerCurve { + ta: (f64, f64), + tb: (f64, f64), + end: Point, +} + /// Accuracy of arc lengths along curved segments (local units). const ARCLEN_ACC: f64 = 1e-6; @@ -382,9 +389,19 @@ impl VectorNetwork { /// the rest of its curve, the arc leaving along its direction there. `None` when no point is /// rounded. pub fn rounded(&self) -> Option { + self.rounded_smoothed(0.0) + } + + /// [`Self::rounded`] with the layer's corner smoothing (0..=1): a rounded point between two + /// straight segments that both belong to a region's loops gets a smoothed corner, drawn with + /// the profile of a smoothed polygon's corners (`figcraft_geom::smoothed_corner`). Other + /// rounded points (on open branches, or next to a curved segment) keep the plain arc, and a + /// point without a radius stays sharp. Without smoothing this is [`Self::rounded`]. + pub fn rounded_smoothed(&self, smoothing: f64) -> Option { if !self.vertices.iter().any(|v| v.radius > 0.0) { return None; } + let smoothing = if smoothing.is_finite() { smoothing.clamp(0.0, 1.0) } else { 0.0 }; let mut incident: Vec> = vec![Vec::new(); self.vertices.len()]; for (i, s) in self.segments.iter().enumerate() { for (v, at_a) in [(s.a, true), (s.b, false)] { @@ -393,7 +410,14 @@ impl VectorNetwork { } } } - let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?)).collect(); + // The segments that bound a closed region, where corners take smoothing. + let mut on_loop = vec![false; if smoothing > 0.0 { self.segments.len() } else { 0 }]; + for &i in self.regions.iter().flat_map(|r| r.loops.iter().flatten()) { + if let Some(x) = on_loop.get_mut(i) { + *x = true; + } + } + let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect(); let mut out = self.clone(); for v in &mut out.vertices { v.radius = 0.0; @@ -420,26 +444,33 @@ impl VectorNetwork { s.ta = (q.p1.x - q.p0.x, q.p1.y - q.p0.y); s.tb = (q.p2.x - q.p3.x, q.p2.y - q.p3.y); } - let mut by_vertex: std::collections::BTreeMap = std::collections::BTreeMap::new(); + // Each rounded point's curves in order from `s1`'s side, by point. + let mut by_vertex: std::collections::BTreeMap)> = std::collections::BTreeMap::new(); for c in corners { if let Some(v) = out.vertices.get_mut(c.v) { (v.x, v.y) = (c.a.x, c.a.y); } - out.vertices.push(Vertex::new(c.b.x, c.b.y)); - let nb = out.vertices.len() - 1; + let mut from = c.v; + let mut arcs = Vec::with_capacity(c.chain.len()); + for CornerCurve { ta, tb, end } in c.chain { + out.vertices.push(Vertex::new(end.x, end.y)); + let to = out.vertices.len() - 1; + out.segments.push(Segment { a: from, b: to, ta, tb }); + arcs.push(out.segments.len() - 1); + from = to; + } if let Some(s) = out.segments.get_mut(c.s2) { if c.s2_at_a { - s.a = nb; + s.a = from; } else { - s.b = nb; + s.b = from; } } - out.segments.push(Segment { a: c.v, b: nb, ta: c.ta, tb: c.tb }); - let arc = out.segments.len() - 1; - by_vertex.insert(c.v, arc); + by_vertex.insert(c.v, (c.s1, arcs)); } - // The arc goes between the two segments wherever a loop walks through the point. Each loop - // is rebuilt in one pass, so a polygon with many rounded corners isn't quadratic. + // 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. 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))) { @@ -453,8 +484,12 @@ impl VectorNetwork { rebuilt.push(x); let Some(s) = self.segments.get(x) else { continue }; cur = if s.a == cur { s.b } else { s.a }; - if let Some(&arc) = by_vertex.get(&cur) { - rebuilt.push(arc); + if let Some((s1, arcs)) = by_vertex.get(&cur) { + if x == *s1 { + rebuilt.extend(arcs.iter().copied()); + } else { + rebuilt.extend(arcs.iter().rev().copied()); + } } } *lp = rebuilt; @@ -463,8 +498,9 @@ impl VectorNetwork { } /// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments - /// run on smoothly or fold back. - fn corner(&self, v: usize, incident: &[(usize, bool)]) -> Option { + /// run on smoothly or fold back. With `smoothing`, a point between two straight segments that + /// are both `on_loop` gets a smoothed corner. + fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option { let r = self.vertices.get(v)?.radius; let [(s1, a1), (s2, a2)] = *incident else { return None }; if !(r > 0.0 && r.is_finite()) || s1 == s2 { @@ -480,6 +516,24 @@ impl VectorNetwork { if !(l1 > 1e-9 && l2 > 1e-9) { return None; } + let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; + let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false); + if smoothing > 0.0 + && is_line(&c1) + && is_line(&c2) + && closed(s1) + && closed(s2) + && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing) + && let (Some(first), Some(last)) = (curves.first(), curves.last()) + { + let (a, b) = (first.p0, last.p3); + let chain = curves + .iter() + .map(|q| CornerCurve { ta: (q.p1.x - q.p0.x, q.p1.y - q.p0.y), tb: (q.p2.x - q.p3.x, q.p2.y - q.p3.y), end: q.p3 }) + .collect(); + let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2); + return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) }); + } let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0); let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2)); // A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between @@ -490,7 +544,6 @@ impl VectorNetwork { if !(k.is_finite() && a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { return None; } - let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; Some(Corner { v, s1, @@ -498,9 +551,7 @@ impl VectorNetwork { s2, s2_at_a: a2, a, - b, - ta: (d1.x * k, d1.y * k), - tb: (d2.x * k, d2.y * k), + chain: vec![CornerCurve { ta: (d1.x * k, d1.y * k), tb: (d2.x * k, d2.y * k), end: b }], cut1: own(a1, k1), cut2: own(a2, k2), }) diff --git a/crates/engine/src/canvas/shapebuilder.rs b/crates/engine/src/canvas/shapebuilder.rs index b68f1e71d..4e6981f14 100644 --- a/crates/engine/src/canvas/shapebuilder.rs +++ b/crates/engine/src/canvas/shapebuilder.rs @@ -132,8 +132,8 @@ fn world_area(doc: &Document, part: Part) -> Option<(BezPath, bool)> { } match (&n.kind, part.region) { (NodeKind::Vector { network }, Some(i)) => { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); let region = net.regions.get(i)?; let path = net.region_path(i)?; (path, if region.winding == WindingRule::EvenOdd { figcraft_render::FillRule::EvenOdd } else { figcraft_render::FillRule::Winding }) diff --git a/crates/engine/src/canvas/vectoredit/regions.rs b/crates/engine/src/canvas/vectoredit/regions.rs index 91763d3aa..6351ce824 100644 --- a/crates/engine/src/canvas/vectoredit/regions.rs +++ b/crates/engine/src/canvas/vectoredit/regions.rs @@ -56,12 +56,10 @@ fn region_filled(n: &figcraft_doc::Node, net: &VectorNetwork, i: usize) -> bool net.regions.get(i).is_some_and(|r| r.fills.as_deref().unwrap_or(&n.fills).iter().any(|f| f.visible)) } -/// The network as its fill draws it: rounded points drawn in (region indexes are kept). -fn drawn(net: &VectorNetwork) -> std::borrow::Cow<'_, VectorNetwork> { - match net.rounded() { - Some(r) => std::borrow::Cow::Owned(r), - None => std::borrow::Cow::Borrowed(net), - } +/// The network as its fill draws it: rounded points drawn in with the layer's corner `smoothing` +/// (region indexes are kept). +fn drawn(net: &VectorNetwork, smoothing: f64) -> std::borrow::Cow<'_, VectorNetwork> { + figcraft_doc::geometry::drawn_network(net, smoothing) } /// The region of the active layer under page point `p` at `zoom`: none when a point is within @@ -90,7 +88,7 @@ pub fn region_hit(doc: &Document, ve: &VectorEdit, p: Point, zoom: f64) -> Optio if (0..net.segments.len()).filter_map(|i| net.cubic(i)).any(|c| c.nearest(lp, 0.01).distance_sq.sqrt() <= sc) { return None; } - let drawn = drawn(net); + let drawn = drawn(net, node.corners.smoothing); (0..drawn.regions.len()).rev().find(|i| region_filled(node, &drawn, *i) && drawn.region_contains(*i, lp)) } @@ -221,7 +219,7 @@ pub fn region_hatch(doc: &Document, ve: &VectorEdit, regions: &[usize], view: Af let zoom = view.determinant().abs().sqrt(); let Some(spacing) = hatch_spacing(zoom).filter(|_| !regions.is_empty()) else { return Vec::new() }; let Some(net) = network(doc, ve.id) else { return Vec::new() }; - let net = drawn(net); + let net = drawn(net, doc.node(ve.id).map_or(0.0, |n| n.corners.smoothing)); let m = view * doc.world_transform(ve.id); let anchor = m * Point::ZERO; let mut out = Vec::new(); diff --git a/crates/engine/src/shapes_behaviour_tests.rs b/crates/engine/src/shapes_behaviour_tests.rs index e628e1683..ca2d16390 100644 --- a/crates/engine/src/shapes_behaviour_tests.rs +++ b/crates/engine/src/shapes_behaviour_tests.rs @@ -233,7 +233,14 @@ fn corner_smoothing_follows_the_documented_rules() { (NodeKind::Frame, true, "frames"), (NodeKind::Polygon { count: 5 }, true, "polygons"), (NodeKind::Star { count: 5, inner_ratio: 0.4 }, true, "stars"), - (NodeKind::Vector { network: Default::default() }, false, "documented for closed vectors; their points round without it here"), + ( + NodeKind::Vector { + network: figcraft_doc::VectorNetwork::from_points(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true), + }, + true, + "vector networks that are closed shapes", + ), + (NodeKind::Vector { network: Default::default() }, false, "an open vector has no closed shape to smooth"), (NodeKind::Line, false, "lines take no radius, so no smoothing"), ]; for (kind, smoothing, why) in doc_rows { @@ -241,6 +248,48 @@ fn corner_smoothing_follows_the_documented_rules() { } } +#[test] +fn closed_vectors_take_corner_smoothing() { + // "Vector networks that are closed shapes" take corner smoothing, which applies to the entire + // shape; a single open stroke does not. + let mut s = Session::new(); + let closed = create(&mut s, "vector.create", json!({"points": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true})); + let open = create(&mut s, "vector.create", json!({"points": [[200, 0], [300, 0], [300, 100]], "closed": false})); + ex(&mut s, "node.set", json!({"ids": [closed, open], "props": {"cornerRadius": 20}})); + let outline = |s: &Session, id: NodeId| figcraft_doc::geometry::shape_path(&node(s, id)).unwrap(); + let svg = |s: &Session, id: NodeId| figcraft_svg::export_svg(s.doc().unwrap(), &[id], &figcraft_svg::SvgOptions::default()).unwrap(); + let render = |s: &Session, id: NodeId| figcraft_render::node_outline(s.doc().unwrap(), &node(s, id)).unwrap().0; + let (round, open_round, svg_round, drawn_round) = (outline(&s, closed), outline(&s, open), svg(&s, closed), render(&s, closed)); + ex(&mut s, "node.set", json!({"ids": [closed, open], "props": {"cornerSmoothing": 0.6}})); + let smooth = outline(&s, closed); + // The smoothed corner reaches 1.6 radii along each edge, as a smoothed rectangle's does. + let want = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6).area().abs(); + assert!((smooth.area().abs() - want).abs() < 0.1, "the closed vector smooths: {} vs {want}", smooth.area().abs()); + assert!((smooth.area().abs() - round.area().abs()).abs() > 1.0, "smoothing changes the closed vector's outline"); + assert_ne!(svg(&s, closed), svg_round, "SVG export draws the smoothed corners"); + assert_ne!(render(&s, closed), drawn_round, "the canvas draws the smoothed corners"); + assert_eq!(outline(&s, open), open_round, "an open vector keeps its plain rounded points"); + let stroke = figcraft_doc::geometry::stroke_geometry(&node(&s, closed)).unwrap(); + assert!((stroke.area().abs() - want).abs() < 0.1, "the stroke follows the smoothed outline"); + // Smoothing needs a radius, and undo restores the plain corners in one step. + s.undo().unwrap(); + assert_eq!(outline(&s, closed), round, "one undo step"); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerRadius": 0}})); + let sharp = outline(&s, closed); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerSmoothing": 0.6}})); + assert_eq!(outline(&s, closed), sharp, "smoothing needs a radius"); + // A vector whose region has paints of its own draws the smoothed corners too, on the canvas + // and in SVG. + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerRadius": 20}})); + if let NodeKind::Vector { network } = &mut s.doc_mut().unwrap().get_mut(closed).unwrap().kind { + network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]); + } + let (region_svg, region_path) = (svg(&s, closed), render(&s, closed)); + assert!((region_path.area().abs() - want).abs() < 0.5, "region paints follow the smoothed outline: {}", region_path.area().abs()); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerSmoothing": 0}})); + assert_ne!(svg(&s, closed), region_svg, "SVG export draws the region's smoothed corners"); +} + #[test] fn rounded_vector_points_are_drawn() { // A converted 100 × 100 square: a point's radius rounds that corner only (it wasn't drawn). diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index 4a97eecb9..ee7293dc9 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -34,10 +34,10 @@ pub(super) fn outlined(n: &Node) -> Option<(Node, String)> { } let path = figcraft_doc::geometry::stroke_geometry(n)?; let net = match &n.kind { - NodeKind::Vector { network } => Some(network), + NodeKind::Vector { network } => Some(figcraft_doc::geometry::drawn_network(network, n.corners.smoothing)), _ => None, }; - let area = figcraft_pathops::stroke_outline_of(&path, sp, figcraft_doc::geometry::is_closed(n), net); + let area = figcraft_pathops::stroke_outline_of(&path, sp, figcraft_doc::geometry::is_closed(n), net.as_deref()); if area.elements().is_empty() || area.elements().len() > MAX_NETWORK / 4 { return None; } diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index 03c82cfb1..6627935ca 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -257,7 +257,7 @@ impl<'d> Exporter<'d> { if net.regions.iter().any(|r| r.winding != winding) { self.warn("vectors whose filled areas use different winding rules use the first one's in their outline"); } - self.geometry("fillGeometry", &net.fill_path(), winding, f); + self.geometry("fillGeometry", &figcraft_doc::geometry::drawn_network(net, n.corners.smoothing).fill_path(), winding, f); } } @@ -309,7 +309,7 @@ impl<'d> Exporter<'d> { self.geometry("strokeGeometry", &ring, WindingRule::EvenOdd, f); } else if sp.align == StrokeAlign::Center { let path = match &n.kind { - NodeKind::Vector { network } => Some(network.stroke_path()), + NodeKind::Vector { .. } => figcraft_doc::geometry::stroke_geometry(n), NodeKind::Text(_) => None, _ => figcraft_doc::geometry::shape_path(n), }; diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 5b4bcb991..45f6866f3 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -912,6 +912,49 @@ fn written_files_decode_and_list_parents_first() { } } +#[test] +fn closed_vector_geometry_is_written_with_its_corner_smoothing() { + // A closed vector with rounded points: its written fill and stroke outlines take the layer's + // corner smoothing, and the smoothing and each point's radius come back on import. + let mut doc = Document::new("smoothing"); + let page = doc.first_page().unwrap(); + let mut network = VectorNetwork::from_points(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y)), true); + for (v, r) in network.vertices.iter_mut().zip([20.0, 0.0, 10.0, 0.0]) { + v.radius = r; + } + let id = doc.create(page, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + doc.node_mut(id).unwrap().strokes = vec![Paint::solid(Color::BLACK)]; + // The vector's written fill and stroke outlines. + let outlines = |doc: &Document| -> Vec> { + let (bytes, _) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let blobs = msg.get("blobs").unwrap().list(); + let changes = msg.get("nodeChanges").unwrap().list(); + let nc = changes.iter().find(|nc| nc.get("type").and_then(Kv::str) == Some("VECTOR")).unwrap(); + ["fillGeometry", "strokeGeometry"] + .iter() + .map(|key| { + let paths = nc.get(key).map(Kv::list).unwrap_or_default(); + let blob = paths.first().unwrap_or_else(|| panic!("{key} is written")).get("commandsBlob").unwrap().f64().unwrap() as usize; + blobs[blob].get("bytes").and_then(Kv::bytes).unwrap().to_vec() + }) + .collect() + }; + let plain = outlines(&doc); + doc.node_mut(id).unwrap().corners.smoothing = 0.6; + let smoothed = outlines(&doc); + assert_ne!(smoothed[0], plain[0], "the fill outline takes the smoothing"); + assert_ne!(smoothed[1], plain[1], "the stroke outline takes the smoothing"); + let (back, _) = round_trip(&doc, "smoothed vector"); + let v = back.nodes().find(|n| matches!(n.kind, NodeKind::Vector { .. })).unwrap(); + assert!((v.corners.smoothing - 0.6).abs() < 1e-6, "smoothing comes back: {}", v.corners.smoothing); + let NodeKind::Vector { network } = &v.kind else { panic!("vector") }; + let radii: Vec = network.vertices.iter().map(|x| x.radius).collect(); + assert_eq!(radii, vec![20.0, 0.0, 10.0, 0.0], "each point keeps its own radius"); +} + #[test] fn the_written_schema_parses_and_round_trips() { let schema = Schema::parse(export::SCHEMA).unwrap(); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 012fca429..d63d84397 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -249,67 +249,133 @@ pub fn smoothed_polygon(points: &[Point], radius: f64, smoothing: f64) -> BezPat }; let (v1, v2) = (*prev - *cur, *next - *cur); let (l1, l2) = (v1.hypot(), v2.hypot()); - let angle = if l1 < 1e-9 || l2 < 1e-9 { 0.0 } else { (v1 / l1).dot(v2 / l2).clamp(-1.0, 1.0).acos() }; - if angle < 1e-6 || (PI - angle) < 1e-6 { + let corner = if l1 < 1e-9 || l2 < 1e-9 { None } else { smooth_corner(*cur, v1 / l1, v2 / l2, l1.min(l2) / 2.0, radius, s) }; + let Some(k) = corner else { line_or_move(&mut path, *cur); continue; + }; + line_or_move(&mut path, k.start); + match k.ease_in { + Some((h1, h2)) => path.curve_to(h1, h2, k.p3), + None => path.line_to(k.p3), } - let (u1, u2) = (v1 / l1, v2 / l2); - // The plain corner's length along each edge, then the fit: smoothing first, then the radius. - let max_p = l1.min(l2) / 2.0; - let mut r = radius; - let mut t = r / (angle / 2.0).tan(); - let mut sm = s; - if (1.0 + sm) * t > max_p { - sm = (max_p / t - 1.0).clamp(0.0, sm); + if k.sweep.abs() > 1e-9 { + kurbo::Arc::new(k.center, (k.r, k.r), k.a0, k.sweep, 0.0).to_cubic_beziers(0.01, |p1, p2, q| path.curve_to(p1, p2, q)); } - if t > max_p { - r *= max_p / t; - t = max_p; - } - let p = ((1.0 + sm) * t).min(max_p); - // Each easing curve covers `beta` of the turn and ends on the arc at `back` along the edge - // and `side` across it; its last handle points along the arc there. - let beta = (PI - angle) * sm / 2.0; - let back = t - r * beta.sin(); - let side = r * (1.0 - beta.cos()); - let c = r * (beta / 2.0).tan() * beta.cos(); - let b = ((p - back - c) / 3.0).max(0.0); - let a = 2.0 * b; - let bisector = (u1 + u2).normalize(); - let center = *cur + bisector * (r / (angle / 2.0).sin()); - // A point `along` an edge from the vertex and `across` it toward the arc's center. - let at = |u: Vec2, along: f64, across: f64| *cur + u * along + (bisector - u * bisector.dot(u)).normalize() * across; - line_or_move(&mut path, at(u1, p, 0.0)); - let p3 = at(u1, back, side); - let p4 = at(u2, back, side); - if a + b + c > 1e-9 { - path.curve_to(at(u1, p - a, 0.0), at(u1, p - a - b, 0.0), p3); - } else { - path.line_to(p3); - } - let a0 = (p3 - center).atan2(); - let mut sweep = (p4 - center).atan2() - a0; - while sweep <= -PI { - sweep += TAU; - } - while sweep > PI { - sweep -= TAU; - } - if sweep.abs() > 1e-9 { - kurbo::Arc::new(center, (r, r), a0, sweep, 0.0).to_cubic_beziers(0.01, |p1, p2, q| path.curve_to(p1, p2, q)); - } - let end = at(u2, p, 0.0); - if a + b + c > 1e-9 { - path.curve_to(at(u2, p - a - b, 0.0), at(u2, p - a, 0.0), end); - } else { - path.line_to(end); + match k.ease_out { + Some((h1, h2)) => path.curve_to(h1, h2, k.end), + None => path.line_to(k.end), } } path.close_path(); path } +/// One smoothed corner as [`smoothed_polygon`] draws it: it starts at `start` on the first edge, +/// eases into a circular arc at `p3` (through handles `ease_in`, or straight when `None`), follows +/// the arc of radius `r` about `center` from angle `a0` through `sweep` to `p4`, and eases out to +/// `end` on the second edge. +struct SmoothCorner { + start: Point, + ease_in: Option<(Point, Point)>, + p3: Point, + center: Point, + r: f64, + a0: f64, + sweep: f64, + p4: Point, + ease_out: Option<(Point, Point)>, + end: Point, +} + +/// The smoothed corner at `cur` between edges that leave it along unit directions `u1` and `u2`, +/// with `max_p` of room along each: `None` where the edges run straight on or fold back. +fn smooth_corner(cur: Point, u1: Vec2, u2: Vec2, max_p: f64, radius: f64, s: f64) -> Option { + let angle = u1.dot(u2).clamp(-1.0, 1.0).acos(); + if angle < 1e-6 || (PI - angle) < 1e-6 { + return None; + } + // The plain corner's length along each edge, then the fit: smoothing first, then the radius. + let mut r = radius; + let mut t = r / (angle / 2.0).tan(); + let mut sm = s; + if (1.0 + sm) * t > max_p { + sm = (max_p / t - 1.0).clamp(0.0, sm); + } + if t > max_p { + r *= max_p / t; + t = max_p; + } + let p = ((1.0 + sm) * t).min(max_p); + // Each easing curve covers `beta` of the turn and ends on the arc at `back` along the edge + // and `side` across it; its last handle points along the arc there. + let beta = (PI - angle) * sm / 2.0; + let back = t - r * beta.sin(); + let side = r * (1.0 - beta.cos()); + let c = r * (beta / 2.0).tan() * beta.cos(); + let b = ((p - back - c) / 3.0).max(0.0); + let a = 2.0 * b; + let bisector = (u1 + u2).normalize(); + let center = cur + bisector * (r / (angle / 2.0).sin()); + // A point `along` an edge from the vertex and `across` it toward the arc's center. + let at = |u: Vec2, along: f64, across: f64| cur + u * along + (bisector - u * bisector.dot(u)).normalize() * across; + let p3 = at(u1, back, side); + let p4 = at(u2, back, side); + let eased = a + b + c > 1e-9; + let a0 = (p3 - center).atan2(); + let mut sweep = (p4 - center).atan2() - a0; + while sweep <= -PI { + sweep += TAU; + } + while sweep > PI { + sweep -= TAU; + } + Some(SmoothCorner { + start: at(u1, p, 0.0), + ease_in: eased.then(|| (at(u1, p - a, 0.0), at(u1, p - a - b, 0.0))), + p3, + center, + r, + a0, + sweep, + p4, + ease_out: eased.then(|| (at(u2, p - a - b, 0.0), at(u2, p - a, 0.0))), + end: at(u2, p, 0.0), + }) +} + +/// The curves of one corner rounded by `radius` with corner smoothing (0..=1) at `corner`, between +/// two straight edges that leave it along unit directions `u1` and `u2` with `max_p` of room along +/// each. The curves follow the profile of [`smoothed_polygon`], with the circular part as one +/// cubic, and run from the point on the `u1` edge to the point on the `u2` edge; a straight piece +/// has its handles on its ends. As in the polygon, smoothing is reduced first when the corner does +/// not fit, then the radius. `None` for a corner that is not rounded, or where the edges run +/// straight on or fold back. +pub fn smoothed_corner(corner: Point, u1: Vec2, u2: Vec2, max_p: f64, radius: f64, smoothing: f64) -> Option> { + let (s, radius, max_p) = (finite(smoothing).clamp(0.0, 1.0), finite(radius).max(0.0), finite(max_p).max(0.0)); + let usable = |u: Vec2| u.x.is_finite() && u.y.is_finite() && u.hypot() > 1e-9; + if radius <= 0.0 || max_p <= 0.0 || !usable(u1) || !usable(u2) || !(corner.x.is_finite() && corner.y.is_finite()) { + return None; + } + let k = smooth_corner(corner, u1 / u1.hypot(), u2 / u2.hypot(), max_p, radius, s)?; + let piece = |p0: Point, handles: Option<(Point, Point)>, p3: Point| { + let (h1, h2) = handles.unwrap_or((p0, p3)); + kurbo::CubicBez::new(p0, h1, h2, p3) + }; + let mut out = vec![piece(k.start, k.ease_in, k.p3)]; + if k.sweep.abs() > 1e-9 { + // The arc as one cubic: handles of 4/3·tan(θ/4)·r along the circle's tangents at its ends. + let h = 4.0 / 3.0 * (k.sweep.abs() / 4.0).tan() * k.r * k.sweep.signum(); + let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()); + out.push(kurbo::CubicBez::new(k.p3, k.p3 + tangent(k.a0) * h, k.p4 - tangent(k.a0 + k.sweep) * h, k.p4)); + } + out.push(piece(k.p4, k.ease_out, k.end)); + out.retain(|q| (q.p3 - q.p0).hypot() > 1e-9 || (q.p1 - q.p0).hypot() > 1e-9 || (q.p2 - q.p3).hypot() > 1e-9); + let finite_point = |p: &Point| p.x.is_finite() && p.y.is_finite(); + let ok = out.iter().all(|q| [q.p0, q.p1, q.p2, q.p3].iter().all(finite_point)); + (ok && !out.is_empty()).then_some(out) +} + /// Starts `path` at `p`, or continues it there with a straight segment. fn line_or_move(path: &mut BezPath, p: Point) { if path.elements().is_empty() { diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 37e6ccab7..1a2391a35 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -52,6 +52,53 @@ fn degenerate_inputs_dont_panic() { let _ = smoothed_polygon(&polygon_points(10.0, 10.0, 5), f64::INFINITY, f64::NAN); let _ = smoothed_polygon(&polygon_points(10.0, 10.0, 5), 3.0, f64::INFINITY); let _ = ellipse(f64::NAN, 10.0, f64::NAN, 100.0, 2.0); + // (corner, first edge, second edge, room, radius, smoothing): none of these is a corner to round. + let x = Vec2::new(1.0, 0.0); + let rows = [ + (Point::ZERO, x, Vec2::new(0.0, 1.0), 10.0, 0.0, 0.6), + (Point::ZERO, x, Vec2::new(0.0, 1.0), 0.0, 5.0, 0.6), + (Point::ZERO, x, x, 10.0, 5.0, 0.6), + (Point::ZERO, x, -x, 10.0, 5.0, 0.6), + (Point::ZERO, Vec2::ZERO, x, 10.0, 5.0, 0.6), + (Point::ZERO, Vec2::new(f64::NAN, 0.0), x, 10.0, 5.0, 0.6), + (Point::new(f64::INFINITY, 0.0), x, Vec2::new(0.0, 1.0), 10.0, 5.0, 0.6), + ]; + for (corner, u1, u2, room, r, s) in rows { + assert!(smoothed_corner(corner, u1, u2, room, r, s).is_none(), "{corner:?} {u1:?} {u2:?} {room} {r} {s}"); + } +} + +#[test] +fn smoothed_corner_draws_the_polygon_corner() { + use kurbo::ParamCurve; + // The corner of a square drawn by itself follows the smoothed polygon's corner and joins its + // edges and its own pieces without a kink. + for s in [0.0, 0.6, 1.0] { + let curves = smoothed_corner(Point::ZERO, Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), 50.0, 20.0, s).unwrap(); + let mut path = BezPath::new(); + path.move_to(curves[0].p0); + for q in &curves { + path.curve_to(q.p1, q.p2, q.p3); + } + path.line_to((100.0, 0.0)); + path.line_to((100.0, 100.0)); + path.line_to((0.0, 100.0)); + path.close_path(); + let want = area(&rounded_rect(100.0, 100.0, [20.0, 0.0, 0.0, 0.0], s)); + assert!((area(&path) - want).abs() < 0.05, "s={s}: {} vs {want}", area(&path)); + assert!((curves[0].p0 - Point::new(0.0, 20.0 * (1.0 + s))).hypot() < 1e-9, "s={s}: it starts 1 + smoothing radii along the edge"); + let last = curves[curves.len() - 1]; + assert!((last.p3 - Point::new(20.0 * (1.0 + s), 0.0)).hypot() < 1e-9, "s={s}: and ends as far along the other"); + let dir = |c: &kurbo::CubicBez, t: f64| { + let d = if t < 0.5 { c.eval(1e-6) - c.eval(0.0) } else { c.eval(1.0) - c.eval(1.0 - 1e-6) }; + d.normalize() + }; + assert!(dir(&curves[0], 0.0).dot(Vec2::new(0.0, -1.0)) > 0.999, "s={s}: it leaves along the first edge"); + assert!(dir(&last, 1.0).dot(Vec2::new(1.0, 0.0)) > 0.999, "s={s}: it arrives along the second edge"); + for pair in curves.windows(2) { + assert!(dir(&pair[0], 1.0).dot(dir(&pair[1], 0.0)) > 0.999, "s={s}: its pieces join smoothly"); + } + } } #[test] diff --git a/crates/pdf/src/draw.rs b/crates/pdf/src/draw.rs index eb1b8aaf1..2ae6e366c 100644 --- a/crates/pdf/src/draw.rs +++ b/crates/pdf/src/draw.rs @@ -338,8 +338,8 @@ impl<'a> Exporter<'a> { if let NodeKind::Vector { network } = &n.kind && network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); if let Some(mut region_path) = net.region_path(i) { diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index cdd85d6bd..110bfa736 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -82,6 +82,27 @@ fn pdf_vector_region_paints_emit_independent_colors() { assert!(content.contains("1 0 0 rg") && content.contains("0 0 1 rg"), "{content}"); } +#[test] +fn pdf_vector_region_paints_draw_smoothed_corners() { + // A closed vector with rounded points and paints on its region: corner smoothing changes the + // exported outline, as on the canvas. + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| figcraft_geom::Point::new(x, y)); + let mut network = VectorNetwork::from_points(&corners, true); + for v in &mut network.vertices { + v.radius = 20.0; + } + network.regions[0].fills = Some(vec![Paint::solid(Color::from_hex("FF0000").unwrap())]); + let mut d = Document::new("smoothing"); + let p = d.first_page().unwrap(); + let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + let content = |d: &Document| inflated(&export_pdf(d, &[id], &PdfOptions::default()).unwrap()); + let plain = content(&d); + d.get_mut(id).unwrap().corners.smoothing = 0.6; + let smoothed = content(&d); + assert!(smoothed.contains("1 0 0 rg"), "{smoothed}"); + assert_ne!(smoothed, plain, "the region's outline takes the smoothing"); +} + /// A page with two frames: shapes, gradients, an image, strokes, a mask, a boolean, effects, text. pub(crate) fn sample_doc() -> (Document, Vec) { let mut d = Document::new("sample"); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index f48899aea..74512ef4f 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -274,7 +274,9 @@ fn cached_stroke_outline(n: &Node, path: &BezPath, closed: bool) -> Arc if let Some(p) = locked(stroke_cache()).get(key) { return p; } - let out = Arc::new(figcraft_pathops::stroke_outline_of(path, props, closed, net)); + // Points with styles of their own are stroked on the network as drawn (smoothed corners in). + let drawn = net.map(|network| figcraft_doc::geometry::drawn_network(network, n.corners.smoothing)); + let out = Arc::new(figcraft_pathops::stroke_outline_of(path, props, closed, drawn.as_deref())); locked(stroke_cache()).insert(key, out.clone()); out } @@ -334,9 +336,9 @@ fn node_outline_at(doc: &Document, n: &Node, depth: usize) -> Option<(BezPath, F Some((p, FillRule::Winding)) } NodeKind::Vector { network } => { + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); let mut areas = BezPath::new(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); @@ -357,7 +359,7 @@ fn node_outline_at(doc: &Document, n: &Node, depth: usize) -> Option<(BezPath, F } let rule = if network.regions.iter().any(|r| r.winding == figcraft_doc::WindingRule::EvenOdd) { FillRule::EvenOdd } else { FillRule::Winding }; - Some((network.fill_path(), rule)) + Some((net.fill_path(), rule)) } _ => figcraft_doc::geometry::shape_path(n).map(|p| (p, FillRule::Winding)), } @@ -849,8 +851,8 @@ fn region_painted(n: &Node) -> Option<&figcraft_doc::VectorNetwork> { /// Each region of a vector with region paints, filled with its own paints (or the layer's) in its /// own paint frame. fn fill_vector_regions(ctx: &Ctx, pix: &mut Pixmap, n: &Node, network: &figcraft_doc::VectorNetwork, xf: Affine) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); if let Some(mut path) = net.region_path(i) { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index de98795d3..b5047cec4 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -537,8 +537,8 @@ impl W<'_> { if let NodeKind::Vector { network } = &n.kind && network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); let fr = if region.winding == figcraft_doc::WindingRule::EvenOdd { " fill-rule=\"evenodd\"" } else { "" }; diff --git a/crates/ui-egui/src/corner_individual_tests.rs b/crates/ui-egui/src/corner_individual_tests.rs index e76f2f57e..281ab6f2a 100644 --- a/crates/ui-egui/src/corner_individual_tests.rs +++ b/crates/ui-egui/src/corner_individual_tests.rs @@ -184,3 +184,36 @@ fn polygons_and_stars_take_corner_smoothing() { assert_eq!(u.app.session.undo_depth().0, history + 1, "{cmd}: 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] +fn closed_vectors_take_corner_smoothing() { + let rows = [(true, json!([[0, 0], [120, 0], [120, 120], [0, 120]])), (false, json!([[0, 0], [120, 0], [120, 120]]))]; + for (closed, points) in rows { + let mut s = Session::new(); + let id = NodeId(s.execute("vector.create", &json!({"points": points, "closed": closed})).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); + 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; + let toggle = nodes.iter().any(|(_, n)| n.role() == Role::Button && n.label() == Some("Corner smoothing")); + assert_eq!(toggle, closed, "closed {closed}: the Corner smoothing button shows only for a closed vector"); + if !closed { + continue; + } + 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()), "no field per corner"); + assert!(u.ctx.read_response(Id::unique("smoothing").with("field")).is_some(), "the smoothing field shows"); + let history = u.app.session.undo_depth().0; + let ios = named_button(&mut u, "iOS"); + click(&mut u, ios); + let n = u.app.session.doc().unwrap().node(id).unwrap().clone(); + assert!((n.corners.smoothing - 0.6).abs() < 1e-9, "iOS sets 60%: {}", n.corners.smoothing); + assert_eq!(u.app.session.undo_depth().0, history + 1, "one undo step"); + } +} diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 58423d252..10301a85e 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -53,7 +53,7 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N 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. let indep_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_independent_corners()); - // For polygons and stars the same panel holds only the Corner smoothing row. + // For polygons, stars 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)); widgets::sublabels(ui, tr("Opacity"), radius_ok.then_some(tr("Corner radius"))); diff --git a/docs/gaps.md b/docs/gaps.md index 5437c6766..b3685c912 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -384,8 +384,8 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **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 smoothing on vectors, 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: corner radius and smoothing on boolean groups that contain + rectangles, 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 489c0e7da..2775c41d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -99,7 +99,7 @@ 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 smoothing on vectors, 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 and stars, 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% | 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 | | 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 | From f56e30e7e3bf992d747881b7d0b0d21ed8e16efd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:42:39 -0700 Subject: [PATCH 009/326] Hit testing: clicks on a closed vector follow its smoothed corners A vector without region paints tested a click against its plain rounded fill while the canvas drew the smoothed corners, so a click between the two could select a layer where no fill is drawn or miss fill that is drawn. The inside test now uses the network as drawn, keeping the even-odd rule. --- crates/doc/src/geometry.rs | 5 +++-- crates/doc/src/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs index 3dbbce6d4..189e06192 100644 --- a/crates/doc/src/geometry.rs +++ b/crates/doc/src/geometry.rs @@ -107,10 +107,11 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o } /// Whether the fill of `n`, drawn as `path`, covers `lp` (vectors follow the rule of -/// [`VectorNetwork::fill_contains`](crate::VectorNetwork::fill_contains): even-odd when any region asks for it). +/// [`VectorNetwork::fill_contains`](crate::VectorNetwork::fill_contains) on the network as drawn: even-odd when any +/// region asks for it). fn fills_point(n: &Node, path: &BezPath, lp: Point) -> bool { match &n.kind { - NodeKind::Vector { network } => network.fill_contains(lp), + NodeKind::Vector { network } => drawn_network(network, n.corners.smoothing).fill_contains(lp), _ => path.winding(lp) != 0, } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 2eb912f45..7dbc8cc94 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -789,6 +789,33 @@ fn smoothed_vector_corners_stay_finite_on_awkward_networks() { assert!(!holed_net.fill_contains(Point::new(50.0, 50.0)) && holed_net.fill_contains(Point::new(12.0, 50.0)), "the hole stays a hole"); } +#[test] +fn clicks_on_a_smoothed_vector_corner_follow_the_drawn_fill() { + // A closed square with rounded points and smoothing: a click between the plain arc and the + // smoothed corner selects the layer only where the smoothed fill is drawn. + let pts = [Point::new(0.0, 0.0), Point::new(1000.0, 0.0), Point::new(1000.0, 1000.0), Point::new(0.0, 1000.0)]; + let mut net = VectorNetwork::from_points(&pts, true); + for v in &mut net.vertices { + v.radius = 200.0; + } + let smoothed = net.rounded_smoothed(1.0).unwrap(); + let mut d = Document::new("x"); + let p = page(&d); + let v = d.create(p, NodeKind::Vector { network: net.clone() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap(); + let n = d.node_mut(v).unwrap(); + n.corners.smoothing = 1.0; + n.strokes.clear(); + // Walk the row 20 units below the top edge inward to where each outline starts covering it. + let first_inside = |inside: &dyn Fn(Point) -> bool| (0..5_000).map(|i| f64::from(i) * 0.1).find(|&x| inside(Point::new(x, 20.0))); + let plain = first_inside(&|pt| net.fill_contains(pt)).unwrap(); + let drawn = first_inside(&|pt| smoothed.fill_contains(pt)).unwrap(); + assert!((plain - drawn).abs() > 5.0, "smoothing moves the corner: plain {plain}, smoothed {drawn}"); + let pt = Point::new((plain + drawn) / 2.0, 20.0); + assert_ne!(net.fill_contains(pt), smoothed.fill_contains(pt)); + assert_eq!(d.hit_test(p, pt, 0.0, None).is_some(), smoothed.fill_contains(pt), "the click follows the smoothed corner at {pt:?}"); + assert_eq!(d.hit_test(p, Point::new(500.0, 500.0), 0.0, None), Some(v)); +} + #[test] fn stored_variable_ids_resolve_only_their_exact_collection() { let mut vars = crate::proto_expr_tests::vars(); From afc5e13972a4a7bc6b019a079397fcd87491031a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:07:17 -0700 Subject: [PATCH 010/326] Export: each export setting chooses a color profile Each export setting has a color profile: Same as file (the default, the document's profile when it exports), sRGB or Display P3. PNG, JPG and WebP settings list it in their advanced settings, and export.add, export.update, file.export, file.exportLayers (for every setting) and the MCP export tool take it as colorProfile. The rendered pixels are converted to the chosen profile (out-of-gamut colors clip) and the file is tagged as before: an sRGB chunk for sRGB PNG, the generated ICC profile (and cICP in PNG) for Display P3; sRGB JPG and WebP stay untagged. A setting keeps its choice when its format changes, and settings saved without one read as Same as file. SVG, PDF and Android XML show no choice and stay sRGB; PDF has no output intent yet. --- crates/doc/src/props.rs | 48 ++++- crates/engine/src/cmd/edit.rs | 4 +- crates/engine/src/cmd/file.rs | 24 ++- crates/engine/src/cmd/file/export.rs | 13 +- crates/engine/src/export_profile_tests.rs | 200 +++++++++++++++++++++ crates/engine/src/lib.rs | 2 + crates/mcp/src/tools.rs | 4 +- crates/mcp/tests/it/export_profile.rs | 29 +++ crates/mcp/tests/it/main.rs | 2 + crates/ui-egui/locales/en.toml | 1 + crates/ui-egui/src/export_preview_tests.rs | 32 ++++ crates/ui-egui/src/panels/export_panel.rs | 35 +++- crates/ui-egui/src/ui_params_tests.rs | 3 +- docs/file-format-parity.md | 11 +- docs/mcp.md | 2 +- 15 files changed, 384 insertions(+), 26 deletions(-) create mode 100644 crates/engine/src/export_profile_tests.rs create mode 100644 crates/mcp/tests/it/export_profile.rs diff --git a/crates/doc/src/props.rs b/crates/doc/src/props.rs index 0c78681f2..4da0da1f4 100644 --- a/crates/doc/src/props.rs +++ b/crates/doc/src/props.rs @@ -1,6 +1,6 @@ //! Node property types: strokes, effects, corners, constraints, auto layout, grids, exports. -use figcraft_color::{BlendMode, Color}; +use figcraft_color::{BlendMode, Color, ColorProfile}; use serde::{Deserialize, Serialize}; /// Where a stroke sits relative to the shape edge. @@ -1481,6 +1481,51 @@ pub struct ExportSetting { /// Android Vector Drawable: what to do with what a drawable can't hold exactly. #[serde(skip_serializing_if = "VdCompat::is_default")] 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")] + pub color_profile: ExportColorProfile, +} + +/// The color profile an export setting writes PNG, JPG and WebP files in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum ExportColorProfile { + /// The document's own profile at the time of the export. + #[default] + SameAsFile, + Srgb, + DisplayP3, +} + +impl ExportColorProfile { + pub const ALL: [ExportColorProfile; 3] = [ExportColorProfile::SameAsFile, ExportColorProfile::Srgb, ExportColorProfile::DisplayP3]; + + fn is_default(&self) -> bool { + *self == ExportColorProfile::SameAsFile + } + + /// The name commands and files use ("sameAsFile", "srgb", "displayP3"). + pub fn key(self) -> &'static str { + match self { + ExportColorProfile::SameAsFile => "sameAsFile", + ExportColorProfile::Srgb => "srgb", + ExportColorProfile::DisplayP3 => "displayP3", + } + } + + pub fn from_key(s: &str) -> Option { + Self::ALL.into_iter().find(|c| c.key() == s) + } + + /// The profile the file is written in when the document is in `file`. + pub fn resolve(self, file: ColorProfile) -> ColorProfile { + match self { + ExportColorProfile::SameAsFile => file, + ExportColorProfile::Srgb => ColorProfile::Srgb, + ExportColorProfile::DisplayP3 => ColorProfile::DisplayP3, + } + } } /// How an Android Vector Drawable export handles what the format can't draw exactly (layer @@ -1531,6 +1576,7 @@ impl Default for ExportSetting { svg_id_attribute: false, svg_simplify_stroke: true, vd_compat: VdCompat::BestEffort, + color_profile: ExportColorProfile::SameAsFile, } } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3f72e429e..5d6efb583 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -418,7 +418,7 @@ pub fn specs() -> Vec { spec!( "export.add", "Add export setting", - "{ids?, setting? {size: 2x|512w|512h|{by: scale|width|height, value}, suffix?, format?: png|jpg|svg|pdf|webp|xml (Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore)}} (without a setting: 1x, then one scale step up with an \"@2x\"-style suffix)", + "{ids?, setting? {size: 2x|512w|512h|{by: scale|width|height, value}, suffix?, format?: png|jpg|svg|pdf|webp|xml (Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), colorProfile? (PNG, JPG and WebP: sameAsFile|srgb|displayP3)}} (without a setting: 1x, then one scale step up with an \"@2x\"-style suffix)", true, |s, p| { let cmd = "export.add"; @@ -436,7 +436,7 @@ pub fn specs() -> Vec { spec!( "export.update", "Edit export setting", - "{ids?, index, size? (2x|512w|512h|{by, value}), suffix?, format? (png|jpg|svg|pdf|webp|xml: Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?}", + "{ids?, index, size? (2x|512w|512h|{by, value}), suffix?, format? (png|jpg|svg|pdf|webp|xml: Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), colorProfile? (PNG, JPG and WebP: sameAsFile (the document's profile when it exports)|srgb|displayP3; kept when the format changes), contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?}", true, |s, p| { let cmd = "export.update"; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0cfdd1ffa..26418f238 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use base64::Engine as _; use figcraft_doc::{ - BOARD_PAGE, Document, ExportFormat, ExportSetting, ExportSize, FileKind, LineHeight, Node, NodeId, NodeKind, PrintSettings, StyleKind, TextStyle, - VdCompat, + BOARD_PAGE, Document, ExportColorProfile, ExportFormat, ExportSetting, ExportSize, FileKind, LineHeight, Node, NodeId, NodeKind, PrintSettings, + StyleKind, TextStyle, VdCompat, }; use figcraft_format::Version; use serde_json::{Value, json}; @@ -118,14 +118,14 @@ pub fn specs() -> Vec { spec!( "file.export", "Export", - "{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings))}", + "{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings)), colorProfile? (PNG, JPG and WebP: sameAsFile (default: the document's profile)|srgb|displayP3; colors convert, out-of-gamut ones clip; SVG, PDF and XML are always sRGB)}", false, export ), spec!( "file.exportLayers", "Export layers", - "{ids? (default the selection, else every layer on the page with export settings), assets? (true: the Inspect tab's assets in and under them instead: layers with export settings, icons as SVG, images as PNG), dir? (folder to write into; else each file comes back as base64 `data`), zip? (no dir: the files come back together as one base64 zip `data` instead), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options): for every PDF instead of each setting's own, vdCompat? (bestEffort|exact|ignore: for every XML instead of each setting's own)} every layer once per export setting, named `.` (\"@2x\" when a scaled export has no suffix; repeats get \" 2\"; slashes in a layer name make folders). Returns {files: [{name, id, bytes, path | data, warnings (XML only)}], skipped (layers without settings), data? (zip)}", + "{ids? (default the selection, else every layer on the page with export settings), assets? (true: the Inspect tab's assets in and under them instead: layers with export settings, icons as SVG, images as PNG), dir? (folder to write into; else each file comes back as base64 `data`), zip? (no dir: the files come back together as one base64 zip `data` instead), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options): for every PDF instead of each setting's own, vdCompat? (bestEffort|exact|ignore: for every XML instead of each setting's own), colorProfile? (sameAsFile|srgb|displayP3: for every PNG, JPG and WebP instead of each setting's own)} every layer once per export setting, named `.` (\"@2x\" when a scaled export has no suffix; repeats get \" 2\"; slashes in a layer name make folders). Returns {files: [{name, id, bytes, path | data, warnings (XML only)}], skipped (layers without settings), data? (zip)}", false, export_layers ), @@ -406,13 +406,25 @@ 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 pix = figcraft_render::render_area(doc, &drawn, area, scale) + let mut pix = figcraft_render::render_area(doc, &drawn, area, scale) .ok_or_else(|| EngineError::Other("render failed (empty or too large)".into()))?; - Ok((figcraft_render::encode_export(&pix, setting.format, doc.color_profile).map_err(EngineError::Other)?, Vec::new())) + // The render is in the document's profile; the setting's profile converts the pixels + // (out-of-gamut colors clip) and tags the file. + let profile = setting.color_profile.resolve(doc.color_profile); + doc.color_profile.conversion_to(profile).apply_pixels(pix.data_mut()); + Ok((figcraft_render::encode_export(&pix, setting.format, profile).map_err(EngineError::Other)?, Vec::new())) } } } +/// The `colorProfile` `p` passes: sameAsFile, srgb or displayP3 (anything else is an error). +fn color_profile_param(cmd: &str, p: &Value) -> Result> { + match get(p, "colorProfile") { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_str().and_then(ExportColorProfile::from_key).map(Some).ok_or_else(|| bad(cmd, "colorProfile: sameAsFile|srgb|displayP3")), + } +} + /// The `vdCompat` `p` passes: bestEffort, exact or ignore (anything else is an error). fn vd_compat_param(cmd: &str, p: &Value) -> Result> { match get(p, "vdCompat") { diff --git a/crates/engine/src/cmd/file/export.rs b/crates/engine/src/cmd/file/export.rs index 68e003d48..0dbd8c3b9 100644 --- a/crates/engine/src/cmd/file/export.rs +++ b/crates/engine/src/cmd/file/export.rs @@ -173,6 +173,9 @@ pub(in crate::cmd) fn export_setting(cmd: &str, mut e: ExportSetting, p: &Value) if let Some(c) = vd_compat_param(cmd, p)? { e.vd_compat = c; } + if let Some(c) = color_profile_param(cmd, p)? { + e.color_profile = c; + } e.print = print_param(cmd, p, e.print)?; for (key, slot) in [ ("contentsOnly", &mut e.contents_only), @@ -327,10 +330,16 @@ pub(super) fn export_layers(s: &mut Session, p: &Value) -> Result { let print = has_print_param(p).then(|| print_param(cmd, p, PrintSettings::default())).transpose()?; // And a compatibility mode for every Android Vector Drawable. let compat = vd_compat_param(cmd, p)?; + // And a color profile for every PNG, JPG and WebP. + let profile = color_profile_param(cmd, p)?; let mut files = Vec::with_capacity(jobs.len()); for job in &jobs { - let setting = - ExportSetting { print: print.unwrap_or(job.setting.print), vd_compat: compat.unwrap_or(job.setting.vd_compat), ..job.setting.clone() }; + let setting = ExportSetting { + print: print.unwrap_or(job.setting.print), + vd_compat: compat.unwrap_or(job.setting.vd_compat), + color_profile: profile.unwrap_or(job.setting.color_profile), + ..job.setting.clone() + }; let scale = export_scale(doc, &[job.id], &setting); let (bytes, warnings) = export_file(doc, &[job.id], &setting, scale)?; let mut f = json!({"name": job.file, "id": job.id, "bytes": bytes.len()}); diff --git a/crates/engine/src/export_profile_tests.rs b/crates/engine/src/export_profile_tests.rs new file mode 100644 index 000000000..5b12b2a03 --- /dev/null +++ b/crates/engine/src/export_profile_tests.rs @@ -0,0 +1,200 @@ +//! The color profile an export setting writes PNG, JPG and WebP files in: same as the file (the +//! default, following the document's profile when it exports), sRGB or Display P3, with the pixels +//! converted and the file tagged; stored per setting, kept across a format switch, passed to +//! export layers, ignored by the always-sRGB SVG, PDF and XML, and bad values refused. + +use base64::Engine as _; +use figcraft_color::{Color, ColorProfile}; +use figcraft_doc::*; +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; + +/// A session with a red 20 × 10 rectangle in an sRGB document. +fn session() -> (Session, NodeId) { + let mut s = Session::new(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 10, "name": "Red"})).unwrap()["id"]).unwrap(); + s.execute("fill.set", &json!({"ids": [r], "color": "#FF0000"})).unwrap(); + (s, r) +} + +fn bytes(v: &Value) -> Vec { + base64::engine::general_purpose::STANDARD.decode(v["data"].as_str().unwrap()).unwrap() +} + +fn export(s: &mut Session, params: Value) -> Vec { + bytes(&s.execute("file.export", ¶ms).unwrap()) +} + +/// Whether `bytes` holds a PNG chunk of `kind` (with `data`, when given). +fn has_chunk(bytes: &[u8], kind: &[u8; 4], data: Option<&[u8]>) -> bool { + bytes.windows(4).enumerate().any(|(i, w)| w == kind && data.is_none_or(|d| bytes.get(i + 4..i + 4 + d.len()) == Some(d))) +} + +/// An embedded ICC display profile (its device class). +fn has_icc(bytes: &[u8]) -> bool { + bytes.windows(4).any(|w| w == b"mntr") +} + +/// The middle pixel's RGB. +fn middle(bytes: &[u8]) -> [u8; 3] { + let img = image::load_from_memory(bytes).unwrap().to_rgba8(); + let [r, g, b, _] = img.get_pixel(img.width() / 2, img.height() / 2).0; + [r, g, b] +} + +/// `c` as 8-bit RGB. +fn rgb8(c: Color) -> [u8; 3] { + [c.r, c.g, c.b].map(|v| (v * 255.0).round() as u8) +} + +fn close(a: [u8; 3], b: [u8; 3], tolerance: u8) -> bool { + a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= tolerance) +} + +/// sRGB red in Display P3 values. +fn red_in_p3() -> [u8; 3] { + rgb8(ColorProfile::Srgb.conversion_to(ColorProfile::DisplayP3).apply(Color::new(1.0, 0.0, 0.0, 1.0))) +} + +#[test] +fn a_display_p3_png_from_an_srgb_file_is_converted_and_tagged() { + let (mut s, r) = session(); + let png = export(&mut s, json!({"ids": [r], "format": "png", "colorProfile": "displayP3"})); + assert!(has_chunk(&png, b"iCCP", None) && has_chunk(&png, b"cICP", Some(&[12, 13, 0, 1])) && !has_chunk(&png, b"sRGB", None)); + let want = red_in_p3(); + assert!(close(middle(&png), want, 1), "{:?} vs {want:?}", middle(&png)); + // The default stays the file's own sRGB. + let png = export(&mut s, json!({"ids": [r], "format": "png"})); + assert!(has_chunk(&png, b"sRGB", None) && !has_chunk(&png, b"iCCP", None)); + assert_eq!(middle(&png), [255, 0, 0]); + // The document is not changed by the export. + assert_eq!(s.doc().unwrap().color_profile, ColorProfile::Srgb); + assert_eq!(crate::paint_tests::fill(&s, r).to_hex(), "FF0000"); +} + +#[test] +fn an_srgb_export_of_a_display_p3_file_converts_back() { + let (mut s, r) = session(); + s.execute("file.colorProfile", &json!({"profile": "displayP3"})).unwrap(); + let same = export(&mut s, json!({"ids": [r], "format": "png"})); + assert!(has_chunk(&same, b"iCCP", None)); + assert!(close(middle(&same), red_in_p3(), 1), "{:?}", middle(&same)); + for p in ["srgb", "displayP3", "sameAsFile"] { + let png = export(&mut s, json!({"ids": [r], "format": "png", "colorProfile": p})); + assert_eq!(has_chunk(&png, b"sRGB", None), p == "srgb", "{p}"); + let want = if p == "srgb" { [255, 0, 0] } else { red_in_p3() }; + assert!(close(middle(&png), want, 1), "{p}: {:?} vs {want:?}", middle(&png)); + } + // A wide-gamut color clips in sRGB and keeps its values in Display P3. + s.execute("fill.set", &json!({"ids": [r], "color": "#00FF00"})).unwrap(); + let srgb = export(&mut s, json!({"ids": [r], "format": "png", "colorProfile": "srgb"})); + let p3 = export(&mut s, json!({"ids": [r], "format": "png", "colorProfile": "displayP3"})); + assert_eq!(middle(&p3), [0, 255, 0]); + let [red, green, blue] = middle(&srgb); + assert!(red == 0 && green == 255 && blue == 0, "P3 green clips to sRGB green: {:?}", middle(&srgb)); +} + +#[test] +fn jpg_and_webp_follow_the_setting() { + let (mut s, r) = session(); + for f in ["jpg", "webp"] { + // sRGB files stay untagged (read as sRGB); Display P3 files embed the generated profile. + assert!(!has_icc(&export(&mut s, json!({"ids": [r], "format": f}))), "{f}"); + let p3 = export(&mut s, json!({"ids": [r], "format": f, "colorProfile": "displayP3"})); + assert!(has_icc(&p3), "{f}"); + let want = red_in_p3(); + assert!(close(middle(&p3), want, 8), "{f}: {:?} vs {want:?}", middle(&p3)); + } + s.execute("file.colorProfile", &json!({"profile": "displayP3"})).unwrap(); + for f in ["jpg", "webp"] { + let srgb = export(&mut s, json!({"ids": [r], "format": f, "colorProfile": "srgb"})); + assert!(!has_icc(&srgb), "{f}"); + assert!(close(middle(&srgb), [255, 0, 0], 8), "{f}: {:?}", middle(&srgb)); + } +} + +#[test] +fn svg_pdf_and_xml_stay_srgb() { + let (mut s, r) = session(); + // A Display P3 file: its red converts back to sRGB #FF0000 whatever the setting says. + s.execute("file.colorProfile", &json!({"profile": "displayP3"})).unwrap(); + for p in ["displayP3", "sameAsFile", "srgb"] { + let svg = String::from_utf8(export(&mut s, json!({"ids": [r], "format": "svg", "colorProfile": p}))).unwrap().to_ascii_uppercase(); + assert!(svg.contains("#FF0000"), "{p}: {svg}"); + let xml = String::from_utf8(export(&mut s, json!({"ids": [r], "format": "xml", "colorProfile": p}))).unwrap().to_ascii_uppercase(); + assert!(xml.contains("#FF0000"), "{p}: {xml}"); + let pdf = export(&mut s, json!({"ids": [r], "format": "pdf", "colorProfile": p})); + assert!(pdf.starts_with(b"%PDF") && !has_icc(&pdf), "{p}"); + } +} + +#[test] +fn same_as_file_follows_the_document_and_a_choice_stays() { + let (mut s, r) = session(); + s.execute("export.add", &json!({"ids": [r]})).unwrap(); + s.execute("export.add", &json!({"ids": [r], "setting": {"suffix": "-srgb", "colorProfile": "srgb"}})).unwrap(); + s.execute("export.add", &json!({"ids": [r], "setting": {"suffix": "-p3", "colorProfile": "displayP3"}})).unwrap(); + let files = |s: &mut Session| -> Vec<(String, bool)> { + let v = s.execute("file.exportLayers", &json!({"ids": [r]})).unwrap(); + v["files"].as_array().unwrap().iter().map(|f| (f["name"].as_str().unwrap().to_string(), has_chunk(&bytes(f), b"iCCP", None))).collect() + }; + let names = |icc: [bool; 3]| -> Vec<(String, bool)> { + ["Red.png", "Red-srgb.png", "Red-p3.png"].into_iter().zip(icc).map(|(n, i)| (n.to_string(), i)).collect() + }; + assert_eq!(files(&mut s), names([false, false, true])); + s.execute("file.colorProfile", &json!({"profile": "displayP3"})).unwrap(); + assert_eq!(files(&mut s), names([true, false, true])); + // A profile passed to export layers stands in for every setting's own. + let v = s.execute("file.exportLayers", &json!({"ids": [r], "colorProfile": "srgb"})).unwrap(); + assert!(v["files"].as_array().unwrap().iter().all(|f| has_chunk(&bytes(f), b"sRGB", None)), "{v}"); +} + +#[test] +fn export_settings_keep_their_color_profile() { + let (mut s, r) = session(); + s.execute("export.add", &json!({"ids": [r], "setting": {"colorProfile": "displayP3"}})).unwrap(); + let e = s.doc().unwrap().node(r).unwrap().exports[0].clone(); + assert_eq!(e.color_profile, ExportColorProfile::DisplayP3); + // Stored camelCase, the default left out, and a row saved without it reads as same as file. + assert_eq!(serde_json::to_value(&e).unwrap()["colorProfile"], "displayP3"); + assert!(serde_json::to_value(ExportSetting::default()).unwrap().get("colorProfile").is_none()); + let old: ExportSetting = serde_json::from_value(json!({"size": {"by": "scale", "value": 2.0}, "suffix": "@2x", "format": "jpg"})).unwrap(); + assert_eq!(old.color_profile, ExportColorProfile::SameAsFile); + // Saved and loaded. + let saved = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap(); + let (back, _) = figcraft_format::load_bytes(&saved).unwrap(); + assert_eq!(back.node(r).unwrap().exports[0], e); + // Edited and undone; a format switch keeps it. + s.execute("export.update", &json!({"ids": [r], "index": 0, "colorProfile": "srgb"})).unwrap(); + assert_eq!(s.doc().unwrap().node(r).unwrap().exports[0].color_profile, ExportColorProfile::Srgb); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().node(r).unwrap().exports[0].color_profile, ExportColorProfile::DisplayP3); + for f in ["svg", "pdf", "png"] { + s.execute("export.update", &json!({"ids": [r], "index": 0, "format": f})).unwrap(); + assert_eq!(s.doc().unwrap().node(r).unwrap().exports[0].color_profile, ExportColorProfile::DisplayP3, "{f}"); + } + // `null` changes nothing. + s.execute("export.update", &json!({"ids": [r], "index": 0, "colorProfile": null})).unwrap(); + assert_eq!(s.doc().unwrap().node(r).unwrap().exports[0].color_profile, ExportColorProfile::DisplayP3); + for p in ExportColorProfile::ALL { + assert_eq!(ExportColorProfile::from_key(p.key()), Some(p)); + } +} + +#[test] +fn bad_color_profiles_are_refused_and_change_nothing() { + let (mut s, r) = session(); + s.execute("export.add", &json!({"ids": [r]})).unwrap(); + for junk in [json!("cmyk"), json!(3), json!(true), json!("SRGB"), json!({})] { + assert!(s.execute("file.export", &json!({"ids": [r], "colorProfile": junk})).is_err(), "{junk}"); + assert!(s.execute("export.update", &json!({"ids": [r], "index": 0, "colorProfile": junk})).is_err(), "{junk}"); + assert!(s.execute("export.add", &json!({"ids": [r], "setting": {"colorProfile": junk}})).is_err(), "{junk}"); + assert!(s.execute("file.exportLayers", &json!({"ids": [r], "colorProfile": junk})).is_err(), "{junk}"); + } + let n = s.doc().unwrap().node(r).unwrap(); + assert_eq!((n.exports.len(), n.exports[0].color_profile), (1, ExportColorProfile::SameAsFile)); + let err = s.execute("file.export", &json!({"ids": [r], "colorProfile": "p3"})).unwrap_err().to_string(); + assert!(err.contains("sameAsFile|srgb|displayP3"), "{err}"); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1c0b7e39a..a70cb5395 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -313,6 +313,8 @@ mod export_bench_tests; #[cfg(test)] mod export_depth_tests; #[cfg(test)] +mod export_profile_tests; +#[cfg(test)] mod extended_chain_tests; #[cfg(test)] mod eyedropper_create_tests; diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 1cb141b58..4e27809f1 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -262,7 +262,7 @@ fn tools() -> Vec { tool( "export", "Export", - "Export layers (default: the selection, else every top-level layer of the current page) as png, jpg, svg, webp, pdf or xml (an Android Vector Drawable, with `warnings` for what it changed or left out, per `vdCompat`) at `scale`, or the whole file as `fig` (experimental: written from public format knowledge, with `warnings` for what was left out; other apps may not open every file) (PDF: with `bleed`, `cropMarks`, `bleedMarks` and `cmyk` for print; options `contentsOnly`, `includeBoundingBox`, and for SVG `svgOutlineText`, `svgIdAttribute`, `svgSimplifyStroke`; for XML `svgIdAttribute` and `vdCompat`). With `path` the file is written there (absolute path recommended) and the result says where. Without `path`: png/jpg/webp come back as an image content block, svg as text, xml as text followed by `{format, warnings}`, other formats as base64 `data`.", + "Export layers (default: the selection, else every top-level layer of the current page) as png, jpg, svg, webp, pdf or xml (an Android Vector Drawable, with `warnings` for what it changed or left out, per `vdCompat`) at `scale`, or the whole file as `fig` (experimental: written from public format knowledge, with `warnings` for what was left out; other apps may not open every file) (PDF: with `bleed`, `cropMarks`, `bleedMarks` and `cmyk` for print; options `contentsOnly`, `includeBoundingBox`, and for SVG `svgOutlineText`, `svgIdAttribute`, `svgSimplifyStroke`; for XML `svgIdAttribute` and `vdCompat`; for png, jpg and webp `colorProfile`). With `path` the file is written there (absolute path recommended) and the result says where. Without `path`: png/jpg/webp come back as an image content block, svg as text, xml as text followed by `{format, warnings}`, other formats as base64 `data`.", obj( json!({ "ids": ids_schema("Layers to export (several are composited into one image)"), @@ -280,6 +280,7 @@ fn tools() -> Vec { "svgIdAttribute": boolean("SVG: layer names as unique `id` attributes (default false)"), "svgSimplifyStroke": boolean("SVG: strokes as `stroke` attributes where exact (default true); false writes outlines"), "vdCompat": {"type": "string", "enum": ["bestEffort", "exact", "ignore"], "description": "XML: what a Vector Drawable can't draw exactly is approximated with a warning (bestEffort, default), left out with a warning (exact), or written as far as it maps without warnings (ignore: overlapping layer opacity dropped, even-odd fills kept as fillType=evenOdd, diamond gradients left out)"}, + "colorProfile": {"type": "string", "enum": ["sameAsFile", "srgb", "displayP3"], "description": "PNG, JPG and WebP: the color profile of the file (default sameAsFile: the document's); colors are converted and out-of-gamut ones clip. SVG, PDF and XML are always sRGB"}, }), &[], ), @@ -1059,6 +1060,7 @@ fn export(b: &mut dyn Backend, a: &Map) -> Result Vec { + let r = c.call("export", args); + assert_eq!(r["isError"], false, "{r}"); + let image = r["content"].as_array().unwrap().iter().find(|block| block["type"] == "image").unwrap(); + base64::engine::general_purpose::STANDARD.decode(image["data"].as_str().unwrap()).unwrap() +} + +fn has_chunk(bytes: &[u8], kind: &[u8; 4]) -> bool { + bytes.windows(4).any(|w| w == kind) +} + +#[test] +fn color_profile_tags_the_png() { + let mut c = Client::new(); + let id = c.create(json!({"type": "rectangle", "x": 0, "y": 0, "width": 24, "height": 16})); + let srgb = png(&mut c, json!({"ids": [id], "format": "png"})); + assert!(has_chunk(&srgb, b"sRGB") && !has_chunk(&srgb, b"iCCP")); + let p3 = png(&mut c, json!({"ids": [id], "format": "png", "colorProfile": "displayP3"})); + assert!(has_chunk(&p3, b"iCCP") && has_chunk(&p3, b"cICP") && !has_chunk(&p3, b"sRGB")); + assert!(c.err("export", json!({"ids": [id], "format": "png", "colorProfile": "cmyk"})).contains("colorProfile")); +} diff --git a/crates/mcp/tests/it/main.rs b/crates/mcp/tests/it/main.rs index 862f46064..7d5195fe7 100644 --- a/crates/mcp/tests/it/main.rs +++ b/crates/mcp/tests/it/main.rs @@ -13,6 +13,8 @@ mod common; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod export_hidden_roots; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod export_profile; +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod export_xml; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod garbage; diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index ba567dd81..808f3c69c 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1292,6 +1292,7 @@ name = "English" "See all templates" = "See all templates" "Select layers and they space themselves as their content changes" = "Select layers and they space themselves as their content changes" "SHA-256: {sha}…" = "SHA-256: {sha}…" +"Same as file ({profile})" = "Same as file ({profile})" "Same as layer" = "Same as layer" "Saturation" = "Saturation" "Save" = "Save" diff --git a/crates/ui-egui/src/export_preview_tests.rs b/crates/ui-egui/src/export_preview_tests.rs index ca1234cfe..a3f4f88e6 100644 --- a/crates/ui-egui/src/export_preview_tests.rs +++ b/crates/ui-egui/src/export_preview_tests.rs @@ -181,3 +181,35 @@ fn advanced_options_offer_the_bounding_box_for_text_layers() { assert!(shown.iter().any(|s| s == "Include bounding box"), "a rectangle that has it on shows it: {shown:?}"); assert!(u.app.session.doc().unwrap().node(r).unwrap().exports[0].include_bounding_box, "the setting is kept"); } + +/// The advanced options of a PNG, JPG or WebP setting list its color profile: same as the file +/// (naming the document's profile), sRGB or Display P3. SVG, PDF and XML settings list none. +#[test] +fn advanced_options_offer_a_color_profile_for_images() { + let mut s = Session::new(); + let r = crate::present_tests::id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 80})).unwrap()); + s.execute("export.add", &json!({"ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let mut u = crate::layers_drag_tests::Ui::new(s); + let options = |u: &mut crate::layers_drag_tests::Ui| { + u.frame(vec![]); + egui::Popup::open_id(&u.ctx, egui::Id::unique(("export_more", 0))); + u.frame(vec![]); + crate::import_report_tests::shown_texts(u.frame_output(vec![]).shapes) + }; + for f in ["png", "jpg", "webp"] { + u.app.run("export.update", json!({"ids": [r], "index": 0, "format": f})); + let shown = options(&mut u); + for label in ["Color profile", "Same as file (sRGB)", "sRGB", "Display P3"] { + assert!(shown.iter().any(|s| s == label), "{f}: no {label:?} in {shown:?}"); + } + } + u.app.run("file.colorProfile", json!({"profile": "displayP3"})); + let shown = options(&mut u); + assert!(shown.iter().any(|s| s == "Same as file (Display P3)"), "{shown:?}"); + for f in ["svg", "pdf", "xml"] { + u.app.run("export.update", json!({"ids": [r], "index": 0, "format": f})); + let shown = options(&mut u); + assert!(!shown.iter().any(|s| s == "Color profile" || s.starts_with("Same as file")), "{f}: {shown:?}"); + } +} diff --git a/crates/ui-egui/src/panels/export_panel.rs b/crates/ui-egui/src/panels/export_panel.rs index 14b5a8904..3ae900956 100644 --- a/crates/ui-egui/src/panels/export_panel.rs +++ b/crates/ui-egui/src/panels/export_panel.rs @@ -7,7 +7,8 @@ use std::collections::BTreeSet; use std::sync::Arc; use egui::{Align2, Color32, CornerRadius, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; -use figcraft_doc::{Document, ExportFormat, ExportSetting, ExportSize, NodeId, NodeKind, PrintSettings, VdCompat}; +use figcraft_doc::color::ColorProfile; +use figcraft_doc::{Document, ExportColorProfile, ExportFormat, ExportSetting, ExportSize, NodeId, NodeKind, PrintSettings, VdCompat}; use figcraft_engine::cmd::file::export_jobs; use serde_json::{Value, json}; @@ -69,7 +70,7 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, sel: &[NodeId widgets::note(ui, tr("Click + to replace mixed content"), t.text_secondary); } for (i, e) in list.iter().enumerate() { - setting_row(app, ui, &ids, i, e, text); + setting_row(app, ui, &ids, i, e, text, doc.color_profile); } let Some(first) = first else { return }; preview(app, ui, doc, first); @@ -84,8 +85,8 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, sel: &[NodeId /// One export setting: size (typed or picked; images only, SVG and PDF are vector), suffix, /// format, advanced options and remove; a PDF's print settings under it. `text`: every layer in -/// `ids` is a text layer. -fn setting_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, e: &ExportSetting, text: bool) { +/// `ids` is a text layer; `file`: the document's color profile. +fn setting_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, e: &ExportSetting, text: bool, file: ColorProfile) { row(ui, 32.0, |ui| { // Tighter spacing so the advanced options and remove buttons fit beside the fields. ui.spacing_mut().item_spacing.x = 4.0; @@ -129,7 +130,7 @@ fn setting_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, e: &Expo .width(216.0) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { - if let Some(mut params) = advanced_options(ui, e, text) { + if let Some(mut params) = advanced_options(ui, e, text, file) { params["ids"] = json!(ids); params["index"] = json!(i); app.run("export.update", params); @@ -161,8 +162,9 @@ const VD_COMPAT: [(VdCompat, &str); 3] = /// A setting's advanced options: ignore overlapping layers (`contentsOnly`), include bounding box /// for text layers (and for any setting that has it on, so it can be turned off); for SVG outline /// text, the id attribute and simplified strokes; for XML (Android Vector Drawable) the id attribute -/// (as `android:name`) and the compatibility mode. Returns the changed option as command params. -fn advanced_options(ui: &mut Ui, e: &ExportSetting, text: bool) -> Option { +/// (as `android:name`) and the compatibility mode; for PNG, JPG and WebP the color profile (`file` +/// is the document's). Returns the changed option as command params. +fn advanced_options(ui: &mut Ui, e: &ExportSetting, text: bool, file: ColorProfile) -> Option { let mut out = None; let mut option = |ui: &mut Ui, key: &str, on: bool, label: &str| { if widgets::checkbox(ui, on, label) { @@ -189,9 +191,28 @@ fn advanced_options(ui: &mut Ui, e: &ExportSetting, text: bool) -> Option } } } + if e.format.is_raster() { + ui.add_space(4.0); + widgets::label(ui, tr("Color profile"), Tokens::get(ui.ctx()).text_secondary); + for p in ExportColorProfile::ALL { + let on = e.color_profile == p; + if widgets::radio(ui, on, &color_profile_label(p, file)) && !on { + out = Some(json!({"colorProfile": p.key()})); + } + } + } out } +/// How the advanced options name an export color profile: "Same as file (Display P3)" names the +/// profile of `file`, the document's. +fn color_profile_label(p: ExportColorProfile, file: ColorProfile) -> String { + match p { + ExportColorProfile::SameAsFile => trf("Same as file ({profile})", &[("profile", &file.label())]), + p => p.resolve(file).label().to_string(), + } +} + /// A PDF setting's print settings: a summary row that opens them. fn print_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &PrintSettings) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/ui_params_tests.rs b/crates/ui-egui/src/ui_params_tests.rs index 6ee71dfc9..7a889a2ba 100644 --- a/crates/ui-egui/src/ui_params_tests.rs +++ b/crates/ui-egui/src/ui_params_tests.rs @@ -1,7 +1,7 @@ //! Params the panels build at run time name only what their commands take: a name a command //! doesn't list is refused (#1413), which would break the control that sent it. -use figcraft_doc::{ExportFormat, ExportSetting, NodeId, PrintSettings, VdCompat}; +use figcraft_doc::{ExportColorProfile, ExportFormat, ExportSetting, NodeId, PrintSettings, VdCompat}; use figcraft_engine::Session; use serde_json::{Value, json}; @@ -30,6 +30,7 @@ fn export_settings_with_every_option_are_taken() { svg_id_attribute: true, svg_simplify_stroke: false, vd_compat: VdCompat::Exact, + color_profile: ExportColorProfile::DisplayP3, ..ExportSetting::default() }; let mut p = crate::export_panel::setting_params(&setting); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 50805f39e..dc28e2959 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-10-31 · **Change:** minor (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-10-31 · **Change:** minor (a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; 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 @@ -53,11 +53,11 @@ export limit, not a native document nesting limit. | Format | Figma | FigCraft | Notes | Hours | |---|---|---|---|---| -| PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels | — | -| JPG | yes | yes | white where transparent; fixed quality (90) | — | +| PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels; a color profile per setting (Same as file, the default, sRGB or Display P3: `colorProfile`), the pixels converted and the file tagged (`sRGB` chunk, or ICC and `cICP`) | — | +| JPG | yes | yes | white where transparent; fixed quality (90); a color profile per setting as for PNG (sRGB untagged, Display P3 with its ICC profile) | — | | SVG | yes (outline text option, ids) | yes | alpha/luminance masks kept; noise, texture, progressive and background blur, glass embedded as images; outline text (off: `` with one `` per line, one style per layer), unique id attributes from layer names, explicit depth-limit refusal, nested frames clipped by their parent's clip (#327), simplified strokes (stroke attributes for centred strokes and for inside and outside strokes on boxes and ellipses) | — | -| PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal | CMYK output intent 2–4 | -| WebP | — | yes (ours) | | — | +| PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal; RGB is always sRGB (no color profile setting and no output intent) | CMYK output intent 2–4 | +| WebP | — | yes (ours) | a color profile per setting as for JPG | — | | Android Vector Drawable (XML) | — | yes (ours) | an `.xml` drawable resource (`file.export {format: "xml"}`, export settings, File ▸ Export…, the CLI and MCP), pretty-printed, sized in dp with the viewport in layer units, for AndroidX (VectorDrawableCompat: gradients and even-odd need API 24 without it). Shapes, booleans and text as path data with transforms baked in; solid fills and linear, radial and sweep gradients (`aapt:attr`, exact for any handles: radial and sweep in a `` that maps the unit circle); centred strokes as stroke attributes where Android draws them the same (uniform scale, one cap, no dashes or variable width), other strokes as filled outlines; clipping frames and masks as `` with ``; `android:name` from layer names with the id attribute option. What the format can't hold goes by the compatibility mode (`vdCompat`): best effort (default) applies layer opacity to each shape, rewrites even-odd fills and clip outlines as non-zero, draws diamond gradients as radial and alpha masks as outline clips, each with a warning; exact leaves out what it can't draw exactly, with a warning; ignore writes what maps without warnings: layer opacity over overlapping shapes is dropped (drawn opaque), even-odd fills keep `fillType="evenOdd"`, even-odd clip outlines clip as non-zero, diamond gradients are left out and alpha masks clip to their outline. Effects, image and pattern fills and blend modes are always left out (warned except in ignore); an export that draws nothing writes one empty path (Android refuses a drawable without a path), with a warning. Checked by parsing the XML, against FigCraft's renderer (gradients pixel by pixel), with `aapt2 compile` and `link`, and by rendering samples (linear, skewed radial and sweep gradients, a sweep with mirrored handles, even-odd booleans, centred and inside strokes, rotated text, a clipping frame, an alpha mask, a translucent group, each compatibility mode) with Android 13's (API 33) VectorDrawable on an emulator, next to FigCraft's PNG export: they match, including where the sweep starts and which way it turns, except what the compatibility mode and its warnings say (best effort: overlapping shapes in a translucent group look denser; exact and ignore leave out or draw opaque what they list). Not checked on API 21–23 (VectorDrawableCompat) | — | | Copy as CSS / SVG / PNG / text / link | yes | yes | Copy as PNG: the whole selection at 2x | — | | Dev Mode code (CSS, iOS SwiftUI, Android Compose) | yes | yes, plus HTML, React, Vue, Leptos, ArkUI and Flutter | see [dev-mode-parity](dev-mode-parity.md) | — | @@ -187,6 +187,7 @@ source paint coordinates. | Date | Change | Summary | |---|---|---| +| 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. 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 | | 2026-10-31 | patch | M4: Dash and Custom strokes have a Dash cap (None, Round, Square) in the advanced stroke settings and `node.set {dashCap}`, on both ends of every dash on the canvas and in PNG, PDF and SVG. Unset, dashes keep taking the end point caps, so older files look the same; the saved file writes it only when set. Numbers unchanged | | 2026-10-30 | minor | `.fig` import: a connector's label without a saved snapshot was skipped; now the connector imports as a frame holding its line and the label, as a connector with a saved snapshot does, the label centred on the line's middle by length (in a 200-wide box, laid out again with the fonts at hand), in the connector's fill paints or black. Its background isn't known without the snapshot and is left out. Not checked on real files. Test: `fig::tests::tail::a_labelled_connector_without_a_snapshot_keeps_its_label` | | 2026-10-30 | minor | Pasted content row: an image the clipboard doesn't carry keeps its name and shows a placeholder that reads as missing; the paste names those layers in its message and opens the import report with its notes (#1646). Numbers unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index 0e9f4f497..9cd36559d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -373,7 +373,7 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match. | `inspect_document {depth, allPages, fields?, outline?}` | The document as JSON (its `id`, layer tree, styles, selection, history); `fields` selects layer properties, `outline: true` gives a compact tree (below). The tools that act on a document also take `document` (see Naming the document below). | | `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. | | `select {ids}` | Replace the selection (`[]` deselects). | -| `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?}` | png, jpg, svg, webp, pdf, xml (an Android Vector Drawable: `svgIdAttribute` writes `android:name`, `vdCompat` is `bestEffort` (default: approximated with a warning), `exact` (left out with a warning) or `ignore` (no warnings: overlapping layer opacity dropped, even-odd fills kept as `fillType="evenOdd"`, diamond gradients left out), and the result lists `warnings` for what was changed or left out), or `fig`: the whole file as `.fig`, experimental (see Exporting `.fig` files below); `size` is `2x`, `512w` or `512h`. The image covers what the layers paint (shadows towards their offset, strokes, unclipped children, a mask group's mask; hidden layers take no room; a slice is its area with everything under it, or only the frame or group it sits in while `contentsOnly` is on); `contentsOnly: false` also draws every other layer showing in that area, `includeBoundingBox` exports the layers' own boxes; SVG: `svgOutlineText: false` keeps ``, `svgIdAttribute` writes unique ids from layer names, `svgSimplifyStroke: false` writes every stroke as an outline. The same options go in export settings (`export.add` / `export.update`). PDF: frames one page each (sized in points), anything else together on one page; print options: `bleed` (points or a length like `"3mm"`, `"0.125in"`), crop and bleed marks, CMYK colour (see Exports below), also taken by `file.export`, `file.exportLayers`, `file.exportFramesPdf` and stored per export setting by `export.add` / `export.update`; `run_command` `file.exportFramesPdf {page?, path?}` writes every top-level frame of a page. Without `path`, images come back as MCP image content, SVG as text, XML as text followed by `{format, bytes, warnings}`. Layers' own export settings: `run_command` with `export.add` / `export.update {index, size?, suffix?, format?}` / `export.remove` and `file.exportLayers {ids?, dir?, assets?}` (every layer once per setting, named `.`, a slash in a layer name making a folder; `assets: true` exports the Inspect tab's assets instead: icons as SVG, images as PNG). | +| `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?, colorProfile?}` | png, jpg, svg, webp, pdf, xml (an Android Vector Drawable: `svgIdAttribute` writes `android:name`, `vdCompat` is `bestEffort` (default: approximated with a warning), `exact` (left out with a warning) or `ignore` (no warnings: overlapping layer opacity dropped, even-odd fills kept as `fillType="evenOdd"`, diamond gradients left out), and the result lists `warnings` for what was changed or left out), or `fig`: the whole file as `.fig`, experimental (see Exporting `.fig` files below); `size` is `2x`, `512w` or `512h`. The image covers what the layers paint (shadows towards their offset, strokes, unclipped children, a mask group's mask; hidden layers take no room; a slice is its area with everything under it, or only the frame or group it sits in while `contentsOnly` is on); `contentsOnly: false` also draws every other layer showing in that area, `includeBoundingBox` exports the layers' own boxes; SVG: `svgOutlineText: false` keeps ``, `svgIdAttribute` writes unique ids from layer names, `svgSimplifyStroke: false` writes every stroke as an outline; png, jpg and webp: `colorProfile` is `sameAsFile` (default: the document's profile), `srgb` or `displayP3`, the pixels converted (out-of-gamut colors clip) and the file tagged for it (SVG, PDF and XML are always sRGB). The same options go in export settings (`export.add` / `export.update`). PDF: frames one page each (sized in points), anything else together on one page; print options: `bleed` (points or a length like `"3mm"`, `"0.125in"`), crop and bleed marks, CMYK colour (see Exports below), also taken by `file.export`, `file.exportLayers`, `file.exportFramesPdf` and stored per export setting by `export.add` / `export.update`; `run_command` `file.exportFramesPdf {page?, path?}` writes every top-level frame of a page. Without `path`, images come back as MCP image content, SVG as text, XML as text followed by `{format, bytes, warnings}`. Layers' own export settings: `run_command` with `export.add` / `export.update {index, size?, suffix?, format?}` / `export.remove` and `file.exportLayers {ids?, dir?, assets?}` (every layer once per setting, named `.`, a slash in a layer name making a folder; `assets: true` exports the Inspect tab's assets instead: icons as SVG, images as PNG). | | `screenshot {ids?, scale?, maxSize?, window?}` | PNG of the page (with background) or of layers, scaled to fit `maxSize` (default 1600). `window: true` captures the app window in front when attached, a window id (see Windows below) that window. | | `open_file {path, variables?, reload?}` / `save_file {path?}` | Open `.figcraft`, `.json` (FigCraft JSON or REST API file JSON with its variables, see below), `.fig` or FigJam `.jam` (best effort, see below), `.sketch` (Sketch 48 and newer, best effort), `.svg` (see Importing SVG below) or an image; save as `.figcraft`. `open_file` returns `opened` (for a file opened anew, a `summary` of `name`, `pages`, `layers` and `images`, and `warnings` or `repairs`; a file that was already open gives its `index`, with `stale: true` when the file changed on disk since that tab read or saved it; `reload: true` reads it again into the tab, refused while the tab has unsaved changes) and the document's `document` outline. | | `undo` / `redo` | Step through history. | From b8fa8b87bec8b3894d1a5fe661b62cd9b183c940 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:20:20 -0700 Subject: [PATCH 011/326] Export: a converted JPG flattens translucent pixels before the conversion A JPG exported in a profile other than the document's was converted while still translucent and then composited over white, so translucent fills, shadows and antialiased edges came out a few levels off what the document shows. The render is now flattened over white in the document's profile first. PNG and WebP keep their alpha and are unchanged. --- crates/engine/src/cmd/file.rs | 14 +++++++++++++- crates/engine/src/export_profile_tests.rs | 13 +++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 26418f238..f9453cf51 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -411,7 +411,19 @@ pub fn export_file(doc: &Document, ids: &[NodeId], setting: &ExportSetting, scal // The render is in the document's profile; the setting's profile converts the pixels // (out-of-gamut colors clip) and tags the file. let profile = setting.color_profile.resolve(doc.color_profile); - doc.color_profile.conversion_to(profile).apply_pixels(pix.data_mut()); + let conversion = doc.color_profile.conversion_to(profile); + // JPG has no alpha: the render is flattened over white in the document's profile + // before the conversion, so translucent pixels match what the document shows. + if setting.format == ExportFormat::Jpg && !conversion.is_identity() { + for [r, g, b, a] in pix.data_mut().as_chunks_mut::<4>().0.iter_mut() { + let under = 255 - *a; + *r = r.saturating_add(under); + *g = g.saturating_add(under); + *b = b.saturating_add(under); + *a = 255; + } + } + conversion.apply_pixels(pix.data_mut()); Ok((figcraft_render::encode_export(&pix, setting.format, profile).map_err(EngineError::Other)?, Vec::new())) } } diff --git a/crates/engine/src/export_profile_tests.rs b/crates/engine/src/export_profile_tests.rs index 5b12b2a03..016aa7dae 100644 --- a/crates/engine/src/export_profile_tests.rs +++ b/crates/engine/src/export_profile_tests.rs @@ -115,6 +115,19 @@ fn jpg_and_webp_follow_the_setting() { } } +#[test] +fn a_translucent_jpg_is_flattened_before_its_conversion() { + let (mut s, r) = session(); + s.execute("fill.set", &json!({"ids": [r], "opacity": 0.5})).unwrap(); + // The sRGB document shows 50% red over white; the Display P3 JPG holds that color converted. + let flat = export(&mut s, json!({"ids": [r], "format": "jpg", "colorProfile": "srgb"})); + let [fr, fg, fb] = middle(&flat); + let shown = Color::new(f32::from(fr) / 255.0, f32::from(fg) / 255.0, f32::from(fb) / 255.0, 1.0); + let want = rgb8(ColorProfile::Srgb.conversion_to(ColorProfile::DisplayP3).apply(shown)); + let p3 = export(&mut s, json!({"ids": [r], "format": "jpg", "colorProfile": "displayP3"})); + assert!(close(middle(&p3), want, 2), "{:?} vs {want:?} (sRGB {:?})", middle(&p3), [fr, fg, fb]); +} + #[test] fn svg_pdf_and_xml_stay_srgb() { let (mut s, r) = session(); From 099cc0375455a63803b49739183583163ef36bf9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:21:43 -0700 Subject: [PATCH 012/326] Vector: simplify, offset and Penpot export keep a closed vector's smoothed corners vector.simplify and vector.offset rebuild a closed vector from its rounded outline with the layer's corner smoothing, as the canvas draws it. A vector whose regions have paints of their own was rebuilt from its sharp points before; it now keeps its rounded corners. The Penpot export writes a stroked vector's path with its smoothed corners. --- crates/engine/src/cmd/structure.rs | 13 ++++--- crates/engine/src/vector_behaviour_tests.rs | 39 +++++++++++++++++++++ crates/format/src/penpot/export.rs | 4 ++- crates/format/src/penpot/export_tests.rs | 26 ++++++++++++++ 4 files changed, 77 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index 52b4a415d..5a79d0a24 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -751,8 +751,11 @@ fn simplify(s: &mut Session, p: &Value) -> Result { for i in req_targets("vector.simplify", s, p)? { let doc = s.doc_mut()?; let n = doc.get_mut(i)?; + let smoothing = n.corners.smoothing; if let NodeKind::Vector { network } = &mut n.kind { let source = network.clone(); + // The regions as the layer draws them: rounded points with the layer's corner smoothing. + let drawn = figcraft_doc::geometry::drawn_network(&source, smoothing); let mut net = VectorNetwork::default(); let legacy = source.regions.iter().all(|region| region.fills.is_none() && region.paint_space.is_none()); if legacy && !source.regions.is_empty() { @@ -761,7 +764,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { } else { WindingRule::NonZero }; - let path = source.fill_path(); + let path = drawn.fill_path(); let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default()); let (path, output_winding) = match figcraft_pathops::simplify_with_rule(&path, winding == WindingRule::EvenOdd) { Ok(path) => (path, WindingRule::EvenOdd), @@ -771,7 +774,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { append_region_path(&mut net, &path, &combined, output_winding); } else { for (index, region) in source.regions.iter().enumerate() { - let Some(path) = source.region_path(index) else { continue }; + let Some(path) = drawn.region_path(index) else { continue }; let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default()); let path = figcraft_pathops::simplify_with_rule(&path, region.winding == WindingRule::EvenOdd).unwrap_or(path); append_region_path(&mut net, &path, region, region.winding); @@ -859,8 +862,10 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { nm.height = bb.height(); continue; } + // The regions as the layer draws them: rounded points with the layer's corner smoothing. + let drawn = figcraft_doc::geometry::drawn_network(source, n.corners.smoothing); if legacy { - let path = source.fill_path(); + let path = drawn.fill_path(); let even_odd = source.regions.iter().any(|region| region.winding == WindingRule::EvenOdd); let path = figcraft_pathops::simplify_with_rule(&path, even_odd).map_err(|error| bad("vector.offset", error.to_string()))?; let ring = figcraft_pathops::stroke_center(&path, d.abs() * 2.0, &props); @@ -880,7 +885,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { append_network(&mut net, part); } else { for (index, region) in source.regions.iter().enumerate() { - let Some(path) = source.region_path(index) else { continue }; + let Some(path) = drawn.region_path(index) else { continue }; let mut paint_region = region.clone(); let (paint_width, paint_height, paint_transform) = region.paint_frame(n.width, n.height); paint_region.paint_space = Some(RegionPaintSpace { width: paint_width, height: paint_height, transform: paint_transform }); diff --git a/crates/engine/src/vector_behaviour_tests.rs b/crates/engine/src/vector_behaviour_tests.rs index 83e585ea0..c990ad348 100644 --- a/crates/engine/src/vector_behaviour_tests.rs +++ b/crates/engine/src/vector_behaviour_tests.rs @@ -278,6 +278,45 @@ fn legacy_evenodd_holes_survive_bucket_offset_and_flatten() { assert!(!net(&s, flattened).fill_contains(Point::new(100.0, 100.0)), "flatten retains the even-odd hole"); } +#[test] +fn simplify_and_offset_keep_a_closed_vectors_smoothed_corners() { + // A closed 100 × 100 vector with radius 20 on every point and corner smoothing 0.6 draws a + // smoothed rectangle's outline; simplify and offset rebuild it from that outline. + let drawn = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6); + let plain = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.0).area().abs(); + let (area, d) = (drawn.area().abs(), 2.0); + // Offsetting a convex outline by d adds its perimeter times d and a circle of radius d. + let grown = area + drawn.perimeter(1e-6) * d + std::f64::consts::PI * d * d; + assert!((area - plain).abs() > 10.0, "smoothing changes the outline: {area} vs {plain}"); + // (command, params, region paints of its own, expected area, tolerance: the offset ring is + // flattened before the union) + let rows = [ + ("vector.simplify", json!({"tolerance": 0.01}), false, area, 1.0), + ("vector.simplify", json!({"tolerance": 0.01}), true, area, 1.0), + ("vector.offset", json!({"offset": d}), false, grown, 4.0), + ("vector.offset", json!({"offset": d}), true, grown, 4.0), + ]; + let mut wrong = Vec::new(); + for (cmd, mut params, painted, expected, tolerance) in rows { + let mut s = Session::new(); + let id = id_of(&ex(&mut s, "vector.create", json!({"points": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true}))["id"]).unwrap(); + ex(&mut s, "node.set", json!({"ids": [id], "props": {"cornerRadius": 20}})); + ex(&mut s, "node.set", json!({"ids": [id], "props": {"cornerSmoothing": 0.6}})); + if painted { + let doc = s.doc_mut().unwrap(); + let NodeKind::Vector { network } = &mut doc.get_mut(id).unwrap().kind else { panic!("expected vector fixture") }; + network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]); + } + params["ids"] = json!([id]); + ex(&mut s, cmd, params); + let got = net(&s, id).fill_path().area().abs(); + if (got - expected).abs() >= tolerance { + wrong.push(format!("{cmd} (region paints: {painted}): {got} vs {expected}")); + } + } + assert!(wrong.is_empty(), "simplify and offset keep the smoothed corners: {wrong:?}"); +} + /// Give vector `id` a painted region, converting a plain shape to a vector first. fn ex_to_vector(doc: &mut figcraft_doc::Document, id: NodeId) { let n = doc.get(id).unwrap(); diff --git a/crates/format/src/penpot/export.rs b/crates/format/src/penpot/export.rs index cacafd0d9..d0b9d3046 100644 --- a/crates/format/src/penpot/export.rs +++ b/crates/format/src/penpot/export.rs @@ -713,7 +713,9 @@ impl<'a> Exporter<'a> { } } } - NodeKind::Vector { network } if node.fills.is_empty() || !node.strokes.is_empty() => self.doc.world_transform(id) * network.stroke_path(), + NodeKind::Vector { network } if node.fills.is_empty() || !node.strokes.is_empty() => { + self.doc.world_transform(id) * figcraft_doc::geometry::drawn_network(network, node.corners.smoothing).stroke_path() + } _ => match figcraft_doc::geometry::shape_path(node) { Some(p) => self.doc.world_transform(id) * p, None => BezPath::new(), diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index 4dacd4eae..1e9e95638 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -174,6 +174,32 @@ fn rectangles_ellipses_and_paths_keep_their_geometry() { assert!(matches!(back.node(named(&back, "Circle")).unwrap().kind, NodeKind::Ellipse { .. })); } +#[test] +fn stroked_closed_vectors_are_written_with_their_corner_smoothing() { + // A stroked closed 100 × 100 vector with radius 20 on every point and corner smoothing 0.6 is + // written as the smoothed outline it draws. + let mut doc = Document::new("Smoothed vector"); + let p = page(&doc); + let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + let mut network = VectorNetwork::from_points(&corners, true); + for v in &mut network.vertices { + v.radius = 20.0; + } + let id = add(&mut doc, p, NodeKind::Vector { network }, "Smoothed", 0.0, 0.0, 100.0, 100.0); + { + let n = doc.node_mut(id).unwrap(); + n.fills = vec![Paint::solid(Color::BLACK)]; + n.strokes = vec![Paint::solid(Color::BLACK)]; + n.corners.smoothing = 0.6; + } + let want = figcraft_doc::geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6).area().abs(); + let plain = figcraft_doc::geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.0).area().abs(); + assert!((want - plain).abs() > 10.0, "smoothing changes the outline: {want} vs {plain}"); + let (back, _, _) = roundtrip(&doc); + let written = figcraft_doc::geometry::shape_path(back.node(named(&back, "Smoothed")).unwrap()).unwrap().area().abs(); + assert!((written - want).abs() < 0.5, "the written path keeps the smoothed corners: {written} vs {want}"); +} + #[test] fn fills_and_strokes_keep_their_order_and_styles() { let mut doc = Document::new("Paints"); From 0e6fcf9bf7dfea9ceff487b0b2682a0960924bb6 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:03:45 +0100 Subject: [PATCH 013/326] Make undo while drawing with the pen remove only the last anchor Fixes #1745 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/canvas/tools.rs | 2 + crates/engine/src/canvas/tools/pen.rs | 37 ++++++++++++++ crates/engine/src/lib.rs | 2 + crates/engine/src/pen_undo_tests.rs | 70 +++++++++++++++++++++++++++ crates/engine/src/session/undo.rs | 8 +++ 5 files changed, 119 insertions(+) create mode 100644 crates/engine/src/pen_undo_tests.rs diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index c68276fd3..591096b36 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -544,6 +544,8 @@ pub struct PenPath { pub closed: bool, /// The path ends connected to this anchor of its own (a vector network). pub join: Option, + /// Anchors taken back by undo, the last one first to come back on redo. + pub undone: Vec<(Point, Vec2, Vec2)>, } #[derive(Clone, Debug, Default)] diff --git a/crates/engine/src/canvas/tools/pen.rs b/crates/engine/src/canvas/tools/pen.rs index d519bc580..b726c3232 100644 --- a/crates/engine/src/canvas/tools/pen.rs +++ b/crates/engine/src/canvas/tools/pen.rs @@ -118,10 +118,47 @@ impl Session { p = at_45_degrees(*last, p); } pen.points.push((p, Vec2::ZERO, Vec2::ZERO)); + pen.undone.clear(); self.tool.gesture = Gesture::PenDrag { anchor: p }; self.pen_update() } + /// Undo while the pen draws (#1745): its last anchor goes (before two anchors, with the layer + /// they made; with the only one, the whole path). Returns whether there was a path. + pub(crate) fn pen_undo(&mut self) -> Result { + let Some(pen) = self.tool.pen.as_mut() else { return Ok(false) }; + let Some(last) = pen.points.pop() else { + self.tool.pen = None; + return Ok(false); + }; + pen.undone.push(last); + let drop_layer = pen.points.len() < 2 && pen.id.take().is_some(); + let empty = pen.points.is_empty(); + self.tool.gesture = Gesture::None; + self.tool.overlay.rubber = None; + self.tool.overlay.rubber_handle = None; + if drop_layer { + self.cancel_interaction()?; + } + if empty { + self.pen_finish()?; + return Ok(true); + } + self.pen_update()?; + Ok(true) + } + + /// Redo while the pen draws: the last anchor undo took back returns. Returns whether there was + /// one. + pub(crate) fn pen_redo(&mut self) -> Result { + let Some(pen) = self.tool.pen.as_mut() else { return Ok(false) }; + let Some(point) = pen.undone.pop() else { return Ok(false) }; + pen.points.push(point); + self.tool.gesture = Gesture::None; + self.pen_update()?; + Ok(true) + } + /// Rebuild the pen's vector node from its anchors. pub(super) fn pen_update(&mut self) -> Result<()> { let Some(pen) = self.tool.pen.clone() else { return Ok(()) }; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1c0b7e39a..a1ceeeb2f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -457,6 +457,8 @@ mod pen_end_tests; #[cfg(test)] mod pen_overlay_tests; #[cfg(test)] +mod pen_undo_tests; +#[cfg(test)] mod pen_vector_edit_tests; #[cfg(test)] mod penpot_export_tests; diff --git a/crates/engine/src/pen_undo_tests.rs b/crates/engine/src/pen_undo_tests.rs new file mode 100644 index 000000000..2314fc66a --- /dev/null +++ b/crates/engine/src/pen_undo_tests.rs @@ -0,0 +1,70 @@ +//! Undo while the pen draws (#1745): each undo takes back the path's last anchor, not the whole +//! path (nor the step before it); redo puts the anchors back. + +use crate::Session; +use crate::tools::{PointerEvent, PointerKind, ToolId}; +use figcraft_doc::NodeKind; +use serde_json::json; + +fn click(s: &mut Session, x: f64, y: f64) { + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::at(kind, x, y, 1.0)).unwrap(); + } +} + +fn layers(s: &Session) -> usize { + s.doc().unwrap().node(s.page().unwrap()).unwrap().children.len() +} + +fn pen_points(s: &Session) -> Option { + s.tool.pen.as_ref().map(|p| p.points.len()) +} + +/// (vertices, segments) of the pen's vector, if it has one. +fn vector(s: &Session) -> Option<(usize, usize)> { + let id = s.tool.pen.as_ref().and_then(|p| p.id)?; + match &s.doc().unwrap().node(id)?.kind { + NodeKind::Vector { network } => Some((network.vertices.len(), network.segments.len())), + _ => None, + } +} + +fn undo(s: &mut Session) -> bool { + s.execute("edit.undo", &json!({})).unwrap()["undone"] == true +} + +fn redo(s: &mut Session) { + s.execute("edit.redo", &json!({})).unwrap(); +} + +#[test] +fn undo_while_drawing_takes_back_one_anchor() { + let mut s = Session::new(); + s.execute("shape.rectangle", &json!({"x": 400, "y": 400, "width": 50, "height": 50})).unwrap(); + assert_eq!(layers(&s), 1); + s.set_tool(ToolId::Pen); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + click(&mut s, 200.0, 200.0); + assert_eq!((pen_points(&s), vector(&s), layers(&s)), (Some(3), Some((3, 2)), 2)); + + assert!(undo(&mut s)); + assert_eq!((pen_points(&s), vector(&s), layers(&s)), (Some(2), Some((2, 1)), 2), "only the last anchor goes"); + assert!(undo(&mut s)); + assert_eq!((pen_points(&s), vector(&s), layers(&s)), (Some(1), None, 1), "one anchor, no layer yet"); + + // Redo puts the anchors back in order. + redo(&mut s); + assert_eq!((pen_points(&s), vector(&s), layers(&s)), (Some(2), Some((2, 1)), 2)); + redo(&mut s); + assert_eq!((pen_points(&s), vector(&s), layers(&s)), (Some(3), Some((3, 2)), 2)); + let pts: Vec<_> = s.tool.pen.as_ref().unwrap().points.iter().map(|(p, _, _)| (p.x, p.y)).collect(); + assert_eq!(pts, vec![(100.0, 100.0), (200.0, 100.0), (200.0, 200.0)]); + + for _ in 0..3 { + assert!(undo(&mut s)); + } + assert_eq!((pen_points(&s), layers(&s)), (None, 1), "the path is gone, the rectangle stays"); + assert!(undo(&mut s)); + assert_eq!(layers(&s), 0, "the next undo takes the rectangle"); +} diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index fdf33b91f..14fdfe5b9 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -114,6 +114,10 @@ impl Session { pub fn undo(&mut self) -> Result { textpreview::end(self); + // While the pen draws, undo works on the anchors of its path (#1745). + if self.ds().is_ok_and(|d| d.preview.is_none()) && self.pen_undo()? { + return Ok(true); + } let live = self.ds().is_ok_and(|d| self.live_doc(d.uid)); let ds = self.ds_mut()?; if ds.preview.is_some() { @@ -152,6 +156,10 @@ impl Session { pub fn redo(&mut self) -> Result { textpreview::end(self); + // While the pen draws, redo works on the anchors of its path (#1745). + if self.ds().is_ok_and(|d| d.preview.is_none()) && self.pen_redo()? { + return Ok(true); + } let live = self.ds().is_ok_and(|d| self.live_doc(d.uid)); let ds = self.ds_mut()?; if ds.preview.is_some() { From c7cd72b09e5f5c4bdbd65d208832dc51532fc4cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:28:23 -0700 Subject: [PATCH 014/326] M3: Selection colors rows apply library color styles and create a style A row's Styles menu lists this file's color styles (library copies are no longer listed as local), then each enabled library's published color styles under the library's name. Choosing a library style copies it in, linked and read-only, and applies it to every fill and stroke the row stands for in one undo step (selection.applyColorStyle with `library`). A row linked to a style or variable now has the Styles button too, so it can switch to another style. Create style on an ordinary row opens a window with the next free "Color n" name. Create makes a style of the row's whole paint (gradient stops, opacity and blend mode included) and links it to every target in one undo step (selection.createColorStyle {targets, name, description?}). A name another style has, an empty name, or a row whose slots no longer share one paint is refused, and the window stays open. Text ranges with fills of their own take the style's value without a link. --- crates/engine/src/cmd/library.rs | 2 +- .../engine/src/selection/selection_colors.rs | 78 +++++- crates/engine/tests/it/selection_colors.rs | 180 ++++++++++++- crates/ui-egui/src/panels/selection_colors.rs | 240 +++++++++++++++--- docs/ui-parity.md | 2 +- 5 files changed, 461 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 5f3263765..8aeb12d49 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -194,7 +194,7 @@ fn with(p: &Value, keys: &[&str], mut base: Value) -> Value { } /// An enabled library of the active document (`library` param), read from its file. -fn library(s: &mut Session, cmd: &str, p: &Value) -> Result<(LibraryLink, Arc)> { +pub(crate) fn library(s: &mut Session, cmd: &str, p: &Value) -> Result<(LibraryLink, Arc)> { let key = req_string(cmd, p, "library")?; let link = find_link(s.doc()?, &key) .cloned() diff --git a/crates/engine/src/selection/selection_colors.rs b/crates/engine/src/selection/selection_colors.rs index 6ab99e819..b653f333b 100644 --- a/crates/engine/src/selection/selection_colors.rs +++ b/crates/engine/src/selection/selection_colors.rs @@ -5,14 +5,14 @@ use std::collections::{BTreeMap, BTreeSet}; use figcraft_color::{Paint, PaintKind}; -use figcraft_doc::{Document, NodeId, NodeKind, StyleKind, VariableType, VariableValue}; +use figcraft_doc::{Document, NodeId, NodeKind, Style, StyleKind, VariableType, VariableValue}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use crate::cmd::lists::{BoundList, list_binding, rebind_edited_paint}; use crate::cmd::styles::{rebind_paint_alpha, unbind_slot}; -use crate::params::{get, paint_of, parse, req_string, targets}; -use crate::{CommandSpec, Result, Session, bad, spec}; +use crate::params::{get, paint_of, parse, req_string, string, targets}; +use crate::{CommandSpec, EngineError, Result, Session, bad, spec}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -127,10 +127,17 @@ pub fn specs() -> Vec { spec!( "selection.applyColorStyle", "Apply selection color style", - "{targets, style}; applies the color style to matching fill/stroke lists (text ranges keep typography)", + "{targets, style (id or name), library? (an enabled library: id, name or path; the style is then one it publishes, copied in linked and read-only)}; applies the color style to matching fill/stroke lists (text ranges keep typography)", true, apply_style ), + spec!( + "selection.createColorStyle", + "Create selection color style", + "{targets, name, description?} → {id}; makes a color style of the paint the targets share and applies it to them as selection.applyColorStyle does; a name another style has is refused", + true, + create_style + ), spec!( "selection.bindColorVariable", "Apply selection color variable", @@ -205,15 +212,72 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { const CMD: &str = "selection.applyColorStyle"; let targets = checked_targets(s, p, CMD)?; let name = req_string(CMD, p, "style")?; + let name = if string(p, "library").is_some() { import_library_style(s, CMD, p, &name)? } else { name }; let style = s.doc()?.style(&name).cloned().ok_or_else(|| bad(CMD, "no such color style"))?; if !matches!(style.kind, StyleKind::Paint { .. }) { return Err(bad(CMD, "a color style is required")); } - for target in &targets { + link_style(s, &targets, &style)?; + Ok(json!({"ok": true})) +} + +/// Copy the color style `key` (id, else name) that the enabled library `library` publishes into the +/// document, linked and read-only, and return the copy's id. +fn import_library_style(s: &mut Session, cmd: &str, p: &Value, key: &str) -> Result { + let (link, lib) = crate::cmd::library::library(s, cmd, p)?; + let published = |st: &&Style| lib.manifest.style(&st.id).is_some_and(|x| x.published); + let styles = || lib.doc.styles.iter().filter(published); + let style = styles() + .find(|st| st.id == key) + .or_else(|| styles().find(|st| st.name == key)) + .ok_or_else(|| bad(cmd, format!("\"{}\" publishes no style `{key}`", link.name)))?; + if !matches!(style.kind, StyleKind::Paint { .. }) { + return Err(bad(cmd, "a color style is required")); + } + let keys = BTreeSet::from([style.id.clone()]); + crate::library::import_styles(s.doc_mut()?, &lib, &keys, false) + .into_values() + .next() + .ok_or_else(|| EngineError::Other("the style didn't import".into())) +} + +fn create_style(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "selection.createColorStyle"; + let targets = checked_targets(s, p, CMD)?; + let doc = s.doc()?; + let paint = targets.first().and_then(|t| t.paint(doc)).ok_or_else(|| bad(CMD, "a selection color target no longer exists"))?; + if !matches!(paint.kind, PaintKind::Solid { .. } | PaintKind::Gradient(_)) { + return Err(bad(CMD, "a solid or gradient paint is required")); + } + if targets.iter().any(|t| t.paint(doc).as_ref() != Some(&paint)) { + return Err(bad(CMD, "the targets no longer share one paint")); + } + let name = crate::cmd::variables::clean_name(&req_string(CMD, p, "name")?).ok_or_else(|| bad(CMD, "name can't be empty"))?; + if doc.styles.iter().any(|st| st.name == name) { + return Err(bad(CMD, format!("a style named `{name}` already exists"))); + } + let doc = s.doc_mut()?; + let id = doc.new_style_id(); + let style = Style { + id: id.clone(), + name, + description: string(p, "description").unwrap_or_default(), + kind: StyleKind::Paint { paints: vec![paint] }, + bound: BTreeMap::new(), + }; + doc.styles.push(style.clone()); + link_style(s, &targets, &style)?; + Ok(json!({"id": id})) +} + +/// Apply paint style `style` to every target: a fill or stroke list is linked to it; a text range +/// takes its resolved paints and keeps its typography. +fn link_style(s: &mut Session, targets: &[PaintTarget], style: &Style) -> Result<()> { + for target in targets { if let Some((start, end)) = target.range { // Text ranges have typography-style links, not paint-style links. Copy resolved paint // values just as an explicit range fill does; never replace its font or size. - let StyleKind::Paint { paints } = crate::style_vars::kind_for(s.doc()?, &style, target.id).into_owned() else { continue }; + let StyleKind::Paint { paints } = crate::style_vars::kind_for(s.doc()?, style, target.id).into_owned() else { continue }; let n = s.doc_mut()?.get_mut(target.id)?; if let NodeKind::Text(t) = &mut n.kind { t.restyle(start, end, |st| st.fills = Some(paints.clone())); @@ -222,7 +286,7 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { crate::cmd::styles::apply_style_ref(s.doc_mut()?, target.id, if target.fills { "fillStyle" } else { "strokeStyle" }, Some(&style.id))?; } } - Ok(json!({"ok": true})) + Ok(()) } /// The binding key (`fills//color` or `strokes//color`) of the slot a target stands for, when the diff --git a/crates/engine/tests/it/selection_colors.rs b/crates/engine/tests/it/selection_colors.rs index c3fc4f97c..41204e5db 100644 --- a/crates/engine/tests/it/selection_colors.rs +++ b/crates/engine/tests/it/selection_colors.rs @@ -156,9 +156,14 @@ fn invalid_or_stale_targets_roll_back_atomically() { assert!(s.execute("selection.setPaint", &json!({"targets":red.targets,"paint":"#0000ff"})).is_err()); assert_eq!(fill(&s, a), "FF0000"); assert_eq!(s.undo_depth(), before); - for command in - ["selection.setPaint", "selection.selectColor", "selection.applyColorStyle", "selection.bindColorVariable", "selection.detachColor"] - { + for command in [ + "selection.setPaint", + "selection.selectColor", + "selection.applyColorStyle", + "selection.bindColorVariable", + "selection.detachColor", + "selection.createColorStyle", + ] { for params in [json!({}), json!({"targets":[]}), json!({"targets":[{"id":a,"fills":true,"index":0,"range":[0,1]}]})] { assert!(s.execute(command, ¶ms).is_err()); } @@ -421,3 +426,172 @@ fn scopes_filter_the_menu_but_the_command_binds_anyway() { run(&mut s, "selection.bindColorVariable", json!({"targets":fill_slot,"variable":"Line"})); assert_eq!(fill(&s, a), "00FF00"); } + +#[test] +fn a_style_created_from_a_row_links_its_fills_and_strokes_in_one_undo_step() { + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let b = rectangle(&mut s, "#0000ff"); + run(&mut s, "stroke.add", json!({"id":b,"color":"#ff0000"})); + let red = group(&s, &[a, b], "FF0000"); + let before = s.undo_depth(); + let id = run(&mut s, "selection.createColorStyle", json!({"targets":red.targets,"name":"Brand/Red"}))["id"].clone(); + let doc = s.doc().unwrap(); + let style = doc.style(id.as_str().unwrap()).unwrap(); + assert_eq!(style.name, "Brand/Red"); + assert!(matches!(&style.kind, figcraft_doc::StyleKind::Paint { paints } if paints.len() == 1 && paints[0] == red.paint)); + assert_eq!(doc.node(a).unwrap().styles.fill.as_deref(), id.as_str()); + assert_eq!(doc.node(b).unwrap().styles.stroke.as_deref(), id.as_str()); + assert_eq!(doc.node(b).unwrap().styles.fill, None); + assert_eq!(fill(&s, b), "0000FF"); + assert_eq!(s.undo_depth().0, before.0 + 1); + run(&mut s, "style.update", json!({"style":id,"value":"#00ff00"})); + assert_eq!(fill(&s, a), "00FF00"); + assert_eq!(s.doc().unwrap().node(b).unwrap().strokes[0].solid_color().unwrap().to_hex(), "00FF00"); + s.undo().unwrap(); + s.undo().unwrap(); + assert!(s.doc().unwrap().style("Brand/Red").is_none()); + assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill, None); + assert_eq!(fill(&s, a), "FF0000"); + s.redo().unwrap(); + assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill.as_deref(), id.as_str()); +} + +#[test] +fn a_created_style_keeps_the_rows_gradient_opacity_and_blend_mode() { + use figcraft_color::{BlendMode, Color, Gradient, GradientKind}; + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let b = rectangle(&mut s, "#0000ff"); + let mut paint = Paint::gradient(Gradient::default_for(GradientKind::Radial, Color::BLACK)); + paint.opacity = 0.5; + paint.blend = BlendMode::Multiply; + for id in [a, b] { + run(&mut s, "fill.set", json!({"id":id,"paint":paint})); + } + let row = collect(s.doc().unwrap(), &[a, b]).into_iter().find(|g| g.paint == paint).unwrap(); + assert_eq!(row.targets.len(), 2); + let id = run(&mut s, "selection.createColorStyle", json!({"targets":row.targets,"name":"Shade"}))["id"].clone(); + let doc = s.doc().unwrap(); + assert!(matches!(&doc.style("Shade").unwrap().kind, figcraft_doc::StyleKind::Paint { paints } if paints == &vec![paint.clone()])); + for n in [a, b] { + assert_eq!(doc.node(n).unwrap().fills, vec![paint.clone()]); + assert_eq!(doc.node(n).unwrap().styles.fill.as_deref(), id.as_str()); + } +} + +#[test] +fn creating_a_style_refuses_taken_or_empty_names_and_stale_rows_and_changes_nothing() { + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let b = rectangle(&mut s, "#ff0000"); + run(&mut s, "style.create", json!({"type":"paint","name":"Brand","value":"#00ff00"})); + let red = group(&s, &[a, b], "FF0000"); + let before = s.undo_depth(); + let styles = s.doc().unwrap().styles.len(); + for name in ["Brand", " Brand ", "", " "] { + assert!(s.execute("selection.createColorStyle", &json!({"targets":red.targets,"name":name})).is_err(), "{name:?}"); + } + assert!(s.execute("selection.createColorStyle", &json!({"targets":red.targets})).is_err()); + // One slot of the row changed since it was listed: the row no longer stands for one paint. + run(&mut s, "fill.set", json!({"id":b,"color":"#0000ff"})); + let before_stale = s.undo_depth(); + assert!(s.execute("selection.createColorStyle", &json!({"targets":red.targets,"name":"Red"})).is_err()); + assert_eq!(s.undo_depth(), before_stale); + assert_eq!(s.undo_depth().0, before.0 + 1); + let doc = s.doc().unwrap(); + assert_eq!(doc.styles.len(), styles); + assert_eq!(doc.node(a).unwrap().styles.fill, None); + assert_eq!(fill(&s, a), "FF0000"); +} + +#[test] +fn a_linked_row_switches_to_another_style() { + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let b = rectangle(&mut s, "#0000ff"); + run(&mut s, "style.create", json!({"type":"paint","name":"Brand","value":"#ff0000"})); + let accent = run(&mut s, "style.create", json!({"type":"paint","name":"Accent","value":"#00ff00"}))["id"].clone(); + run(&mut s, "style.apply", json!({"id":a,"style":"Brand","target":"fill"})); + let linked = collect(s.doc().unwrap(), &[a, b]).into_iter().find(|g| g.style.is_some()).unwrap(); + run(&mut s, "selection.applyColorStyle", json!({"targets":linked.targets,"style":"Accent"})); + assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill.as_deref(), accent.as_str()); + assert_eq!(fill(&s, a), "00FF00"); + assert_eq!(fill(&s, b), "0000FF"); +} + +struct Fixture(std::path::PathBuf); + +impl Drop for Fixture { + #[allow(clippy::disallowed_methods)] + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A saved library file publishing the color style "Brand" (#0000ff) and the text style "Heading", +/// with the color style "_Draft" left unpublished; the fixture, the file and the library's id. +#[allow(clippy::disallowed_methods)] +fn color_library(tag: &str) -> (Fixture, std::path::PathBuf, Value) { + let fixture = Fixture(std::env::temp_dir().join(format!("figcraft-selection-colors-{tag}-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&fixture.0); + std::fs::create_dir(&fixture.0).unwrap(); + let path = fixture.0.join("library.figcraft"); + let mut publisher = Session::new(); + run(&mut publisher, "style.create", json!({"type":"paint","name":"Brand","value":"#0000ff"})); + run(&mut publisher, "style.create", json!({"type":"paint","name":"_Draft","value":"#00ff00"})); + let text = run(&mut publisher, "text.create", json!({"text":"Title"}))["id"].clone(); + run(&mut publisher, "style.create", json!({"type":"text","name":"Heading","from":text})); + let published = run(&mut publisher, "library.publish", json!({})); + assert_eq!(published["styles"], 2); + run(&mut publisher, "file.saveAs", json!({"path":path})); + (fixture, path, published["id"].clone()) +} + +#[test] +fn a_row_applies_a_published_library_style_as_a_linked_copy_in_one_undo_step() { + let (_fixture, path, library) = color_library("apply"); + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let b = rectangle(&mut s, "#00ff00"); + run(&mut s, "stroke.add", json!({"id":b,"color":"#ff0000"})); + run(&mut s, "library.add", json!({"path":path})); + let red = group(&s, &[a, b], "FF0000"); + let before = s.undo_depth(); + run(&mut s, "selection.applyColorStyle", json!({"targets":red.targets,"style":"Brand","library":library})); + let doc = s.doc().unwrap(); + let copy = doc.node(a).unwrap().styles.fill.clone().unwrap(); + assert!(figcraft_engine::library::is_remote_style(doc, ©)); + assert_eq!(doc.node(b).unwrap().styles.stroke.as_deref(), Some(copy.as_str())); + assert_eq!(fill(&s, a), "0000FF"); + assert_eq!(fill(&s, b), "00FF00"); + assert_eq!(s.undo_depth().0, before.0 + 1); + s.undo().unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.style(©).is_none()); + assert_eq!(doc.node(a).unwrap().styles.fill, None); + assert_eq!(fill(&s, a), "FF0000"); + // Choosing it again reuses the one copy. + s.redo().unwrap(); + let blue = group(&s, &[a, b], "0000FF"); + run(&mut s, "selection.applyColorStyle", json!({"targets":blue.targets,"style":"Brand","library":library})); + assert_eq!(s.doc().unwrap().styles.len(), 1); +} + +#[test] +fn library_styles_that_are_unpublished_not_colors_or_not_enabled_are_refused() { + let (_fixture, path, library) = color_library("refuse"); + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + rectangle(&mut s, "#00ff00"); + let red = group(&s, &[a], "FF0000"); + assert!(s.execute("selection.applyColorStyle", &json!({"targets":red.targets,"style":"Brand","library":library})).is_err()); + run(&mut s, "library.add", json!({"path":path})); + let before = s.undo_depth(); + for (style, lib) in [("_Draft", library.clone()), ("Heading", library.clone()), ("Missing", library.clone()), ("Brand", json!("Elsewhere"))] { + assert!(s.execute("selection.applyColorStyle", &json!({"targets":red.targets,"style":style,"library":lib})).is_err(), "{style}"); + } + assert_eq!(s.undo_depth(), before); + assert!(s.doc().unwrap().styles.is_empty()); + assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill, None); +} diff --git a/crates/ui-egui/src/panels/selection_colors.rs b/crates/ui-egui/src/panels/selection_colors.rs index 97333367f..7a8189ddb 100644 --- a/crates/ui-egui/src/panels/selection_colors.rs +++ b/crates/ui-egui/src/panels/selection_colors.rs @@ -4,8 +4,9 @@ use std::sync::Arc; use egui::{Id, Ui}; -use figcraft_color::Color; -use figcraft_doc::{Document, NodeId, StyleKind, VariableType}; +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Document, NodeId, PublishedLibrary, Style, StyleKind, VariableType}; +use figcraft_engine::library; use figcraft_engine::selection_colors::{PaintTarget, SelectionColor, bind_refusal, collect, in_scope}; use serde_json::json; @@ -58,13 +59,15 @@ 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 -/// edits, style/variable detach/apply/bind, and “select layers with this color”; disabled -/// during an interaction. +/// 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]) { let Ok(ds) = app.session.ds() else { return }; let interacting = ds.interaction.is_some(); - let colors = colors(ui, ds.uid, doc, ids, interacting); + let uid = ds.uid; + let colors = colors(ui, uid, doc, ids, interacting); if colors.len() < 2 { + ui.data_mut(|d| d.remove::(create_form_id())); return; } let t = Tokens::get(ui.ctx()); @@ -77,12 +80,14 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId crate::right::row(ui, 32.0, |ui| { let swatch = widgets::swatch(ui, &group.paint, 24.0).tip(tr("Edit colour")); toggle(app, group.targets.clone(), Some(&swatch)); - let width = (ui.available_width() - 116.0).max(40.0); let linked_name = group .style .as_ref() .and_then(|id| doc.style(id).map(|s| s.name.as_str())) .or_else(|| group.variable.as_ref().and_then(|id| doc.variables.get_by_id(id).map(|v| v.name.as_str()))); + // A linked row has a Detach button beside its Styles button. + let buttons = if linked_name.is_some() { 148.0 } else { 116.0 }; + let width = (ui.available_width() - buttons).max(40.0); if let Some(name) = linked_name { let response = widgets::dropdown(ui, name, width, None); toggle(app, group.targets.clone(), Some(&response)); @@ -112,28 +117,14 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId paint.opacity = (value / 100.0).clamp(0.0, 1.0); app.run("selection.setPaint", json!({"targets": group.targets, "paint": paint})); } - if linked_name.is_some() { - let detach = if group.style.is_some() { tr("Detach style") } else { tr("Detach variable") }; - if icons::button(ui, Icon::Detach, 24.0, false, detach).clicked() { - app.run("selection.detachColor", json!({"targets": group.targets})); - } - } else { - let styles = icons::button(ui, Icon::Styles, 24.0, false, tr("Color styles")); - crate::right::menu_popup(&styles).show(|ui| { - let mut any = false; - for style in &doc.styles { - if !matches!(style.kind, StyleKind::Paint { .. }) { - continue; - } - any = true; - if crate::right::menu_item(ui, &style.name, "") { - app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id})); - app.ui.picker = None; - ui.close(); - } - } - if !any { - widgets::label(ui, tr("No color styles"), t.text_secondary); + let styles = icons::button(ui, Icon::Styles, 24.0, false, tr("Color styles")); + crate::right::menu_popup(&styles).show(|ui| { + style_items(app, ui, doc, group, &t); + if linked_name.is_none() { + ui.separator(); + if crate::right::menu_item(ui, tr("Create style"), "") { + open_create_form(app, ui, doc, group); + ui.close(); } let variables: Vec<_> = doc .variables @@ -156,7 +147,13 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId ui.close(); } } - }); + } + }); + if linked_name.is_some() { + let detach = if group.style.is_some() { tr("Detach style") } else { tr("Detach variable") }; + if icons::button(ui, Icon::Detach, 24.0, false, detach).clicked() { + app.run("selection.detachColor", json!({"targets": group.targets})); + } } if icons::button(ui, Icon::Move, 24.0, false, tr("Select layers with this color")).clicked() { app.run("selection.selectColor", json!({"targets": group.targets})); @@ -168,6 +165,106 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId }); ui.add_space(8.0); widgets::separator(ui); + create_form(app, ui.ctx(), uid); +} + +/// The paint styles a row's Styles menu offers: this file's (not library copies), then each enabled +/// library's published ones under its name (a library this session hasn't read offers none). A choice +/// applies the style to the row's targets. +fn style_items(app: &mut FigApp, ui: &mut Ui, doc: &Document, group: &SelectionColor, t: &Tokens) { + let paint = |s: &&Style| matches!(s.kind, StyleKind::Paint { .. }); + let local: Vec<&Style> = library::local_styles(doc).filter(paint).collect(); + let libs = crate::variable_ui::libraries(app, doc); + let offered: Vec<(&PublishedLibrary, Vec<&Style>)> = libs + .iter() + .map(|l| (l.as_ref(), l.doc.styles.iter().filter(|s| l.manifest.style(&s.id).is_some_and(|x| x.published)).filter(paint).collect::>())) + .filter(|(_, list)| !list.is_empty()) + .collect(); + if local.is_empty() && offered.is_empty() { + widgets::label(ui, tr("No color styles"), t.text_secondary); + } + for style in local { + if crate::right::menu_item(ui, &style.name, "") { + app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id})); + app.ui.picker = None; + ui.close(); + } + } + for (lib, list) in offered { + ui.separator(); + widgets::label(ui, &lib.manifest.name, t.text_secondary); + for style in list { + if crate::right::menu_item(ui, &style.name, "") { + app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id, "library": lib.manifest.id})); + app.ui.picker = None; + ui.close(); + } + } + } +} + +/// The Create style window's state: the document and row it was opened for, and the name typed. +#[derive(Clone)] +struct CreateForm { + document: u64, + targets: Vec, + paint: Paint, + name: String, +} + +fn create_form_id() -> Id { + Id::unique("selection_color_create_style") +} + +/// Open the Create style window for `group`, with the next free "Color n" name. +fn open_create_form(app: &mut FigApp, ui: &Ui, doc: &Document, group: &SelectionColor) { + let Ok(ds) = app.session.ds() else { return }; + let form = CreateForm { + document: ds.uid, + targets: group.targets.clone(), + paint: group.paint.clone(), + name: crate::style_picker::next_name(doc, "Color"), + }; + app.ui.picker = None; + ui.data_mut(|d| d.insert_temp(create_form_id(), form)); +} + +/// The Create style window: the row's paint, a name, Cancel and Create (Enter creates). Create runs +/// `selection.createColorStyle`; when it fails (a name in use, a row that changed) the window stays +/// open with the name for correction. +fn create_form(app: &mut FigApp, ctx: &egui::Context, document: u64) { + let Some(mut form) = ctx.data(|d| d.get_temp::(create_form_id())) else { return }; + if form.document != document { + ctx.data_mut(|d| d.remove::(create_form_id())); + return; + } + let (mut open, mut cancel, mut create) = (true, false, false); + crate::dialogs::window(tr("Create style"), ctx).id(create_form_id().with("window")).open(&mut open).show(ctx, |ui| { + ui.set_width(240.0); + ui.horizontal(|ui| { + widgets::swatch(ui, &form.paint, 24.0); + ui.label(widgets::paint_name(&form.paint)); + }); + ui.add_space(6.0); + let name = ui.add(egui::TextEdit::singleline(&mut form.name).hint_text(tr("Name")).desired_width(220.0)); + widgets::select_all_on_focus(ui, &name, &form.name); + if ui.memory(|m| m.focused().is_none()) { + name.request_focus(); + } + ui.add_space(10.0); + let ready = !form.name.trim().is_empty(); + ui.horizontal(|ui| { + cancel = widgets::button(ui, tr("Cancel"), false, true).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)); + let enter = name.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + create = (widgets::button(ui, tr("Create"), true, ready).clicked() || enter) && ready; + }); + }); + let made = create && app.run("selection.createColorStyle", json!({"targets": form.targets, "name": form.name.trim()})).is_some(); + if open && !cancel && !made { + ctx.data_mut(|d| d.insert_temp(create_form_id(), form)); + } else { + ctx.data_mut(|d| d.remove::(create_form_id())); + } } #[cfg(test)] @@ -369,4 +466,89 @@ mod tests { assert!(texts.iter().any(|(s, _)| s == "FF0000") && texts.iter().any(|(s, _)| s == "0000FF")); assert!(p.app.ui.last_error.is_none()); } + + fn text_at(texts: &[(String, Pos2)], s: &str) -> Pos2 { + texts.iter().rev().find(|(t, _)| t == s).unwrap_or_else(|| panic!("{s:?} isn't drawn")).1 + } + + #[test] + fn styles_menu_offers_an_enabled_librarys_published_color_styles() { + let dir = std::env::temp_dir().join(format!("figcraft-selection-colors-panel-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let path = dir.join("library.figcraft"); + let mut publisher = Session::new(); + publisher.execute("style.create", &json!({"type":"paint","name":"Ocean","value":"#00ffff"})).unwrap(); + publisher.execute("style.create", &json!({"type":"paint","name":"_Draft","value":"#ffff00"})).unwrap(); + publisher.execute("library.publish", &json!({})).unwrap(); + publisher.execute("file.saveAs", &json!({"path":path})).unwrap(); + let (mut p, a, b) = Panel::new(); + p.app.run("library.add", json!({"path":path})); + let red = text_at(&p.frame(vec![]), "FF0000"); + p.click(Pos2::new(228.0, red.y)); + let texts = p.frame(vec![]); + let library_name = p.app.session.doc().unwrap().libraries.enabled[0].name.clone(); + assert!(texts.iter().any(|(s, _)| *s == library_name), "library styles are listed under the library's name"); + assert!(!texts.iter().any(|(s, _)| s == "_Draft"), "unpublished styles aren't offered"); + p.click(text_at(&texts, "Ocean")); + let _ = std::fs::remove_dir_all(&dir); + let doc = p.app.session.doc().unwrap(); + let copy = doc.node(a).unwrap().styles.fill.clone().unwrap(); + assert!(library::is_remote_style(doc, ©)); + assert_eq!(doc.node(a).unwrap().fills[0].solid_color().unwrap().to_hex(), "00FFFF"); + assert!(doc.node(b).unwrap().styles.fill.is_none()); + assert!(p.app.ui.last_error.is_none()); + // The copy is listed under its library, not as one of this file's styles. + let blue = text_at(&p.frame(vec![]), "0000FF"); + p.click(Pos2::new(228.0, blue.y)); + let texts = p.frame(vec![]); + assert_eq!(texts.iter().filter(|(s, _)| s == "Ocean").count(), 2, "the linked row's name and the library's entry"); + } + + #[test] + fn create_style_names_the_row_links_it_and_stays_open_on_a_taken_name() { + let (mut p, a, b) = Panel::new(); + let red = text_at(&p.frame(vec![]), "FF0000"); + p.click(Pos2::new(228.0, red.y)); + let create = text_at(&p.frame(vec![]), "Create style"); + p.click(create); + for _ in 0..2 { + p.frame(vec![]); + } + let form = p.ctx.data(|d| d.get_temp::(create_form_id())).expect("Create style opens its window"); + assert_eq!(form.name, "Color 1"); + // Another style takes the name first: Create fails and the window stays for a new name. + p.app.run("style.create", json!({"type":"paint","name":"Color 1","value":"#00ff00"})); + let button = text_at(&p.frame(vec![]), "Create"); + p.click(button); + assert!(p.ctx.data(|d| d.get_temp::(create_form_id())).is_some()); + assert!(p.app.session.doc().unwrap().node(a).unwrap().styles.fill.is_none()); + p.ctx.data_mut(|d| d.get_temp_mut_or_insert_with(create_form_id(), || form.clone()).name = "Brand".into()); + let before = p.app.session.undo_depth(); + let button = text_at(&p.frame(vec![]), "Create"); + p.click(button); + assert!(p.ctx.data(|d| d.get_temp::(create_form_id())).is_none()); + let doc = p.app.session.doc().unwrap(); + let brand = doc.style("Brand").unwrap().id.clone(); + assert_eq!(doc.node(a).unwrap().styles.fill.as_deref(), Some(brand.as_str())); + assert!(doc.node(b).unwrap().styles.fill.is_none()); + assert_eq!(p.app.session.undo_depth().0, before.0 + 1); + assert!(p.frame(vec![]).iter().any(|(s, _)| s == "Brand")); + } + + #[test] + fn a_linked_rows_styles_menu_switches_its_style() { + let (mut p, a, _) = Panel::new(); + p.app.run("style.create", json!({"type":"paint","name":"Brand","value":"#ff0000"})); + p.app.run("style.create", json!({"type":"paint","name":"Accent","value":"#00ff00"})); + p.app.run("style.apply", json!({"id":a,"style":"Brand","target":"fill"})); + let row = text_at(&p.frame(vec![]), "Brand"); + p.click(Pos2::new(196.0, row.y)); + let texts = p.frame(vec![]); + assert!(!texts.iter().any(|(s, _)| s == "Create style"), "a linked row has a style already"); + p.click(text_at(&texts, "Accent")); + let doc = p.app.session.doc().unwrap(); + assert_eq!(doc.node(a).unwrap().styles.fill.as_deref(), doc.style("Accent").map(|s| s.id.as_str())); + assert!(p.app.ui.last_error.is_none()); + } } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0286fd37d..5e634bc2b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -74,7 +74,7 @@ interaction feel not yet compared. | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | 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 | 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 and blend mode 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 From 889983ffe23c709fb8d669d944f97acaeb343f37 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:41:03 -0700 Subject: [PATCH 015/326] Selection colors: Create style refuses a row whose fill or stroke list holds other paints A created style holds the row's one paint, and linking it replaces the target's whole fill or stroke list, so a layer with other fills or strokes lost them. selection.createColorStyle now refuses such targets before any change, and the Styles menu leaves Create style out for those rows. --- .../engine/src/selection/selection_colors.rs | 15 ++++++++++- crates/engine/tests/it/selection_colors.rs | 26 ++++++++++++++++++- crates/ui-egui/src/panels/selection_colors.rs | 15 +++++++++-- 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/selection/selection_colors.rs b/crates/engine/src/selection/selection_colors.rs index b653f333b..54b9703b8 100644 --- a/crates/engine/src/selection/selection_colors.rs +++ b/crates/engine/src/selection/selection_colors.rs @@ -134,7 +134,7 @@ pub fn specs() -> Vec { spec!( "selection.createColorStyle", "Create selection color style", - "{targets, name, description?} → {id}; makes a color style of the paint the targets share and applies it to them as selection.applyColorStyle does; a name another style has is refused", + "{targets, name, description?} → {id}; makes a color style of the paint the targets share and applies it to them as selection.applyColorStyle does; a name another style has, or a target whose list holds other paints, is refused", true, create_style ), @@ -252,6 +252,9 @@ fn create_style(s: &mut Session, p: &Value) -> Result { if targets.iter().any(|t| t.paint(doc).as_ref() != Some(&paint)) { return Err(bad(CMD, "the targets no longer share one paint")); } + if let Some(why) = create_refusal(doc, &targets) { + return Err(bad(CMD, why)); + } let name = crate::cmd::variables::clean_name(&req_string(CMD, p, "name")?).ok_or_else(|| bad(CMD, "name can't be empty"))?; if doc.styles.iter().any(|st| st.name == name) { return Err(bad(CMD, format!("a style named `{name}` already exists"))); @@ -270,6 +273,16 @@ fn create_style(s: &mut Session, p: &Value) -> Result { Ok(json!({"id": id})) } +/// Why a color style can't be made from `targets` (`selection.createColorStyle`), if it can't: a +/// linked style replaces the whole fill or stroke list, so a target whose list holds other paints +/// would lose them. The Selection colors menu leaves Create style out for such rows. +pub fn create_refusal(doc: &Document, targets: &[PaintTarget]) -> Option<&'static str> { + targets + .iter() + .any(|t| t.paints(doc).is_none_or(|paints| paints.len() != 1)) + .then_some("a style can only be made from a fill or stroke list that holds this one paint") +} + /// Apply paint style `style` to every target: a fill or stroke list is linked to it; a text range /// takes its resolved paints and keeps its typography. fn link_style(s: &mut Session, targets: &[PaintTarget], style: &Style) -> Result<()> { diff --git a/crates/engine/tests/it/selection_colors.rs b/crates/engine/tests/it/selection_colors.rs index 41204e5db..7fdbfb635 100644 --- a/crates/engine/tests/it/selection_colors.rs +++ b/crates/engine/tests/it/selection_colors.rs @@ -2,7 +2,7 @@ use figcraft_color::Paint; use figcraft_doc::NodeId; use figcraft_engine::{ Session, - selection_colors::{SelectionColor, collect}, + selection_colors::{self, SelectionColor, collect}, }; use serde_json::{Value, json}; @@ -505,6 +505,30 @@ fn creating_a_style_refuses_taken_or_empty_names_and_stale_rows_and_changes_noth assert_eq!(fill(&s, a), "FF0000"); } +#[test] +fn creating_a_style_refuses_a_row_whose_list_holds_other_paints() { + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let b = rectangle(&mut s, "#ff0000"); + run(&mut s, "fill.add", json!({"id":a,"paint":"#0000ff"})); + let red = group(&s, &[a, b], "FF0000"); + let before = s.undo_depth(); + let styles = s.doc().unwrap().styles.len(); + let err = s.execute("selection.createColorStyle", &json!({"targets":red.targets,"name":"Red"})).unwrap_err(); + assert!(err.to_string().contains("holds this one paint"), "{err}"); + assert!(selection_colors::create_refusal(s.doc().unwrap(), &red.targets).is_some()); + assert_eq!(s.undo_depth(), before); + let doc = s.doc().unwrap(); + assert_eq!(doc.styles.len(), styles); + assert_eq!(doc.node(a).unwrap().fills.len(), 2, "the layer keeps its other fill"); + assert!(doc.node(b).unwrap().styles.fill.is_none()); + // The single-paint layer alone still makes a style. + let b_only: Vec<_> = red.targets.iter().filter(|t| t.id == b).cloned().collect(); + assert!(selection_colors::create_refusal(s.doc().unwrap(), &b_only).is_none()); + run(&mut s, "selection.createColorStyle", json!({"targets":b_only,"name":"Red"})); + assert!(s.doc().unwrap().node(b).unwrap().styles.fill.is_some()); +} + #[test] fn a_linked_row_switches_to_another_style() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/panels/selection_colors.rs b/crates/ui-egui/src/panels/selection_colors.rs index 7a8189ddb..4d5682e35 100644 --- a/crates/ui-egui/src/panels/selection_colors.rs +++ b/crates/ui-egui/src/panels/selection_colors.rs @@ -7,7 +7,7 @@ use egui::{Id, Ui}; use figcraft_color::{Color, Paint}; use figcraft_doc::{Document, NodeId, PublishedLibrary, Style, StyleKind, VariableType}; use figcraft_engine::library; -use figcraft_engine::selection_colors::{PaintTarget, SelectionColor, bind_refusal, collect, in_scope}; +use figcraft_engine::selection_colors::{PaintTarget, SelectionColor, bind_refusal, collect, create_refusal, in_scope}; use serde_json::json; use crate::a11y::Tip; @@ -122,7 +122,7 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc, ids: &[NodeId style_items(app, ui, doc, group, &t); if linked_name.is_none() { ui.separator(); - if crate::right::menu_item(ui, tr("Create style"), "") { + if create_refusal(doc, &group.targets).is_none() && crate::right::menu_item(ui, tr("Create style"), "") { open_create_form(app, ui, doc, group); ui.close(); } @@ -536,6 +536,17 @@ mod tests { assert!(p.frame(vec![]).iter().any(|(s, _)| s == "Brand")); } + #[test] + fn create_style_is_left_out_for_a_row_whose_list_holds_other_paints() { + let (mut p, a, _) = Panel::new(); + p.app.run("fill.add", json!({"id":a,"paint":"#00ff00"})); + let red = text_at(&p.frame(vec![]), "FF0000"); + p.click(Pos2::new(228.0, red.y)); + let texts = p.frame(vec![]); + assert!(texts.iter().any(|(s, _)| s == "No color styles"), "the Styles menu opens"); + assert!(!texts.iter().any(|(s, _)| s == "Create style")); + } + #[test] fn a_linked_rows_styles_menu_switches_its_style() { let (mut p, a, _) = Panel::new(); From 1b7d9221e20c36b177d97c74aa89298d929abfc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:47:01 -0700 Subject: [PATCH 016/326] Selection colors: a library that is not a string is refused instead of linking a local style selection.applyColorStyle chose the library path only when `library` read as a string, so an object or array fell through and linked a local style of the same name. Any non-null `library` now goes to the library lookup, which refuses a non-string before any change. --- crates/engine/src/selection/selection_colors.rs | 2 +- crates/engine/tests/it/selection_colors.rs | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/selection/selection_colors.rs b/crates/engine/src/selection/selection_colors.rs index 54b9703b8..52e39483b 100644 --- a/crates/engine/src/selection/selection_colors.rs +++ b/crates/engine/src/selection/selection_colors.rs @@ -212,7 +212,7 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { const CMD: &str = "selection.applyColorStyle"; let targets = checked_targets(s, p, CMD)?; let name = req_string(CMD, p, "style")?; - let name = if string(p, "library").is_some() { import_library_style(s, CMD, p, &name)? } else { name }; + let name = if get(p, "library").is_some() { import_library_style(s, CMD, p, &name)? } else { name }; let style = s.doc()?.style(&name).cloned().ok_or_else(|| bad(CMD, "no such color style"))?; if !matches!(style.kind, StyleKind::Paint { .. }) { return Err(bad(CMD, "a color style is required")); diff --git a/crates/engine/tests/it/selection_colors.rs b/crates/engine/tests/it/selection_colors.rs index 7fdbfb635..7778fedc3 100644 --- a/crates/engine/tests/it/selection_colors.rs +++ b/crates/engine/tests/it/selection_colors.rs @@ -619,3 +619,19 @@ fn library_styles_that_are_unpublished_not_colors_or_not_enabled_are_refused() { assert!(s.doc().unwrap().styles.is_empty()); assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill, None); } + +#[test] +fn a_library_that_is_not_a_string_is_refused_rather_than_linking_a_local_style() { + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + run(&mut s, "style.create", json!({"type":"paint","name":"Brand","value":"#0000ff"})); + let red = group(&s, &[a], "FF0000"); + let before = s.undo_depth(); + for lib in [json!({}), json!([]), json!({"id":"Brand"})] { + let err = s.execute("selection.applyColorStyle", &json!({"targets":red.targets,"style":"Brand","library":lib})).unwrap_err(); + assert!(err.to_string().contains("`library` must be a string"), "{lib}: {err}"); + } + assert_eq!(s.undo_depth(), before); + assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill, None); + assert_eq!(fill(&s, a), "FF0000"); +} From cb429813f3bd9399054508082f2f64a910f7bba2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:58:28 -0700 Subject: [PATCH 017/326] Selection colors: Create style keeps the variables bound to the row's paint selection.createColorStyle gives the new style the variable bindings of the fill or stroke it is made from, the color and the gradient stops, so linked layers keep following the variables. Targets bound to different variables are refused, and the Styles menu leaves Create style out for them. --- .../engine/src/selection/selection_colors.rs | 39 ++++++++----- crates/engine/tests/it/selection_colors.rs | 57 +++++++++++++++++++ docs/ui-parity.md | 2 +- 3 files changed, 83 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/selection/selection_colors.rs b/crates/engine/src/selection/selection_colors.rs index 52e39483b..53ef11fae 100644 --- a/crates/engine/src/selection/selection_colors.rs +++ b/crates/engine/src/selection/selection_colors.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; use figcraft_color::{Paint, PaintKind}; -use figcraft_doc::{Document, NodeId, NodeKind, Style, StyleKind, VariableType, VariableValue}; +use figcraft_doc::{Document, NodeId, NodeKind, Style, StyleKind, VariableId, VariableType, VariableValue}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -134,7 +134,7 @@ pub fn specs() -> Vec { spec!( "selection.createColorStyle", "Create selection color style", - "{targets, name, description?} → {id}; makes a color style of the paint the targets share and applies it to them as selection.applyColorStyle does; a name another style has, or a target whose list holds other paints, is refused", + "{targets, name, description?} → {id}; makes a color style of the paint the targets share and applies it to them as selection.applyColorStyle does, keeping the variables bound to the paint; a name another style has, a target whose list holds other paints, or targets bound to different variables are refused", true, create_style ), @@ -259,15 +259,11 @@ fn create_style(s: &mut Session, p: &Value) -> Result { if doc.styles.iter().any(|st| st.name == name) { return Err(bad(CMD, format!("a style named `{name}` already exists"))); } + let kind = StyleKind::Paint { paints: vec![paint] }; + let bound = targets.first().map(|t| target_bindings(doc, t, &kind)).unwrap_or_default(); let doc = s.doc_mut()?; let id = doc.new_style_id(); - let style = Style { - id: id.clone(), - name, - description: string(p, "description").unwrap_or_default(), - kind: StyleKind::Paint { paints: vec![paint] }, - bound: BTreeMap::new(), - }; + let style = Style { id: id.clone(), name, description: string(p, "description").unwrap_or_default(), kind, bound }; doc.styles.push(style.clone()); link_style(s, &targets, &style)?; Ok(json!({"id": id})) @@ -275,12 +271,27 @@ fn create_style(s: &mut Session, p: &Value) -> Result { /// Why a color style can't be made from `targets` (`selection.createColorStyle`), if it can't: a /// linked style replaces the whole fill or stroke list, so a target whose list holds other paints -/// would lose them. The Selection colors menu leaves Create style out for such rows. +/// would lose them. The new style takes over the variables bound to the paint, so targets bound to +/// different variables are refused too. The Selection colors menu leaves Create style out for such rows. pub fn create_refusal(doc: &Document, targets: &[PaintTarget]) -> Option<&'static str> { - targets - .iter() - .any(|t| t.paints(doc).is_none_or(|paints| paints.len() != 1)) - .then_some("a style can only be made from a fill or stroke list that holds this one paint") + if targets.iter().any(|t| t.paints(doc).is_none_or(|paints| paints.len() != 1)) { + return Some("a style can only be made from a fill or stroke list that holds this one paint"); + } + let paint = targets.first().and_then(|t| t.paint(doc))?; + let kind = StyleKind::Paint { paints: vec![paint] }; + let mut bindings = targets.iter().map(|t| target_bindings(doc, t, &kind)); + let first = bindings.next()?; + bindings.any(|b| b != first).then_some("the targets are bound to different variables") +} + +/// The variable bindings a paint style of `kind` made from `target` takes over: those on the fill or +/// stroke list the target stands for. A text range with fills of its own holds none. +fn target_bindings(doc: &Document, target: &PaintTarget, kind: &StyleKind) -> BTreeMap { + if list_field(doc, target).is_none() { + return BTreeMap::new(); + } + let field = if target.fills { "fillStyle" } else { "strokeStyle" }; + doc.node(target.id).map(|n| crate::style_vars::from_layer(n, field, kind)).unwrap_or_default() } /// Apply paint style `style` to every target: a fill or stroke list is linked to it; a text range diff --git a/crates/engine/tests/it/selection_colors.rs b/crates/engine/tests/it/selection_colors.rs index 7778fedc3..be661e21a 100644 --- a/crates/engine/tests/it/selection_colors.rs +++ b/crates/engine/tests/it/selection_colors.rs @@ -529,6 +529,63 @@ fn creating_a_style_refuses_a_row_whose_list_holds_other_paints() { assert!(s.doc().unwrap().node(b).unwrap().styles.fill.is_some()); } +#[test] +fn a_style_created_from_a_variable_bound_row_keeps_following_the_variable() { + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let b = rectangle(&mut s, "#ff0000"); + let v = theme_variable(&mut s, "Brand", "#ff0000"); + for id in [a, b] { + run(&mut s, "variable.bind", json!({"id":id,"field":"fill","variable":v})); + } + let red = group(&s, &[a, b], "FF0000"); + assert_eq!(red.targets.len(), 2); + run(&mut s, "selection.createColorStyle", json!({"targets":red.targets,"name":"Brand"})); + let style = s.doc().unwrap().style("Brand").unwrap(); + assert_eq!(style.bound.get("fills/0/color").map(String::as_str), v.as_str()); + run(&mut s, "variable.set", json!({"variable":v,"value":"#00ff00"})); + assert_eq!(fill(&s, a), "00FF00"); + assert_eq!(fill(&s, b), "00FF00"); +} + +#[test] +fn a_style_created_from_a_gradient_keeps_its_stop_variables() { + use figcraft_color::{Color, Gradient, GradientKind, PaintKind}; + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let paint = Paint::gradient(Gradient::default_for(GradientKind::Linear, Color::BLACK)); + run(&mut s, "fill.set", json!({"id":a,"paint":paint})); + let v = theme_variable(&mut s, "Brand", "#ff0000"); + run(&mut s, "variable.bind", json!({"id":a,"field":"fills/0/stops/0/color","variable":v})); + let row = collect(s.doc().unwrap(), &[a]).into_iter().next().unwrap(); + run(&mut s, "selection.createColorStyle", json!({"targets":row.targets,"name":"Shade"})); + assert!(s.doc().unwrap().style("Shade").unwrap().bound.contains_key("fills/0/stops/0/color")); + run(&mut s, "variable.set", json!({"variable":v,"value":"#00ff00"})); + let PaintKind::Gradient(g) = &s.doc().unwrap().node(a).unwrap().fills[0].kind else { panic!("not a gradient") }; + assert_eq!(g.stops[0].color.to_hex(), "00FF00"); +} + +#[test] +fn creating_a_style_refuses_targets_bound_to_different_variables() { + let mut s = Session::new(); + let a = rectangle(&mut s, "#ff0000"); + let b = rectangle(&mut s, "#ff0000"); + let v = theme_variable(&mut s, "Brand", "#ff0000"); + run(&mut s, "variable.bind", json!({"id":a,"field":"fill","variable":v})); + let targets: Vec<_> = collect(s.doc().unwrap(), &[a, b]).into_iter().flat_map(|g| g.targets).collect(); + assert_eq!(targets.len(), 2); + assert!(selection_colors::create_refusal(s.doc().unwrap(), &targets).is_some()); + let before = s.undo_depth(); + let styles = s.doc().unwrap().styles.len(); + let err = s.execute("selection.createColorStyle", &json!({"targets":targets,"name":"Red"})).unwrap_err(); + assert!(err.to_string().contains("different variables"), "{err}"); + assert_eq!(s.undo_depth(), before); + let doc = s.doc().unwrap(); + assert_eq!(doc.styles.len(), styles); + assert!(!doc.node(a).unwrap().bound.is_empty()); + assert!(doc.node(b).unwrap().styles.fill.is_none()); +} + #[test] fn a_linked_row_switches_to_another_style() { let mut s = Session::new(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5e634bc2b..5d0ba4b96 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -74,7 +74,7 @@ interaction feel not yet compared. | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | 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`). 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 and blend mode 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 | 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) | | 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 From b957160379280a9dbbc1aca20ffa8cad263fa451 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:37:01 +0100 Subject: [PATCH 018/326] Fix code export printing inf for very large finite numbers (#1757) * Fix code export printing inf for very large finite numbers Found while testing crates/engine/src/dev/codegen.rs:185 (num) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 * Keep rem values finite past num6's scaling overflow num6 had the same x1e6 overflow as num: a huge finite length printed 0rem (CodeRabbit on #1757). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Haiku 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/dev/codegen.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 6d2ab92dd..55786d52d 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -182,7 +182,9 @@ pub(crate) fn num(v: f64) -> String { if !v.is_finite() { return "0".into(); } - let r = (v * 100.0).round() / 100.0; + let scaled = v * 100.0; + // Past the x100 overflow every value is whole anyway, so keep it as is. + let r = if scaled.is_finite() { scaled.round() / 100.0 } else { v }; if (r - r.round()).abs() < 1e-9 { // `as i64` saturates past 2^63, so larger whole values are printed from the float. if r.abs() < 9e18 { format!("{}", r.round() as i64) } else { format!("{:.0}", r.round()) } @@ -193,7 +195,9 @@ pub(crate) fn num(v: f64) -> String { /// `v` without trailing zeros (6 decimals), for lengths that must convert back to the same pixels. fn num6(v: f64) -> String { - let r = (v * 1_000_000.0).round() / 1_000_000.0; + let scaled = v * 1_000_000.0; + // Past the x1e6 overflow every value is whole anyway, so keep it as is. + let r = if scaled.is_finite() { scaled.round() / 1_000_000.0 } else { v }; if r.is_finite() && r != 0.0 { format!("{r}") } else { "0".into() } } @@ -458,6 +462,21 @@ mod tests { use crate::params::id_of; use serde_json::json; + #[test] + fn num_keeps_finite_values_past_the_x100_overflow() { + for v in [1e307, -1e307, f64::MAX] { + let s = num(v); + assert_eq!(s, format!("{v:.0}")); + assert_eq!(s.parse::(), Ok(v)); + } + } + + #[test] + fn num6_keeps_finite_values_past_the_x1e6_overflow() { + assert_eq!(num6(1e305).parse::(), Ok(1e305)); + assert_eq!(num6(0.1234567), "0.123457"); + } + #[test] fn num_keeps_huge_whole_numbers() { assert_eq!(num(1e20), "100000000000000000000"); From 3b5de555876ccb8d2f9d9a4ce9468dbf4632a980 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:37:05 +0100 Subject: [PATCH 019/326] Keep huge finite values finite when stepping number fields (#1753) Found while testing crates/ui-egui/src/widgets/field_math.rs:168 (stepped, used by widgets.rs:131 scrubbed) Co-authored-by: Claude Haiku 5.5 --- crates/ui-egui/src/widgets/field_math.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/widgets/field_math.rs b/crates/ui-egui/src/widgets/field_math.rs index f81500e67..9de90e278 100644 --- a/crates/ui-egui/src/widgets/field_math.rs +++ b/crates/ui-egui/src/widgets/field_math.rs @@ -167,7 +167,12 @@ pub fn eval(text: &str, cur: Option) -> Option { /// (0.1 + 0.2). pub fn stepped(from: f64, steps: f64, step: f64) -> f64 { let v = from + steps * step; - if v.is_finite() { (v * 1e6).round() / 1e6 } else { from } + if !v.is_finite() { + return from; + } + let rounded = (v * 1e6).round() / 1e6; + // Past ~1.8e302 the scaling overflows; such a value has no dust to remove. + if rounded.is_finite() { rounded } else { v } } #[cfg(test)] @@ -182,4 +187,10 @@ mod tests { assert_eq!(parse("50 %", true), Some(Typed::Value(50.0))); assert_eq!(parse("3 px + 2 px", true), Some(Typed::Value(5.0))); } + + #[test] + fn stepped_keeps_a_huge_finite_value_finite() { + assert_eq!(stepped(1e305, 1.0, 1.0), 1e305); + assert!(stepped(f64::MAX / 2.0, 0.0, 1.0).is_finite()); + } } From fad47ac8bcd876333d7e75377190a80c7740055d Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:37:09 +0100 Subject: [PATCH 020/326] Relative line height and letter spacing edits with a unit suffix add to the current value (#1755) Found while testing crates/ui-egui/src/panels/typography/spacing.rs:166 (parse_line_height, px branch; also :183 and :180 in parse_letter_spacing, px and % branches) Co-authored-by: Claude Haiku 5.5 --- .../ui-egui/src/panels/typography/spacing.rs | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/typography/spacing.rs b/crates/ui-egui/src/panels/typography/spacing.rs index 54c327dd0..5ffaf22a2 100644 --- a/crates/ui-egui/src/panels/typography/spacing.rs +++ b/crates/ui-egui/src/panels/typography/spacing.rs @@ -164,7 +164,11 @@ pub(crate) fn parse_line_height(s: &str, cur: Option) -> Option Some(p), + _ => None, + }; + return widgets::eval(px.trim(), cur_px).filter(|v| v.is_finite()).map(|v| json!(v.max(0.0))); } match cur { Some(LineHeight::Percent(p)) => widgets::eval(s, Some(p)).filter(|v| v.is_finite()).map(|v| json!(format!("{}%", trim_num(v.max(0.0))))), @@ -178,10 +182,18 @@ pub(crate) fn parse_line_height(s: &str, cur: Option) -> Option) -> Option { let s = s.trim(); if let Some(p) = s.strip_suffix('%') { - return widgets::eval(p.trim(), None).filter(|v| v.is_finite()).map(|v| json!(format!("{}%", trim_num(v)))); + let cur_pct = match cur { + Some(LetterSpacing::Percent(p)) => Some(p), + _ => None, + }; + return widgets::eval(p.trim(), cur_pct).filter(|v| v.is_finite()).map(|v| json!(format!("{}%", trim_num(v)))); } if let Some(p) = s.strip_suffix("px") { - return widgets::eval(p.trim(), None).filter(|v| v.is_finite()).map(|v| json!(v)); + let cur_px = match cur { + Some(LetterSpacing::Pixels(p)) => Some(p), + _ => None, + }; + return widgets::eval(p.trim(), cur_px).filter(|v| v.is_finite()).map(|v| json!(v)); } match cur { Some(LetterSpacing::Pixels(px)) => widgets::eval(s, Some(px)).filter(|v| v.is_finite()).map(|v| json!(v)), @@ -206,3 +218,21 @@ pub(crate) fn letter_spacing_of(v: &Value) -> Option { other => other.as_f64().filter(|v| v.is_finite()).map(LetterSpacing::Pixels), } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relative_edit_with_unit_suffix_adds_to_current() { + let lh = Some(LineHeight::Pixels(10.0)); + assert_eq!(parse_line_height("+2", lh), Some(json!(12.0))); + assert_eq!(parse_line_height("+2px", lh), Some(json!(12.0))); + let ls = Some(LetterSpacing::Pixels(10.0)); + assert_eq!(parse_letter_spacing("+1", ls), Some(json!(11.0))); + assert_eq!(parse_letter_spacing("+1px", ls), Some(json!(11.0))); + let pct = Some(LetterSpacing::Percent(10.0)); + assert_eq!(parse_letter_spacing("+1%", pct), parse_letter_spacing("+1", pct)); + assert_eq!(parse_letter_spacing("+1%", pct), Some(json!("11%"))); + } +} From 45e5a25370fc4fe0df00ac2f15589092ab24229b Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:37:13 +0100 Subject: [PATCH 021/326] Escape backslashes and line breaks in CSS font-family export (#1752) * Escape backslashes and line breaks in CSS font-family export Found while testing crates/engine/src/dev/codegen/css.rs:223 (text_decls, the font-family put) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 * Escape quotes and < in CSS font-family export A double quote in a family name is escaped instead of turned into a single quote (CodeRabbit on #1752), and < is written as \3C so a name can't end the generated page's "})); + let css = crate::codegen::css_decls(s.doc().unwrap(), s.doc().unwrap().node(t).unwrap(), &mut Default::default(), (true, true)); + assert!(css.contains(r#"font-family: "Foo\"\3C /style>";"#), "{css}"); +} From 9a7e5d1a1634a927895cd2c1d116523e322dfe82 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:37:18 +0100 Subject: [PATCH 022/326] Apply paint opacity to CSS gradient stops in code export (#1750) Found while testing crates/engine/src/dev/codegen/css.rs:121 (css_decls, the PaintKind::Gradient arm calling css_gradient at :255) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/dev/codegen.rs | 12 ++++++++++++ crates/engine/src/dev/codegen/css.rs | 11 ++++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 55786d52d..925acdd0a 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -494,6 +494,18 @@ mod tests { f } + #[test] + fn css_gradient_folds_in_paint_opacity() { + let mut s = Session::new(); + let f = id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap()["id"]).unwrap(); + let mut p = figcraft_color::Paint::gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, Color::BLACK)); + p.opacity = 0.5; + s.doc_mut().unwrap().get_mut(f).unwrap().fills = vec![p]; + let css = code_for(s.doc().unwrap(), f, CodeLang::Css); + assert!(css.contains("rgba(0, 0, 0, 0.50) 0%"), "{css}"); + assert!(!css.contains("#000000 0%"), "{css}"); + } + #[test] fn swiftui_and_compose_for_an_auto_layout_card() { let mut s = Session::new(); diff --git a/crates/engine/src/dev/codegen/css.rs b/crates/engine/src/dev/codegen/css.rs index 0e07f0bf1..087eb7905 100644 --- a/crates/engine/src/dev/codegen/css.rs +++ b/crates/engine/src/dev/codegen/css.rs @@ -120,7 +120,7 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo // A variable binds the first paint's colour. put(key, if i == 0 { tok(doc, n, &["fill"], c, t) } else { c }); } - PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height)), + PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)), PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()), PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()), } @@ -307,8 +307,13 @@ fn decoration_decls(s: &figcraft_doc::TextStyle, put: &mut impl FnMut(&str, Stri /// A gradient fill on a `w`×`h` box as a CSS background: linear along its handles' direction /// (CSS angles: 0deg up, 90deg right), radial with its handles' radii, angular as a conic /// gradient from its start direction. -fn css_gradient(g: &figcraft_color::Gradient, w: f64, h: f64) -> String { - let stops = g.sorted_stops().iter().map(|s| format!("{} {}%", s.color.to_css(), (s.position * 100.0).round())).collect::>().join(", "); +fn css_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String { + let stops = g + .sorted_stops() + .iter() + .map(|s| format!("{} {}%", s.color.with_alpha(s.color.a * opacity).to_css(), (s.position * 100.0).round())) + .collect::>() + .join(", "); let (dx, dy) = ((g.to.0 - g.from.0) * w, (g.to.1 - g.from.1) * h); let angle = if dx == 0.0 && dy == 0.0 { 180.0 } else { dx.atan2(-dy).to_degrees().rem_euclid(360.0) }; let pct = |v: f64| format!("{}%", num(v * 100.0)); From 556d44d47a94c6be320ce42f99064bfed970ea34 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:37:22 +0100 Subject: [PATCH 023/326] Reject '+' sign in comment parse_link thread ids (#1740) Found while testing crates/engine/src/cmd/comment.rs:55 (parse_link) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/cmd/comment.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index cf675d0fc..c2eb69b12 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -52,7 +52,12 @@ pub fn link(id: u64) -> String { /// The thread id in a link (or a bare id). pub fn parse_link(s: &str) -> Option { let s = s.trim(); - s.strip_prefix(LINK_PREFIX).unwrap_or(s).trim_end_matches('/').parse().ok() + let s = s.strip_prefix(LINK_PREFIX).unwrap_or(s).trim_end_matches('/'); + // Digits only: `u64::parse` would also accept a leading '+'. + if !s.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + s.parse().ok() } /// Which threads a list shows. @@ -997,6 +1002,15 @@ mod tests { use crate::Session; + #[test] + fn parse_link_rejects_sign() { + assert_eq!(super::parse_link("+5"), None); + assert_eq!(super::parse_link("figcraft://comment/+5"), None); + assert_eq!(super::parse_link(""), None); + assert_eq!(super::parse_link("5"), Some(5)); + assert_eq!(super::parse_link("figcraft://comment/5/"), Some(5)); + } + #[test] fn comment_thread_lifecycle_and_anchoring() { let mut s = Session::new(); From 96dcb3eda9bd063b66da13cb20cb7086090b8f38 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:37:26 +0100 Subject: [PATCH 024/326] Give each variable a unique custom property in CSS export (#1738) Found while testing crates/engine/src/cmd/variables_io.rs:~80-105 (css, non-tailwind `name` closure using css_var_of) with crates/engine/src/dev/codegen/css.rs:41 (css_var_name) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/variables_io.rs | 6 ++- crates/engine/src/dev/codegen.rs | 2 +- crates/engine/src/dev/codegen/css.rs | 52 ++++++++++++++++++++++++- crates/engine/src/variables_io_tests.rs | 23 +++++++++++ 4 files changed, 78 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/variables_io.rs b/crates/engine/src/cmd/variables_io.rs index dfdee7b80..1b3b4ee29 100644 --- a/crates/engine/src/cmd/variables_io.rs +++ b/crates/engine/src/cmd/variables_io.rs @@ -8,7 +8,7 @@ use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, Variable, V use serde_json::{Value, json}; use super::CommandSpec; -use crate::codegen::{css_var_name, css_var_of}; +use crate::codegen::{CssNames, css_var_name}; use crate::library::{is_remote_collection, local_collections}; use crate::params::{get, string}; use crate::{EngineError, Result, Session, bad, spec}; @@ -73,7 +73,9 @@ fn css(doc: &Document, colls: &[&Collection], tailwind: bool) -> String { let flattener = vars.flattener(); // Tailwind theme names, unique per file and the same ones page code reads. let theme = crate::tailwind::Theme::new(doc); - let name = |v: &Variable| if tailwind { theme.name(v) } else { css_var_of(v) }; + // CSS names, unique per file and the same ones generated code reads. + let names = CssNames::new(doc); + let name = |v: &Variable| if tailwind { theme.name(v) } else { names.name(v) }; // Lengths need a unit where CSS reads them (`border-radius: var(--radius)`); opacity and // font weight don't. let roles = crate::token_roles::Roles::new(doc); diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 925acdd0a..b9df04f12 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -30,8 +30,8 @@ pub(crate) use compose::{compose, kotlin_color}; pub(crate) use css::Tokens; #[cfg(test)] pub(crate) use css::css_decls; +pub use css::{CssNames, css_var_name, css_var_of}; use css::{css, tok}; -pub use css::{css_var_name, css_var_of}; pub(crate) use flutter::{FLUTTER_IMPORT, Place, flutter, flutter_indent}; use html::html; pub(crate) use html::{Markup, class_name}; diff --git a/crates/engine/src/dev/codegen/css.rs b/crates/engine/src/dev/codegen/css.rs index 087eb7905..eb9406f2a 100644 --- a/crates/engine/src/dev/codegen/css.rs +++ b/crates/engine/src/dev/codegen/css.rs @@ -1,3 +1,7 @@ +use std::collections::{HashMap, HashSet}; + +use figcraft_doc::VariableId; + use super::{ ContentAlign, CrossAlign, Document, EffectKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, PADDING, PaintKind, TextAlignH, TextCase, TextDecoration, Variable, css_borders, num, @@ -13,13 +17,18 @@ pub(crate) struct Tokens { pub tailwind: bool, /// The file's theme names (computed on first use). theme: Option, + /// The file's CSS names (computed on first use). + names: Option, } impl Tokens { /// `var(--name, value)`, remembering the variable. fn var(&mut self, doc: &Document, variable: &Variable, value: String) -> String { - let name = - if self.tailwind { self.theme.get_or_insert_with(|| crate::tailwind::Theme::new(doc)).name(variable) } else { css_var_of(variable) }; + let name = if self.tailwind { + self.theme.get_or_insert_with(|| crate::tailwind::Theme::new(doc)).name(variable) + } else { + self.names.get_or_insert_with(|| CssNames::new(doc)).name(variable) + }; let out = format!("var({name}, {value})"); if !self.vars.iter().any(|(n, _)| *n == name) { self.vars.push((name, value)); @@ -60,6 +69,45 @@ pub fn css_var_of(v: &Variable) -> String { if valid { inner.chars().take(80).collect() } else { css_var_name(inner) } } +/// The file's variables' CSS custom properties, unique in the file: [`css_var_of`], and where an +/// earlier variable already has that name, the name with a numeric suffix (`--brand-primary-2`). +pub struct CssNames { + names: HashMap, +} + +impl CssNames { + pub fn new(doc: &Document) -> Self { + let vars = &doc.variables.variables; + let mut names = HashMap::with_capacity(vars.len()); + // Every plain name is reserved first, so a suffixed name never takes another's plain one; + // the next suffix per base keeps this linear. + let plain: Vec = vars.iter().map(css_var_of).collect(); + let mut taken: HashSet = HashSet::with_capacity(vars.len()); + let all: HashSet<&str> = plain.iter().map(String::as_str).collect(); + let mut next: HashMap<&str, usize> = HashMap::new(); + for (v, base) in vars.iter().zip(&plain) { + let mut name = base.clone(); + if !taken.insert(name.clone()) { + let k = next.entry(base.as_str()).or_insert(1); + loop { + *k += 1; + name = format!("{base}-{k}"); + if !all.contains(name.as_str()) && taken.insert(name.clone()) { + break; + } + } + } + names.insert(v.id.clone(), name); + } + CssNames { names } + } + + /// The custom property for `v` (its [`css_var_of`] name for a variable not in the file). + pub fn name(&self, v: &Variable) -> String { + self.names.get(&v.id).cloned().unwrap_or_else(|| css_var_of(v)) + } +} + /// `value`, or a reference to the variable bound to the first of `fields` that has one. pub(super) fn tok(doc: &Document, n: &Node, fields: &[&str], value: String, t: &mut Tokens) -> String { match fields.iter().find_map(|f| crate::devinspect::bound_variable(doc, n, f)) { diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index 57473a057..eba692802 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -639,3 +639,26 @@ fn stored_variable_ids_reset_only_the_inherited_parent_and_collection() { assert_eq!(result.overrides, std::collections::BTreeSet::from([light])); } } + +#[test] +fn css_export_gives_clashing_variable_names_their_own_property() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Brand"})); + ex(&mut s, "variable.create", json!({"collection": "Brand", "name": "Brand/Primary", "type": "color", "value": "#ff0000"})); + let blue = ex(&mut s, "variable.create", json!({"collection": "Brand", "name": "Brand Primary", "type": "color", "value": "#0000ff"})); + ex(&mut s, "variable.create", json!({"collection": "Brand", "name": "link", "type": "color", "value": {"alias": blue["id"]}})); + let css = ex(&mut s, "variable.export", json!({"format": "css"}))["text"].as_str().unwrap_or_default().to_string(); + let decls: Vec<(&str, &str)> = + css.lines().filter_map(|l| l.trim().strip_prefix("--").and_then(|d| d.strip_suffix(';')).and_then(|d| d.split_once(": "))).collect(); + let mut names: Vec<&str> = decls.iter().map(|(n, _)| *n).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), decls.len(), "{css}"); + let red = decls.iter().find(|(_, v)| *v == "#FF0000").map(|(n, _)| *n); + let blue = decls.iter().find(|(_, v)| *v == "#0000FF").map(|(n, _)| *n); + // The first keeps its plain name; the alias reads the one its target is declared under. + assert_eq!(red, Some("brand-primary"), "{css}"); + let blue = blue.unwrap_or_default(); + assert_ne!(blue, "brand-primary", "{css}"); + assert!(css.contains(&format!("--link: var(--{blue});")), "{css}"); +} From e04c5d2274329587b9213f27ad8f88708ea77748 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9D=90=A7=F0=9D=90=9E=F0=9D=90=AB=F0=9D=90=AC?= Date: Sat, 31 Oct 2026 15:38:47 +0100 Subject: [PATCH 025/326] text: use craft-font-catalog on Unix (#1765) * text: use craft-font-catalog on Unix On Linux and BSD distributions that do not follow traditional FHS layout (such as NixOS and Guix), or systems using custom font configurations, fonts are not located under `/usr/share/fonts` or `/usr/local/share/fonts`. Instead, font directories are declared in `/etc/fonts/fonts.conf` and its included configuration files (such as `/etc/fonts/conf.d`), or under `$XDG_DATA_DIRS/fonts`. `figcraft-text` already depends on `craft-font-catalog`, which provides `craft_font_catalog::font_dirs`: - Preserves all existing directory sources (`/usr/share/fonts`, `/usr/local/share/fonts`, and user font directories). - Adds Flatpak host directories (`/run/host/fonts`), `$XDG_DATA_DIRS`, and fontconfig directory trees (`/etc/fonts/fonts.conf`). - Deduplicates the combined list via `craft_font_catalog::dedup_dirs` using canonical paths, ensuring equivalent directories and symlinks are not redundantly scanned. Use `craft_font_catalog::font_dirs` in `system_font_dirs()` on Unix, and retain `unix_user_font_dirs` under `#[cfg(test)]` for its unit tests. * text: walk each system font folder once Fontconfig usually lists folders the scan already has (/usr/share/fonts); the list is deduplicated so their faces aren't indexed twice (CodeRabbit on #1765). Co-Authored-By: Claude Opus 5.5 * text: scan the catalog's full Unix font folder list fontconfig_dirs alone dropped /usr/share/fonts, ~/.fonts and the XDG folders when no fontconfig configuration exists; font_dirs keeps them, adds what fontconfig names, and deduplicates, as the PR description intended. The local user-folder helper it replaces is removed with its tests (the catalog applies the same XDG rules). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/text/src/fontdb.rs | 25 ++++++------------------- crates/text/src/fontdb_tests.rs | 33 +++++++-------------------------- 2 files changed, 13 insertions(+), 45 deletions(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index fa708a1bd..2c6aac948 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -1250,14 +1250,17 @@ fn system_font_dirs() -> Vec { } #[cfg(all(unix, not(target_os = "macos")))] { - v.push("/usr/share/fonts".into()); - v.push("/usr/local/share/fonts".into()); - v.extend(unix_user_font_dirs(std::env::var_os("HOME"), std::env::var_os("XDG_DATA_HOME"))); + // The standard folders, the user's (`~/.fonts`, `$XDG_DATA_HOME/fonts`), `$XDG_DATA_DIRS` + // and those fontconfig names (NixOS and Guix keep fonts only there). + v.extend(craft_font_catalog::font_dirs(&craft_font_catalog::FontEnv::from_process())); } // Fonts any Craft app downloaded into the suite's font store (a download being installed is a // `.part` file, which the walk skips). #[cfg(not(target_arch = "wasm32"))] v.extend(craft_font_catalog::font_store_dir(&craft_font_catalog::FontEnv::from_process())); + // Fontconfig usually lists folders already here (`/usr/share/fonts`): walk each once. + let mut seen = std::collections::HashSet::new(); + v.retain(|d| seen.insert(d.clone())); v } @@ -1270,22 +1273,6 @@ fn font_asset_dirs(store: &std::path::Path) -> Vec { rd.flatten().filter(|e| e.file_name().to_str().is_some_and(|n| n.starts_with("com_apple_MobileAsset_Font"))).map(|e| e.path()).collect() } -// Fontconfig's default configuration uses $XDG_DATA_HOME/fonts for user fonts. -// Ignore relative XDG paths, as required by the XDG Base Directory Specification. -#[cfg(all(unix, not(target_os = "macos")))] -fn unix_user_font_dirs(home: Option, data_home: Option) -> Vec { - let home = home.map(std::path::PathBuf::from); - let data = data_home.map(std::path::PathBuf::from).filter(|p| p.is_absolute()).or_else(|| home.as_ref().map(|h| h.join(".local/share"))); - let mut dirs = Vec::new(); - if let Some(home) = home { - dirs.push(home.join(".fonts")); - } - if let Some(data) = data { - dirs.push(data.join("fonts")); - } - dirs -} - /// Adds the faces of every font file under `dir` (up to six folders deep) to `out`, keyed by /// lowercased family: files named `.ttf`, `.otf`, `.ttc` or `.otc`, and files without an extension /// that start with a font signature. diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index dc75b13cb..5f0fa522b 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -264,32 +264,6 @@ fn every_platform_has_a_symbol_font_in_the_fallbacks() { assert!(at("Noto Sans") < at("Noto Sans Symbols") && at("DejaVu Sans") < at("Noto Sans Math")); } -#[cfg(all(unix, not(target_os = "macos")))] -#[test] -fn user_font_dirs_follow_xdg_data_home() { - use std::ffi::OsString; - use std::path::PathBuf; - let dirs = |home: Option<&str>, data: Option<&str>| unix_user_font_dirs(home.map(OsString::from), data.map(OsString::from)); - let paths = |items: &[&str]| items.iter().map(PathBuf::from).collect::>(); - assert_eq!(dirs(Some("/home/user"), Some("/custom user data")), paths(&["/home/user/.fonts", "/custom user data/fonts"])); - for data in [None, Some(""), Some("relative/data")] { - assert_eq!(dirs(Some("/home/user"), data), paths(&["/home/user/.fonts", "/home/user/.local/share/fonts"])); - } - assert_eq!(dirs(None, Some("/custom-data")), paths(&["/custom-data/fonts"])); - assert_eq!(dirs(None, None), paths(&[])); - assert_eq!(dirs(None, Some("relative")), paths(&[])); -} - -#[cfg(all(unix, not(target_os = "macos")))] -#[test] -fn user_font_dirs_preserve_non_utf8_paths() { - use std::ffi::OsString; - use std::os::unix::ffi::{OsStrExt, OsStringExt}; - let dirs = unix_user_font_dirs(Some(OsString::from_vec(b"/home/\xff".to_vec())), Some(OsString::from_vec(b"/data/\xfe".to_vec()))); - assert_eq!(dirs[0].as_os_str().as_bytes(), b"/home/\xff/.fonts"); - assert_eq!(dirs[1].as_os_str().as_bytes(), b"/data/\xfe/fonts"); -} - #[test] fn the_scan_reads_font_files_without_an_extension() { // #298: Adobe Fonts keeps the fonts it activates in hidden files named by number. Any installed @@ -614,3 +588,10 @@ fn core_text_lists_the_installed_font_files() { assert!(files.iter().any(|f| f.starts_with("/System/Library/Fonts")), "{} files", files.len()); assert!(files.iter().all(|f| f.is_absolute())); } + +#[test] +fn system_font_dirs_are_walked_once_each() { + let dirs = super::system_font_dirs(); + let unique: std::collections::HashSet<_> = dirs.iter().collect(); + assert_eq!(unique.len(), dirs.len(), "{dirs:?}"); +} From 7bee269c4d6c48c805bba45859c8df48e27ea856 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 31 Oct 2026 10:58:09 -0400 Subject: [PATCH 026/326] M8: posting a comment in the browser no longer stops the app (#1764) The event log read the clock through std::time::SystemTime and Instant, which panic on wasm32-unknown-unknown ("time not implemented on this platform"). Every mutating comment.* command appends an event, so the first comment posted in the web build hit it. The log now takes SystemTime, UNIX_EPOCH and Instant from web_time, as the rest of the engine does. A test checks the stamp is a current Unix time read through the same clock. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/events.rs | 6 +++++- crates/engine/src/events_tests.rs | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/events.rs b/crates/engine/src/events.rs index fbc1b9b6c..328d6ba5e 100644 --- a/crates/engine/src/events.rs +++ b/crates/engine/src/events.rs @@ -7,10 +7,14 @@ use std::collections::VecDeque; use std::sync::{Condvar, Mutex, PoisonError}; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use std::time::Duration; use serde::Serialize; use serde_json::Value; +// The browser build has no `std` clock: `std::time::SystemTime::now()` panics on +// wasm32-unknown-unknown ("time not implemented on this platform"), and every `comment.*` command +// stamps an event. `web_time` is `std::time` on native targets and the JavaScript clock on wasm. +use web_time::{Instant, SystemTime, UNIX_EPOCH}; /// Most events kept; the oldest are dropped. pub const MAX_EVENTS: usize = 1024; diff --git a/crates/engine/src/events_tests.rs b/crates/engine/src/events_tests.rs index 36b118a79..ad20974c5 100644 --- a/crates/engine/src/events_tests.rs +++ b/crates/engine/src/events_tests.rs @@ -44,6 +44,18 @@ fn events_keep_sequence_and_filter_topics() { assert_eq!(r.events[0].kind, "document.changed"); } +#[test] +fn events_are_stamped_with_the_wall_clock() { + // The stamp is read through `web_time`, the clock the browser build has as well: with + // `std::time::SystemTime` every comment posted on the web panicked (#1764). + let log = EventLog::default(); + log.push("comment.added", "Doc", None, json!({"commentId": 1})); + let r = log.poll(0, &comments(), 10, Duration::ZERO); + let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs_f64(); + let time = r.events[0].time; + assert!(time > 1_700_000_000.0 && time <= now, "{time} is seconds since the Unix epoch, read just before {now}"); +} + #[test] fn a_poll_wakes_for_a_push() { let log = Arc::new(EventLog::default()); From 03151d86849a3bf6f02eb8304eb09f832d5190ef Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 31 Oct 2026 11:10:18 -0400 Subject: [PATCH 027/326] M7: a gap between Import and Export in the Local variables window (#1754) The window lays itself out with zero item spacing, and the header button bar is a child Ui that inherited it, so Import and Export touched. The bar now spaces its buttons 16 px apart, the gap Export has to the Close button glyph. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/dialogs/variables_panel.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index 9a1011a42..28d9a21e5 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -181,6 +181,9 @@ fn header(app: &mut FigApp, ui: &mut Ui, open: &mut bool) { // Import and export, left of Close. let bar = Rect::from_min_max(pos2(r.max.x - 280.0, r.min.y + 10.0), pos2(r.max.x - 40.0, r.max.y - 10.0)); let mut bar = ui.new_child(UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); + // The window lays itself out without item spacing (set by the caller); the buttons in this bar + // keep the same gap between them as the one between Export and the Close button (#1754). + bar.spacing_mut().item_spacing.x = 16.0; let export = widgets::button(&mut bar, tr("Export…"), false, true); crate::right::menu_popup(&export).show(|ui| { for (label, format) in [(tr("Variables JSON…"), "json"), (tr("CSS custom properties…"), "css"), (tr("Dart constants for Flutter…"), "dart")] From 40534ddf14f204743e7e6558bb0a9f8a8d71d144 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 31 Oct 2026 11:20:21 -0400 Subject: [PATCH 028/326] M1: the page background opacity can be edited in the Page section (#1748) The Design panel drew the page opacity as a "100 %" label, so it could not be changed from the panel although the model, page.setBackground and the colour picker already handled a translucent page. The label is now a percent number field like the other opacity fields (named Opacity for screen readers), committing page.setBackground; a scrub stays one undo step. The hex field keeps the current opacity unless the typed colour carries one, as the colour picker does. Regression test in field_tests. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 41 ++++++++++++++++++++++++++++++ crates/ui-egui/src/panels/right.rs | 39 +++++++++++++++++++++------- 2 files changed, 71 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 566f0828b..63995fc80 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1194,3 +1194,44 @@ fn sidebar_field_text_stays_in_place_on_focus() { assert!((before.center().y - after.center().y).abs() <= 0.5, "numeric={numeric}: before={before:?}, after={after:?}"); } } + +/// 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. +#[test] +fn the_page_background_opacity_field_sets_the_page_colour_alpha() { + let mut u = Ui::new(Session::new()); + u.ctx.enable_accesskit(); + u.frame(vec![]); + let page_bg = |u: &Ui| { + let page = u.app.session.page().unwrap(); + match &u.app.session.doc().unwrap().node(page).unwrap().kind { + figcraft_doc::NodeKind::Page { background, .. } => *background, + _ => panic!("the page"), + } + }; + // Within an 8-bit step: the colour travels as RRGGBBAA. + let near = |a: f32, b: f32| (a - b).abs() < 1.0 / 255.0; + assert!(near(page_bg(&u).a, 1.0)); + let steps = undo_steps(&u); + type_into(&mut u, "Opacity", "50", Key::Enter); + assert!(near(page_bg(&u).a, 0.5), "{:?}", page_bg(&u)); + assert_eq!(undo_steps(&u), steps + 1, "one undo step for the commit"); + // The hex field keeps the opacity when the typed colour has none, and takes one it carries. + let hex = |u: &mut Ui| u.ctx.read_response(Id::unique("pagebg").with("click")).expect("the hex field").rect.center(); + let at = hex(&mut u); + click(&mut u, at); + u.frame(vec![Event::Text("FF0000".into())]); + key(&mut u, Key::Enter, Modifiers::NONE); + let c = page_bg(&u); + assert!(near(c.r, 1.0) && near(c.g, 0.0) && near(c.a, 0.5), "{c:?}"); + let at = hex(&mut u); + click(&mut u, at); + u.frame(vec![Event::Text("00FF0080".into())]); + key(&mut u, Key::Enter, Modifiers::NONE); + let c = page_bg(&u); + assert!(near(c.g, 1.0) && near(c.a, 128.0 / 255.0), "{c:?}"); + assert_eq!(undo_steps(&u), steps + 3); + u.app.run("edit.undo", json!({})); + assert!(near(page_bg(&u).r, 1.0) && near(page_bg(&u).a, 0.5), "undo takes back the last colour alone"); +} diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 6dde13136..4f31f4089 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -311,27 +311,48 @@ fn design(app: &mut FigApp, ui: &mut Ui) { /// Draw the page section: background and colour profile, local variables/styles, and the /// page export section. fn page_section(app: &mut FigApp, ui: &mut Ui, doc: &Document) { - let t = Tokens::get(ui.ctx()); let Ok(page) = app.session.page() else { return }; let bg = match doc.node(page).map(|n| &n.kind) { Some(NodeKind::Page { background, .. }) => *background, _ => figcraft_color::Color::DEFAULT_PAGE, }; widgets::section_header(ui, tr("Page"), &[], false); - let mut new_hex = None; + // The new colour and, from a scrub, whether the scrub is over (live edits stay one undo step). + 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); app.picker_control(crate::colorpicker::PickerTarget::PageBackground, &sw); - if let Some(h) = widgets::text_field(ui, Id::unique("pagebg"), &bg.to_hex(), 96.0, "") { - new_hex = Some(h); + // A typed colour keeps the page's opacity unless it carries one (`FF000080`), as the + // colour picker's hex field does. + 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) + { + new_color = Some((c.with_alpha(if c.a < 1.0 { c.a } else { 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) { + Some(FieldEdit::Set(v)) => new_color = Some((alpha(v), None)), + Some(FieldEdit::Scrub(v, done)) => new_color = Some((alpha(v), Some(done))), + None => {} } - widgets::label(ui, "100 %", t.text); }); - if let Some(h) = new_hex - && let Some(c) = figcraft_color::Color::from_hex_or_name(&h) - { - app.run("page.setBackground", json!({"color": c.to_css_hex()})); + if let Some((c, scrub)) = new_color { + let p = json!({"color": c.to_css_hex()}); + match scrub { + None => { + app.run("page.setBackground", p); + } + Some(done) => { + let _ = app.session.begin_interaction("Page background"); + let _ = app.session.execute("page.setBackground", &p); + if done { + let _ = app.session.commit_interaction(); + } + } + } } widgets::separator(ui); widgets::section_header(ui, tr("Color profile"), &[], false); From 01214c6e12aff34a2ac56503b1f7dbe8cb9a60c8 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 31 Oct 2026 11:26:45 -0400 Subject: [PATCH 029/326] M8: CSS colours take none and every hue unit, refuse nan and inf, and to_css keeps the 8-bit alpha Found while testing crates/color/src/lib.rs (no existing issue), each with a test that fails before and passes after: rgb() accepted nan/inf/infinity identifiers (Rust float syntax, not CSS numbers); hsl() refused the turn, grad and rad hue units lch() and oklch() already take, and accepted repeated suffixes; none was refused in rgb() and hsl() and read as opaque in a lch()/oklch() alpha, where CSS Color 4 section 4.4 says a missing component is zero; to_css could print an alpha that read back as a different 8-bit value, and printed NaN or negative alphas from a field-built colour. One css_f32 number reader (sign, digits, point, exponent) and a css_fraction helper (number, percentage or none) now serve every CSS number path. Co-Authored-By: Claude Fable 5.1 --- crates/color/src/lch_tests.rs | 5 ++- crates/color/src/lib.rs | 79 ++++++++++++++++++++++++----------- crates/color/src/tests.rs | 76 +++++++++++++++++++++++++++++++++ 3 files changed, 135 insertions(+), 25 deletions(-) diff --git a/crates/color/src/lch_tests.rs b/crates/color/src/lch_tests.rs index 0bf249b07..d3998261d 100644 --- a/crates/color/src/lch_tests.rs +++ b/crates/color/src/lch_tests.rs @@ -73,7 +73,10 @@ fn css_hue_units_and_none() { assert_eq!(Color::parse_css(&format!("oklch(0.6 0.2 {h})")).unwrap().to_hex(), blue.to_hex(), "{h}"); } assert_eq!(Color::parse_css("lch(50 none none)").unwrap().to_hex(), Color::parse_css("lch(50 0 0)").unwrap().to_hex()); - assert_eq!(Color::parse_css("oklch(none 0 0 / none)").unwrap().to_rgba8(), [0, 0, 0, 255]); + // A missing alpha is zero like any other missing component (CSS Color 4 §4.4), so it is + // transparent; only an *omitted* alpha defaults to opaque. + assert_eq!(Color::parse_css("oklch(none 0 0 / none)").unwrap().to_rgba8(), [0, 0, 0, 0]); + assert_eq!(Color::parse_css("oklch(none 0 0)").unwrap().to_rgba8(), [0, 0, 0, 255]); } #[test] diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 190fdbb9c..764069742 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -158,14 +158,9 @@ impl Color { } if let Some(inner) = t.strip_prefix("rgba(").or_else(|| t.strip_prefix("rgb(")).and_then(|r| r.strip_suffix(')')) { let parts = css_args(inner)?; - let num = |i: usize| -> Option { - let p = parts.get(i)?; - if let Some(pc) = p.strip_suffix('%') { - pc.trim().parse::().ok().map(|v| v / 100.0) - } else { - p.parse::().ok().map(|v| v / 255.0) - } - }; + // A channel is a number of 255, a percentage or `none`; out-of-range values (a number + // too big for f32 included) clamp in `Color::new`, as CSS Color 4 §5.1 asks. + let num = |i: usize| css_fraction(parts.get(i)?, 255.0); let alpha = match parts.get(3) { Some(a) => parse_alpha(a)?, None => 1.0, @@ -177,10 +172,12 @@ impl Color { } if let Some(inner) = t.strip_prefix("hsla(").or_else(|| t.strip_prefix("hsl(")).and_then(|r| r.strip_suffix(')')) { let parts = css_args(inner)?; - let h = parts.first()?.trim_end_matches("deg").parse::().ok()?; - let s = parts.get(1)?.trim_end_matches('%').parse::().ok()? / 100.0; - let l = parts.get(2)?.trim_end_matches('%').parse::().ok()? / 100.0; - if !(h.is_finite() && s.is_finite() && l.is_finite()) { + // The hue takes every CSS angle unit; saturation and lightness are percentages, numbers + // read as percentages (CSS Color 4 §7) or `none`. + let h = css_hue(parts.first()?)?; + let s = css_fraction(parts.get(1)?, 100.0)?; + let l = css_fraction(parts.get(2)?, 100.0)?; + if !(s.is_finite() && l.is_finite()) { return None; } let alpha = match parts.get(3) { @@ -209,14 +206,23 @@ impl Color { /// CSS `rgba(...)` / hex text for copy-as-CSS. pub fn to_css(self) -> String { - let [r, g, b, _] = self.to_rgba8(); - if self.a >= 0.999 { + let [r, g, b, a8] = self.to_rgba8(); + let a = clamp01(self.a); + if a >= 0.999 { return self.to_css_hex(); } - // Two decimals when they keep the 8-bit alpha, three otherwise (near-transparent colours). - let a8 = |a: f32| (a.clamp(0.0, 1.0) * 255.0).round() as u8; - let short = format!("{:.2}", self.a); - let alpha = if short.parse::().is_ok_and(|v| a8(v) == a8(self.a)) { short } else { format!("{:.3}", self.a) }; + // The fewest decimals that read back as the same 8-bit alpha: two, else three, else three + // of the 8-bit value itself (within half a step of it, so it always reads back). + let keeps = |s: &str| s.parse::().is_ok_and(|v| (v * 255.0).round() as u8 == a8); + let two = format!("{a:.2}"); + let three = format!("{a:.3}"); + let alpha = if keeps(&two) { + two + } else if keeps(&three) { + three + } else { + format!("{:.3}", f32::from(a8) / 255.0) + }; format!("rgba({r}, {g}, {b}, {alpha})") } @@ -268,19 +274,42 @@ fn css_polar(inner: &str, l_full: f32, c_full: f32) -> Option<([f32; 3], f32)> { let l = css_number(parts.first()?, l_full)?; let c = css_number(parts.get(1)?, c_full)?; let h = css_hue(parts.get(2)?)?; - let alpha = match parts.get(3).map(String::as_str) { - None | Some("none") => 1.0, + let alpha = match parts.get(3) { + None => 1.0, Some(a) => parse_alpha(a)?, }; Some(([l, c, h], alpha)) } +/// A CSS `` as f32: a sign, digits, a decimal point and an exponent only. Rust's float +/// parser also reads `inf`, `infinity` and `nan`, which are identifiers in CSS, not numbers. A +/// value too big for f32 comes back as an infinity for the caller to clamp or refuse. +fn css_f32(s: &str) -> Option { + if !s.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E')) { + return None; + } + s.parse::().ok() +} + +/// A CSS number, percentage or `none` as a fraction of one: a percentage is of 100, a bare number +/// of `number_full` (255 for an rgb() channel, 100 for hsl() saturation and lightness, 1 for +/// alpha) and `none` is 0 (CSS Color 4 §4.4). +fn css_fraction(p: &str, number_full: f32) -> Option { + if p == "none" { + return Some(0.0); + } + match p.strip_suffix('%') { + Some(pc) => Some(css_f32(pc)? / 100.0), + None => Some(css_f32(p)? / number_full), + } +} + /// A CSS number, a percentage of `full` or `none` (0); finite only. fn css_number(p: &str, full: f32) -> Option { let v = match p.strip_suffix('%') { _ if p == "none" => 0.0, - Some(pc) => pc.trim().parse::().ok()? / 100.0 * full, - None => p.parse::().ok()?, + Some(pc) => css_f32(pc)? / 100.0 * full, + None => css_f32(p)?, }; v.is_finite().then_some(v) } @@ -294,12 +323,14 @@ fn css_hue(p: &str) -> Option { .into_iter() .find_map(|(unit, k)| p.strip_suffix(unit).map(|n| (n, k))) .unwrap_or((p, 1.0)); - let v = num.parse::().ok()? / per_degree; + let v = css_f32(num)? / per_degree; v.is_finite().then_some(v) } +/// A CSS ``: a number, a percentage or `none` (0: a missing alpha is transparent, CSS +/// Color 4 §4.4); finite only. An *omitted* alpha is the caller's default of 1. fn parse_alpha(a: &str) -> Option { - let v = if let Some(pc) = a.strip_suffix('%') { pc.parse::().ok().map(|v| v / 100.0) } else { a.parse::().ok() }?; + let v = css_fraction(a, 1.0)?; v.is_finite().then_some(v) } diff --git a/crates/color/src/tests.rs b/crates/color/src/tests.rs index a41d0dd2e..6100a89ad 100644 --- a/crates/color/src/tests.rs +++ b/crates/color/src/tests.rs @@ -157,3 +157,79 @@ fn css_rejects_empty_arguments() { assert!(Color::parse_css("rgb(255 0 0 / 50%)").is_some()); assert!(Color::parse_css("hsl(120deg 50% 50%)").is_some()); } + +#[test] +fn css_rgb_rejects_non_numeric_channels() { + // `nan`, `inf` and `infinity` are identifiers, not CSS numbers; the hsl(), lch() and oklch() + // branches and the alpha already refuse them, and so must rgb() channels (which previously read + // `rgb(nan, 0, 0)` as black and `rgb(inf, 0, 0)` as red). + for s in ["rgb(nan, 0, 0)", "rgb(inf, 0, 0)", "rgb(0, 0, infinity)", "rgb(-inf, 0, 0)", "rgb(nan%, 0, 0)", "rgb(NaN 0 0)", "rgba(0, 0, 0, inf)"] { + assert_eq!(Color::parse_css(s), None, "{s}"); + } + // A genuine number that overflows f32 is still a number and clamps (CSS Color 4 §5.1). + assert_eq!(Color::parse_css("rgb(1e40, -1e40, 0)").unwrap().to_rgba8(), [255, 0, 0, 255]); + assert_eq!(Color::parse_css("rgb(+255, .5%, 1E2)").unwrap().to_rgba8(), [255, 1, 100, 255]); +} + +#[test] +fn css_hsl_takes_every_hue_unit() { + // CSS Color 4 §4.3: ` = | `, so turn, grad and rad are as valid as deg. + let cyan = Color::parse_css("hsl(180, 100%, 50%)").unwrap(); + assert_eq!(cyan.to_hex(), "00FFFF"); + let units = + ["hsl(0.5turn, 100%, 50%)", "hsl(200grad 100% 50%)", "hsl(3.1415927rad 100% 50%)", "hsl(180deg 100% 50%)", "hsla(-0.5turn, 100%, 50%, 1)"]; + for s in units { + assert_eq!(Color::parse_css(s).map(|c| c.to_hex()), Some(cyan.to_hex()), "{s}"); + } + // One unit only: a repeated or stray unit is not a dimension. + for s in ["hsl(120degdeg, 100%, 50%)", "hsl(120, 100%%, 50%)", "hsl(0.5turndeg 100% 50%)", "hsl(deg 100% 50%)"] { + assert_eq!(Color::parse_css(s), None, "{s}"); + } +} + +#[test] +fn css_none_is_zero_in_every_function() { + // CSS Color 4 §4.4: every modern-syntax component may be `none`, and outside interpolation a + // missing component "behaves as a zero value" -- including a missing alpha, which renders + // fully transparent. + assert_eq!(Color::parse_css("rgb(none 0 0)").unwrap().to_rgba8(), [0, 0, 0, 255]); + assert_eq!(Color::parse_css("rgb(255 none none)").unwrap().to_rgba8(), [255, 0, 0, 255]); + assert_eq!(Color::parse_css("rgb(255 0 0 / none)").unwrap().to_rgba8(), [255, 0, 0, 0]); + assert_eq!(Color::parse_css("hsl(none 100% 50%)").unwrap().to_hex(), "FF0000"); + assert_eq!(Color::parse_css("hsl(120 none 50%)").unwrap().to_hex(), "808080"); + assert_eq!(Color::parse_css("hsl(120 100% none)").unwrap().to_hex(), "000000"); + assert_eq!(Color::parse_css("hsl(120 100% 50% / none)").unwrap().to_rgba8(), [0, 255, 0, 0]); + assert_eq!(Color::parse_css("oklch(0.5 0.1 20 / none)").unwrap().a, 0.0); + assert_eq!(Color::parse_css("lch(50 50 50 / none)").unwrap().a, 0.0); + // An omitted alpha still defaults to opaque. + assert_eq!(Color::parse_css("rgb(none none none)").unwrap().a, 1.0); +} + +#[test] +fn to_css_keeps_the_8_bit_alpha_for_any_alpha() { + // Three decimals of the alpha can still round across an 8-bit step (0.0055 -> "0.006" reads + // back as 2/255, not 1/255); the text must always read back to the same 8-bit alpha. + for i in 0..=10_000u32 { + let a = i as f32 / 10_000.0; + let c = Color::new(0.1, 0.2, 0.3, a); + let css = c.to_css(); + assert_eq!(Color::parse_css(&css).map(|b| b.to_rgba8()), Some(c.to_rgba8()), "alpha {a}: {css}"); + } + let c = Color::new(0.1, 0.2, 0.3, 0.0055); + assert_eq!(Color::parse_css(&c.to_css()).unwrap().to_rgba8()[3], 1, "{}", c.to_css()); + // Still the short forms where they are exact. + assert_eq!(Color::new(1.0, 0.0, 0.0, 0.5).to_css(), "rgba(255, 0, 0, 0.50)"); + assert_eq!(Color::from_rgba8(255, 0, 0, 85).to_css(), "rgba(255, 0, 0, 0.333)"); +} + +#[test] +fn to_css_sanitizes_an_unclamped_alpha() { + // The RGB channels go through `to_rgba8` and are sanitized; the alpha must be too, or a colour + // built field-by-field prints `rgba(0, 0, 0, NaN)` / `rgba(0, 0, 0, -0.50)`, which is not CSS. + for a in [f32::NAN, -0.5, f32::NEG_INFINITY] { + let c = Color { r: 0.0, g: 0.0, b: 0.0, a }; + let css = c.to_css(); + assert_eq!(Color::parse_css(&css).map(|b| b.to_rgba8()), Some([0, 0, 0, 0]), "alpha {a}: {css}"); + } + assert_eq!(Color { r: 1.0, g: 0.0, b: 0.0, a: f32::INFINITY }.to_css(), "#FF0000"); +} From fcab85ddd017e929fe5a38d8c67d3c8e36f31760 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 31 Oct 2026 11:34:55 -0400 Subject: [PATCH 030/326] M4: the Pencil draws white on a dark page or frame, and previews in that colour (#1741) Figma: "a round 3px stroke weight in black, unless you are sketching on a dark canvas or frame". The Pencil always drew black. It now takes the colour from the same dark-background rule new text uses (the nearest ancestor with a mostly opaque solid fill, else the page), and the overlay carries that colour for the stroke in progress so the preview matches. Engine and UI regression tests. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/brush_tests.rs | 32 +++++++++++++++++++++++ crates/engine/src/canvas/tools.rs | 3 +++ crates/engine/src/canvas/tools/draw.rs | 1 + crates/engine/src/canvas/tools/handles.rs | 31 ++++++++++++++++------ crates/engine/src/canvas/tools/pen.rs | 13 ++++++++- crates/engine/src/canvas/tools/pointer.rs | 2 ++ crates/ui-egui/src/canvas/overlays.rs | 6 +++-- crates/ui-egui/src/canvas_fixes_tests.rs | 17 ++++++++++++ 8 files changed, 94 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/brush_tests.rs b/crates/engine/src/brush_tests.rs index e4e8b428b..984eaaad5 100644 --- a/crates/engine/src/brush_tests.rs +++ b/crates/engine/src/brush_tests.rs @@ -107,3 +107,35 @@ fn the_pencil_records_pressure_and_its_brush() { let last = doc.nodes().filter(|n| matches!(n.kind, NodeKind::Vector { .. })).max_by_key(|n| n.id).unwrap(); assert!(last.stroke.profile().is_none() && last.stroke.brush.is_none()); } + +/// The Pencil draws black on a light page and white on a dark page or inside a dark frame, the +/// rule new text follows (#1741; Figma: "in black, unless you're sketching on a dark canvas or +/// frame"), and the stroke in progress previews in that colour. +#[test] +fn the_pencil_draws_white_on_a_dark_background() { + use figcraft_color::Color; + let mut s = Session::new(); + s.execute("tool.set", &json!({"tool": "pencil"})).unwrap(); + // A stroke from (x, y); its colour, and the preview colour the overlay carried while drawing. + let stroke = |s: &mut Session, x: f64, y: f64| { + s.pointer(&PointerEvent::at(PointerKind::Down, x, y, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Move, x + 40.0, y + 10.0, 1.0)).unwrap(); + let preview = s.tool.overlay.pen_color; + s.pointer(&PointerEvent::at(PointerKind::Move, x + 80.0, y, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Up, x + 80.0, y, 1.0)).unwrap(); + assert!(s.tool.overlay.pen_color.is_none(), "no preview colour after the stroke"); + let doc = s.doc().unwrap(); + let last = doc.nodes().filter(|n| matches!(n.kind, NodeKind::Vector { .. })).max_by_key(|n| n.id).unwrap(); + (last.strokes.first().and_then(|p| p.solid_color()).unwrap(), preview) + }; + assert_eq!(stroke(&mut s, 0.0, 0.0), (Color::BLACK, Some(Color::BLACK)), "a light page"); + s.execute("page.setBackground", &json!({"color": "#1E1E1E"})).unwrap(); + assert_eq!(stroke(&mut s, 0.0, 100.0), (Color::WHITE, Some(Color::WHITE)), "a dark page"); + // A dark frame on a light page, and a light frame on a dark page. + s.execute("page.setBackground", &json!({"color": "#F5F5F5"})).unwrap(); + s.execute("node.create", &json!({"type": "frame", "x": 300, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#202020"]}})).unwrap(); + assert_eq!(stroke(&mut s, 320.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "inside a dark frame"); + s.execute("page.setBackground", &json!({"color": "#1E1E1E"})).unwrap(); + s.execute("node.create", &json!({"type": "frame", "x": 600, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#FFFFFF"]}})).unwrap(); + assert_eq!(stroke(&mut s, 620.0, 320.0), (Color::BLACK, Some(Color::BLACK)), "inside a light frame on a dark page"); +} diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index c68276fd3..9b8271695 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -327,6 +327,9 @@ pub struct Overlay { pub cursor: Cursor, /// Pen tool: the in-progress path's anchor points and the rubber band to the pointer. pub pen: Vec<[f64; 2]>, + /// Pencil: the colour of the stroke in progress, for its preview (white over a dark page or + /// frame); None outside a Pencil stroke. + pub pen_color: Option, pub rubber: Option<[f64; 4]>, /// Pen tool: the handles shaping the segments at the pen (anchor x, y, handle x, y): the last /// anchor's in and out handles and the one before's out handle. diff --git a/crates/engine/src/canvas/tools/draw.rs b/crates/engine/src/canvas/tools/draw.rs index d59a2b904..7df150e43 100644 --- a/crates/engine/src/canvas/tools/draw.rs +++ b/crates/engine/src/canvas/tools/draw.rs @@ -221,6 +221,7 @@ impl Session { } Gesture::Pencil { mut points, mut pressure } => { self.tool.overlay.pen.clear(); + self.tool.overlay.pen_color = None; // The stroke ends where the button came up, even without a move to get there. if points.last().is_none_or(|l| (*l - ev.p()).hypot() > 0.5 / ev.zoom.max(1e-6)) { points.push(ev.p()); diff --git a/crates/engine/src/canvas/tools/handles.rs b/crates/engine/src/canvas/tools/handles.rs index 7ccaca403..9bd1c5973 100644 --- a/crates/engine/src/canvas/tools/handles.rs +++ b/crates/engine/src/canvas/tools/handles.rs @@ -36,16 +36,31 @@ pub fn anchor_name(a: (u8, u8)) -> &'static str { ANCHORS.get(usize::from(a.1.min(2)) * 3 + usize::from(a.0.min(2))).copied().unwrap_or("tl") } +/// Whether what is drawn in `parent` sits on a dark background: the nearest layer from `parent` +/// out whose top visible fill is a mostly opaque solid colour, else the page (#362). +pub(crate) fn on_dark_background(doc: &Document, parent: NodeId) -> bool { + std::iter::once(parent) + .chain(doc.ancestors(parent)) + .filter_map(|id| doc.node(id)) + .find_map(|n| match &n.kind { + NodeKind::Page { background, .. } => Some(background.is_dark()), + _ => n.fills.iter().rev().find(|p| p.visible).and_then(|p| p.solid_color()).filter(|c| c.a >= 0.5).map(|c| c.is_dark()), + }) + .unwrap_or(false) +} + /// The fill new text takes to be readable where it is drawn, in `parent`: white on a dark -/// background (None: the model's default, black). The background is the nearest layer from `parent` -/// out whose top visible fill is a mostly opaque solid colour, else the page (#362). For text made -/// in the app: by the Text tool, or by a command that names no fill while the interface is up. +/// background (None: the model's default, black). For text made in the app: by the Text tool, or +/// by a command that names no fill while the interface is up. pub(crate) fn readable_text_fills(doc: &Document, parent: NodeId) -> Option> { - let dark = std::iter::once(parent).chain(doc.ancestors(parent)).filter_map(|id| doc.node(id)).find_map(|n| match &n.kind { - NodeKind::Page { background, .. } => Some(background.is_dark()), - _ => n.fills.iter().rev().find(|p| p.visible).and_then(|p| p.solid_color()).filter(|c| c.a >= 0.5).map(|c| c.is_dark()), - }); - dark.unwrap_or(false).then(|| vec![figcraft_color::Paint::solid(figcraft_color::Color::WHITE)]) + on_dark_background(doc, parent).then(|| vec![figcraft_color::Paint::solid(figcraft_color::Color::WHITE)]) +} + +/// The colour the Pencil draws with in `parent`: [`PENCIL_STROKE`]'s black, or white on a dark +/// background by the rule text follows (#1741; "in black, unless you're sketching on a dark canvas +/// or frame"). +pub(crate) fn pencil_color(doc: &Document, parent: NodeId) -> figcraft_color::Color { + if on_dark_background(doc, parent) { figcraft_color::Color::WHITE } else { PENCIL_STROKE.0 } } const ANCHORS: [&str; 9] = ["tl", "t", "tr", "l", "c", "r", "bl", "b", "br"]; diff --git a/crates/engine/src/canvas/tools/pen.rs b/crates/engine/src/canvas/tools/pen.rs index d519bc580..8de56bec7 100644 --- a/crates/engine/src/canvas/tools/pen.rs +++ b/crates/engine/src/canvas/tools/pen.rs @@ -296,7 +296,9 @@ impl Session { let mut local = fitted.clone(); local.apply_affine(pw.inverse()); let _ = d; - let (color, weight) = PENCIL_STROKE; + // Black, or white on a dark page or frame (#1741). + let (_, weight) = PENCIL_STROKE; + let color = super::handles::pencil_color(self.doc()?, parent); let mut props = json!({"fills": [], "strokes": [color.to_css_hex()], "strokeWeight": weight, "strokeCap": "round", "strokeJoin": "round", "strokeAlign": "center"}); // Pen pressure becomes the stroke's width profile (brushes follow it too). if let Some(points) = pressure_profile(points, pressure) { @@ -311,4 +313,13 @@ impl Session { )?; Ok(()) } + + /// The colour a Pencil stroke starting at `p` will have: it goes into the frame under `p` + /// (else the page), and is white when that is dark (`pencil_color`). + pub(super) fn pencil_color_at(&self, p: figcraft_geom::Point) -> Result { + let page = self.page()?; + let doc = self.doc()?; + let parent = frame_at(doc, page, p, &[]).unwrap_or(page); + Ok(super::handles::pencil_color(doc, parent)) + } } diff --git a/crates/engine/src/canvas/tools/pointer.rs b/crates/engine/src/canvas/tools/pointer.rs index 1493604dc..bd4fa94e7 100644 --- a/crates/engine/src/canvas/tools/pointer.rs +++ b/crates/engine/src/canvas/tools/pointer.rs @@ -156,6 +156,8 @@ impl Session { ToolId::TextOnPath => self.text_on_path_down(ev), ToolId::Pen => self.pen_down(ev), ToolId::Pencil => { + // The preview draws in the colour the stroke will have (#1741). + self.tool.overlay.pen_color = self.pencil_color_at(ev.p()).ok(); self.tool.gesture = Gesture::Pencil { points: vec![ev.p()], pressure: vec![ev.pressure] }; Ok(()) } diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 483a180b9..2434bbf7f 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -421,8 +421,10 @@ fn pen_overlay(app: &FigApp, painter: &egui::Painter, zoom: f64) { if !ov.pen.is_empty() { let pts: Vec = ov.pen.iter().map(|[x, y]| app.to_screen(*x, *y)).collect(); if app.session.tool.tool == ToolId::Pencil { - // The stroke it will make, in its colour and weight (at least a point when zoomed out). - let (color, weight) = figcraft_engine::tools::PENCIL_STROKE; + // The stroke it will make, in its colour and weight (at least a point when zoomed out): + // white over a dark page or frame, as the stroke will be (#1741). + let (default, weight) = figcraft_engine::tools::PENCIL_STROKE; + let color = ov.pen_color.unwrap_or(default); painter.add(Shape::line(pts, stroke(doc_c32(painter.ctx(), color), ((weight * zoom) as f32).max(1.0)))); } else { for [x0, y0, x1, y1] in &ov.pen_handles { diff --git a/crates/ui-egui/src/canvas_fixes_tests.rs b/crates/ui-egui/src/canvas_fixes_tests.rs index d8112a3aa..cdb19492a 100644 --- a/crates/ui-egui/src/canvas_fixes_tests.rs +++ b/crates/ui-egui/src/canvas_fixes_tests.rs @@ -186,6 +186,23 @@ fn the_pencil_previews_its_stroke_in_its_colour_and_weight() { assert!((w - 1.0).abs() < 0.01, "at least a point: {w}"); } +/// Over a dark page the Pencil's preview is white, as the stroke it makes will be (#1741). +#[test] +fn the_pencil_previews_white_over_a_dark_page() { + let mut u = Ui::new(Session::new()); + u.app.run("page.setBackground", json!({"color": "#1E1E1E"})); + u.app.run("tool.set", json!({"tool": "pencil"})); + let white = egui::epaint::ColorMode::Solid(crate::theme::c32(figcraft_color::Color::WHITE)); + let at = |u: &Ui, x: f64, y: f64| u.app.to_screen(x, y); + u.button(at(&u, 10.0, 10.0), true); + for i in 1..=6 { + let p = at(&u, 10.0 + 12.0 * f64::from(i), 10.0 + 6.0 * f64::from(i % 2)); + u.frame(vec![egui::Event::PointerMoved(p)]); + } + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(shapes.iter().any(|s| matches!(s, Shape::Path(p) if !p.closed && p.points.len() >= 3 && p.stroke.color == white)), "a white preview"); +} + #[test] fn a_selected_layer_shows_its_constraint_guides_in_its_frame() { // A child pinned left (the default) in a frame without auto layout: a dashed guide runs from its From 1aa6b81d017fb0c7e60864b85665c74a92d400b3 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:23:54 +0100 Subject: [PATCH 031/326] Reject invalid entries in vector.create points instead of dropping them Found while testing crates/engine/src/cmd/create.rs:~286 (create, the `points` branch using filter_map) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/create.rs | 9 ++++++++- crates/engine/src/draw_tools_tests.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 9caf4551a..52b34e101 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -302,7 +302,14 @@ pub fn create(s: &mut Session, p: &Value) -> Result { } (w, h, offset) = (shape.width, shape.height, shape.offset); } else if let Some(Value::Array(pts)) = get(p, "points") { - let pts: Vec = pts.iter().filter_map(|v| Some(Point::new(f64_of(v.get(0)?)?, f64_of(v.get(1)?)?))).collect(); + let pts: Vec = pts + .iter() + .map(|v| { + let xy = v.as_array().filter(|a| a.len() == 2)?; + Some(Point::new(f64_of(&xy[0])?, f64_of(&xy[1])?)) + }) + .collect::>() + .ok_or_else(|| bad(cmd, "`points` entries must be numeric [x, y] pairs"))?; if pts.len() < 2 { return Err(bad(cmd, "`points` needs at least two [x, y] pairs")); } diff --git a/crates/engine/src/draw_tools_tests.rs b/crates/engine/src/draw_tools_tests.rs index c5b84d210..6a7b47b59 100644 --- a/crates/engine/src/draw_tools_tests.rs +++ b/crates/engine/src/draw_tools_tests.rs @@ -378,3 +378,12 @@ fn the_text_on_a_path_tool_carries_a_fill_bound_through_fills() { let t = editing(&s).expect("typing starts on the path"); assert_eq!(s.doc().unwrap().node(t).unwrap().bound, bound, "the fill keeps following its variable"); } + +#[test] +fn bad_point_is_rejected() { + let mut s = Session::new(); + assert!(s.execute("vector.create", &json!({"points": [[0, 0], ["abc", 5], [100, 100]], "closed": false})).is_err()); + assert!(s.execute("vector.create", &json!({"points": [[0, 0], [1], [100, 100]]})).is_err()); + assert!(s.execute("vector.create", &json!({"points": [[0, 0], 7, [100, 100]]})).is_err()); + assert!(s.execute("vector.create", &json!({"points": [[0, 0], [50, 5], [100, 100]]})).is_ok()); +} From f137e9df9a8bf9ced198f8faa7177bd1ca242798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 20:29:10 +0100 Subject: [PATCH 032/326] fix(pathops): M2.1: keep Fenwick indices Rust 1.95 compatible --- crates/pathops/src/budget.rs | 4 ++-- crates/pathops/src/budget_tests.rs | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/pathops/src/budget.rs b/crates/pathops/src/budget.rs index ff6f9cab4..714611ceb 100644 --- a/crates/pathops/src/budget.rs +++ b/crates/pathops/src/budget.rs @@ -112,7 +112,7 @@ impl Fenwick { let mut i = rank + 1; while let Some(c) = self.0.get_mut(i) { *c += by; - i += i.isolate_lowest_one(); + i += i & i.wrapping_neg(); } } @@ -123,7 +123,7 @@ impl Fenwick { && let Some(c) = self.0.get(i) { n += c; - i -= i.isolate_lowest_one(); + i -= i & i.wrapping_neg(); } u64::try_from(n).unwrap_or(0) } diff --git a/crates/pathops/src/budget_tests.rs b/crates/pathops/src/budget_tests.rs index b53b5545d..a55e58e85 100644 --- a/crates/pathops/src/budget_tests.rs +++ b/crates/pathops/src/budget_tests.rs @@ -93,3 +93,9 @@ fn a_fold_stops_once_it_has_swept_its_budget() { assert_eq!(steps, MAX_FOLD_SEGMENTS / 100_004); assert_eq!(budget.spend(&BezPath::new(), &BezPath::new()), Err(PathOpsError::TooComplex), "spent stays spent"); } + +#[test] +fn overlapping_rectangle_bounds_count_self_and_cross_pairs() { + let shapes = rects([Rect::new(0.0, 0.0, 2.0, 2.0), Rect::new(1.0, 1.0, 3.0, 3.0), Rect::new(4.0, 4.0, 5.0, 5.0)]); + assert_eq!(complexity([&shapes]), Some(Complexity { segments: 12, crossings: 14 })); +} From e3df030be97c427b070cfee648cc2daf07ae35f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 20:45:51 +0100 Subject: [PATCH 033/326] fix(text): M2.1: simplify font file filter --- crates/text/src/fontdb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 2c6aac948..6ebd7ec45 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -1304,7 +1304,7 @@ fn index_font_file(path: &std::path::Path, meta: &std::fs::Metadata, out: &mut B return; } let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).unwrap_or_default(); - if !matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") && !(path.extension().is_none() && starts_like_a_font(path)) { + if !(matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") || path.extension().is_none() && starts_like_a_font(path)) { return; } // Very large files are indexed all the same (Apple Color Emoji is ~180 MB and is where the From 650601593e02d6ef687dd26becac92907bc5a335 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:05:43 +0100 Subject: [PATCH 034/326] Reject negative or fractional index in page.move Found while testing crates/engine/src/cmd/page.rs:132 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/page.rs | 2 +- crates/engine/src/panels_behaviour_tests.rs | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/page.rs b/crates/engine/src/cmd/page.rs index 2835deff3..458e7572c 100644 --- a/crates/engine/src/cmd/page.rs +++ b/crates/engine/src/cmd/page.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { }), spec!("page.move", "Move page", "{id?, index}", true, |s, p| { let id = id(p, "id").unwrap_or(s.page()?); - let k = req_num("page.move", p, "index")?.max(0.0) as usize; + let k = req_index("page.move", p, "index")?; let doc = s.doc_mut()?; if !doc.pages.contains(&id) { return Err(bad("page.move", format!("{id} is not a page"))); diff --git a/crates/engine/src/panels_behaviour_tests.rs b/crates/engine/src/panels_behaviour_tests.rs index d97d25075..e44d99fc0 100644 --- a/crates/engine/src/panels_behaviour_tests.rs +++ b/crates/engine/src/panels_behaviour_tests.rs @@ -393,6 +393,20 @@ fn page_select_and_doc_switch_refuse_negative_or_fractional_indexes() { } } +#[test] +fn page_move_refuses_negative_or_fractional_indexes() { + let mut s = Session::new(); + ex(&mut s, "page.add", json!({})); + let p3 = id(&ex(&mut s, "page.add", json!({}))); + let before = pages(&mut s); + for bad_index in [json!(-1), json!(1.5)] { + assert!(s.execute("page.move", &json!({"id": p3, "index": bad_index})).is_err(), "page.move index {bad_index} must fail"); + assert_eq!(pages(&mut s), before, "page.move index {bad_index} leaves the order alone"); + } + ex(&mut s, "page.move", json!({"id": p3, "index": 0})); + assert_eq!(pages(&mut s)[0]["id"], json!(p3), "a valid index still moves the page"); +} + #[test] fn assets_panel_lists_files_and_drops_by_the_documented_rules() { let mut s = Session::new(); From b0673ffc8b659c7d0b0b04dea80d8d2314afcc86 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 31 Oct 2026 18:52:48 -0400 Subject: [PATCH 035/326] packaging(flatpak): add OCI image build and GHCR publishing helper (#1784) --- packaging/linux/flatpak-bundle.sh | 8 ++++ packaging/linux/flatpak-oci.sh | 64 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100755 packaging/linux/flatpak-oci.sh diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index b3353b386..808de718f 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -21,10 +21,12 @@ APP_ID=ai.storyteller.figcraft FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 +OCI=0 TARBALL="" while [[ $# -gt 0 ]]; do case "$1" in --no-test) TEST=0; shift ;; + --oci) OCI=1; shift ;; -h | --help) sed -n '2,14p' "$0"; exit 0 ;; -*) echo "unknown argument: $1" >&2; exit 2 ;; *) TARBALL="$1"; shift ;; @@ -62,6 +64,12 @@ OUT="$DIST/$BASENAME.flatpak" # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable echo "wrote $OUT" +if [[ "$OCI" = 1 ]]; then + OUT_OCI="$DIST/$BASENAME-oci" + rm -rf "$OUT_OCI" + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + echo "wrote OCI layout to $OUT_OCI" +fi if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" diff --git a/packaging/linux/flatpak-oci.sh b/packaging/linux/flatpak-oci.sh new file mode 100755 index 000000000..33ec81cd9 --- /dev/null +++ b/packaging/linux/flatpak-oci.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Build figcraft as an OCI container layout and push it to GitHub Container Registry (GHCR) +# for consumption by Flatpak OCI clients (flatpak-oci-specs). +# +# Usage: +# packaging/linux/flatpak-oci.sh [--push] [TARBALL] +# +# Environment variables: +# REGISTRY Target registry image (default: ghcr.io/storytold/figcraft) +# TAG Target image tag (default: $VERSION-$ARCH, also tags stable-$ARCH) +# GITHUB_TOKEN Token for GHCR authentication when --push is used +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/linux" + +PUSH=0 +TARBALL="" +while [[ $# -gt 0 ]]; do + case "$1" in + --push) PUSH=1; shift ;; + -h | --help) sed -n '2,12p' "$0"; exit 0 ;; + -*) echo "unknown argument: $1" >&2; exit 2 ;; + *) TARBALL="$1"; shift ;; + esac +done + +ARCH="$(uname -m)" +case "$ARCH" in + x86_64) ;; + aarch64 | arm64) ARCH=aarch64 ;; + *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; +esac + +BASENAME="figcraft-$VERSION-linux-$ARCH" +OUT_OCI="$DIST/$BASENAME-oci" + +echo "==> Building Flatpak OCI layout for $BASENAME" +"$HERE/flatpak-bundle.sh" --oci --no-test "${TARBALL:-}" + +[[ -d "$OUT_OCI" ]] || { echo "error: $OUT_OCI layout not generated" >&2; exit 1; } + +REGISTRY="${REGISTRY:-ghcr.io/storytold/figcraft}" +TAG="${TAG:-$VERSION-$ARCH}" + +echo "==> OCI layout ready at $OUT_OCI (Target: $REGISTRY:$TAG)" + +if [[ "$PUSH" = 1 ]]; then + command -v skopeo >/dev/null || { echo "error: skopeo is required to push OCI images (apt install skopeo)" >&2; exit 1; } + + AUTH_ARGS=() + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + AUTH_ARGS=(--dest-creds "${GITHUB_ACTOR:-storytold}:$GITHUB_TOKEN") + fi + + echo "==> Pushing to $REGISTRY:$TAG" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:$TAG" + + # Also update architecture-specific stable tag + echo "==> Pushing to $REGISTRY:stable-$ARCH" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:stable-$ARCH" + + echo "==> Push complete" +fi From 53259cf50eba496998ae156ddc3270197ac056c5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 31 Oct 2026 23:43:14 -0400 Subject: [PATCH 036/326] ci: grant packages write permission to release workflow --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f93219fae..68a705399 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,7 @@ on: permissions: contents: write + packages: write concurrency: group: release-${{ github.ref }} From f26226590ad579f0dcf9931d842050e915e6688e Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 1 Nov 2026 05:13:36 +0100 Subject: [PATCH 037/326] Reject negative and fractional index in variable.moveMode Found while testing crates/engine/src/cmd/variables.rs:267 (move_mode) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/variables.rs | 6 +++--- crates/engine/src/variables_behaviour_tests.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index 59ad46ced..75607ae64 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -12,7 +12,7 @@ use serde_json::{Value, json}; use super::lists::BoundList; use super::{CommandSpec, ok}; -use crate::params::{boolean, get, num, req_string, string}; +use crate::params::{boolean, get, req_index, req_string, string}; use crate::{Result, Session, bad, spec}; pub fn specs() -> Vec { @@ -258,13 +258,13 @@ fn remove_mode(s: &mut Session, p: &Value) -> Result { fn move_mode(s: &mut Session, p: &Value) -> Result { let cmd = "variable.moveMode"; - let to = num(p, "to").filter(|x| x.is_finite()).ok_or_else(|| bad(cmd, "`to` must be a number"))?; + let to = req_index(cmd, p, "to")?; let doc = s.doc_mut()?; let (ci, mode) = mode_of(doc, cmd, p)?; let coll = doc.variables.collections.get_mut(ci).ok_or_else(|| bad(cmd, "no such collection"))?; let from = coll.modes.iter().position(|m| m.id == mode).ok_or_else(|| bad(cmd, "no such mode"))?; let m = coll.modes.remove(from); - let at = (to.max(0.0) as usize).min(coll.modes.len()); + let at = to.min(coll.modes.len()); coll.modes.insert(at, m); ok() } diff --git a/crates/engine/src/variables_behaviour_tests.rs b/crates/engine/src/variables_behaviour_tests.rs index 306a8fba9..2717726f8 100644 --- a/crates/engine/src/variables_behaviour_tests.rs +++ b/crates/engine/src/variables_behaviour_tests.rs @@ -68,6 +68,20 @@ fn types_and_their_starting_values() { assert!(s.execute("variable.create", &json!({"collection": "C", "name": "y", "type": "number", "value": "wide"})).is_err()); } +#[test] +fn move_mode_rejects_negative_and_fractional_indexes() { + let mut s = Session::new(); + theme(&mut s); + run(&mut s, "variable.addMode", json!({"collection": "Theme", "name": "Dim"})); + let order = + |s: &Session| -> Vec { s.doc().unwrap().variables.collection("Theme").unwrap().modes.iter().map(|m| m.name.clone()).collect() }; + let before = order(&s); + for to in [json!(-1), json!(1.9)] { + assert!(s.execute("variable.moveMode", &json!({"collection": "Theme", "mode": "Dim", "to": to})).is_err(), "{to}"); + assert_eq!(order(&s), before, "{to}"); + } +} + #[test] fn modes_new_duplicated_reordered_and_the_default() { // Documented: a new mode starts with the default mode's values and a duplicated one with its From 25b128e5385af20f1b7f34ab6f68cf4eebf40d54 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:14:22 -0400 Subject: [PATCH 038/326] Pencil colour: document the dark threshold; tests for a frame without a fill, a see-through fill and the threshold Review follow-up on #1775: the dark rule is the one text uses (on_dark_background); a frame with no fill, or a fill under 50% alpha, is looked through to what is behind it, and the threshold is Color::is_dark (#757575 is dark, #767676 is light). Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/brush_tests.rs | 10 ++++++++++ crates/engine/src/canvas/tools/handles.rs | 4 +++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/brush_tests.rs b/crates/engine/src/brush_tests.rs index 984eaaad5..35dba6a7f 100644 --- a/crates/engine/src/brush_tests.rs +++ b/crates/engine/src/brush_tests.rs @@ -138,4 +138,14 @@ fn the_pencil_draws_white_on_a_dark_background() { s.execute("page.setBackground", &json!({"color": "#1E1E1E"})).unwrap(); s.execute("node.create", &json!({"type": "frame", "x": 600, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#FFFFFF"]}})).unwrap(); assert_eq!(stroke(&mut s, 620.0, 320.0), (Color::BLACK, Some(Color::BLACK)), "inside a light frame on a dark page"); + // A frame without a fill, or with a see-through one, is looked through to what is behind it. + s.execute("node.create", &json!({"type": "frame", "x": 900, "y": 300, "width": 200, "height": 200, "props": {"fills": []}})).unwrap(); + assert_eq!(stroke(&mut s, 920.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "a frame without a fill on a dark page"); + s.execute("node.create", &json!({"type": "frame", "x": 1200, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#FFFFFF40"]}})).unwrap(); + assert_eq!(stroke(&mut s, 1220.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "a mostly transparent light frame on a dark page"); + // The threshold is Color::is_dark: white reads better than black from #757575 down. + for (bg, want) in [("#767676", Color::BLACK), ("#757575", Color::WHITE)] { + s.execute("page.setBackground", &json!({"color": bg})).unwrap(); + assert_eq!(stroke(&mut s, 0.0, 600.0).0, want, "on {bg}"); + } } diff --git a/crates/engine/src/canvas/tools/handles.rs b/crates/engine/src/canvas/tools/handles.rs index 9bd1c5973..9fa04d9bb 100644 --- a/crates/engine/src/canvas/tools/handles.rs +++ b/crates/engine/src/canvas/tools/handles.rs @@ -37,7 +37,9 @@ pub fn anchor_name(a: (u8, u8)) -> &'static str { } /// Whether what is drawn in `parent` sits on a dark background: the nearest layer from `parent` -/// out whose top visible fill is a mostly opaque solid colour, else the page (#362). +/// out whose top visible fill is a mostly opaque (alpha 0.5 or more) solid colour, else the page +/// (#362); a frame without such a fill is looked through to what is behind it. Dark means white +/// reads better on it than black (`Color::is_dark`: `#757575` is dark, `#767676` is light). pub(crate) fn on_dark_background(doc: &Document, parent: NodeId) -> bool { std::iter::once(parent) .chain(doc.ancestors(parent)) From 467607762616424b9345c8f1cefe09198e6e2d8e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:16:56 -0400 Subject: [PATCH 039/326] SVG color-mix(): a missing alpha is taken from the other colour before the mix Review follow-up on #1773: with a none alpha now zero when a colour is rendered on its own (CSS Color 4 section 4.4), color-mix() needs the carry-forward rule of CSS Color 5 section 4.1, else color-mix(in srgb, rgb(255 0 0 / none), blue) came out half transparent instead of opaque purple. The operand reports a missing alpha and mix() fills it from the other colour; both missing stays zero. Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import/css_color.rs | 33 ++++++++++++++++++------ crates/svg/src/import/css_color_tests.rs | 6 +++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/crates/svg/src/import/css_color.rs b/crates/svg/src/import/css_color.rs index 40bf0ab40..e330959fe 100644 --- a/crates/svg/src/import/css_color.rs +++ b/crates/svg/src/import/css_color.rs @@ -219,9 +219,16 @@ fn mix(args: &str, profile: ColorProfile, depth: usize) -> Eval { ["in", ..] => (Space::Srgb, Some("only srgb, oklab and oklch mixes are read: it was mixed in sRGB")), _ => return Err("color-mix() starts with `in` and a colour space"), }; - let (a, pa, why_a) = operand(first, profile, depth)?; - let (b, pb, why_b) = operand(second, profile, depth)?; + let (a, pa, why_a, a_none) = operand(first, profile, depth)?; + let (b, pb, why_b, b_none) = operand(second, profile, depth)?; why = why.or(why_a).or(why_b); + // A missing alpha (`/ none`) is carried over from the other colour before the mix (CSS Color 5 + // section 4.1); rendered on its own the same colour is transparent. + let (a, b) = match (a_none, b_none) { + (true, false) => (a.with_alpha(b.a), b), + (false, true) => (a, b.with_alpha(a.a)), + _ => (a, b), + }; if [pa, pb].into_iter().flatten().any(|p| !(0.0..=100.0).contains(&p)) { return Err("mix percentages are between 0% and 100%"); } @@ -239,8 +246,11 @@ fn mix(args: &str, profile: ColorProfile, depth: usize) -> Eval { Ok((mixed.with_alpha(mixed.a * (sum / 100.0).min(1.0)), why)) } -/// One colour of a mix and its percentage (before or after it). -fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result<(Color, Option, Option<&'static str>), &'static str> { +/// One colour of a mix: the colour, its percentage (before or after it), a note, and whether its +/// alpha is missing (`rgb(255 0 0 / none)`), which [`mix`] fills from the other colour. +type Operand = (Color, Option, Option<&'static str>, bool); + +fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result { let words = split_top(s, char::is_whitespace); let pct = |w: &str| w.strip_suffix('%').and_then(|p| p.parse::().ok()).filter(|p| p.is_finite()); let (color, p) = match words.as_slice() { @@ -249,12 +259,19 @@ fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result<(Color, Optio [p, c] if pct(p).is_some() => (*c, pct(p)), _ => return Err("a mix colour is a colour and an optional percentage"), }; - let (c, why) = if color.starts_with("color(") || color.starts_with("color-mix(") { - eval(color, profile, depth + 1)? + let (c, why, alpha_missing) = if color.starts_with("color(") || color.starts_with("color-mix(") { + let (c, why) = eval(color, profile, depth + 1)?; + (c, why, false) } else { - (Color::parse_css(color).ok_or("a mix colour isn't read")?, None) + (Color::parse_css(color).ok_or("a mix colour isn't read")?, None, alpha_is_none(color)) }; - Ok((c, p, why)) + Ok((c, p, why, alpha_missing)) +} + +/// Whether a colour function's text (already lower case) gives its alpha as `none`: what follows +/// its last `/`. +fn alpha_is_none(color: &str) -> bool { + color.rsplit_once('/').is_some_and(|(_, rest)| rest.trim().trim_end_matches(')').trim_end() == "none") } /// `a` and `b` mixed `t` of the way to `b`, premultiplied by their alpha. diff --git a/crates/svg/src/import/css_color_tests.rs b/crates/svg/src/import/css_color_tests.rs index dbf3856a0..1c7177e1c 100644 --- a/crates/svg/src/import/css_color_tests.rs +++ b/crates/svg/src/import/css_color_tests.rs @@ -73,6 +73,12 @@ fn color_mix_in_srgb_oklab_and_oklch() { // Percentages under 100% lower the alpha; alphas mix premultiplied. assert_eq!(rgba8(fill("color-mix(in srgb, red 20%, blue 20%)").0), Some([128, 0, 128, 102])); assert_eq!(rgba8(fill("color-mix(in srgb, red, transparent)").0), Some([255, 0, 0, 128])); + // A missing alpha (`/ none`) takes the other colour's before the mix (CSS Color 5 section 4.1); + // on its own the same colour renders transparent. + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), blue)").0), Some([128, 0, 128, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, red, rgb(0 0 255 / none) 50%)").0), Some([128, 0, 128, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / 50%))").0), Some([128, 0, 128, 128])); + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / none))").0), Some([128, 0, 128, 0]), "both missing: zero"); // Nested, with color() inside. assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, red, blue), color(srgb 0 1 0) 0%)").0), Some([128, 0, 128, 255])); } From 12c9acbf0cf4a12d632c7a73617161aa3e02f6bb Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:17:54 -0400 Subject: [PATCH 040/326] events test: the stamp is within a minute of a second clock read, not ordered against it Review follow-up on #1766: a backward wall-clock step between the push and the test read made the ordering assertion flaky. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/events_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/events_tests.rs b/crates/engine/src/events_tests.rs index ad20974c5..304a8f8d1 100644 --- a/crates/engine/src/events_tests.rs +++ b/crates/engine/src/events_tests.rs @@ -53,7 +53,8 @@ fn events_are_stamped_with_the_wall_clock() { let r = log.poll(0, &comments(), 10, Duration::ZERO); let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs_f64(); let time = r.events[0].time; - assert!(time > 1_700_000_000.0 && time <= now, "{time} is seconds since the Unix epoch, read just before {now}"); + // Within a minute of the same clock read afterwards (not ordered: the wall clock can step). + assert!(time > 1_700_000_000.0 && (time - now).abs() < 60.0, "{time} is seconds since the Unix epoch, read next to {now}"); } #[test] From 16b13919aa72c3eff4c8f3a52140bf8771492ce9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:20:29 -0400 Subject: [PATCH 041/326] Page hex field: an 8-digit hex asking for opaque sets 100% Review follow-up on #1770: the typed colour keeps the page opacity only when the text carries no alpha (not 4 or 8 hex digits); FF0000FF on a translucent page now sets 100%. Test extended. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 11 +++++++++-- crates/ui-egui/src/panels/right.rs | 8 +++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 63995fc80..8802bb7e9 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1231,7 +1231,14 @@ fn the_page_background_opacity_field_sets_the_page_colour_alpha() { key(&mut u, Key::Enter, Modifiers::NONE); let c = page_bg(&u); assert!(near(c.g, 1.0) && near(c.a, 128.0 / 255.0), "{c:?}"); - assert_eq!(undo_steps(&u), steps + 3); + // Eight digits asking for opaque set 100 %: an alpha of 1 in the text is not "no alpha". + let at = hex(&mut u); + click(&mut u, at); + u.frame(vec![Event::Text("0000FFFF".into())]); + key(&mut u, Key::Enter, Modifiers::NONE); + let c = page_bg(&u); + assert!(near(c.b, 1.0) && near(c.a, 1.0), "{c:?}"); + assert_eq!(undo_steps(&u), steps + 4); u.app.run("edit.undo", json!({})); - assert!(near(page_bg(&u).r, 1.0) && near(page_bg(&u).a, 0.5), "undo takes back the last colour alone"); + assert!(near(page_bg(&u).g, 1.0) && near(page_bg(&u).a, 128.0 / 255.0), "undo takes back the last colour alone"); } diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 4f31f4089..e9987ec49 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -323,12 +323,14 @@ fn page_section(app: &mut FigApp, ui: &mut Ui, doc: &Document) { let p = Paint::solid(bg); let sw = widgets::swatch(ui, &p, 16.0); app.picker_control(crate::colorpicker::PickerTarget::PageBackground, &sw); - // A typed colour keeps the page's opacity unless it carries one (`FF000080`), as the - // colour picker's hex field does. + // 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) { - new_color = Some((c.with_alpha(if c.a < 1.0 { c.a } else { bg.a }), None)); + 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); From 16d97cf8e96ab81868e192e1e78930f47d01c67c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:33:58 -0400 Subject: [PATCH 042/326] M6: SVG import: a stretched image stays stretched, and a dash offset on a closed outline is kept Found while testing crates/svg import (no existing issue), each with a test that fails before and passes after. An took ImageScaleMode::Fill, which keeps the picture aspect and crops; a box of a different aspect now takes a whole-picture Crop, which the renderer draws as a stretch (SVG 2 section 8.6). A stroke-dashoffset equal to half the first dash was skipped on every shape because an open line starts half a dash in by itself; a closed outline runs its pattern from its start, so the exemption now applies to open outlines only (SVG 2 section 13.5.6). Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import.rs | 72 +++++++++++++++++++----- crates/svg/src/import/structure_tests.rs | 39 +++++++++++++ crates/svg/src/import/text.rs | 2 +- 3 files changed, 99 insertions(+), 14 deletions(-) diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 71c6c3b05..ed390ca4a 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -374,8 +374,11 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { let local = to_bez(p.data()); let (fill, stroke) = (p.fill(), p.stroke()); let shaped = shape::recognize(&local, stroke.is_none()).and_then(|prim| primitive(prim, world)); - let (kind, transform, w, h, radius) = match shaped { - Some(s) => s, + let (kind, transform, w, h, radius, closed_outline) = match shaped { + Some((kind, transform, w, h, radius)) => { + let closed_outline = !matches!(kind, NodeKind::Line); + (kind, transform, w, h, radius, closed_outline) + } None => { let mut path = local; path.apply_affine(world); @@ -406,7 +409,10 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { let fill_only = Node::new(cx.doc.alloc_id(), vector(&closed, true), format!("{} fill", layer_name(p.id(), "Vector")), bb.width(), bb.height()); let stroke_only = Node::new(cx.doc.alloc_id(), vector(&snapped, false), layer_name(p.id(), "Vector"), bb.width(), bb.height()); - let mut layers = [paint_path(cx, p, fill_only, at, world, true, false), paint_path(cx, p, stroke_only, at, world, false, true)]; + let mut layers = [ + paint_path(cx, p, fill_only, at, world, Paints { fill: true, stroke: false, closed: true }), + paint_path(cx, p, stroke_only, at, world, Paints { fill: false, stroke: true, closed: every_subpath_closed(&snapped) }), + ]; if p.paint_order() == usvg::PaintOrder::StrokeAndFill { layers.reverse(); } @@ -415,7 +421,8 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { } return; } - (vector(if fill.is_some() { &closed } else { &path }, fill.is_some()), at, bb.width(), bb.height(), 0.0) + let outline = if fill.is_some() { &closed } else { &path }; + (vector(outline, fill.is_some()), at, bb.width(), bb.height(), 0.0, every_subpath_closed(outline)) } }; let fallback = match kind { @@ -426,19 +433,28 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { }; let mut n = Node::new(cx.doc.alloc_id(), kind, layer_name(p.id(), fallback), w, h); n.corners.radii = [radius; 4]; - let n = paint_path(cx, p, n, transform, world, true, true); + let n = paint_path(cx, p, n, transform, world, Paints { fill: true, stroke: true, closed: closed_outline }); cx.add(n, parent); } +/// Which of a path's paints a layer takes, and whether its stroked outline closes on itself (see +/// [`stroke_props`]). +#[derive(Clone, Copy)] +struct Paints { + fill: bool, + stroke: bool, + closed: bool, +} + /// Layer `n` of path `p` placed at `transform`, with the path's fill and / or stroke. -fn paint_path(cx: &mut Ctx, p: &usvg::Path, mut n: Node, transform: Affine, world: Affine, with_fill: bool, with_stroke: bool) -> Node { +fn paint_path(cx: &mut Ctx, p: &usvg::Path, mut n: Node, transform: Affine, world: Affine, paints: Paints) -> Node { n.transform = transform; let target = Target { to_node: transform.inverse() * world, size: (n.width, n.height) }; - n.fills = p.fill().filter(|_| with_fill).and_then(|f| paint::paint(cx, f.paint(), f.opacity().get(), target)).into_iter().collect(); + n.fills = p.fill().filter(|_| paints.fill).and_then(|f| paint::paint(cx, f.paint(), f.opacity().get(), target)).into_iter().collect(); n.strokes.clear(); - if let Some(s) = p.stroke().filter(|_| with_stroke) { + if let Some(s) = p.stroke().filter(|_| paints.stroke) { n.strokes = paint::paint(cx, s.paint(), s.opacity().get(), target).into_iter().collect(); - n.stroke = stroke_props(s, length_scale(world)); + n.stroke = stroke_props(s, length_scale(world), paints.closed); // A stroke painted under the fill shows only its outer half. if p.paint_order() == usvg::PaintOrder::StrokeAndFill && !n.fills.is_empty() && figcraft_doc::geometry::is_closed(&n) { n.stroke.align = StrokeAlign::Outside; @@ -521,7 +537,27 @@ fn primitive(prim: Prim, world: Affine) -> Option<(NodeKind, Affine, f64, f64, f } } -pub(crate) fn stroke_props(s: &usvg::Stroke, k: f64) -> figcraft_doc::StrokeProps { +/// Whether every subpath of `path` closes on itself (and a dash pattern on it runs from its start, +/// as on any closed outline; an open one starts half a dash in). +fn every_subpath_closed(path: &BezPath) -> bool { + use figcraft_geom::kurbo::PathEl; + let els = path.elements(); + let mut closed = true; + for e in els { + match e { + PathEl::MoveTo(_) if !closed => return false, + PathEl::ClosePath => closed = true, + _ => closed = false, + } + } + !els.is_empty() && closed +} + +/// The stroke of `s` on a layer whose lengths `world` scales by `k`; `closed` says whether its +/// outline closes on itself: a closed outline runs a dash pattern from its start, so an offset into +/// the pattern rotates it, while an open line starts half a dash in by itself (and export writes +/// that offset), so that one is already there. +pub(crate) fn stroke_props(s: &usvg::Stroke, k: f64, closed: bool) -> figcraft_doc::StrokeProps { let cap = match s.linecap() { usvg::LineCap::Round => StrokeCap::Round, usvg::LineCap::Square => StrokeCap::Square, @@ -530,8 +566,8 @@ pub(crate) fn stroke_props(s: &usvg::Stroke, k: f64) -> figcraft_doc::StrokeProp let mut dashes: Vec = s.dasharray().unwrap_or(&[]).iter().map(|v| f64::from(*v) * k).collect(); if !dashes.is_empty() { let offset = f64::from(s.dashoffset()) * k; - // Half a dash in is how a line starts by itself (and how export writes one). - if dashes.first().is_none_or(|d| (d / 2.0 - offset).abs() > 1e-3) { + let half_dash_in = !closed && dashes.first().is_some_and(|d| (d / 2.0 - offset).abs() <= 1e-3); + if !half_dash_in { dashes = dash_offset(&dashes, offset, cap == StrokeCap::None).unwrap_or(dashes); } } @@ -608,7 +644,17 @@ fn image(cx: &mut Ctx, img: &usvg::Image, id: &str, parent: NodeId, base: Affine let hash = add_image(cx.doc, bytes, iw, ih); let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Rectangle, layer_name(id, "Image"), w, h); n.transform = transform; - n.fills = vec![Paint::image(hash, ImageScaleMode::Fill)]; + let mut fill = Paint::image(hash, ImageScaleMode::Fill); + // usvg sizes the box to the picture (`meet` and `slice` are in the transform), so a box of + // another shape is `preserveAspectRatio="none"`: the picture stretched edge to edge. A Fill + // would keep its shape and crop it; a crop of the whole picture stretches it. + if (w * ih - h * iw).abs() > 1e-6 * (w * ih).max(h * iw) + && let figcraft_color::PaintKind::Image(ip) = &mut fill.kind + { + ip.scale_mode = ImageScaleMode::Crop; + ip.crop = Some(Affine::IDENTITY.as_coeffs()); + } + n.fills = vec![fill]; cx.add(n, parent); } diff --git a/crates/svg/src/import/structure_tests.rs b/crates/svg/src/import/structure_tests.rs index adeedb005..ee76c2238 100644 --- a/crates/svg/src/import/structure_tests.rs +++ b/crates/svg/src/import/structure_tests.rs @@ -129,6 +129,45 @@ fn strokes_scale_with_their_layer() { assert_eq!((l.width, l.stroke.weight, l.stroke.dashes.clone()), (30.0, 6.0, vec![12.0, 6.0])); } +/// `stroke-dashoffset` is how far into the pattern the stroke starts. A closed outline runs the +/// pattern from its start, so the offset rotates the pattern; an open line starts half a dash in by +/// itself (see `figcraft_pathops::width::line_dashes`), so an offset of half the first dash is +/// already there and only that one is left out. +#[test] +fn a_closed_outline_keeps_a_dash_offset_of_half_a_dash() { + let (d, f) = import( + r##""##, + ); + // Two in: a dash of 2 is left, then the gap, then the pattern as it is (`dash_offset`). + let rotated = vec![2.0, 2.0, 2.0, 0.0]; + assert_eq!(node(&d, f, "r").stroke.dashes, rotated, "rectangle"); + assert_eq!(node(&d, f, "p").stroke.dashes, rotated, "closed path"); + assert_eq!(node(&d, f, "c").stroke.dashes, rotated, "circle"); + assert_eq!(node(&d, f, "l").stroke.dashes, vec![4.0, 2.0], "an open line starts half a dash in anyway"); +} + +/// `preserveAspectRatio="none"` stretches a picture into its box edge to edge. usvg sizes the +/// box to the picture for `meet` and `slice` (the fit is in the transform), so a box of another +/// shape is a stretch: a Fill, which keeps the picture's shape and crops it, would show the +/// middle of the picture instead. +#[test] +fn an_image_stretched_into_its_box_stays_stretched() { + use figcraft_color::{ImageScaleMode, PaintKind}; + let (d, f) = + import(&format!(r##""##)); + let n = node(&d, f, "pic"); + assert_eq!((n.width, n.height), (40.0, 40.0)); + let Some(PaintKind::Image(ip)) = n.fills.first().map(|p| &p.kind) else { panic!("{:?}", n.fills) }; + // The 4 × 2 picture's pixels map onto the whole 40 × 40 box: 10 across, 20 down. + let m = figcraft_render::paint::image_transform(ip, 4.0, 2.0, n.width, n.height); + assert_eq!((m.sx, m.ky, m.kx, m.sy, m.tx, m.ty), (10.0, 0.0, 0.0, 20.0, 0.0, 0.0), "{ip:?}"); + // With the aspect kept (the default) the box is the picture's own shape and a Fill is exact. + let (d, f) = import(&format!(r##""##)); + let n = node(&d, f, "pic"); + assert_eq!((n.width, n.height), (40.0, 20.0)); + assert!(matches!(n.fills.first().map(|p| &p.kind), Some(PaintKind::Image(i)) if i.scale_mode == ImageScaleMode::Fill), "{:?}", n.fills); +} + #[test] fn linked_files_are_never_read() { let dir = std::env::temp_dir().join("figcraft-svg-linked"); diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index b651f859b..cee54bbd8 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -340,7 +340,7 @@ fn add_layer(cx: &mut Ctx, layer: TextLayer<'_, '_, '_>) { n.fills = base_fill; if let Some(st) = spans.first().and_then(|sp| sp.stroke()) { n.strokes = paint(cx, st.paint(), st.opacity().get(), target).into_iter().collect(); - n.stroke = super::stroke_props(st, s); + n.stroke = super::stroke_props(st, s, true); } cx.add(n, parent); } From 8b6c92796eb3492968ae8fdfaadb207496892101 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:39:38 -0400 Subject: [PATCH 043/326] SVG color-mix(): every missing component is carried over, through nested mixes too Review follow-up on #1773: the carry-forward now covers red, green and blue in an sRGB mix (converted first in another space, so zero there, per CSS Color 5 section 4.1 on analogous components) as well as the alpha in every mix, and a component missing in both colours stays missing in the result, so an enclosing mix carries it from its other colour. Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import/css_color.rs | 87 ++++++++++++++++++------ crates/svg/src/import/css_color_tests.rs | 7 ++ 2 files changed, 72 insertions(+), 22 deletions(-) diff --git a/crates/svg/src/import/css_color.rs b/crates/svg/src/import/css_color.rs index e330959fe..9301275ed 100644 --- a/crates/svg/src/import/css_color.rs +++ b/crates/svg/src/import/css_color.rs @@ -27,8 +27,50 @@ const GREY_CHROMA: f32 = 0.000_2; /// The attributes that can hold a colour (with `style`, which can hold any property). const COLOR_ATTRS: [&str; 8] = ["fill", "stroke", "stop-color", "flood-color", "lighting-color", "color", "solid-color", "style"]; -/// A colour read from a call, with why it is only an approximation; or why it can't be read. -type Eval = Result<(Color, Option<&'static str>), &'static str>; +/// A colour read from a call, with why it is only an approximation (or why it can't be read) and +/// which of its components a mix should treat as missing. +type Eval = Result<(Color, Option<&'static str>, Missing), &'static str>; + +/// Which components a colour gave as `none`: red, green, blue and alpha. A mix takes a missing +/// component from its other colour before interpolating (CSS Color 5 section 4.1): red, green and +/// blue only in an sRGB mix (in another space they are converted first, and a missing one is 0), +/// the alpha in every mix. Missing in both colours, a component stays missing (and 0). +#[derive(Clone, Copy)] +struct Missing { + r: bool, + g: bool, + b: bool, + a: bool, +} + +impl Missing { + const NONE: Self = Self { r: false, g: false, b: false, a: false }; + + /// What a colour function's text (lower case) gives as `none`: the four values of `rgb()` or + /// `rgba()`, else only an alpha after a `/`. + fn of(color: &str) -> Self { + let rgb = color.strip_prefix("rgba(").or_else(|| color.strip_prefix("rgb(")).and_then(|r| r.strip_suffix(')')); + match rgb { + Some(inner) => { + let parts = split_top(inner, |c| c == ',' || c == '/' || c.is_whitespace()); + let at = |i: usize| parts.get(i).is_some_and(|p| *p == "none"); + Self { r: at(0), g: at(1), b: at(2), a: at(3) } + } + None => Self { a: alpha_is_none(color), ..Self::NONE }, + } + } +} + +/// Fill a component missing on one side from the other; true when it is missing on both. +fn carry(a: &mut f32, b: &mut f32, a_missing: bool, b_missing: bool) -> bool { + match (a_missing, b_missing) { + (true, false) => *a = *b, + (false, true) => *b = *a, + (true, true) => return true, + (false, false) => {} + } + false +} /// `data` with its `color()` and `color-mix()` calls replaced by colours usvg reads, and notes on /// those it read only approximately or not at all; `None` when there are none (or `data` isn't @@ -90,8 +132,8 @@ fn rewrite_calls(text: &str, range: Range, profile: ColorProfile, edits: }; let call = s.get(start..end).unwrap_or_default(); let color = match eval(call, profile, 0) { - Ok((c, None)) => c, - Ok((c, Some(why))) => { + Ok((c, None, _)) => c, + Ok((c, Some(why), _)) => { notes.push(note(call, why)); c } @@ -181,7 +223,7 @@ fn color_fn(args: &str, profile: ColorProfile) -> Eval { "display-p3" => (ColorProfile::DisplayP3, None), _ => (ColorProfile::Srgb, Some("only the srgb and display-p3 spaces are read: its values were taken as sRGB")), }; - Ok((from.conversion_to(profile).apply(c), why)) + Ok((from.conversion_to(profile).apply(c), why, Missing::NONE)) } /// A CSS number, a percentage (100% is 1) or `none` (0); finite only. @@ -219,15 +261,17 @@ fn mix(args: &str, profile: ColorProfile, depth: usize) -> Eval { ["in", ..] => (Space::Srgb, Some("only srgb, oklab and oklch mixes are read: it was mixed in sRGB")), _ => return Err("color-mix() starts with `in` and a colour space"), }; - let (a, pa, why_a, a_none) = operand(first, profile, depth)?; - let (b, pb, why_b, b_none) = operand(second, profile, depth)?; + let (mut a, pa, why_a, ma) = operand(first, profile, depth)?; + let (mut b, pb, why_b, mb) = operand(second, profile, depth)?; why = why.or(why_a).or(why_b); - // A missing alpha (`/ none`) is carried over from the other colour before the mix (CSS Color 5 - // section 4.1); rendered on its own the same colour is transparent. - let (a, b) = match (a_none, b_none) { - (true, false) => (a.with_alpha(b.a), b), - (false, true) => (a, b.with_alpha(a.a)), - _ => (a, b), + // Missing components are carried over from the other colour before the mix (see `Missing`); + // rendered on its own, the same colour has them at 0. + let srgb = matches!(space, Space::Srgb); + let missing = Missing { + r: srgb && carry(&mut a.r, &mut b.r, ma.r, mb.r), + g: srgb && carry(&mut a.g, &mut b.g, ma.g, mb.g), + b: srgb && carry(&mut a.b, &mut b.b, ma.b, mb.b), + a: carry(&mut a.a, &mut b.a, ma.a, mb.a), }; if [pa, pb].into_iter().flatten().any(|p| !(0.0..=100.0).contains(&p)) { return Err("mix percentages are between 0% and 100%"); @@ -243,12 +287,12 @@ fn mix(args: &str, profile: ColorProfile, depth: usize) -> Eval { return Err("mix percentages add up to 0%"); } let mixed = interpolate(space, a, b, pb / sum); - Ok((mixed.with_alpha(mixed.a * (sum / 100.0).min(1.0)), why)) + Ok((mixed.with_alpha(mixed.a * (sum / 100.0).min(1.0)), why, missing)) } -/// One colour of a mix: the colour, its percentage (before or after it), a note, and whether its -/// alpha is missing (`rgb(255 0 0 / none)`), which [`mix`] fills from the other colour. -type Operand = (Color, Option, Option<&'static str>, bool); +/// One colour of a mix: the colour, its percentage (before or after it), a note, and the +/// components it gave as `none` (see [`Missing`]). +type Operand = (Color, Option, Option<&'static str>, Missing); fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result { let words = split_top(s, char::is_whitespace); @@ -259,13 +303,12 @@ fn operand(s: &str, profile: ColorProfile, depth: usize) -> Result (*c, pct(p)), _ => return Err("a mix colour is a colour and an optional percentage"), }; - let (c, why, alpha_missing) = if color.starts_with("color(") || color.starts_with("color-mix(") { - let (c, why) = eval(color, profile, depth + 1)?; - (c, why, false) + let (c, why, missing) = if color.starts_with("color(") || color.starts_with("color-mix(") { + eval(color, profile, depth + 1)? } else { - (Color::parse_css(color).ok_or("a mix colour isn't read")?, None, alpha_is_none(color)) + (Color::parse_css(color).ok_or("a mix colour isn't read")?, None, Missing::of(color)) }; - Ok((c, p, why, alpha_missing)) + Ok((c, p, why, missing)) } /// Whether a colour function's text (already lower case) gives its alpha as `none`: what follows diff --git a/crates/svg/src/import/css_color_tests.rs b/crates/svg/src/import/css_color_tests.rs index 1c7177e1c..ee66b42da 100644 --- a/crates/svg/src/import/css_color_tests.rs +++ b/crates/svg/src/import/css_color_tests.rs @@ -79,6 +79,13 @@ fn color_mix_in_srgb_oklab_and_oklch() { assert_eq!(rgba8(fill("color-mix(in srgb, red, rgb(0 0 255 / none) 50%)").0), Some([128, 0, 128, 255])); assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / 50%))").0), Some([128, 0, 128, 128])); assert_eq!(rgba8(fill("color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / none))").0), Some([128, 0, 128, 0]), "both missing: zero"); + // A missing red, green or blue is carried over as well in an sRGB mix; in another space the + // converted channels are plain zeros (only analogous components carry, CSS Color 5 section 4.1). + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(none 0 0), red)").0), Some([255, 0, 0, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, rgb(none 0 0), rgb(255 none 0))").0), Some([255, 0, 0, 255])); + assert_eq!(rgba8(fill("color-mix(in oklab, rgb(none 0 0), red)").0), rgba8(fill("color-mix(in oklab, black, red)").0)); + // Missing in both stays missing through a nested mix and is carried in the outer one. + assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, rgb(0 255 0 / none), rgb(0 255 0 / none)), red)").0), Some([128, 128, 0, 255])); // Nested, with color() inside. assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, red, blue), color(srgb 0 1 0) 0%)").0), Some([128, 0, 128, 255])); } From 058cc24befd3602da169a2565328ccba741f9e4e Mon Sep 17 00:00:00 2001 From: samhyun Date: Sun, 1 Nov 2026 18:06:56 +0900 Subject: [PATCH 044/326] M8: grains stay in their cells whatever origin a render starts from Noise and texture lay their grain cells out in the layer's own coordinates, so a patch, a band or a pan should draw the grains a full render draws. At a zoom of 1.7, a 1-unit cell is 1.7 pixels across and every tenth edge falls on a row of pixel centres; a render whose origin is a whole number of pixels off reached that edge with another rounding error and moved the row into the next cell. An edit over a textured layer patched up to 197 levels off a full render, and a noisy one 224. Cell positions are now rounded to 1/2^20 of a cell before they're cut into cells, and texture adds its scatter to the pixel index in whole pixels instead of flooring it in f32 together with the index. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/grain.rs | 20 +++++++++++++++---- crates/render/src/grain_tests.rs | 20 +++++++++++++++++++ crates/render/src/retained_tests.rs | 30 +++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/render/src/grain.rs b/crates/render/src/grain.rs index d339a29fd..0ee827765 100644 --- a/crates/render/src/grain.rs +++ b/crates/render/src/grain.rs @@ -26,6 +26,14 @@ fn unit(h: u64, at: u32) -> f32 { f32::from(((h >> at) & 0xFFFF) as u16) / 65536.0 } +/// Cell positions are rounded to 1 / `STEPS_PER_CELL` of a cell before they're cut into cells. A +/// pixel centre can fall exactly on a cell edge (at a zoom of 1.7, a 1-unit cell is 1.7 pixels +/// across: every tenth edge does), and a view whose origin is a whole number of pixels off (a +/// patch, a band, a pan) reaches it with another rounding error. Unrounded, a row of grains lands +/// in the next cell; rounded, the edge moves 1 / 2²¹ of a cell aside, off the centres layers at +/// round positions and zooms put it on. +const STEPS_PER_CELL: f64 = 1_048_576.0; + /// Maps layer pixels to the grain cells under their centres. struct Cells { /// Layer pixels → local units, divided by the grain size: `[a, b, c, d, e, f]`. @@ -44,7 +52,8 @@ impl Cells { fn at(&self, x: u32, y: u32) -> (i64, i64) { let (px, py) = (f64::from(x) + 0.5, f64::from(y) + 0.5); let [a, b, c, d, e, f] = self.m; - ((a * px + c * py + e).floor() as i64, (b * px + d * py + f).floor() as i64) + let cell = |v: f64| ((v * STEPS_PER_CELL).round() / STEPS_PER_CELL).floor() as i64; + (cell(a * px + c * py + e), cell(b * px + d * py + f)) } } @@ -120,11 +129,14 @@ pub fn texture(layer: &mut Pixmap, t: &Texture, xf: Affine, scale: f64, seed: u3 let hv = hash(ix, iy, seed ^ 0x7E57_u32); // A uniform point in the disc of radius r. let (ang, dist) = (unit(hv, 0) * std::f32::consts::TAU, unit(hv, 16).sqrt() * r); - let (fx, fy) = (x as f32 + 0.5 + ang.cos() * dist, y as f32 + 0.5 + ang.sin() * dist); + // The move in whole pixels, apart from `x` and `y`: the same pixel of the page moves + // the same way wherever the layer's pixels start. + let (mx, my) = ((0.5 + ang.cos() * dist).floor() as i64, (0.5 + ang.sin() * dist).floor() as i64); + let (fx, fy) = (i64::from(x) + mx, i64::from(y) + my); let i = ((y * w + x) * 4) as usize; let mut px = [0u8; 4]; - if fx >= 0.0 && fy >= 0.0 && (fx as u32) < w && (fy as u32) < h { - let j = (((fy as u32) * w + fx as u32) * 4) as usize; + if fx >= 0 && fy >= 0 && fx < i64::from(w) && fy < i64::from(h) { + let j = ((fy * i64::from(w) + fx) * 4) as usize; if let Some(s) = src.get(j..j + 4) { px.copy_from_slice(s); } diff --git a/crates/render/src/grain_tests.rs b/crates/render/src/grain_tests.rs index bde0129a4..a06a445df 100644 --- a/crates/render/src/grain_tests.rs +++ b/crates/render/src/grain_tests.rs @@ -96,6 +96,26 @@ fn noise_grains_have_their_size_and_stay_put() { assert_eq!(px(&z, 23, 23), c); } +/// Panning by whole pixels at a zoom where grain edges fall on pixel centres (1.7: a 1-unit grain +/// is 1.7 pixels, every tenth edge on a centre) reaches those edges from another origin, with +/// another rounding error: the grains still stay put. +#[test] +fn grains_stay_put_where_their_edges_fall_on_pixel_centres() { + let s = 1.7; + for (why, kind) in [ + ("noise", noise(Noise { density: 0.5, size: 0.5, color: Color::BLACK, ..Noise::default() })), + ("texture", EffectKind::Texture(Texture { size: 0.5, radius: 12.0, clip_to_shape: false, ..Texture::default() })), + ] { + let (d, r) = square(kind); + let a = render_at(&d, r, (0.0, 0.0), s); + for (dx, dy) in [(79u32, 62u32), (13, 7), (31, 47), (5, 99)] { + let b = render_at(&d, r, (f64::from(dx) / s, f64::from(dy) / s), s); + let off = (0..200 - dy).flat_map(|y| (0..200 - dx).map(move |x| (x, y))).filter(|&(x, y)| px(&a, x + dx, y + dy) != px(&b, x, y)).count(); + assert_eq!(off, 0, "{why}, a pan by ({dx}, {dy}) pixels"); + } + } +} + #[test] fn noise_blend_mode_applies() { let (d, r) = square(noise(Noise { density: 1.0, color: Color::WHITE, blend: figcraft_color::BlendMode::Multiply, ..Noise::default() })); diff --git a/crates/render/src/retained_tests.rs b/crates/render/src/retained_tests.rs index dd93abc72..103178542 100644 --- a/crates/render/src/retained_tests.rs +++ b/crates/render/src/retained_tests.rs @@ -569,3 +569,33 @@ fn pans_patch_backdrops_at_the_edges_that_moved_in() { } } } + +#[test] +fn grainy_layers_patch_as_they_render() { + fonts(); + let texture = |clip_to_shape| EffectKind::Texture(figcraft_doc::Texture { size: 0.5, radius: 12.0, clip_to_shape, ..Default::default() }); + let noise = EffectKind::Noise(figcraft_doc::Noise { size: 0.5, density: 0.4, color: Color::BLACK, ..Default::default() }); + // At a zoom of 1.7, a grain of 0.5 is 1.7 pixels across: every tenth grain edge falls on a row + // of pixel centres, and a patch renders those rows from another origin than a full render. + for (why, kind) in [("texture", texture(false)), ("texture clipped to its shape", texture(true)), ("noise", noise)] { + let mut d = Document::new("grain"); + let p = d.first_page().unwrap(); + let e = d.create(p, NodeKind::Rectangle, "E", 60.0, 50.0, 120.0, 90.0).unwrap(); + solid(d.get_mut(e).unwrap(), "E03030"); + d.get_mut(e).unwrap().effects = vec![Effect { kind, visible: true }]; + let m = d.create(p, NodeKind::Rectangle, "M", 220.0, 60.0, 30.0, 30.0).unwrap(); + solid(d.get_mut(m).unwrap(), "20A060"); + let doc = Arc::new(d); + let v = View { origin: (0.0, 0.0), scale: 1.7, width: 400, height: 300 }; + let mut r = Retained::default(); + check(&mut r, &doc, p, &v); + // Over the grainy layer, which is redrawn whole. + let over = edit(&doc, |d| d.get_mut(m).unwrap().transform = Affine::translate((100.0, 80.0))); + let (shown, pix, work) = r.render(&over, p, &v, &Options::default()).unwrap(); + let pix = pix.clone(); + let full = render_view(&over, p, &shown, &Options::default()).unwrap(); + let worst = pix.data().iter().zip(full.data()).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0); + assert!(partial(work), "{why}: {work:?}"); + assert!(worst <= 2, "{why}: {work:?} is {worst} levels off a full render"); + } +} From e39e563408aa64b89be507326dd68aabdb25cb68 Mon Sep 17 00:00:00 2001 From: samhyun Date: Sun, 1 Nov 2026 18:21:00 +0900 Subject: [PATCH 045/326] M8: dots halfway between pixels stay put across pans, bands and patches The board's dot grid puts each mark on the device pixel nearest its page position, measured from the view's top-left. At a zoom of 1.0625 a step of 24 is 25.5 pixels, so every second mark falls halfway between two pixels, and a view a whole number of pixels on could put it on the other one: `round` sends halves away from zero, so a mark left of the view's origin went left and one right of it went right, and the origin `(px + offset) / scale` reached the half with another rounding error. A pan moved those marks by a pixel (up to 123 levels off). Positions are now rounded to 1/65536 px and then half up. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/dots.rs | 11 ++++++++++- crates/render/src/dots_tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/render/src/dots.rs b/crates/render/src/dots.rs index b13cbdd57..f3effd1f1 100644 --- a/crates/render/src/dots.rs +++ b/crates/render/src/dots.rs @@ -57,7 +57,7 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) { let strong = |k: i64| k.rem_euclid(major) == 0; // The device-pixel span of the mark on line `k` along an axis `len` pixels long from `o`. let span = |k: i64, o: f64, len: i64| { - let a = ((k as f64 * d.step * s - o).round() as i64).saturating_sub(lead); + let a = (nearest_px(k as f64 * d.step * s - o) as i64).saturating_sub(lead); (a.max(0), a.saturating_add(side).min(len)) }; let row = w as usize * 4; @@ -92,6 +92,15 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) { } } +/// The device pixel nearest `p` pixels from the view's top-left. A mark halfway between two pixels +/// goes to the right (or lower) one on either side of the origin, and `p` is first rounded to +/// 1/65536 px: a view a whole number of pixels off (a pan, a band, a patch) reaches it with another +/// rounding error, and would otherwise put the marks that fall halfway on the other pixel. +fn nearest_px(p: f64) -> f64 { + const STEPS: f64 = 65_536.0; + ((p * STEPS).round() / STEPS + 0.5).floor() +} + /// Which line covers each device pixel along an axis: 0 none, 1 a faded one, 2 a strong one. type Cover = Vec; diff --git a/crates/render/src/dots_tests.rs b/crates/render/src/dots_tests.rs index 53d052062..a5ff2edc9 100644 --- a/crates/render/src/dots_tests.rs +++ b/crates/render/src/dots_tests.rs @@ -134,3 +134,27 @@ fn graph_paper_is_strong_every_major_line() { assert_eq!(at(x, -195), strong, "a strong line at {x}"); } } + +/// At a zoom of 1.0625, a step of 24 is 25.5 pixels: every second dot falls halfway between two +/// pixels. A view a whole number of pixels on (a pan, a band, a patch) has to put it on the same +/// one, on whichever side of that view's origin it is. +#[test] +fn dots_halfway_between_pixels_stay_put() { + let (d, page) = page_with_square(); + for lines in [false, true] { + let opts = Options { dots: Some(Dots { lines, ..dots() }), ..Default::default() }; + let s = 1.0625; + let full = View { origin: (0.0, 0.0), scale: s, width: 400, height: 300 }; + let a = render_view_single(&d, page, &full, &opts).unwrap(); + for dx in 1..100u32 { + let dy = (dx * 37) % 100; + let v = View { origin: (f64::from(dx) / s, f64::from(dy) / s), scale: s, width: 250, height: 180 }; + let b = render_view_single(&d, page, &v, &opts).unwrap(); + for y in 0..180 { + for x in 0..250 { + assert_eq!(rgba(&b, x, y), rgba(&a, x + dx, y + dy), "lines {lines}, a pan by ({dx}, {dy}), at {x}, {y}"); + } + } + } + } +} From a46e2369bcd86afa8f8c859f6e914250606d4a40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Mittelst=C3=A4dt?= <62167861+TheGalitube@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:31:20 +0000 Subject: [PATCH 046/326] Preserve finite values at large rounding precision Found while testing crates/geom/src/transform.rs:59 Co-Authored-By: GPT-5.6-Luna Co-Authored-By: GPT-6-Luna --- crates/geom/src/tests.rs | 7 +++++++ crates/geom/src/transform.rs | 3 +++ 2 files changed, 10 insertions(+) diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 37e6ccab7..509db9779 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -163,6 +163,13 @@ fn set_rotation_keeps_center() { } } +#[test] +fn round_to_handles_large_precision_without_changing_finite_values() { + assert_eq!(round_to(1.25, 400), 1.25); + assert_eq!(round_to(-1.25, 400), -1.25); + assert_eq!(round_to(1.23456, 2), 1.23); +} + #[test] fn reverse_subpaths_preserves_open_and_closed() { let mut open = BezPath::new(); diff --git a/crates/geom/src/transform.rs b/crates/geom/src/transform.rs index f992060fd..69c6c788d 100644 --- a/crates/geom/src/transform.rs +++ b/crates/geom/src/transform.rs @@ -57,6 +57,9 @@ pub fn rotate_about(xf: Affine, pivot: Point, degrees: f64) -> Affine { /// Round a value to `digits` decimals for display (avoids `-0` and float noise). pub fn round_to(v: f64, digits: i32) -> f64 { let f = 10f64.powi(digits); + if v.is_finite() && !f.is_finite() { + return v; + } let r = (v * f).round() / f; if r == 0.0 { 0.0 } else { r } } From f797cbe0291f3e862ceb00914c6ab62529df9c7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Mittelst=C3=A4dt?= <62167861+TheGalitube@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:39:49 +0000 Subject: [PATCH 047/326] Reject duplicate Kiwi field IDs Found while testing crates/format/src/fig/kiwi.rs:615 Co-Authored-By: GPT-5.6-Luna Co-Authored-By: GPT-6-Luna --- crates/format/src/fig/kiwi.rs | 6 ++++++ crates/format/src/fig/tests.rs | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/crates/format/src/fig/kiwi.rs b/crates/format/src/fig/kiwi.rs index d34b3774d..26e8284e4 100644 --- a/crates/format/src/fig/kiwi.rs +++ b/crates/format/src/fig/kiwi.rs @@ -270,6 +270,9 @@ impl Schema { let ty = r.var_int()?; let array = r.byte()? & 1 != 0; let value = r.var_uint()?; + if kind == Kind::Message && fields.iter().any(|f: &Field| f.value == value) { + return err(format!("schema: duplicate field id {value} in {name}")); + } raw_types.push(ty); fields.push(Field { name: fname, ty: None, array, value }); } @@ -621,6 +624,9 @@ impl Schema { } .ok_or_else(|| KiwiError(format!("schema text: unknown type {base}")))?; let (name, value) = numbered(n.trim(), id)?; + if *kind == "message" && fields.iter().any(|f: &Field| f.value == value) { + return err(format!("schema text: duplicate field id {value} in {name}")); + } fields.push(Field { name, ty: Some(ty), array: t.ends_with("[]"), value }); } (if *kind == "struct" { Kind::Struct } else { Kind::Message }, fields) diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index 657f2f81d..50c50c3d0 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -562,6 +562,11 @@ fn oversized_grid_track_lists_warn_and_use_default_tracks() { assert!(warnings.iter().any(|w| w.contains("grid track list exceeds 1000 entries")), "{warnings:?}"); } +#[test] +fn duplicate_explicit_field_ids_are_ambiguous() { + assert!(Schema::parse("message M uint a=1, uint b=1").is_err()); +} + #[test] fn kiwi_round_trip() { let sc = schema(); From c8f34acc59052e6d3482396866bae670a5a93e05 Mon Sep 17 00:00:00 2001 From: samhyun Date: Sun, 1 Nov 2026 18:40:05 +0900 Subject: [PATCH 048/326] M8: dots on the 1/65536 px rounding step stay put too Review of #1796: rounding a mark's position to 1/65536 px with `round` sent the halves of that step away from zero, the asymmetry the PR set out to remove, one step further down. At a step of 25.5 - 2^-17 px, a pan by 26 pixels put the first mark a pixel off a full render. Both roundings now go half up. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/dots.rs | 11 ++++++----- crates/render/src/dots_tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/render/src/dots.rs b/crates/render/src/dots.rs index f3effd1f1..5d4ae1fc1 100644 --- a/crates/render/src/dots.rs +++ b/crates/render/src/dots.rs @@ -92,13 +92,14 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) { } } -/// The device pixel nearest `p` pixels from the view's top-left. A mark halfway between two pixels -/// goes to the right (or lower) one on either side of the origin, and `p` is first rounded to -/// 1/65536 px: a view a whole number of pixels off (a pan, a band, a patch) reaches it with another -/// rounding error, and would otherwise put the marks that fall halfway on the other pixel. +/// The first device pixel of a mark whose edge is `p` pixels from the view's top-left: the one +/// whose left (or top) edge is nearest, and the right (or lower) one when two are as near. `p` is +/// first rounded to 1/65536 px, halves up as well: a view a whole number of pixels off (a pan, a +/// band, a patch) reaches it with another rounding error, and, rounded either way, would put the +/// marks that fall halfway on the other pixel. fn nearest_px(p: f64) -> f64 { const STEPS: f64 = 65_536.0; - ((p * STEPS).round() / STEPS + 0.5).floor() + ((p * STEPS + 0.5).floor() / STEPS + 0.5).floor() } /// Which line covers each device pixel along an axis: 0 none, 1 a faded one, 2 a strong one. diff --git a/crates/render/src/dots_tests.rs b/crates/render/src/dots_tests.rs index a5ff2edc9..18d96345f 100644 --- a/crates/render/src/dots_tests.rs +++ b/crates/render/src/dots_tests.rs @@ -158,3 +158,25 @@ fn dots_halfway_between_pixels_stay_put() { } } } + +/// A mark that rounds to a half step of 1/65536 px goes the same way on both sides of a view's +/// origin too: at a step of 25.5 − 2⁻¹⁷ px, the first mark is where 1/65536 px rounds up. +#[test] +fn dots_on_the_rounding_step_stay_put() { + let (d, page) = page_with_square(); + let step = 25.5 - 2f64.powi(-17); + for lines in [false, true] { + let opts = Options { dots: Some(Dots { step, lines, ..dots() }), ..Default::default() }; + let full = View { origin: (0.0, 0.0), scale: 1.0, width: 300, height: 200 }; + let a = render_view_single(&d, page, &full, &opts).unwrap(); + for pan in 1..60u32 { + let v = View { origin: (f64::from(pan), f64::from(pan)), scale: 1.0, width: 200, height: 120 }; + let b = render_view_single(&d, page, &v, &opts).unwrap(); + for y in 0..120 { + for x in 0..200 { + assert_eq!(rgba(&b, x, y), rgba(&a, x + pan, y + pan), "lines {lines}, a pan by {pan}, at {x}, {y}"); + } + } + } + } +} From 12b0bcddcba1b0098e09250e0f9075c0a0826197 Mon Sep 17 00:00:00 2001 From: samhyun Date: Sun, 1 Nov 2026 18:47:09 +0900 Subject: [PATCH 049/326] M8: a test for texture's whole-pixel moves in wide layers Review of #1795: the tests checked the rounding of grain cells but not the move texture now adds in whole pixels. Rounded cells with the old `f32` move still passed them. A pan across a 2,400-pixel-wide striped layer catches it: past 1,024 pixels, the old move came out a pixel off for some pixels. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/grain_tests.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/render/src/grain_tests.rs b/crates/render/src/grain_tests.rs index a06a445df..743530944 100644 --- a/crates/render/src/grain_tests.rs +++ b/crates/render/src/grain_tests.rs @@ -158,3 +158,32 @@ fn hostile_grain_values_do_not_crash() { let _ = render_at(&d, r, (0.0, 0.0), 1.0); } } + +/// Texture moves each pixel by whole pixels, the same in any layer: far from the layer's left edge +/// (past 1024 pixels), a move worked out in `f32` together with the pixel's index came out a +/// pixel off for some indices, so a pan changed which pixel a grain took. (The stripes' gradient +/// itself can differ by a level between the two renders; a grain taking the wrong pixel differs by +/// far more.) +#[test] +fn texture_moves_far_into_a_wide_layer_stay_put() { + use figcraft_color::{ColorStop, Gradient, GradientKind}; + let mut d = Document::new("wide"); + let p = d.first_page().unwrap(); + let r = d.create(p, NodeKind::Rectangle, "Stripes", 0.0, 0.0, 2400.0, 60.0).unwrap(); + let n = d.get_mut(r).unwrap(); + // Black and white stripes, 3 units each: a pixel's neighbours differ. + let stops = (0..=800).map(|i| ColorStop { position: i as f32 / 800.0, color: if i % 2 == 0 { Color::BLACK } else { Color::WHITE } }).collect(); + n.fills = vec![Paint::gradient(Gradient { kind: GradientKind::Linear, stops, from: (0.0, 0.5), to: (1.0, 0.5), width: (0.0, 1.0) })]; + n.effects = + vec![Effect { kind: EffectKind::Texture(Texture { size: 1.0, radius: 12.0, clip_to_shape: false, ..Texture::default() }), visible: true }]; + let view = |x: f64, w: u32| View { origin: (x, -20.0), scale: 1.0, width: w, height: 100 }; + let mut a = Pixmap::new(2440, 100).unwrap(); + render_nodes_into(&d, &[r], &view(-20.0, 2440), &mut a); + for dx in [300u32, 1021, 1500] { + let mut b = Pixmap::new(900, 100).unwrap(); + render_nodes_into(&d, &[r], &view(f64::from(dx) - 20.0, 900), &mut b); + let far = |p: [u8; 4], q: [u8; 4]| p.iter().zip(q).any(|(u, v)| u.abs_diff(v) > 8); + let off = (0..100).flat_map(|y| (0..900).map(move |x| (x, y))).filter(|&(x, y)| far(px(&a, x + dx, y), px(&b, x, y))).count(); + assert_eq!(off, 0, "a pan by {dx} pixels"); + } +} From 3f7f5f38ce985132d64b0b803fb96b83654fb86c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Mittelst=C3=A4dt?= <62167861+TheGalitube@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:09:26 +0000 Subject: [PATCH 050/326] Reject overflowing u32 varints Found while testing crates/format/src/fig/kiwi.rs:190 Co-Authored-By: GPT-5.6-Luna Co-Authored-By: GPT-6-Luna --- crates/format/src/fig/kiwi.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/format/src/fig/kiwi.rs b/crates/format/src/fig/kiwi.rs index d34b3774d..c564e445d 100644 --- a/crates/format/src/fig/kiwi.rs +++ b/crates/format/src/fig/kiwi.rs @@ -187,9 +187,13 @@ impl<'b> Reader<'b> { let mut shift = 0; loop { let b = self.byte()?; - value |= u32::from(b & 127).checked_shl(shift).unwrap_or(0); + let part = b & 127; + if shift == 28 && (part > 0x0f || b & 128 != 0) { + return err("u32 varint overflow"); + } + value |= u32::from(part) << shift; shift += 7; - if b & 128 == 0 || shift >= 35 { + if b & 128 == 0 { return Ok(value); } } @@ -640,3 +644,17 @@ fn numbered(token: &str, default: u32) -> Result<(String, u32), KiwiError> { Some((name, n)) => Ok((name.to_string(), n.parse().map_err(|_| KiwiError(format!("schema text: bad number in `{token}`")))?)), } } + +#[cfg(test)] +mod tests { + use super::Reader; + + #[test] + fn overflowing_u32_varint_is_rejected() { + let mut boundary = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x0f], pos: 0 }; + assert_eq!(boundary.var_uint(), Ok(u32::MAX)); + + let mut overflowing = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x7f], pos: 0 }; + assert!(overflowing.var_uint().is_err(), "overflowing u32 varint was accepted"); + } +} From dfe703deb26857bd8b930bcf992d079ef22142b9 Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 13:46:24 +0330 Subject: [PATCH 051/326] Add files via upload --- map.rs | 490 +++++++++++++++++ tests.rs | 1588 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 2078 insertions(+) create mode 100644 map.rs create mode 100644 tests.rs diff --git a/map.rs b/map.rs new file mode 100644 index 000000000..98239cd7b --- /dev/null +++ b/map.rs @@ -0,0 +1,490 @@ +//! Decoded `.fig` message → REST API file JSON, which [`crate::rest`] then imports. +//! +//! The message lists node changes; each names its id (`guid`), its parent and its position among +//! the siblings (`parentIndex`). Nodes are read by field name, so files written with newer +//! schemas still import what is understood. Instances carry only their overrides: their layers +//! are expanded here from the main component (overrides and derived layout matched by id path, +//! component property values applied) so the import looks as saved. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::rc::Rc; + +use figcraft_doc::VectorNetwork; +use figcraft_doc::geom::{Affine, Point}; +use figcraft_doc::proto::{MAX_ACTION_DEPTH, MAX_EXPR_DEPTH}; +use serde_json::{Map, Value, json}; + +use super::kiwi::Kv; +use super::network; + +mod component; +mod connector; +mod document; +mod layer; +mod layout; +mod paint; +mod proto; +mod text; +mod variables; + +use component::OverrideScope; +#[cfg(test)] +use paint::paint; + +type Obj = Map; + +/// Deepest nesting followed. +const MAX_DEPTH: usize = 256; +/// Most path commands read from one geometry blob. +const MAX_COMMANDS: usize = 200_000; +const MAX_GRID_TRACKS: usize = 1_000; +pub(super) const MAX_GRID_TRACK_VALUE: f64 = 1e6; +/// Id of "no style". +const NO_STYLE: &str = "4294967295:4294967295"; +/// Longest asset `key` or `version` kept for resolving references given as assets. +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`]). +pub(super) fn to_rest(msg: &Kv, name: &str, max_nodes: usize) -> (Value, Vec, Vec>) { + let mut m = Mapper::new(msg, max_nodes); + let _canon = VarCanon::install(&m); + let doc = m.document(); + // Large values are moved in, never passed through `json!`, which serialises its arguments: + // a deep copy of the whole tree, briefly holding it twice. + let mut out = json!({"name": name}); + out["document"] = doc; + if !m.library_contexts.is_empty() { + out[crate::rest::FIG_LIBRARY_CONTEXTS_FIELD] = Value::Array(std::mem::take(&mut m.library_contexts)); + } + // Mains in the file that the layer cap kept out: their instances are told apart from those of + // components the file doesn't have (#981). + if m.count >= m.max_nodes { + let capped: Vec = m.referenced_mains.difference(&m.mapped_mains).map(|id| json!(id)).collect(); + if !capped.is_empty() { + out[crate::rest::FIG_CAPPED_MAINS_FIELD] = Value::Array(capped); + } + } + if !m.styles.is_empty() { + out["styles"] = Value::Object(std::mem::take(&mut m.styles)); + } + if !m.components.is_empty() { + out["components"] = Value::Object(std::mem::take(&mut m.components)); + } + if !m.sets.is_empty() { + out["componentSets"] = Value::Object(std::mem::take(&mut m.sets)); + } + if let Some(vars) = m.variables() { + out["meta"] = vars; + } + let styles = m.style_definitions(); + if !styles.is_empty() { + out["styleDefinitions"] = Value::Array(styles); + } + (out, m.warnings.finish(), m.networks) +} + +#[cfg(test)] +mod image_filter_tests; + +/// REST importer warnings reworded for a `.fig` import (`None`: drop it). +pub(super) fn adapt_warning(w: String) -> Option { + if w.contains("geometry=paths") { + return None; + } + Some(w.replace("the variables JSON", "the file").replace("the file JSON", "the file")) +} + +// ---- small readers ---- + +/// A generated child is identified by one exact template GUID, not its array position. +fn generated_record<'a>(v: &View<'a>, field: &str, local_id: u32) -> Option<&'a Kv<'a>> { + v.get(field)?.get("overrides")?.list().iter().find(|row| { + row.get("guidPath").and_then(|path| path.get("guids")).map(Kv::list).is_some_and(|guids| { + guids.len() == 1 && num(&guids[0], "sessionID") == Some(40_000_000.0) && num(&guids[0], "localID") == Some(f64::from(local_id)) + }) + }) +} + +fn num(n: &Kv, k: &str) -> Option { + n.get(k).and_then(Kv::f64) +} + +fn guid(v: &Kv) -> Option { + Some(format!("{}:{}", num(v, "sessionID")? as u64, num(v, "localID")? as u64)) +} + +#[cfg(test)] +mod connector_snapshot_budget_tests; + +/// A `GUID`-holding reference (`StyleId`, `VariableID`, …): its `guid`. +fn ref_guid(v: &Kv) -> Option { + v.get("guid").and_then(guid).filter(|g| g != NO_STYLE) +} + +fn vec2(v: &Kv) -> Option { + Some(json!({"x": num(v, "x")?, "y": num(v, "y")?})) +} + +fn size(v: &Kv) -> Option<(f64, f64)> { + Some((num(v, "x")?, num(v, "y")?)) +} + +fn matrix(m: &Kv) -> Option { + let c = |k: &str| num(m, k); + let a = Affine::new([c("m00")?, c("m10")?, c("m01")?, c("m11")?, c("m02")?, c("m12")?]); + a.as_coeffs().iter().all(|x| x.is_finite()).then_some(a) +} + +fn rows(a: Affine) -> Value { + let [a, b, c, d, e, f] = a.as_coeffs(); + json!([[a, c, e], [b, d, f]]) +} + +fn copy_num(o: &mut Obj, n: &View, from: &str, to: &str) { + if let Some(x) = n.num(from) { + o.insert(to.into(), json!(x)); + } +} + +fn copy_str(o: &mut Obj, n: &View, from: &str, to: &str) { + if let Some(s) = n.str(from) { + o.insert(to.into(), json!(s)); + } +} + +/// A node seen through override layers: the last layer with a field wins. +#[derive(Clone)] +struct View<'a> { + layers: Vec<&'a Kv<'a>>, + /// Size and transform worked out from the constraints, over the layers' own. + fitted: Option<((f64, f64), Affine)>, +} + +impl<'a> View<'a> { + fn of(n: &'a Kv<'a>) -> Self { + Self { layers: vec![n], fitted: None } + } + + fn size(&self) -> Option<(f64, f64)> { + self.fitted.map(|f| f.0).or_else(|| self.get("size").and_then(size)) + } + + fn transform(&self) -> Option { + self.fitted.map(|f| f.1).or_else(|| self.get("transform").and_then(matrix)) + } + + fn with(&self, top: impl IntoIterator>) -> Self { + let mut v = self.clone(); + v.layers.extend(top); + v + } + + /// This view with `style` just above the layer that links it in `key` (or `legacy`): the style + /// beats that layer's and lower layers' copies of its fields (stale when the style changed + /// since, or written for the style linked before), and override rows above the link beat it. + fn styled(&self, style: Option<&'a Kv<'a>>, key: &str, legacy: &str) -> Self { + let mut v = self.clone(); + if let Some(s) = style { + let linked_in = |k: &str| v.layers.iter().rposition(|l| l.get(k).is_some()); + let at = linked_in(key).or_else(|| linked_in(legacy)).map_or(1, |i| i + 1); + v.layers.insert(at.min(v.layers.len()), s); + } + v + } + + fn get(&self, k: &str) -> Option<&'a Kv<'a>> { + self.layers.iter().rev().find_map(|l| l.get(k)) + } + + fn num(&self, k: &str) -> Option { + self.get(k).and_then(Kv::f64) + } + + fn str(&self, k: &str) -> Option<&'a str> { + self.get(k).and_then(Kv::str) + } + + fn flag(&self, k: &str) -> Option { + self.get(k).and_then(Kv::bool) + } + + fn list(&self, k: &str) -> &'a [Kv<'a>] { + self.get(k).map(Kv::list).unwrap_or_default() + } +} + +struct Mapper<'a> { + nodes: BTreeMap>, + kids: BTreeMap>, + blobs: Vec<&'a [u8]>, + /// Component property definitions: id → (REST name "Name#id", type). + prop_defs: BTreeMap, + /// The copies of a set's definitions each variant keeps (no name or type of their own; the + /// variant's layers and its instances' assignments use them): copy id → the definition's id. + prop_parents: BTreeMap, + /// File nodes by asset `key` and `version`: references can name a collection, variable or + /// style as the asset instead of the guid, and the file carries the resources to resolve + /// them (the collection node itself says the same `key`). + assets: BTreeMap>, + styles: Obj, + /// Descriptions of components and component sets (REST `components` / `componentSets`). + components: Obj, + sets: Obj, + /// Layers and keys of each main, built when an instance of it first needs them. + override_scopes: BTreeMap>, + /// Entries held by `override_scopes` (bounded by `max_nodes` together). + override_scope_entries: usize, + /// Component-bearing branches of the file's internal canvases (cached library definitions). + library_contexts: Vec, + /// Layers visited while scanning internal canvases, across all of them. + library_scan_count: usize, + warnings: crate::rest::Warnings, + count: usize, + /// The mains in the file that instances or instance swap defaults name, and the mains mapped + /// as layers: the difference is what the layer cap kept out. + referenced_mains: BTreeSet, + mapped_mains: BTreeSet, + /// Most layers produced or scanned, instance expansion included; the one place the cap comes + /// from (see [`super::layer_budget`]). + max_nodes: usize, + /// Layers kept back for the visible pages' top level while library copies are mapped, so the + /// copies can't take the whole budget and leave the pages empty. + reserved: usize, + /// Vector networks, each built once: the layers that show one (every instance of a main + /// holding it) name it by `vectorNetworkRef`. Kept out of the JSON, where a large file's + /// networks took gigabytes. + networks: Vec>, + /// Index in `networks` by what a network is made from: its blob, its scale and its style table. + network_ids: HashMap<(usize, u64, u64, usize), usize>, + /// 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, +} + +impl<'a> Mapper<'a> { + fn new(msg: &'a Kv<'a>, max_nodes: usize) -> Self { + let mut nodes = BTreeMap::new(); + let mut kids: BTreeMap> = BTreeMap::new(); + let mut prop_defs = BTreeMap::new(); + let mut prop_parents = BTreeMap::new(); + let changes = msg.get("nodeChanges").map(Kv::list).unwrap_or_default(); + // The last change of a GUID wins; a REMOVED change deletes what came before it. + for n in changes { + let Some(id) = n.get("guid").and_then(guid) else { continue }; + if n.get("phase").and_then(Kv::str) == Some("REMOVED") { + nodes.remove(&id); + } else { + nodes.insert(id, n); + } + } + for n in changes { + let Some(id) = n.get("guid").and_then(guid) else { continue }; + if !nodes.get(&id).is_some_and(|latest| std::ptr::eq(*latest, n)) { + continue; + } + // Variables and their collections are read from the node list (`of_type`), never + // as layers: out of the layer tree, an instance's expansion doesn't walk them again for + // every instance without counting them (#1077). + if let Some(p) = n.get("parentIndex") + && let Some(parent) = p.get("guid").and_then(guid) + && !matches!(n.get("type").and_then(Kv::str), Some("VARIABLE" | "VARIABLE_SET")) + { + kids.entry(parent).or_default().push((p.get("position").and_then(Kv::str).unwrap_or(""), id.clone())); + } + for d in n.get("componentPropDefs").map(Kv::list).unwrap_or_default() { + let Some(did) = d.get("id").and_then(guid) else { continue }; + if let (Some(name), Some(ty)) = (d.get("name").and_then(Kv::str), d.get("type").and_then(Kv::str)) { + prop_defs.insert(did.clone(), (format!("{name}#{did}"), ty)); + } else if let Some(parent) = d.get("parentPropDefId").and_then(guid) { + prop_parents.insert(did, parent); + } + } + } + for list in kids.values_mut() { + list.sort(); + list.dedup_by(|a, b| a.1 == b.1); + } + let blobs = + msg.get("blobs").map(Kv::list).unwrap_or_default().iter().map(|b| b.get("bytes").and_then(Kv::bytes).unwrap_or_default()).collect(); + let mut assets: BTreeMap> = BTreeMap::new(); + for n in msg.get("nodeChanges").map(Kv::list).unwrap_or_default() { + let (Some(key), Some(id)) = (n.get("key").and_then(Kv::str), n.get("guid").and_then(guid)) else { continue }; + if key.is_empty() || key.len() > MAX_ASSET_PART { + continue; + } + let version = n.get("version").and_then(Kv::str).filter(|v| !v.is_empty() && v.len() <= MAX_ASSET_PART).unwrap_or(""); + assets.entry(key.to_string()).or_default().entry(version.to_string()).or_insert(id); + } + Self { + nodes, + kids, + blobs, + prop_defs, + prop_parents, + assets, + styles: Obj::new(), + components: Obj::new(), + sets: Obj::new(), + override_scopes: BTreeMap::new(), + override_scope_entries: 0, + library_contexts: Vec::new(), + library_scan_count: 0, + warnings: crate::rest::Warnings::default(), + count: 0, + referenced_mains: BTreeSet::new(), + mapped_mains: BTreeSet::new(), + max_nodes, + reserved: 0, + networks: Vec::new(), + network_ids: HashMap::new(), + region_paint_elements: 0, + } + } + + /// The id of the resource a `VariableSetID` (or `VariableID`, `StyleId`) names: its `guid`, + /// else the file node its asset `key` and `version` names (a collection from a library is + /// referenced as the asset, and the file's own node for it says the same `key`). `None` when + /// the reference has neither or the asset names nothing (or ambiguously) in the file. + /// Original code for this importer: the field names are those of the schema each file embeds. + fn resource_id(&self, v: &Kv) -> Option { + // A guid names the resource when this file holds a node by it. One from another file (the + // library a style or collection came from, as a paste carries) names nothing here: the + // asset it also names finds the file's copy (#1638). + if let Some(g) = v.get("guid").and_then(guid).filter(|g| *g != NO_STYLE && self.nodes.contains_key(g)) { + return Some(g); + } + let asset = v.get("assetRef")?; + let key = asset.get("key").and_then(Kv::str)?; + let versions = self.assets.get(key)?; + let version = asset.get("version").and_then(Kv::str); + match version { + Some(v) => versions.get(v), + // Without a version: an unversioned record, else the file's only one. + None => versions.get("").or_else(|| (versions.len() == 1).then(|| versions.values().next()).flatten()), + } + .cloned() + } + + /// The collection a `VariableSetID` names, as one collection per library asset: a file that + /// took several updates of a library holds a copy of the collection for each version it met, + /// all with the same asset `key`. Variables and explicit modes may name any of those copies, + /// while the mode ids stay the same across them, so every copy maps to the newest one (the + /// one [`Self::variables`] keeps, with the modes of the others added). Without this, a page set + /// to a mode an older copy didn't have yet lost its mode, and the layers fell back to the + /// default mode of the newest copy. + pub(super) fn collection_id(&self, v: &Kv) -> Option { + let id = self.resource_id(v)?; + Some(self.canonical_collection(&id).unwrap_or(id)) + } + + /// The newest live copy of collection node `id`'s library asset, when it has a key. + pub(super) fn canonical_collection(&self, id: &str) -> Option { + let key = self.nodes.get(id)?.get("key").and_then(Kv::str).filter(|k| !k.is_empty())?; + let live_set = |n: &Kv| n.get("type").and_then(Kv::str) == Some("VARIABLE_SET") && n.get("isSoftDeleted").and_then(Kv::bool) != Some(true); + self.assets + .get(key)? + .iter() + .filter(|(_, nid)| self.nodes.get(nid.as_str()).is_some_and(|n| live_set(n))) + .max_by_key(|(ver, _)| version_rank(ver)) + .map(|(_, nid)| nid.clone()) + } + + /// A note about what this file's mapping left out or changed. Counted, as the REST importer + /// counts its own: these notes are met once per layer, so the kinds were named once each with + /// no sign of how much of the file they covered -- a file whose every text layer lost a + /// setting read the same as one where a single layer did (#467). The collector keeps the + /// first-seen order and the same cap, since some notes name fields of the file (image + /// filters). + fn warn(&mut self, w: impl Into) { + self.warnings.add(w.into()); + } + + fn children(&self, id: &str) -> Vec { + self.kids.get(id).map(|k| k.iter().map(|(_, c)| c.clone()).collect()).unwrap_or_default() + } + + /// How many layers may be produced now: the cap, less what is kept for the visible pages. + fn budget(&self) -> usize { + self.max_nodes.saturating_sub(self.reserved) + } +} + +/// A library version (`"40727:1183"`) as numbers to order by; unparsable parts rank lowest. +fn version_rank(v: &str) -> (u64, u64) { + let mut parts = v.split(':').map(|p| p.trim().parse::().unwrap_or(0)); + (parts.next().unwrap_or(0), parts.next().unwrap_or(0)) +} + +/// Library variables, one per asset. A file that took several updates of a library keeps a copy +/// of a variable for each version it met (same `key`, another `version`), and layers and other +/// variables name them by that asset (`assetRef {key, version}`) rather than by guid. Each +/// reference goes to the newest copy: it has the values of every mode the library has now, where +/// an older one lacks the modes added since (a layer under a page set to such a mode fell back to +/// the default one). Kept per thread while a file is mapped: the paint and variable readers that +/// meet references are free functions. +#[derive(Default)] +pub(super) struct VarCanon { + by_key: HashMap, + by_id: HashMap, +} + +thread_local! { + static VAR_CANON: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// Removes the thread's table when the mapping is done. +pub(super) struct VarCanonGuard; + +impl Drop for VarCanonGuard { + fn drop(&mut self) { + VAR_CANON.with(|c| c.borrow_mut().take()); + } +} + +impl VarCanon { + fn install(m: &Mapper) -> VarCanonGuard { + let mut newest: HashMap = HashMap::new(); + let mut copies: Vec<(String, String)> = Vec::new(); + for (id, n) in &m.nodes { + if n.get("type").and_then(Kv::str) != Some("VARIABLE") || n.get("isSoftDeleted").and_then(Kv::bool) == Some(true) { + continue; + } + let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) else { continue }; + let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or("")); + copies.push((id.clone(), key.to_string())); + let e = newest.entry(key.to_string()).or_insert_with(|| (rank, id.clone())); + if rank > e.0 || (rank == e.0 && *id > e.1) { + *e = (rank, id.clone()); + } + } + let mut t = VarCanon::default(); + for (id, key) in copies { + if let Some((_, canon)) = newest.get(&key) { + t.by_id.insert(id, canon.clone()); + } + } + t.by_key = newest.into_iter().map(|(k, (_, id))| (k, id)).collect(); + VAR_CANON.with(|c| *c.borrow_mut() = Some(t)); + VarCanonGuard + } + + /// The variable a reference (`{guid}` or `{assetRef}`) names, as its newest copy. + pub(super) fn resolve(r: &Kv) -> Option { + let by_guid = r.get("guid").and_then(guid).filter(|g| g != NO_STYLE); + VAR_CANON.with(|c| { + let c = c.borrow(); + let Some(t) = c.as_ref() else { return by_guid.clone() }; + if let Some(g) = &by_guid { + return Some(t.by_id.get(g).cloned().unwrap_or_else(|| g.clone())); + } + let key = r.get("assetRef")?.get("key").and_then(Kv::str)?; + t.by_key.get(key).cloned() + }) + } + + /// Whether variable node `id` is an older copy another one replaces. + pub(super) fn superseded(id: &str) -> bool { + VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.by_id.get(id)).is_some_and(|canon| canon != id)) + } +} diff --git a/tests.rs b/tests.rs new file mode 100644 index 000000000..0e2c5016e --- /dev/null +++ b/tests.rs @@ -0,0 +1,1588 @@ +//! `.fig` import tests on fixtures built in code: a small schema written in a compact text form, +//! a message encoded with our own kiwi encoder, compressed (deflate and zstd), framed and zipped. + +use std::io::Write; + +use figcraft_doc::{NodeKind, VariableType}; +use serde_json::Value; + +use super::kiwi::{Def, Field, Kind, Kv, Schema, Type, encode}; +use super::*; + +/// The fixture schema: `enum Name A B …`, `struct|message Name type field, type field[] …`. +/// Message field ids count from 1; enum values from 0. +const SCHEMA: &str = " +enum NodeType NONE DOCUMENT CANVAS GROUP FRAME BOOLEAN_OPERATION VECTOR STAR LINE ELLIPSE RECTANGLE REGULAR_POLYGON ROUNDED_RECTANGLE TEXT SLICE SYMBOL INSTANCE STICKY VARIABLE VARIABLE_SET SHAPE_WITH_TEXT CONNECTOR TABLE +enum PaintType SOLID GRADIENT_LINEAR IMAGE EMOJI +enum ImageScaleMode STRETCH FIT FILL TILE +enum WindingRule NONZERO ODD +enum StyleType NONE FILL TEXT +enum StackMode NONE HORIZONTAL VERTICAL +enum PropType BOOL TEXT +enum VariableField MISSING VISIBLE TEXT_DATA +enum DataType BOOLEAN FLOAT STRING ALIAS COLOR PROP_REF EXPRESSION +enum ResolvedType BOOLEAN FLOAT STRING COLOR +enum InteractionType ON_CLICK ON_HOVER +enum ConnectionType NONE INTERNAL_NODE URL BACK CLOSE SET_VARIABLE CONDITIONAL SET_VARIABLE_MODE +enum StrokeCap NONE ROUND SQUARE ARROW_LINES ARROW_EQUILATERAL +enum StrokeJoin MITER BEVEL ROUND +enum VectorMirror NONE ANGLE ANGLE_AND_LENGTH +enum ShapeWithTextType SQUARE ELLIPSE +enum ConnectorLineStyle ELBOWED STRAIGHT CURVED +enum ExpressionFunction ADDITION SUBTRACTION RESOLVE_VARIANT MULTIPLY DIVIDE EQUALS +enum NavigationType NAVIGATE OVERLAY +enum TransitionType INSTANT_TRANSITION DISSOLVE SMART_ANIMATE +enum EasingType IN_CUBIC OUT_CUBIC +enum ConstraintType MIN CENTER MAX STRETCH SCALE +enum LeadingTrim NONE CAP_HEIGHT +struct GUID uint sessionID, uint localID +struct Color float r, float g, float b, float a +struct Vector float x, float y +struct Matrix float m00, float m01, float m02, float m10, float m11, float m12 +struct ColorStop Color color, float position +message Image byte[] hash, string name, uint dataBlob +message AssetRef string key, string version +message VariableID GUID guid, AssetRef assetRef +message PropRefValue GUID defId +message AnyValue bool boolValue, float floatValue, VariableID alias, Color colorValue, PropRefValue propRefValue, TextData textDataValue, string textValue, Expression expressionValue +message Expression ExpressionFunction expressionFunction, VariableData[] expressionArguments +message VariableTarget VariableID id +message VariableSetID GUID guid, AssetRef assetRef +message ConditionalActions Action[] actions, VariableData condition +message VectorData uint vectorNetworkBlob, Vector normalizedSize, NodeChange[] styleOverrideTable +message ConnectorEndpoint GUID endpointNodeID, Vector position, Vector relativePosition +message VariableData AnyValue value, DataType dataType +message Paint PaintType type, Color color, float opacity, bool visible, Image image, Matrix transform, ColorStop[] stops, VariableData colorVar, ImageScaleMode imageScaleMode +message ParentIndex GUID guid, string position +message FontName string family, string style, string postscript +message TextData string characters, uint[] characterStyleIDs, NodeChange[] styleOverrideTable +message Path WindingRule windingRule, uint commandsBlob +message GUIDPath GUID[] guids +message SymbolData GUID symbolID, NodeChange[] symbolOverrides +message StyleId GUID guid, AssetRef assetRef +message PropValue bool boolValue, TextData textValue +message PropDef GUID id, string name, PropValue initialValue, PropType type +message PropAssignment GUID defID, PropValue value +message MapEntry VariableData variableData, VariableField variableField +message VariableDataMap MapEntry[] entries +message SetMode GUID id, string name, string sortPosition +message ValuesEntry GUID modeID, VariableData variableData +message Values ValuesEntry[] entries +message ModeEntry VariableID variableSetID, GUID variableModeID +message ModeMap ModeEntry[] entries +message Event InteractionType interactionType +message Action GUID transitionNodeID, TransitionType transitionType, float transitionDuration, EasingType easingType, ConnectionType connectionType, NavigationType navigationType, VariableTarget targetVariable, VariableData targetVariableData, VariableSetID targetVariableSetID, GUID targetVariableModeID, ConditionalActions[] conditionalActions +message Interaction Event event, Action[] actions +message StartingPoint string name, string position +message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern +message Blob byte[] bytes +message Message NodeChange[] nodeChanges, Blob[] blobs +"; + +pub(super) fn schema() -> Schema { + Schema::parse(SCHEMA).unwrap() +} + +pub(super) fn o(fields: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { + Kv::Object(fields) +} +pub(super) fn f(x: f64) -> Kv<'static> { + Kv::Float(x as f32) +} +pub(super) fn u(x: u64) -> Kv<'static> { + Kv::Uint(x) +} +pub(super) fn e(n: &'static str) -> Kv<'static> { + Kv::Enum(n) +} +pub(super) fn s(x: impl Into) -> Kv<'static> { + Kv::Str(x.into()) +} +pub(super) fn g(l: u64) -> Kv<'static> { + o(vec![("sessionID", u(1)), ("localID", u(l))]) +} +pub(super) fn arr(v: Vec>) -> Kv<'static> { + Kv::Array(v) +} +pub(super) fn xy(x: f64, y: f64) -> Kv<'static> { + o(vec![("x", f(x)), ("y", f(y))]) +} +pub(super) fn at(x: f64, y: f64) -> Kv<'static> { + o(vec![("m00", f(1.0)), ("m01", f(0.0)), ("m02", f(x)), ("m10", f(0.0)), ("m11", f(1.0)), ("m12", f(y))]) +} +fn rgb(r: f64, gr: f64, b: f64) -> Kv<'static> { + o(vec![("r", f(r)), ("g", f(gr)), ("b", f(b)), ("a", f(1.0))]) +} +pub(super) fn solid(r: f64, gr: f64, b: f64) -> Kv<'static> { + o(vec![("type", e("SOLID")), ("color", rgb(r, gr, b)), ("opacity", f(1.0)), ("visible", Kv::Bool(true))]) +} +fn root_guid() -> Kv<'static> { + o(vec![("sessionID", u(0)), ("localID", u(0))]) +} +fn alias_data(l: u64) -> Kv<'static> { + o(vec![("value", o(vec![("alias", o(vec![("guid", g(l))]))])), ("dataType", e("ALIAS"))]) +} +fn prop_ref(def: u64, field: &'static str) -> Kv<'static> { + let data = o(vec![("value", o(vec![("propRefValue", o(vec![("defId", g(def))]))])), ("dataType", e("PROP_REF"))]); + o(vec![("entries", arr(vec![o(vec![("variableData", data), ("variableField", e(field))])]))]) +} + +/// A node: id (0: the document), parent (id, position), type, name and further fields. +pub(super) fn node(id: u64, par: Option<(u64, &str)>, ty: &'static str, name: &str, mut more: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { + let mut v = vec![("guid", if id == 0 { root_guid() } else { g(id) })]; + if let Some((p, pos)) = par { + v.push(("parentIndex", o(vec![("guid", if p == 0 { root_guid() } else { g(p) }), ("position", s(pos))]))); + } + v.push(("type", e(ty))); + v.push(("name", s(name))); + v.append(&mut more); + o(v) +} + +/// A path blob: a closed triangle. +fn triangle_blob() -> Vec { + let mut b = Vec::new(); + for (cmd, pts) in [(1u8, vec![0.0f32, 0.0]), (2, vec![10.0, 0.0]), (2, vec![5.0, 8.0]), (0, vec![])] { + b.push(cmd); + for p in pts { + b.extend_from_slice(&p.to_le_bytes()); + } + } + b +} + +/// A 2×1 PNG. +pub(super) fn png() -> Vec { + let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([255, 0, 0, 255])); + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +const HASH: [u8; 20] = [0xab; 20]; + +/// The fixture message: a page with a frame holding a rectangle (image fill, click interaction), +/// a two-style text, a group with a triangle vector and a star, a layer with a linked fill style, +/// one with a variable-bound fill, and an instance of a component with a boolean property +/// (property off, child renamed); a flow and an explicit variable mode; an unsupported sticky +/// note; styles and variables on the internal page. +fn message() -> Kv<'static> { + let modes = arr(vec![ + o(vec![("id", g(90)), ("name", s("Light")), ("sortPosition", s("!"))]), + o(vec![("id", g(91)), ("name", s("Dark")), ("sortPosition", s("\""))]), + ]); + let color_value = |c| o(vec![("value", o(vec![("colorValue", c)])), ("dataType", e("COLOR"))]); + let values = o(vec![( + "entries", + arr(vec![ + o(vec![("modeID", g(90)), ("variableData", color_value(rgb(1.0, 1.0, 1.0)))]), + o(vec![("modeID", g(91)), ("variableData", color_value(rgb(0.0, 0.0, 0.0)))]), + ]), + )]); + let click = o(vec![ + ("event", o(vec![("interactionType", e("ON_CLICK"))])), + ( + "actions", + arr(vec![o(vec![ + ("transitionNodeID", g(20)), + ("transitionType", e("SMART_ANIMATE")), + ("transitionDuration", f(0.25)), + ("easingType", e("OUT_CUBIC")), + ("connectionType", e("INTERNAL_NODE")), + ("navigationType", e("NAVIGATE")), + ])]), + ), + ]); + let font = |style: &str| o(vec![("family", s("Inter")), ("style", s(style)), ("postscript", s(""))]); + let text = o(vec![ + ("characters", s("Hi there")), + ("characterStyleIDs", arr(vec![u(0), u(0), u(0), u(5), u(5), u(5)])), + ("styleOverrideTable", arr(vec![o(vec![("fontName", font("Bold")), ("styleID", u(5))])])), + ]); + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page A", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node(3, Some((2, "!")), "RECTANGLE", "Brand", vec![("styleType", e("FILL")), ("fillPaints", arr(vec![solid(0.0, 0.0, 1.0)]))]), + node(4, Some((2, "\"")), "VARIABLE_SET", "Theme", vec![("variableSetModes", modes)]), + node( + 5, + Some((2, "#")), + "VARIABLE", + "surface", + vec![("variableSetID", o(vec![("guid", g(4))])), ("variableResolvedType", e("COLOR")), ("variableDataValues", values)], + ), + // Listed before the frame, but its position puts it second. + node( + 20, + Some((1, "\"")), + "SYMBOL", + "Button", + vec![ + ("size", xy(100.0, 40.0)), + ("transform", at(500.0, 0.0)), + ("fillPaints", arr(vec![solid(0.0, 1.0, 0.0)])), + ( + "componentPropDefs", + arr(vec![o(vec![ + ("id", g(80)), + ("name", s("Show icon")), + ("initialValue", o(vec![("boolValue", Kv::Bool(true))])), + ("type", e("BOOL")), + ])]), + ), + ("stackMode", e("HORIZONTAL")), + ("stackSpacing", f(8.0)), + ("stackHorizontalPadding", f(12.0)), + ("stackVerticalPadding", f(4.0)), + ], + ), + node( + 21, + Some((20, "!")), + "ELLIPSE", + "Icon", + vec![("size", xy(16.0, 16.0)), ("transform", at(12.0, 12.0)), ("parameterConsumptionMap", prop_ref(80, "VISIBLE"))], + ), + node( + 10, + Some((1, "!")), + "FRAME", + "Screen", + vec![ + ("size", xy(400.0, 300.0)), + ("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)])), + ("prototypeStartingPoint", o(vec![("name", s("Main flow")), ("position", s("!"))])), + ( + "variableModeBySetMap", + o(vec![("entries", arr(vec![o(vec![("variableSetID", o(vec![("guid", g(4))])), ("variableModeID", g(91))])]))]), + ), + ], + ), + node( + 11, + Some((10, "!")), + "ROUNDED_RECTANGLE", + "Photo", + vec![ + ("size", xy(50.0, 40.0)), + ("transform", at(10.0, 20.0)), + ("cornerRadius", f(6.0)), + ("fillPaints", arr(vec![o(vec![("type", e("IMAGE")), ("image", o(vec![("hash", Kv::Bytes(HASH.to_vec()))]))])])), + ("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])), + ("strokeWeight", f(2.0)), + ("prototypeInteractions", arr(vec![click])), + ], + ), + node( + 12, + Some((10, "\"")), + "TEXT", + "Title", + vec![ + ("size", xy(120.0, 20.0)), + ("transform", at(10.0, 80.0)), + ("fillPaints", arr(vec![solid(0.0, 0.0, 0.0)])), + ("fontSize", f(16.0)), + ("fontName", font("Regular")), + ("leadingTrim", e("CAP_HEIGHT")), + ("textData", text), + ], + ), + node(13, Some((10, "#")), "FRAME", "Group", vec![("size", xy(30.0, 30.0)), ("transform", at(100.0, 100.0)), ("resizeToFit", Kv::Bool(true))]), + node( + 14, + Some((13, "!")), + "VECTOR", + "Tri", + vec![ + ("size", xy(10.0, 8.0)), + ("transform", at(5.0, 6.0)), + ("fillPaints", arr(vec![solid(1.0, 0.0, 0.0)])), + ("fillGeometry", arr(vec![o(vec![("windingRule", e("NONZERO")), ("commandsBlob", u(0))])])), + ], + ), + node( + 15, + Some((13, "\"")), + "STAR", + "Star", + vec![("size", xy(20.0, 20.0)), ("transform", at(10.0, 10.0)), ("count", u(6)), ("starInnerScale", f(0.5))], + ), + node( + 16, + Some((10, "$")), + "ROUNDED_RECTANGLE", + "Styled", + vec![ + ("size", xy(10.0, 10.0)), + ("transform", at(0.0, 200.0)), + // A stale copy of the style's paint: the style wins. + ("fillPaints", arr(vec![solid(0.5, 0.5, 0.5)])), + ("styleIdForFill", o(vec![("guid", g(3))])), + ], + ), + node( + 17, + Some((10, "%")), + "ROUNDED_RECTANGLE", + "Card", + vec![ + ("size", xy(10.0, 10.0)), + ("transform", at(20.0, 200.0)), + ("fillPaints", arr(vec![o(vec![("type", e("SOLID")), ("color", rgb(0.0, 0.0, 0.0)), ("colorVar", alias_data(5))])])), + ], + ), + node( + 18, + Some((10, "&")), + "INSTANCE", + "Button copy", + vec![ + ("size", xy(100.0, 40.0)), + ("transform", at(200.0, 200.0)), + ("fillPaints", arr(vec![solid(1.0, 0.0, 0.0)])), + ("stackMode", e("HORIZONTAL")), + ( + "symbolData", + o(vec![ + ("symbolID", g(20)), + ("symbolOverrides", arr(vec![o(vec![("guidPath", o(vec![("guids", arr(vec![g(21)]))])), ("name", s("Renamed icon"))])])), + ]), + ), + ("componentPropAssignments", arr(vec![o(vec![("defID", g(80)), ("value", o(vec![("boolValue", Kv::Bool(false))]))])])), + ], + ), + node(19, Some((10, "'")), "STICKY", "Note", vec![]), + ]; + o(vec![("nodeChanges", arr(nodes)), ("blobs", arr(vec![o(vec![("bytes", Kv::Bytes(triangle_blob()))])]))]) +} + +/// `canvas.fig`: magic, version, deflated schema, zstd message. +pub(super) fn canvas(schema: &Schema, msg: &Kv) -> Vec { + let root = schema.find("Message").unwrap(); + let mut z = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); + z.write_all(&encode::schema(schema)).unwrap(); + let schema_chunk = z.finish().unwrap(); + let msg_chunk = ruzstd::encoding::compress_to_vec(&encode::message(schema, root, msg).unwrap()[..], ruzstd::encoding::CompressionLevel::Fastest); + let mut out = b"fig-kiwi".to_vec(); + out.extend_from_slice(&101u32.to_le_bytes()); + for c in [schema_chunk, msg_chunk] { + out.extend_from_slice(&(c.len() as u32).to_le_bytes()); + out.extend_from_slice(&c); + } + out +} + +fn zip_file(canvas: &[u8]) -> Vec { + let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + let image_name = format!("images/{}", HASH.iter().map(|b| format!("{b:02x}")).collect::()); + for (name, bytes) in [("canvas.fig", canvas.to_vec()), ("meta.json", br#"{"file_name":"Fixture"}"#.to_vec()), (image_name.as_str(), png())] { + z.start_file(name, stored).unwrap(); + z.write_all(&bytes).unwrap(); + } + z.finish().unwrap().into_inner() +} + +fn fixture() -> Vec { + zip_file(&canvas(&schema(), &message())) +} + +fn named<'d>(doc: &'d figcraft_doc::Document, name: &str) -> &'d figcraft_doc::Node { + doc.nodes().find(|n| n.name == name).unwrap_or_else(|| panic!("no layer {name}")) +} + +/// The shared schema plus the grid sizing definitions only these tests use. +fn grid_schema() -> Schema { + const NODE_FIELDS: &str = ", GridTrackMap gridColumns, GridTrackMap gridRows, GridTrackSizeMap gridColumnsSizing, GridTrackSizeMap gridRowsSizing, GUID gridColumnAnchor, GUID gridRowAnchor, uint gridColumnSpan, uint gridRowSpan, float gridColumnGap, float gridRowGap"; + const TYPES: &str = " +enum GridTrackSizingType FLEX FIXED HUG UNKNOWN +message GridTrackSizeFunction GridTrackSizingType type, float value +message GridTrackSize GridTrackSizeFunction minSizing, GridTrackSizeFunction maxSizing +message GridTrackSizeEntry GUID id, GridTrackSize trackSize +message GridTrackSizeMap GridTrackSizeEntry[] entries +message GridTrackEntry GUID id, string position +message GridTrackMap GridTrackEntry[] entries +message Blob "; + let text = SCHEMA.replace("enum StackMode NONE HORIZONTAL VERTICAL\n", "enum StackMode NONE HORIZONTAL VERTICAL GRID\n").replacen( + "\nmessage Blob ", + &format!("{NODE_FIELDS}{TYPES}"), + 1, + ); + Schema::parse(&text).unwrap() +} + +fn track_size(kind: &'static str, value: f64) -> Kv<'static> { + let sizing = || o(vec![("type", e(kind)), ("value", f(value))]); + o(vec![("minSizing", sizing()), ("maxSizing", sizing())]) +} + +fn ranged_track_size(min: Kv<'static>, max: Kv<'static>) -> Kv<'static> { + o(vec![("minSizing", min), ("maxSizing", max)]) +} + +fn track_map_entry(id: u64, size: Kv<'static>) -> Kv<'static> { + o(vec![("id", g(id)), ("trackSize", size)]) +} + +fn positioned_track(id: u64, position: &'static str) -> Kv<'static> { + o(vec![("id", g(id)), ("position", s(position))]) +} + +fn unpositioned_track(id: u64) -> Kv<'static> { + o(vec![("id", g(id))]) +} + +#[test] +fn grid_tracks_import_by_guid_and_keep_track_order() { + let cols = arr(vec![positioned_track(13, "$"), unpositioned_track(10), positioned_track(12, "#"), unpositioned_track(11)]); + let rows = arr(vec![positioned_track(21, "\""), positioned_track(20, "!")]); + // Sizing entries intentionally differ from track order. Their GUIDs define the join. + let col_sizes = arr(vec![ + track_map_entry(12, track_size("FLEX", 1.0)), + track_map_entry(10, track_size("FIXED", 120.0)), + track_map_entry(13, track_size("FLEX", 2.0)), + track_map_entry(11, track_size("HUG", 80.0)), + ]); + let row_sizes = arr(vec![track_map_entry(21, track_size("HUG", 30.0)), track_map_entry(20, track_size("FIXED", 50.0))]); + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node( + 2, + Some((1, "!")), + "FRAME", + "Grid", + vec![ + ("size", xy(600.0, 300.0)), + ("transform", at(0.0, 0.0)), + ("stackMode", e("GRID")), + ("gridColumns", o(vec![("entries", cols)])), + ("gridRows", o(vec![("entries", rows)])), + ("gridColumnsSizing", o(vec![("entries", col_sizes)])), + ("gridRowsSizing", o(vec![("entries", row_sizes)])), + ("gridColumnGap", f(10.0)), + ("gridRowGap", f(12.0)), + ], + ), + node( + 3, + Some((2, "!")), + "RECTANGLE", + "Hug child", + vec![ + ("size", xy(80.0, 30.0)), + ("transform", at(0.0, 0.0)), + ("gridColumnAnchor", g(11)), + ("gridRowAnchor", g(21)), + ("gridColumnSpan", u(2)), + ("gridRowSpan", u(1)), + ], + ), + ]; + let bytes = canvas(&grid_schema(), &o(vec![("nodeChanges", arr(nodes))])); + let (doc, warnings) = import(&bytes, "Grid tracks").unwrap(); + let grid = named(&doc, "Grid").layout.as_ref().unwrap(); + assert_eq!((grid.mode, grid.grid_columns, grid.grid_rows, grid.gap, grid.cross_gap), (figcraft_doc::LayoutMode::Grid, 4, 2, 10.0, 12.0)); + assert_eq!( + grid.column_tracks, + vec![ + figcraft_doc::GridTrack::fixed(120.0), + figcraft_doc::GridTrack::hug(), + figcraft_doc::GridTrack::fill(1.0), + figcraft_doc::GridTrack::fill(2.0), + ] + ); + assert_eq!(grid.row_tracks, vec![figcraft_doc::GridTrack::fixed(50.0), figcraft_doc::GridTrack::hug()]); + let child = &named(&doc, "Hug child").child_layout; + assert_eq!((child.grid_column, child.grid_row, child.grid_column_span, child.grid_row_span), (Some(1), Some(1), 2, 1)); + assert!(!warnings.iter().any(|w| w.contains("grid track")), "{warnings:?}"); +} + +#[test] +fn malformed_grid_tracks_warn_and_keep_equal_track_fallbacks() { + let tracks = arr(vec![positioned_track(30, "!"), positioned_track(31, "\""), positioned_track(32, "#"), positioned_track(33, "$")]); + let sizing = arr(vec![ + track_map_entry(30, track_size("FIXED", -1.0)), + track_map_entry(31, ranged_track_size(o(vec![("type", e("FLEX")), ("value", f(1.0))]), o(vec![("type", e("FLEX")), ("value", f(2.0))]))), + track_map_entry(33, track_size("UNKNOWN", 5.0)), + track_map_entry(34, track_size("FLEX", 3.0)), + ]); + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node( + 2, + Some((1, "!")), + "FRAME", + "Grid", + vec![ + ("size", xy(100.0, 100.0)), + ("transform", at(0.0, 0.0)), + ("stackMode", e("GRID")), + ("gridColumns", o(vec![("entries", tracks)])), + ("gridColumnsSizing", o(vec![("entries", sizing)])), + ], + ), + ]; + let bytes = canvas(&grid_schema(), &o(vec![("nodeChanges", arr(nodes))])); + let (doc, warnings) = import(&bytes, "Malformed grid tracks").unwrap(); + let layout = named(&doc, "Grid").layout.as_ref().unwrap(); + assert_eq!(layout.column_tracks, vec![figcraft_doc::GridTrack::default(); 4]); + assert!(warnings.iter().any(|w| w.contains("grid track sizing is unsupported or malformed")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("stale or invalid grid track sizing entries")), "{warnings:?}"); +} + +#[test] +fn oversized_grid_track_lists_warn_and_use_default_tracks() { + let oversized: Vec> = (0..1_001).map(|i| unpositioned_track(100 + i)).collect(); + let sizing = vec![track_map_entry(100, track_size("FIXED", 40.0))]; + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node( + 2, + Some((1, "!")), + "FRAME", + "Grid", + vec![ + ("size", xy(100.0, 100.0)), + ("transform", at(0.0, 0.0)), + ("stackMode", e("GRID")), + ("gridColumns", o(vec![("entries", arr(oversized))])), + ("gridColumnsSizing", o(vec![("entries", arr(sizing))])), + ], + ), + ]; + let bytes = canvas(&grid_schema(), &o(vec![("nodeChanges", arr(nodes))])); + let (doc, warnings) = import(&bytes, "Oversized grid tracks").unwrap(); + let layout = named(&doc, "Grid").layout.as_ref().unwrap(); + assert!(layout.column_tracks.is_empty(), "{:?}", layout.column_tracks.len()); + assert!(warnings.iter().any(|w| w.contains("grid track list exceeds 1000 entries")), "{warnings:?}"); +} + +#[test] +fn kiwi_round_trip() { + let sc = schema(); + let back = Schema::decode(&encode::schema(&sc)).unwrap(); + assert_eq!(back.defs.len(), sc.defs.len()); + for (a, b) in sc.defs.iter().zip(&back.defs) { + assert_eq!((a.name.as_str(), a.kind), (b.name.as_str(), b.kind)); + let fields = |d: &Def| d.fields.iter().map(|f| (f.name.clone(), f.ty, f.array, f.value)).collect::>(); + assert_eq!(fields(a), fields(b)); + } + let msg = message(); + let root = sc.find("Message").unwrap(); + assert_eq!(back.decode_message(root, &encode::message(&sc, root, &msg).unwrap()).unwrap(), msg); +} + +#[test] +fn kiwi_scalars() { + let names = ["f", "i", "u", "i64", "u64", "s", "b"]; + let types = [Type::Float, Type::Int, Type::Uint, Type::Int64, Type::Uint64, Type::Str, Type::Bool]; + let fields = names + .iter() + .zip(types) + .enumerate() + .map(|(i, (n, t))| Field { name: n.to_string(), ty: Some(t), array: false, value: i as u32 + 1 }) + .collect(); + let sc = Schema { defs: vec![Def { name: "M".into(), kind: Kind::Message, fields }] }; + let cases = [ + (0.0f32, 0i32, 0u32, 0i64, 0u64), + (-1.5, -7, 300, i64::MIN, u64::MAX), + (3.25e7, i32::MAX, u32::MAX, i64::MAX, 1 << 60), + (1e-40, i32::MIN, 1, -1, 127), + ]; + for (fv, iv, uv, i64v, u64v) in cases { + // Written by hand: the generic encoder goes through f64, which can't hold every 64-bit value. + let mut w = encode::Writer::default(); + w.var_uint(1); + w.var_float(fv); + w.var_uint(2); + w.var_int(iv); + w.var_uint(3); + w.var_uint(uv); + w.var_uint(4); + w.var_int64(i64v); + w.var_uint(5); + w.var_uint64(u64v); + w.var_uint(6); + w.string("héllo"); + w.var_uint(7); + w.byte(1); + w.var_uint(0); + let got = sc.decode_message(0, &w.0).unwrap(); + // Denormals are stored as zero. + let want_f = if fv.abs() < f32::MIN_POSITIVE { 0.0 } else { fv }; + assert_eq!(got.get("f"), Some(&Kv::Float(want_f))); + assert_eq!(got.get("i"), Some(&Kv::Int(i64::from(iv)))); + assert_eq!(got.get("u"), Some(&Kv::Uint(u64::from(uv)))); + assert_eq!(got.get("i64"), Some(&Kv::Int(i64v))); + assert_eq!(got.get("u64"), Some(&Kv::Uint(u64v))); + assert_eq!(got.get("s"), Some(&s("héllo"))); + assert_eq!(got.get("b"), Some(&Kv::Bool(true))); + } +} + +#[test] +fn imports_the_fixture() { + let bytes = fixture(); + assert!(is_fig(&bytes)); + let (doc, warnings) = import(&bytes, "fallback").unwrap(); + assert_eq!(doc.name, "Fixture"); + assert_fixture_layers(&doc); + assert_fixture_styles(&doc); + assert_fixture_variables(&doc); + assert_fixture_components(&doc); + assert_fixture_prototype(&doc, &warnings); +} + +fn assert_fixture_layers(doc: &Document) { + // The internal page is skipped. + assert_eq!(doc.pages.len(), 1); + let page = doc.node(doc.pages[0]).unwrap(); + assert_eq!(page.name, "Page A"); + // Siblings by position: the frame comes first even though it's listed after the component. + assert_eq!(doc.node(page.children[0]).unwrap().name, "Screen"); + let screen = named(doc, "Screen"); + let names: Vec<&str> = screen.children.iter().map(|c| doc.node(*c).unwrap().name.as_str()).collect(); + assert_eq!(names, ["Photo", "Title", "Group", "Styled", "Card", "Button copy", "Note"]); + // Image fill from the archive. + let photo = named(doc, "Photo"); + let figcraft_doc::color::PaintKind::Image(img) = &photo.fills[0].kind else { panic!("not an image fill") }; + assert_eq!(doc.images.get(&img.image).map(|i| (i.width, i.height)), Some((2, 1))); + assert_eq!((photo.corners.radii[0], photo.stroke.weight), (6.0, 2.0)); + // Text with a bold run over "the". + let NodeKind::Text(t) = &named(doc, "Title").kind else { panic!("not text") }; + assert_eq!(t.characters, "Hi there"); + assert_eq!(t.style.font_size, 16.0); + assert_eq!(t.leading_trim, figcraft_doc::LeadingTrim::CapHeight, "vertical trim (#466)"); + assert_eq!(t.runs.len(), 1); + assert_eq!((t.runs[0].start, t.runs[0].end, t.runs[0].style.font_style.as_str()), (3, 6, "Bold")); + // The group's children keep their place on the page (group at 100, 100). + assert!(matches!(named(doc, "Group").kind, NodeKind::Group)); + let tri = named(doc, "Tri"); + assert!(matches!(&tri.kind, NodeKind::Vector { network } if !network.regions.is_empty())); + let abs = doc.world_transform(tri.id).translation(); + assert!((abs.x - 105.0).abs() < 1e-6 && (abs.y - 106.0).abs() < 1e-6, "{abs:?}"); + assert!(matches!(named(doc, "Star").kind, NodeKind::Star { count: 6, .. })); +} + +fn assert_fixture_styles(doc: &Document) { + let styled = named(doc, "Styled"); + assert_eq!(styled.styles.fill.as_deref(), Some("1:3")); + assert!(doc.styles.iter().any(|s| s.name == "Brand")); + let figcraft_doc::color::PaintKind::Solid { color } = styled.fills[0].kind else { panic!("not solid") }; + assert_eq!((color.r, color.g, color.b), (0.0, 0.0, 1.0)); +} + +fn assert_fixture_variables(doc: &Document) { + let screen = named(doc, "Screen"); + assert_eq!(doc.variables.collections.len(), 1); + assert_eq!(doc.variables.variables[0].kind, VariableType::Color); + assert_eq!(named(doc, "Card").bound.get("fill").map(String::as_str), Some("1:5")); + assert_eq!(screen.var_modes.get("1:4").map(String::as_str), Some("1:91")); +} + +fn assert_fixture_components(doc: &Document) { + let button = named(doc, "Button"); + assert!(matches!(&button.kind, NodeKind::Component { props, .. } if props.contains_key("Show icon"))); + let inst = named(doc, "Button copy"); + assert!( + matches!(&inst.kind, NodeKind::Instance { component, props } if *component == button.id && props.get("Show icon") == Some(&Value::Bool(false))) + ); + let icon = doc.node(inst.children[0]).unwrap(); + assert_eq!(icon.name, "Renamed icon"); + assert!(!icon.visible); +} + +fn assert_fixture_prototype(doc: &Document, warnings: &[String]) { + let button = named(doc, "Button"); + let screen = named(doc, "Screen"); + let it = &named(doc, "Photo").interactions[0]; + assert!(matches!(it.actions[0], figcraft_doc::proto::Action::Navigate { dest, .. } if dest == button.id)); + assert_eq!(it.duration_ms, 250); + let Some(NodeKind::Page { flows, .. }) = doc.node(doc.pages[0]).map(|p| &p.kind) else { panic!("no page") }; + assert_eq!((flows[0].name.as_str(), flows[0].start), ("Main flow", screen.id)); + // The sticky note comes in as a frame, with a warning. + assert!(matches!(named(doc, "Note").kind, NodeKind::Frame)); + assert!(warnings.iter().any(|w| w.contains("sticky layers import as frames")), "{warnings:?}"); +} + +#[test] +fn bare_canvas_and_zlib_chunks_open() { + let sc = schema(); + let c = canvas(&sc, &message()); + let (doc, w) = import(&c, "Bare").unwrap(); + assert_eq!(doc.name, "Bare"); + // Without the archive the image is a placeholder, reported. + assert!(w.iter().any(|w| w.contains("isn't in the file")), "{w:?}"); + // A zlib-wrapped schema chunk reads too. + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + z.write_all(&encode::schema(&sc)).unwrap(); + let zl = z.finish().unwrap(); + let parts = chunks(&c).unwrap(); + let mut out = c[..12].to_vec(); + for ch in [zl.as_slice(), parts[1]] { + out.extend_from_slice(&(ch.len() as u32).to_le_bytes()); + out.extend_from_slice(ch); + } + assert!(import(&out, "Z").is_ok()); +} + +/// The fixture message with the photo's image bytes in its own blobs, as copies written by plugins +/// and tools carry them: the PNG goes at the end of `blobs` and `image.dataBlob` points `shift` +/// places past it (0 is the PNG itself). +fn message_with_image_in_blobs(shift: u64) -> Kv<'static> { + fn point_images_at(value: &mut Kv<'static>, blob: u64) { + match value { + Kv::Object(fields) => { + for (name, field) in fields.iter_mut() { + match field { + Kv::Object(image) if *name == "image" => image.push(("dataBlob", u(blob))), + _ => point_images_at(field, blob), + } + } + } + Kv::Array(items) => items.iter_mut().for_each(|item| point_images_at(item, blob)), + _ => {} + } + } + let mut msg = message(); + let index = { + let Kv::Object(fields) = &mut msg else { panic!("the message is an object") }; + let Some((_, Kv::Array(blobs))) = fields.iter_mut().find(|(name, _)| *name == "blobs") else { panic!("no blobs") }; + blobs.push(o(vec![("bytes", Kv::Bytes(png()))])); + blobs.len() as u64 - 1 + }; + point_images_at(&mut msg, index + shift); + msg +} + +#[test] +fn a_bare_canvas_reads_images_carried_in_its_blobs() { + // The clipboard holds a bare canvas (no `images/`); the image comes from `image.dataBlob`. + let c = canvas(&schema(), &message_with_image_in_blobs(0)); + let (doc, warnings) = import(&c, "Pasted").unwrap(); + let photo = named(&doc, "Photo"); + let figcraft_doc::color::PaintKind::Image(img) = &photo.fills[0].kind else { panic!("not an image fill") }; + assert_eq!(doc.images.get(&img.image).map(|i| (i.width, i.height)), Some((2, 1))); + assert!(!warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); +} + +#[test] +fn a_data_blob_past_the_blobs_stays_a_placeholder() { + let c = canvas(&schema(), &message_with_image_in_blobs(5)); + let (_, warnings) = import(&c, "Pasted").unwrap(); + assert!(warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); +} + +/// A file can point any number of image hashes at one large blob; each used to get its own copy +/// of it (#1059). +#[test] +fn hashes_naming_one_blob_share_one_copy_of_it() { + let image = |hash: u8, blob: u64| o(vec![("image", o(vec![("hash", Kv::Bytes(vec![hash; 20])), ("dataBlob", u(blob))]))]); + let msg = o(vec![ + ("blobs", Kv::Array(vec![o(vec![("bytes", Kv::Bytes(png()))]), o(vec![("bytes", Kv::Bytes(vec![7; 16]))])])), + ("nodeChanges", Kv::Array((1..=50).map(|h| image(h, 0)).chain([image(99, 1), image(98, 2)]).collect())), + ]); + let copies = embedded_copies(&msg); + assert_eq!(copies.len(), 51, "the hash naming no blob is left out"); + let first = &copies[&"01".repeat(20)]; + assert_eq!(**first, *png()); + assert_eq!(copies.values().filter(|c| Arc::ptr_eq(c, first)).count(), 50); + assert_eq!(*copies[&"63".repeat(20)], [7; 16]); +} + +mod image_budget { + use super::*; + + fn image(hash: u8) -> Vec { + let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([hash, 0, 0, 255])); + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + fn file(references: &[u8], members: &[(u8, Vec)]) -> Vec { + let mut nodes = vec![node(0, None, "DOCUMENT", "Document", vec![]), node(1, Some((0, "!")), "CANVAS", "Page", vec![])]; + for (i, hash) in references.iter().enumerate() { + nodes.push(node( + i as u64 + 2, + Some((1, &format!("{i:04}"))), + "RECTANGLE", + &format!("Image {i}"), + vec![ + ("size", xy(10.0, 10.0)), + ("fillPaints", arr(vec![o(vec![("type", e("IMAGE")), ("image", o(vec![("hash", Kv::Bytes(vec![*hash; 20]))]))])])), + ], + )); + } + let canvas = canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])); + let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let deflated = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + z.start_file("canvas.fig", deflated).unwrap(); + z.write_all(&canvas).unwrap(); + for (hash, bytes) in members { + z.start_file(format!("images/{}", format!("{hash:02x}").repeat(20)), deflated).unwrap(); + z.write_all(bytes).unwrap(); + } + z.finish().unwrap().into_inner() + } + + fn bytes(doc: &Document, index: usize) -> &[u8] { + let node = named(doc, &format!("Image {index}")); + let figcraft_doc::color::PaintKind::Image(fill) = &node.fills[0].kind else { panic!("not an image fill") }; + &doc.images[&fill.image].bytes + } + + fn budget_warnings(warnings: &[String]) -> Vec<&str> { + warnings.iter().filter(|w| w.contains("total ZIP image byte budget")).map(String::as_str).collect() + } + + fn change_member_field(zip: &mut [u8], hash: u8, offset: usize, value: u32) { + let start = { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(&*zip)).unwrap(); + z.by_name(&format!("images/{}", format!("{hash:02x}").repeat(20))).unwrap().central_header_start() as usize + }; + zip[start + offset..start + offset + 4].copy_from_slice(&value.to_le_bytes()); + } + + #[test] + fn exact_total_limit_keeps_all_images_and_each_import_gets_its_own_budget() { + let members = [(1, image(1)), (2, image(2))]; + let limit = members.iter().map(|(_, b)| b.len() as u64).sum(); + let zip = file(&[1, 2], &members); + for _ in 0..2 { + let (doc, warnings) = import_with_image_limit(&zip, "Images", limit).unwrap(); + assert_eq!(bytes(&doc, 0), members[0].1); + assert_eq!(bytes(&doc, 1), members[1].1); + assert!(warnings.is_empty(), "{warnings:?}"); + } + } + + #[test] + fn individually_acceptable_images_overflow_the_total_and_leave_placeholders() { + let members = [(1, image(1)), (2, image(2))]; + let limit = members.iter().map(|(_, b)| b.len() as u64).sum::() - 1; + assert!(members.iter().all(|(_, b)| b.len() as u64 <= limit)); + let (doc, warnings) = import_with_image_limit(&file(&[1, 2], &members), "Images", limit).unwrap(); + assert_eq!(bytes(&doc, 0), members[0].1); + assert_ne!(bytes(&doc, 1), members[1].1); + assert!(!doc.images.contains_key(&crate::image_hash(&members[1].1))); + let notes = budget_warnings(&warnings); + assert_eq!(notes.len(), 1, "{warnings:?}"); + assert!(notes[0].contains("1 ZIP image") && notes[0].contains(&limit.to_string()), "{warnings:?}"); + } + + #[test] + fn repeated_references_do_not_charge_or_count_a_rejection_twice() { + let members = [(1, image(1)), (2, image(2))]; + let (doc, warnings) = import_with_image_limit(&file(&[1, 1, 2, 2, 1], &members), "Images", members[0].1.len() as u64).unwrap(); + for i in [0, 1, 4] { + assert_eq!(bytes(&doc, i), members[0].1); + } + assert_eq!(bytes(&doc, 2), bytes(&doc, 3)); + assert_ne!(bytes(&doc, 2), members[1].1); + let notes = budget_warnings(&warnings); + assert_eq!(notes.len(), 1, "{warnings:?}"); + assert!(notes[0].contains("1 ZIP image"), "{warnings:?}"); + } + + #[test] + fn distinct_members_with_identical_contents_still_use_the_read_budget() { + let png = image(1); + let members = [(1, png.clone()), (2, png.clone())]; + let (doc, warnings) = import_with_image_limit(&file(&[1, 2], &members), "Images", png.len() as u64).unwrap(); + assert_eq!(bytes(&doc, 0), png); + assert_ne!(bytes(&doc, 1), png); + assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); + } + + #[test] + fn rejecting_a_member_before_reading_leaves_room_for_a_smaller_one() { + let png = image(1); + let members = [(1, vec![0; png.len() + 1]), (2, png.clone())]; + let (doc, warnings) = import_with_image_limit(&file(&[1, 2], &members), "Images", png.len() as u64).unwrap(); + assert_ne!(bytes(&doc, 0), members[0].1); + assert_eq!(bytes(&doc, 1), png); + assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); + } + + #[test] + fn failed_crc_reads_still_consume_the_bytes_read() { + let members = [(1, image(1)), (2, image(2))]; + let mut zip = file(&[1, 2], &members); + change_member_field(&mut zip, 1, 16, 0); + let (doc, warnings) = import_with_image_limit(&zip, "Images", members[0].1.len() as u64 + 1).unwrap(); + assert_ne!(bytes(&doc, 0), members[0].1); + assert_ne!(bytes(&doc, 1), members[1].1); + assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); + } + + #[test] + fn a_truncated_deflate_read_keeps_its_partial_charge() { + let members = [(1, image(1)), (2, image(2))]; + let mut zip = file(&[1, 2], &members); + // Shorten the first member's compressed size, cutting its deflate stream mid-image. + change_member_field(&mut zip, 1, 20, 15); + let limit = members[0].1.len() as u64; + let archive = Archive::open(&zip).unwrap(); + archive.image_budget.remaining.set(limit); + assert!(archive.image(&"01".repeat(20)).is_none()); + let remaining = archive.image_budget.remaining.get(); + assert!(remaining > 0 && remaining < limit, "partial read left {remaining} of {limit} bytes"); + assert!(archive.image(&"02".repeat(20)).is_none()); + assert_eq!(archive.image_budget.remaining.get(), remaining); + let (doc, warnings) = import_with_image_limit(&zip, "Images", limit).unwrap(); + assert_ne!(bytes(&doc, 1), members[1].1); + assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); + } + + #[test] + fn the_individual_image_cap_is_preserved_without_reading_a_large_member() { + let members = [(1, image(1)), (2, image(2))]; + let mut zip = file(&[1, 2], &members); + change_member_field(&mut zip, 1, 24, (MAX_IMAGE + 1) as u32); + let (doc, warnings) = import_with_image_limit(&zip, "Images", members[1].1.len() as u64).unwrap(); + assert_ne!(bytes(&doc, 0), members[0].1); + assert_eq!(bytes(&doc, 1), members[1].1); + assert!(budget_warnings(&warnings).is_empty(), "{warnings:?}"); + } + + #[test] + fn crc_is_checked_even_when_the_read_ends_exactly_at_the_budget() { + let members = [(1, image(1))]; + let mut zip = file(&[1], &members); + change_member_field(&mut zip, 1, 16, 0); + let (doc, warnings) = import_with_image_limit(&zip, "Images", members[0].1.len() as u64).unwrap(); + assert_ne!(bytes(&doc, 0), members[0].1); + assert!(warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); + assert!(budget_warnings(&warnings).is_empty(), "{warnings:?}"); + } + + #[test] + fn an_understated_size_cannot_read_past_the_remaining_budget() { + let members = [(1, image(1)), (2, image(2))]; + let mut zip = file(&[1, 2], &members); + change_member_field(&mut zip, 1, 24, 1); + let archive = Archive::open(&zip).unwrap(); + archive.image_budget.remaining.set(members[0].1.len() as u64 - 1); + assert!(archive.image(&"01".repeat(20)).is_none()); + assert_eq!(archive.image_budget.remaining.get(), 0); + assert_eq!(archive.image_budget.skipped.get(), 1); + assert!(archive.image(&"02".repeat(20)).is_none()); + assert_eq!(archive.image_budget.remaining.get(), 0); + assert_eq!(archive.image_budget.skipped.get(), 2); + } + + #[test] + fn invalid_image_contents_are_charged_before_image_validation() { + let members = [(1, vec![0; 8]), (2, image(2))]; + let limit = members[1].1.len() as u64 + 7; + let (doc, warnings) = import_with_image_limit(&file(&[1, 2], &members), "Images", limit).unwrap(); + assert_ne!(bytes(&doc, 1), members[1].1); + assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); + } + + #[test] + fn missing_and_unreferenced_members_do_not_consume_the_budget() { + let members = [(1, image(1)), (2, vec![0; 128])]; + let (doc, warnings) = import_with_image_limit(&file(&[9, 1], &members), "Images", members[0].1.len() as u64).unwrap(); + assert_eq!(bytes(&doc, 1), members[0].1); + assert!(warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); + assert!(budget_warnings(&warnings).is_empty(), "{warnings:?}"); + } + + #[test] + fn embedded_image_fallback_is_independent_of_the_zip_budget() { + let canvas = canvas(&schema(), &message_with_image_in_blobs(0)); + for bytes in [&canvas, &zip_file(&canvas)] { + let (doc, warnings) = import_with_image_limit(bytes, "Images", 0).unwrap(); + let photo = named(&doc, "Photo"); + let figcraft_doc::color::PaintKind::Image(fill) = &photo.fills[0].kind else { panic!("not an image fill") }; + assert_eq!(*doc.images[&fill.image].bytes, png()); + assert!(!warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); + assert_eq!(budget_warnings(&warnings).len(), usize::from(bytes.starts_with(b"PK")), "{warnings:?}"); + } + } + + #[test] + fn default_import_preserves_image_bytes_dimensions_and_existing_warnings() { + let members = [(1, image(1)), (2, image(2))]; + let (doc, warnings) = import(&file(&[1, 2], &members), "Images").unwrap(); + assert_eq!(bytes(&doc, 0), members[0].1); + assert_eq!(bytes(&doc, 1), members[1].1); + assert!(doc.images.values().all(|img| (img.width, img.height) == (2, 1))); + assert!(warnings.is_empty(), "{warnings:?}"); + let (doc, warnings) = import(&fixture(), "Fixture").unwrap(); + assert!(doc.images.values().any(|img| *img.bytes == png() && (img.width, img.height) == (2, 1))); + assert!(budget_warnings(&warnings).is_empty(), "{warnings:?}"); + } +} + +#[test] +fn other_files_are_not_fig() { + assert!(try_import(b"{\"document\": {}}", "x").is_none()); + assert!(try_import(b"", "x").is_none()); + let native = crate::save_bytes(&figcraft_doc::Document::new("N"), None).unwrap(); + assert!(try_import(&native, "x").is_none()); +} + +/// A cheap deterministic generator (mangled inputs, generated fixtures). +pub(super) struct Lcg(pub(super) u64); +impl Lcg { + pub(super) fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + self.0 >> 33 + } +} + +#[test] +fn mangled_files_never_panic() { + let bytes = fixture(); + let c = canvas(&schema(), &message()); + let mut r = Lcg(7); + for src in [&bytes, &c] { + for cut in (0..src.len()).step_by(37) { + let _ = import(&src[..cut], "x"); + } + for _ in 0..300 { + let mut m = src.clone(); + for _ in 0..1 + r.next() % 8 { + let i = (r.next() as usize) % m.len(); + m[i] ^= 1 << (r.next() % 8); + } + let _ = import(&m, "x"); + } + } +} + +#[test] +fn mangled_kiwi_never_panics() { + let sc = schema(); + let root = sc.find("Message").unwrap(); + let schema_bytes = encode::schema(&sc); + let msg = encode::message(&sc, root, &message()).unwrap(); + let mut r = Lcg(11); + for cut in 0..schema_bytes.len() { + let _ = Schema::decode(&schema_bytes[..cut]); + } + for cut in (0..msg.len()).step_by(3) { + if let Ok(kv) = sc.decode_message(root, &msg[..cut]) { + let _ = map::to_rest(&kv, "x", crate::rest::MAX_NODES); + } + } + for _ in 0..2000 { + let mut m = msg.clone(); + for _ in 0..1 + r.next() % 4 { + let i = (r.next() as usize) % m.len(); + m[i] = r.next() as u8; + } + if let Ok(kv) = sc.decode_message(root, &m) { + let (json, _, networks) = map::to_rest(&kv, "x", crate::rest::MAX_NODES); + let _ = crate::rest::import_with_networks(&json, &crate::rest::no_images, networks, crate::rest::MAX_NODES); + } + let mut sbytes = schema_bytes.clone(); + let i = (r.next() as usize) % sbytes.len(); + sbytes[i] = r.next() as u8; + if let Ok(s2) = Schema::decode(&sbytes) + && let Some(rt) = s2.find("Message") + { + let _ = s2.decode_message(rt, &msg); + } + } + // Pure junk, bare and framed. + for _ in 0..500 { + let junk: Vec = (0..(r.next() % 200)).map(|_| r.next() as u8).collect(); + let _ = Schema::decode(&junk); + let _ = sc.decode_message(root, &junk); + let mut framed = b"fig-kiwi\0\0\0\0".to_vec(); + framed.extend_from_slice(&junk); + let _ = import(&framed, "x"); + } +} + +#[test] +fn large_files_get_a_larger_value_budget() { + // Small files keep the fixed floor: a few bytes can't expand into a huge tree. + assert_eq!(kiwi::value_budget(0), 20_000_000); + assert_eq!(kiwi::value_budget(1 << 20), 20_000_000); + // A real 400 000-layer file: an 83.5 MB canvas whose message unpacks to 334 MB and holds + // 30.5 million values was refused as "too many values". + assert!(kiwi::value_budget(83_491_232) > 30_514_899); + // A real 194 MB design-system file (UX4G): a 39.5 MB canvas holding 29.7 million values. + assert!(kiwi::value_budget(39_528_420) > 29_703_730); + // Still bounded by the largest canvas read. + assert!(kiwi::value_budget(MAX_CANVAS as usize) <= 128 << 20); + // Counting every scalar field, a dense file may reach about 2.4 values per compressed byte (the + // 15 MB text-heavy fixture in `value_budget_tests` measures 1.8): below the ceiling the budget must + // cover that, the floor still holds up to 5 MB of canvas, and 32 MiB is enough for the ceiling. + assert!(kiwi::value_budget(8 << 20) >= (8 << 20) * 12 / 5); + #[cfg(not(target_pointer_width = "32"))] + assert!(kiwi::value_budget(30_000_000) >= 30_000_000 * 12 / 5); + assert_eq!(kiwi::value_budget(5_000_000), 20_000_000); + assert_eq!(kiwi::value_budget(32 << 20), kiwi::value_budget(MAX_CANVAS as usize)); +} + +#[test] +fn the_layer_cap_follows_the_file_size() { + // A small (or broken) file keeps the REST import's cap: instances expand into a layer per + // layer of their component, and a few bytes mustn't claim millions of layers. + assert_eq!(layer_budget(0), crate::rest::MAX_NODES); + assert_eq!(layer_budget(1 << 20), crate::rest::MAX_NODES); + // A real 894 004-layer file (an 83.5 MB canvas) stopped at 200 000 and came in with 27 of + // its 30 pages empty. + assert!(layer_budget(83_491_232) > 894_004); + // No file gets more than the ceiling. + assert_eq!(layer_budget(MAX_CANVAS as usize), MAX_FIG_NODES); +} + +#[test] +fn a_small_file_that_unpacks_large_gets_no_larger_budgets() { + // 40 MB of zeros in a blob pack into a few KB. Keyed to the unpacked message, they lifted the + // layer cap above the 231 231 layers its instances expand into; keyed to the file, the cap + // stays at the REST import's. + let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])]; + nodes.push(node(5, Some((1, "!")), "SYMBOL", "Main", vec![("size", xy(10.0, 10.0))])); + nodes.extend((10..1010).map(|i| node(i, Some((5, "!")), "RECTANGLE", "R", vec![("size", xy(1.0, 1.0))]))); + nodes.extend((2000..2230).map(|i| node(i, Some((1, "!")), "INSTANCE", "I", vec![("symbolData", o(vec![("symbolID", g(5))]))]))); + let blob = o(vec![("bytes", Kv::Bytes(vec![0; 40 << 20]))]); + let file = canvas(&schema(), &o(vec![("nodeChanges", arr(nodes)), ("blobs", arr(vec![blob]))])); + assert!(file.len() < 1 << 20, "{} bytes", file.len()); + let (doc, warnings) = import(&file, "x").unwrap(); + assert!(warnings.iter().any(|w| w.contains("more than 200000 layers")), "{warnings:?}"); + assert!(doc.node_count() <= crate::rest::MAX_NODES + 10); +} + +#[test] +fn the_mapper_stops_at_the_layer_cap_it_is_given() { + let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])]; + nodes.extend((2..12).map(|i| node(i, Some((1, "!")), "RECTANGLE", "R", vec![("size", xy(1.0, 1.0))]))); + let msg = o(vec![("nodeChanges", arr(nodes))]); + let (_, warnings, _) = map::to_rest(&msg, "x", 5); + assert!(warnings.iter().any(|w| w.contains("more than 5 layers")), "{warnings:?}"); + let (_, warnings, _) = map::to_rest(&msg, "x", crate::rest::MAX_NODES); + assert!(!warnings.iter().any(|w| w.contains("more than")), "{warnings:?}"); +} + +#[test] +fn scalar_fields_count_against_the_value_budget() { + // A message of 1000 scalar fields (id 1, `true`) is 1001 values: a budget of 10 refuses it. + let fields = vec![Field { name: "b".into(), ty: Some(Type::Bool), array: false, value: 1 }]; + let sc = Schema { defs: vec![Def { name: "Message".into(), kind: Kind::Message, fields }] }; + let mut data = [1u8, 1].repeat(1000); + data.push(0); + let e = sc.decode_message_within(0, &data, 10).unwrap_err(); + assert_eq!(e.0, "message: too many values"); + assert!(sc.decode_message_within(0, &data, 1001).is_ok()); +} + +#[test] +fn hostile_input_is_refused() { + // A message that contains itself, nested past the depth cap. + let field = |ty, array| vec![Field { name: "m".into(), ty: Some(ty), array, value: 1 }]; + let nested = Schema { defs: vec![Def { name: "Message".into(), kind: Kind::Message, fields: field(Type::Def(0), false) }] }; + assert!(nested.decode_message(0, &[1u8; 10_000]).is_err()); + // An array count larger than the data. + let array = Schema { defs: vec![Def { name: "Message".into(), kind: Kind::Message, fields: field(Type::Uint, true) }] }; + assert!(array.decode_message(0, &[1, 0xff, 0xff, 0xff, 0xff, 0x0f]).is_err()); + // A field type naming a missing definition. + let mut w = encode::Writer::default(); + w.var_uint(1); + w.string("Message"); + w.byte(2); + w.var_uint(1); + w.string("x"); + w.var_int(5); + w.byte(0); + w.var_uint(1); + assert!(Schema::decode(&w.0).is_err()); + // A schema without a Message definition. + let c = canvas(&Schema { defs: vec![Def { name: "Message".into(), kind: Kind::Message, fields: vec![] }] }, &Kv::Object(vec![])); + let renamed: Vec = { + let sc = Schema { defs: vec![Def { name: "Other".into(), kind: Kind::Message, fields: vec![] }] }; + let mut z = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); + z.write_all(&encode::schema(&sc)).unwrap(); + let sch = z.finish().unwrap(); + let mut out = c[..12].to_vec(); + out.extend_from_slice(&(sch.len() as u32).to_le_bytes()); + out.extend_from_slice(&sch); + out.extend_from_slice(&c[12 + 4 + chunks(&c).unwrap()[0].len()..]); + out + }; + assert!(import(&c, "x").is_ok()); + assert!(import(&renamed, "x").is_err()); +} + +#[test] +fn instances_inside_their_own_main_stop() { + let sym = node(5, Some((1, "!")), "SYMBOL", "Loop", vec![("size", xy(10.0, 10.0))]); + let inner = node(6, Some((5, "!")), "INSTANCE", "Self", vec![("symbolData", o(vec![("symbolID", g(5))]))]); + let doc_nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![]), sym, inner]; + let (doc, _) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(doc_nodes))])), "x").unwrap(); + assert!(doc.nodes().any(|n| n.name == "Self")); +} + +/// A collection from a library is named by its asset key, not a guid — also in the explicit mode +/// map of the frames, components and instances set it on, and in the variables' collection link. +#[test] +fn modes_of_collections_named_by_asset_import() { + let modes = arr(vec![ + o(vec![("id", g(90)), ("name", s("Dark")), ("sortPosition", s("!"))]), + o(vec![("id", g(91)), ("name", s("Light")), ("sortPosition", s("\""))]), + ]); + let color_value = |c| o(vec![("value", o(vec![("colorValue", c)])), ("dataType", e("COLOR"))]); + let values = o(vec![( + "entries", + arr(vec![ + o(vec![("modeID", g(90)), ("variableData", color_value(rgb(0.0, 0.0, 0.0)))]), + o(vec![("modeID", g(91)), ("variableData", color_value(rgb(1.0, 1.0, 1.0)))]), + ]), + )]); + let by_asset = |key: &'static str, version: Option<&'static str>| { + let mut r = vec![("key", s(key))]; + r.extend(version.map(|v| ("version", s(v)))); + o(vec![("assetRef", o(r))]) + }; + let mode_map = |set: Kv<'static>| o(vec![("entries", arr(vec![o(vec![("variableSetID", set), ("variableModeID", g(91))])]))]); + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page A", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + // The collection itself says the asset key its references name. + node(4, Some((2, "!")), "VARIABLE_SET", "Schema", vec![("variableSetModes", modes), ("key", s("schema-collection")), ("version", s("7"))]), + node( + 5, + Some((2, "\"")), + "VARIABLE", + "surface", + vec![("variableSetID", by_asset("schema-collection", Some("7"))), ("variableResolvedType", e("COLOR")), ("variableDataValues", values)], + ), + node( + 10, + Some((1, "!")), + "FRAME", + "Light section", + vec![("size", xy(400.0, 300.0)), ("variableModeBySetMap", mode_map(by_asset("schema-collection", Some("7"))))], + ), + node( + 20, + Some((1, "\"")), + "SYMBOL", + "Button", + vec![("size", xy(100.0, 40.0)), ("variableModeBySetMap", mode_map(by_asset("schema-collection", None)))], + ), + node( + 21, + Some((1, "#")), + "INSTANCE", + "Button copy", + vec![ + ("size", xy(100.0, 40.0)), + ("symbolData", o(vec![("symbolID", g(20))])), + ("variableModeBySetMap", mode_map(by_asset("schema-collection", Some("7")))), + ], + ), + // One names a collection that isn't in the file: its mode is skipped, with a warning. + node(11, Some((1, "$")), "FRAME", "Gone", vec![("size", xy(400.0, 300.0)), ("variableModeBySetMap", mode_map(by_asset("gone", None)))]), + ]; + let (doc, warnings) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + assert_eq!(doc.variables.collections.len(), 1); + assert_eq!(doc.variables.variables.len(), 1); + assert_eq!(doc.variables.variables[0].collection, "1:4"); + for name in ["Light section", "Button", "Button copy"] { + let n = named(&doc, name); + assert_eq!(n.var_modes.get("1:4").map(String::as_str), Some("1:91"), "{name}"); + } + assert!(named(&doc, "Gone").var_modes.is_empty()); + assert!(warnings.iter().any(|w| w.contains("variable modes of collections that aren't in the file")), "{warnings:?}"); +} + +#[test] +fn resized_instances_lay_their_layers_out_by_their_constraints() { + let pin = |h: &'static str, v: &'static str| vec![("horizontalConstraint", e(h)), ("verticalConstraint", e(v))]; + let layer = |id, pos, ty, name, w, h, x, y, c: Vec<(&'static str, Kv<'static>)>| { + node(id, Some((5, pos)), ty, name, [vec![("size", xy(w, h)), ("transform", at(x, y))], c].concat()) + }; + let nodes = vec![ + node(0, None, "DOCUMENT", "D", vec![]), + node(1, Some((0, "!")), "CANVAS", "P", vec![]), + node(5, Some((1, "!")), "SYMBOL", "Logo", vec![("size", xy(132.0, 22.0)), ("transform", at(0.0, 0.0))]), + layer(6, "!", "ROUNDED_RECTANGLE", "Mark", 132.0, 22.0, 0.0, 0.0, pin("SCALE", "SCALE")), + layer(7, "\"", "ROUNDED_RECTANGLE", "Badge", 32.0, 10.0, 100.0, 12.0, pin("MAX", "MAX")), + layer(8, "#", "ROUNDED_RECTANGLE", "Bar", 112.0, 2.0, 10.0, 0.0, pin("STRETCH", "MIN")), + // A group scales its layers with it. + layer(11, "$", "FRAME", "Wordmark", 66.0, 22.0, 66.0, 0.0, [pin("SCALE", "SCALE"), vec![("resizeToFit", Kv::Bool(true))]].concat()), + node(12, Some((11, "!")), "ROUNDED_RECTANGLE", "Letter", vec![("size", xy(66.0, 22.0)), ("transform", at(0.0, 0.0))]), + node( + 9, + Some((1, "\"")), + "INSTANCE", + "Small logo", + vec![("size", xy(90.0, 15.0)), ("transform", at(0.0, 100.0)), ("symbolData", o(vec![("symbolID", g(5))]))], + ), + // Derived layout the file gives wins over the constraints. + node( + 10, + Some((1, "#")), + "INSTANCE", + "Derived logo", + vec![ + ("size", xy(90.0, 15.0)), + ("transform", at(0.0, 200.0)), + ("symbolData", o(vec![("symbolID", g(5))])), + ("derivedSymbolData", arr(vec![o(vec![("guidPath", o(vec![("guids", arr(vec![g(6)]))])), ("size", xy(50.0, 5.0))])])), + ], + ), + // A size the instance overrides: the place still follows the constraints. + node( + 13, + Some((1, "$")), + "INSTANCE", + "Resized badge", + vec![ + ("size", xy(90.0, 15.0)), + ("transform", at(0.0, 300.0)), + ( + "symbolData", + o(vec![ + ("symbolID", g(5)), + ("symbolOverrides", arr(vec![o(vec![("guidPath", o(vec![("guids", arr(vec![g(7)]))])), ("size", xy(20.0, 10.0))])])), + ]), + ), + ], + ), + ]; + let (doc, _) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + let box_of = |inst: &str, name: &str| { + let i = named(&doc, inst); + let n = i.children.iter().map(|c| doc.node(*c).unwrap()).find(|n| n.name == name).unwrap(); + let t = n.transform.translation(); + [t.x, t.y, n.width, n.height].map(|x| (x * 1e3).round() / 1e3) + }; + assert_eq!(box_of("Small logo", "Mark"), [0.0, 0.0, 90.0, 15.0]); + assert_eq!(box_of("Small logo", "Badge"), [58.0, 5.0, 32.0, 10.0]); + assert_eq!(box_of("Small logo", "Bar"), [10.0, 0.0, 70.0, 2.0]); + // The main's own, then the instances'. + let mut letters: Vec<[f64; 2]> = + doc.nodes().filter(|n| n.name == "Letter").map(|n| [n.width, n.height].map(|x| (x * 1e3).round() / 1e3)).collect(); + letters.sort_by(|a, b| a[0].total_cmp(&b[0])); + assert_eq!(letters, [[45.0, 15.0], [45.0, 15.0], [45.0, 15.0], [66.0, 22.0]]); + assert_eq!(box_of("Derived logo", "Mark")[2..], [50.0, 5.0]); + assert_eq!(box_of("Resized badge", "Badge"), [58.0, 5.0, 20.0, 10.0]); +} + +#[test] +fn nested_instances_resized_again_drop_the_layout_derived_for_their_old_size() { + let stretch = || vec![("horizontalConstraint", e("STRETCH")), ("verticalConstraint", e("MIN"))]; + let nodes = vec![ + node(0, None, "DOCUMENT", "D", vec![]), + node(1, Some((0, "!")), "CANVAS", "P", vec![]), + node(20, Some((1, "!")), "SYMBOL", "Track", vec![("size", xy(100.0, 10.0)), ("transform", at(0.0, 0.0))]), + node(21, Some((20, "!")), "ROUNDED_RECTANGLE", "Fill", [vec![("size", xy(100.0, 10.0)), ("transform", at(0.0, 0.0))], stretch()].concat()), + node(30, Some((1, "\"")), "SYMBOL", "Slider", vec![("size", xy(200.0, 50.0)), ("transform", at(0.0, 100.0))]), + // The nested instance is 150 wide in its main, with the layout derived for that. + node( + 31, + Some((30, "!")), + "INSTANCE", + "Inner", + [ + vec![ + ("size", xy(150.0, 10.0)), + ("transform", at(0.0, 0.0)), + ("symbolData", o(vec![("symbolID", g(20))])), + ( + "derivedSymbolData", + arr(vec![o(vec![ + ("guidPath", o(vec![("guids", arr(vec![g(21)]))])), + ("size", xy(150.0, 10.0)), + ("fillPaints", arr(vec![solid(1.0, 0.0, 0.0)])), + ])]), + ), + ], + stretch(), + ] + .concat(), + ), + node( + 40, + Some((1, "#")), + "INSTANCE", + "Wide slider", + vec![("size", xy(300.0, 50.0)), ("transform", at(0.0, 200.0)), ("symbolData", o(vec![("symbolID", g(30))]))], + ), + ]; + let (doc, _) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + let width = |outer: &str| { + let inner = doc.node(named(&doc, outer).children[0]).unwrap(); + (inner.width, doc.node(inner.children[0]).unwrap().width) + }; + // In its main the derived layout holds; stretched to 250 it no longer does. + assert_eq!(width("Slider"), (150.0, 150.0)); + assert_eq!(width("Wide slider"), (250.0, 250.0)); + // What else the derived data gives (the colour a variable resolves to, say) still holds. + let fill = doc.node(doc.node(named(&doc, "Wide slider").children[0]).unwrap().children[0]).unwrap(); + assert!(matches!(fill.fills.first().map(|p| &p.kind), Some(figcraft_doc::color::PaintKind::Solid { color }) if color.r == 1.0 && color.g == 0.0)); +} + +#[path = "tail_tests.rs"] +mod tail; + +#[path = "image_filter_tests.rs"] +mod image_filters; + +#[path = "text_list_tests.rs"] +mod text_list; + +/// `.fig` files in the folder `FIGCRAFT_FIG_SAMPLES` names (none when it's unset). +pub(super) fn samples() -> Vec { + let Some(dir) = std::env::var_os("FIGCRAFT_FIG_SAMPLES") else { return Vec::new() }; + let dir = std::fs::read_dir(dir).into_iter().flatten().flatten(); + dir.map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "fig")).collect() +} + +/// Local only (`FIGCRAFT_FIG_SAMPLES`): every file imports without warnings. +#[test] +fn local_samples_import() { + for p in samples() { + let bytes = std::fs::read(&p).unwrap(); + let (doc, warnings) = import(&bytes, "sample").unwrap_or_else(|e| panic!("{}: {e}", p.display())); + assert!(warnings.is_empty(), "{}: {warnings:?}", p.display()); + assert!(doc.node_count() > 5, "{}", p.display()); + } +} + +/// Local only: dumps each sample's schema, decoded message and REST JSON when `FIG_DUMP` names a +/// folder (for working on the importer). +#[test] +fn dump_samples() { + let Ok(out) = std::env::var("FIG_DUMP") else { return }; + for p in samples() { + let bytes = std::fs::read(&p).unwrap(); + let a = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&a.canvas).unwrap(); + let stem = p.file_stem().unwrap().to_string_lossy().to_string(); + let mut txt = String::new(); + for d in &schema.defs { + txt += &format!("{:?} {}\n", d.kind, d.name); + for f in &d.fields { + let ty = match f.ty { + Some(Type::Def(i)) => schema.defs[i].name.clone(), + Some(t) => format!("{t:?}"), + None => String::new(), + }; + txt += &format!(" {} {}{} = {}\n", f.name, ty, if f.array { "[]" } else { "" }, f.value); + } + } + 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())); + std::fs::write(format!("{out}/{stem}.rest.json"), serde_json::to_string_pretty(&rest).unwrap()).unwrap(); + } +} + +#[path = "board_import_tests.rs"] +mod board; + +/// A file that took several updates of a library holds a copy of its collection and of each of +/// its variables per version it met (same asset key, another version). Layers and modes name any +/// of them by asset, never by guid: they all become the newest copy, which has every mode — a page +/// set to a mode only the newer copies have keeps it, and fills bound to an older copy of a +/// variable follow its newest values. +#[test] +fn library_copies_of_several_versions_become_the_newest() { + let mode = |id, name: &'static str, pos: &'static str| o(vec![("id", g(id)), ("name", s(name)), ("sortPosition", s(pos))]); + let by_asset = |key: &'static str, version: &'static str| o(vec![("assetRef", o(vec![("key", s(key)), ("version", s(version))]))]); + let color_value = |c| o(vec![("value", o(vec![("colorValue", c)])), ("dataType", e("COLOR"))]); + let values = |pairs: Vec<(u64, Kv<'static>)>| { + o(vec![("entries", arr(pairs.into_iter().map(|(m, c)| o(vec![("modeID", g(m)), ("variableData", color_value(c))])).collect()))]) + }; + let asset_alias = + |key: &'static str, version: &'static str| o(vec![("value", o(vec![("alias", by_asset(key, version))])), ("dataType", e("ALIAS"))]); + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + // The page is set to "Purple", a mode the oldest copy of the collection didn't have yet. + node( + 1, + Some((0, "!")), + "CANVAS", + "Page", + vec![( + "variableModeBySetMap", + o(vec![("entries", arr(vec![o(vec![("variableSetID", by_asset("products", "10:1")), ("variableModeID", g(92))])]))]), + )], + ), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node( + 4, + Some((2, "!")), + "VARIABLE_SET", + "Products", + vec![("variableSetModes", arr(vec![mode(90, "Blue", "!")])), ("key", s("products")), ("version", s("10:1"))], + ), + node( + 6, + Some((2, "#")), + "VARIABLE_SET", + "Products", + vec![("variableSetModes", arr(vec![mode(90, "Blue", "!"), mode(92, "Purple", "\"")])), ("key", s("products")), ("version", s("20:1"))], + ), + node( + 5, + Some((2, "\"")), + "VARIABLE", + "button-bg", + vec![ + ("variableSetID", by_asset("products", "10:1")), + ("variableResolvedType", e("COLOR")), + ("variableDataValues", values(vec![(90, rgb(0.0, 0.0, 1.0))])), + ("key", s("button-bg")), + ("version", s("10:1")), + ], + ), + node( + 7, + Some((2, "$")), + "VARIABLE", + "button-bg", + vec![ + ("variableSetID", by_asset("products", "20:1")), + ("variableResolvedType", e("COLOR")), + ("variableDataValues", values(vec![(90, rgb(0.0, 0.0, 1.0)), (92, rgb(0.5, 0.0, 0.5))])), + ("key", s("button-bg")), + ("version", s("20:1")), + ], + ), + // The button names the older copy of the variable. + node( + 10, + Some((1, "!")), + "FRAME", + "Button", + vec![ + ("size", xy(100.0, 40.0)), + ( + "fillPaints", + arr(vec![o(vec![("type", e("SOLID")), ("color", rgb(0.0, 0.0, 1.0)), ("colorVar", asset_alias("button-bg", "10:1"))])]), + ), + ], + ), + ]; + let (doc, warnings) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + assert_eq!(doc.variables.collections.len(), 1, "{:?}", doc.variables.collections); + let products = &doc.variables.collections[0]; + assert_eq!(products.modes.iter().map(|m| m.name.as_str()).collect::>(), ["Blue", "Purple"]); + assert_eq!(doc.variables.variables.len(), 1); + let var = &doc.variables.variables[0]; + assert_eq!(var.collection, products.id); + assert_eq!(var.values.len(), 2, "the newest copy's values: {:?}", var.values); + let page = doc.nodes().find(|n| n.name == "Page").unwrap(); + assert_eq!(page.var_modes.get(&products.id).map(String::as_str), Some("1:92")); + let button = named(&doc, "Button"); + assert_eq!(button.bound.values().next(), Some(&var.id), "{:?}", button.bound); + assert!(!warnings.iter().any(|w| w.contains("variable modes of collections")), "{warnings:?}"); +} From a5ebc01d2c912f6308e5f10040880b816aac8445 Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 13:50:48 +0330 Subject: [PATCH 052/326] Add files via upload --- crates/format/src/fig/map/document.rs | 59 ++++++++++++++++++-------- crates/format/src/fig/map/variables.rs | 4 +- 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/crates/format/src/fig/map/document.rs b/crates/format/src/fig/map/document.rs index 69f221c1a..6868de485 100644 --- a/crates/format/src/fig/map/document.rs +++ b/crates/format/src/fig/map/document.rs @@ -259,28 +259,37 @@ impl<'a> Mapper<'a> { }; let mut order = Vec::new(); let mut collections = Obj::new(); + // Copies of one library collection (one per version the file met) become one: the newest + // keeps its modes in its order, the others add the modes it no longer has. + let mut extra: BTreeMap> = BTreeMap::new(); for (id, n) in of_type("VARIABLE_SET", "parentIndex") { - order.push(json!(id)); - let mut modes: Vec<(&str, Value)> = n - .get("variableSetModes") - .map(Kv::list) - .unwrap_or_default() - .iter() - .filter_map(|m| { - let mode = json!({"modeId": m.get("id").and_then(guid)?, "name": m.get("name").and_then(Kv::str).unwrap_or("Mode")}); - Some((m.get("sortPosition").and_then(Kv::str).unwrap_or(""), mode)) - }) - .collect(); - modes.sort_by(|a, b| a.0.cmp(b.0)); - let default = modes.first().map_or(Value::Null, |m| m.1["modeId"].clone()); - let name = n.get("name").and_then(Kv::str).unwrap_or("Collection"); - let modes: Vec = modes.into_iter().map(|m| m.1).collect(); - collections.insert(id.clone(), json!({"id": id, "name": name, "modes": modes, "defaultModeId": default})); + let modes = sorted_modes(n); + match self.canonical_collection(id).filter(|c| c != id) { + Some(canonical) => extra.entry(canonical).or_default().extend(modes), + None => { + order.push(json!(id)); + let default = modes.first().map_or(Value::Null, |m| m.1["modeId"].clone()); + let name = n.get("name").and_then(Kv::str).unwrap_or("Collection"); + let modes: Vec = modes.into_iter().map(|m| m.1).collect(); + collections.insert(id.clone(), json!({"id": id, "name": name, "modes": modes, "defaultModeId": default})); + } + } + } + for (canonical, more) in extra { + let Some(modes) = collections.get_mut(&canonical).and_then(|c| c.get_mut("modes")).and_then(Value::as_array_mut) else { continue }; + for (_, m) in more { + if !modes.iter().any(|x| x["modeId"] == m["modeId"]) { + modes.push(m); + } + } } let mut variable_order = Vec::new(); let mut variables = Obj::new(); for (id, n) in of_type("VARIABLE", "sortPosition") { - let Some(set) = n.get("variableSetID").and_then(|s| self.resource_id(s)).filter(|s| collections.contains_key(s)) else { continue }; + if super::VarCanon::superseded(id) { + continue; + } + let Some(set) = n.get("variableSetID").and_then(|s| self.collection_id(s)).filter(|s| collections.contains_key(s)) else { continue }; let ty = n.get("variableResolvedType").and_then(Kv::str).unwrap_or(""); if !matches!(ty, "BOOLEAN" | "FLOAT" | "STRING" | "COLOR") { continue; @@ -306,3 +315,19 @@ impl<'a> Mapper<'a> { .then(|| json!({"variableCollections": collections, "variables": variables, "collectionOrder": order, "variableOrder": variable_order})) } } + +/// A collection node's modes in their order (`sortPosition`), as `(position, {modeId, name})`. +fn sorted_modes(n: &Kv) -> Vec<(String, Value)> { + let mut modes: Vec<(String, Value)> = n + .get("variableSetModes") + .map(Kv::list) + .unwrap_or_default() + .iter() + .filter_map(|m| { + let mode = json!({"modeId": m.get("id").and_then(guid)?, "name": m.get("name").and_then(Kv::str).unwrap_or("Mode")}); + Some((m.get("sortPosition").and_then(Kv::str).unwrap_or("").to_string(), mode)) + }) + .collect(); + modes.sort_by(|a, b| a.0.cmp(&b.0)); + modes +} diff --git a/crates/format/src/fig/map/variables.rs b/crates/format/src/fig/map/variables.rs index 8d891ded7..12b433fc0 100644 --- a/crates/format/src/fig/map/variables.rs +++ b/crates/format/src/fig/map/variables.rs @@ -49,7 +49,7 @@ impl<'a> Mapper<'a> { let mut lost = false; for e in v.get("variableModeBySetMap").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() { let (Some(set), Some(mode)) = (e.get("variableSetID"), e.get("variableModeID").and_then(guid)) else { continue }; - match self.resource_id(set) { + match self.collection_id(set) { Some(id) => { modes.insert(id, json!(mode)); } @@ -143,7 +143,7 @@ pub(super) fn alias(d: Option<&Kv>) -> Option { if d.get("dataType").and_then(Kv::str) != Some("ALIAS") { return None; } - d.get("value").and_then(|v| v.get("alias")).and_then(ref_guid) + d.get("value").and_then(|v| v.get("alias")).and_then(super::VarCanon::resolve) } pub(super) fn variable_value(d: &Kv) -> Option { From 8c93d0559fbb70d4b9478e286a506cf9abe6447d Mon Sep 17 00:00:00 2001 From: samhyun Date: Sun, 1 Nov 2026 19:03:53 +0900 Subject: [PATCH 053/326] M8: dots quantize their position apart from the view's origin Review of #1796: quantizing the mark's distance from the view's corner took in the error of the view's origin converted to pixels, so a mark one 1/65536 px step short of a half could still cross it. At a step of 24 and a zoom of (75.5 - 2^-17) / 24, a pan by 51 pixels moved the first mark. The mark's position and the origin are now each quantized before the one is taken from the other. The origin rounds its halves down: some 4 x 10^10 pixels out, its error is exactly half a step, and rounded up it moved the marks again. Past 2^37 pixels the step is finer than f64 and values are used as they are, so huge ones no longer overflow to infinity and come out as a mark at the view's corner. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/dots.rs | 22 +++++++++----- crates/render/src/dots_tests.rs | 54 +++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 8 deletions(-) diff --git a/crates/render/src/dots.rs b/crates/render/src/dots.rs index 5d4ae1fc1..c33e89a22 100644 --- a/crates/render/src/dots.rs +++ b/crates/render/src/dots.rs @@ -57,7 +57,7 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) { let strong = |k: i64| k.rem_euclid(major) == 0; // The device-pixel span of the mark on line `k` along an axis `len` pixels long from `o`. let span = |k: i64, o: f64, len: i64| { - let a = (nearest_px(k as f64 * d.step * s - o) as i64).saturating_sub(lead); + let a = (nearest_px(k as f64 * d.step * s, o) as i64).saturating_sub(lead); (a.max(0), a.saturating_add(side).min(len)) }; let row = w as usize * 4; @@ -92,14 +92,20 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) { } } -/// The first device pixel of a mark whose edge is `p` pixels from the view's top-left: the one -/// whose left (or top) edge is nearest, and the right (or lower) one when two are as near. `p` is -/// first rounded to 1/65536 px, halves up as well: a view a whole number of pixels off (a pan, a -/// band, a patch) reaches it with another rounding error, and, rounded either way, would put the -/// marks that fall halfway on the other pixel. -fn nearest_px(p: f64) -> f64 { +/// The first device pixel of a mark whose edge is `at` pixels from the page origin, in a view whose +/// top-left is `o` pixels from it: the pixel whose left (or top) edge is nearest, and the right (or +/// lower) one when two are as near. A view a whole number of pixels off (a pan, a band, a patch) +/// gets `o` back from its origin with a rounding error, so `at` and `o` are each rounded to +/// 1/65536 px first: the mark's own position decides the pixel, and the view only counts it out +/// from its corner. The mark's halves go up and the origin's down: far out, where the origin's +/// error is half a step, it still comes back to the whole pixel. Past 2³⁷ px the step is finer +/// than `f64` and values are used as they are. +fn nearest_px(at: f64, o: f64) -> f64 { const STEPS: f64 = 65_536.0; - ((p * STEPS + 0.5).floor() / STEPS + 0.5).floor() + const EXACT: f64 = 137_438_953_472.0; // 2³⁷ + let up = |v: f64| if v.abs() < EXACT { (v * STEPS + 0.5).floor() / STEPS } else { v }; + let down = |v: f64| if v.abs() < EXACT { (v * STEPS - 0.5).ceil() / STEPS } else { v }; + (up(at) - down(o) + 0.5).floor() } /// Which line covers each device pixel along an axis: 0 none, 1 a faded one, 2 a strong one. diff --git a/crates/render/src/dots_tests.rs b/crates/render/src/dots_tests.rs index 18d96345f..75932a2bf 100644 --- a/crates/render/src/dots_tests.rs +++ b/crates/render/src/dots_tests.rs @@ -180,3 +180,57 @@ fn dots_on_the_rounding_step_stay_put() { } } } + +/// The view's origin is quantized apart from the marks: converted to pixels, a whole-pixel origin +/// comes back a hair off, and taken together with a mark one step short of a half it would push the +/// mark across. +#[test] +fn dots_one_rounding_step_short_of_a_half_stay_put() { + let (d, page) = page_with_square(); + let s = (75.5 - 2f64.powi(-17)) / 24.0; + for lines in [false, true] { + let opts = Options { dots: Some(Dots { lines, ..dots() }), ..Default::default() }; + let a = render_view_single(&d, page, &View { origin: (0.0, 0.0), scale: s, width: 300, height: 200 }, &opts).unwrap(); + for pan in 1..100u32 { + let v = View { origin: (f64::from(pan) / s, f64::from(pan) / s), scale: s, width: 200, height: 100 }; + let b = render_view_single(&d, page, &v, &opts).unwrap(); + for y in 0..100 { + for x in 0..200 { + assert_eq!(rgba(&b, x, y), rgba(&a, x + pan, y + pan), "lines {lines}, a pan by {pan}, at {x}, {y}"); + } + } + } + } +} + +/// Far out (some 4 × 10¹⁰ pixels), a whole-pixel origin comes back from page units exactly half a +/// rounding step off: rounded up, it would move the marks that fall halfway between pixels. +#[test] +fn far_out_dots_stay_put() { + let (d, page) = page_with_square(); + let s = 0.3; + let at = 42_536_140_695.0; + let opts = Options { dots: Some(Dots { step: 5.0, ..dots() }), ..Default::default() }; + let a = render_view_single(&d, page, &View { origin: (at / s, 0.0), scale: s, width: 420, height: 40 }, &opts).unwrap(); + for dx in 1..200u32 { + let v = View { origin: ((at + f64::from(dx)) / s, 0.0), scale: s, width: 200, height: 40 }; + let b = render_view_single(&d, page, &v, &opts).unwrap(); + for y in 0..40 { + for x in 0..200 { + assert_eq!(rgba(&b, x, y), rgba(&a, x + dx, y), "a pan by {dx}, at {x}, {y}"); + } + } + } +} + +/// Positions too far out to quantize draw nothing rather than a mark at the corner. +#[test] +fn dots_out_past_any_page_draw_nothing() { + let (d, page) = page_with_square(); + let plain = render_view_single(&d, page, &View { origin: (1e304, 0.0), scale: 1.0, width: 40, height: 40 }, &Options::default()).unwrap(); + for (step, x) in [(1e290, 1e304), (1e299, 1e305), (3e303, 1.5e308)] { + let opts = Options { dots: Some(Dots { step, ..dots() }), ..Default::default() }; + let p = render_view_single(&d, page, &View { origin: (x, 0.0), scale: 1.0, width: 40, height: 40 }, &opts).unwrap(); + assert_eq!(p.data(), plain.data(), "a step of {step} at {x}"); + } +} From 69692323267133138377d14e03fbc7b142fb0638 Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 13:53:11 +0330 Subject: [PATCH 054/326] Add files via upload --- crates/format/src/fig/map.rs | 104 +++++++++++++++++++++++++++++++++ crates/format/src/fig/tests.rs | 99 +++++++++++++++++++++++++++++++ 2 files changed, 203 insertions(+) diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index 3d410e07d..98239cd7b 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -48,6 +48,7 @@ const MAX_ASSET_PART: usize = 256; /// vector networks its layers name by `vectorNetworkRef` (for [`crate::rest::import_with_networks`]). pub(super) fn to_rest(msg: &Kv, name: &str, max_nodes: usize) -> (Value, Vec, Vec>) { let mut m = Mapper::new(msg, max_nodes); + let _canon = VarCanon::install(&m); let doc = m.document(); // Large values are moved in, never passed through `json!`, which serialises its arguments: // a deep copy of the whole tree, briefly holding it twice. @@ -365,6 +366,30 @@ impl<'a> Mapper<'a> { .cloned() } + /// The collection a `VariableSetID` names, as one collection per library asset: a file that + /// took several updates of a library holds a copy of the collection for each version it met, + /// all with the same asset `key`. Variables and explicit modes may name any of those copies, + /// while the mode ids stay the same across them, so every copy maps to the newest one (the + /// one [`Self::variables`] keeps, with the modes of the others added). Without this, a page set + /// to a mode an older copy didn't have yet lost its mode, and the layers fell back to the + /// default mode of the newest copy. + pub(super) fn collection_id(&self, v: &Kv) -> Option { + let id = self.resource_id(v)?; + Some(self.canonical_collection(&id).unwrap_or(id)) + } + + /// The newest live copy of collection node `id`'s library asset, when it has a key. + pub(super) fn canonical_collection(&self, id: &str) -> Option { + let key = self.nodes.get(id)?.get("key").and_then(Kv::str).filter(|k| !k.is_empty())?; + let live_set = |n: &Kv| n.get("type").and_then(Kv::str) == Some("VARIABLE_SET") && n.get("isSoftDeleted").and_then(Kv::bool) != Some(true); + self.assets + .get(key)? + .iter() + .filter(|(_, nid)| self.nodes.get(nid.as_str()).is_some_and(|n| live_set(n))) + .max_by_key(|(ver, _)| version_rank(ver)) + .map(|(_, nid)| nid.clone()) + } + /// A note about what this file's mapping left out or changed. Counted, as the REST importer /// counts its own: these notes are met once per layer, so the kinds were named once each with /// no sign of how much of the file they covered -- a file whose every text layer lost a @@ -384,3 +409,82 @@ impl<'a> Mapper<'a> { self.max_nodes.saturating_sub(self.reserved) } } + +/// A library version (`"40727:1183"`) as numbers to order by; unparsable parts rank lowest. +fn version_rank(v: &str) -> (u64, u64) { + let mut parts = v.split(':').map(|p| p.trim().parse::().unwrap_or(0)); + (parts.next().unwrap_or(0), parts.next().unwrap_or(0)) +} + +/// Library variables, one per asset. A file that took several updates of a library keeps a copy +/// of a variable for each version it met (same `key`, another `version`), and layers and other +/// variables name them by that asset (`assetRef {key, version}`) rather than by guid. Each +/// reference goes to the newest copy: it has the values of every mode the library has now, where +/// an older one lacks the modes added since (a layer under a page set to such a mode fell back to +/// the default one). Kept per thread while a file is mapped: the paint and variable readers that +/// meet references are free functions. +#[derive(Default)] +pub(super) struct VarCanon { + by_key: HashMap, + by_id: HashMap, +} + +thread_local! { + static VAR_CANON: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// Removes the thread's table when the mapping is done. +pub(super) struct VarCanonGuard; + +impl Drop for VarCanonGuard { + fn drop(&mut self) { + VAR_CANON.with(|c| c.borrow_mut().take()); + } +} + +impl VarCanon { + fn install(m: &Mapper) -> VarCanonGuard { + let mut newest: HashMap = HashMap::new(); + let mut copies: Vec<(String, String)> = Vec::new(); + for (id, n) in &m.nodes { + if n.get("type").and_then(Kv::str) != Some("VARIABLE") || n.get("isSoftDeleted").and_then(Kv::bool) == Some(true) { + continue; + } + let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) else { continue }; + let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or("")); + copies.push((id.clone(), key.to_string())); + let e = newest.entry(key.to_string()).or_insert_with(|| (rank, id.clone())); + if rank > e.0 || (rank == e.0 && *id > e.1) { + *e = (rank, id.clone()); + } + } + let mut t = VarCanon::default(); + for (id, key) in copies { + if let Some((_, canon)) = newest.get(&key) { + t.by_id.insert(id, canon.clone()); + } + } + t.by_key = newest.into_iter().map(|(k, (_, id))| (k, id)).collect(); + VAR_CANON.with(|c| *c.borrow_mut() = Some(t)); + VarCanonGuard + } + + /// The variable a reference (`{guid}` or `{assetRef}`) names, as its newest copy. + pub(super) fn resolve(r: &Kv) -> Option { + let by_guid = r.get("guid").and_then(guid).filter(|g| g != NO_STYLE); + VAR_CANON.with(|c| { + let c = c.borrow(); + let Some(t) = c.as_ref() else { return by_guid.clone() }; + if let Some(g) = &by_guid { + return Some(t.by_id.get(g).cloned().unwrap_or_else(|| g.clone())); + } + let key = r.get("assetRef")?.get("key").and_then(Kv::str)?; + t.by_key.get(key).cloned() + }) + } + + /// Whether variable node `id` is an older copy another one replaces. + pub(super) fn superseded(id: &str) -> bool { + VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.by_id.get(id)).is_some_and(|canon| canon != id)) + } +} diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index 657f2f81d..0e2c5016e 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -1487,3 +1487,102 @@ fn dump_samples() { #[path = "board_import_tests.rs"] mod board; + +/// A file that took several updates of a library holds a copy of its collection and of each of +/// its variables per version it met (same asset key, another version). Layers and modes name any +/// of them by asset, never by guid: they all become the newest copy, which has every mode — a page +/// set to a mode only the newer copies have keeps it, and fills bound to an older copy of a +/// variable follow its newest values. +#[test] +fn library_copies_of_several_versions_become_the_newest() { + let mode = |id, name: &'static str, pos: &'static str| o(vec![("id", g(id)), ("name", s(name)), ("sortPosition", s(pos))]); + let by_asset = |key: &'static str, version: &'static str| o(vec![("assetRef", o(vec![("key", s(key)), ("version", s(version))]))]); + let color_value = |c| o(vec![("value", o(vec![("colorValue", c)])), ("dataType", e("COLOR"))]); + let values = |pairs: Vec<(u64, Kv<'static>)>| { + o(vec![("entries", arr(pairs.into_iter().map(|(m, c)| o(vec![("modeID", g(m)), ("variableData", color_value(c))])).collect()))]) + }; + let asset_alias = + |key: &'static str, version: &'static str| o(vec![("value", o(vec![("alias", by_asset(key, version))])), ("dataType", e("ALIAS"))]); + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + // The page is set to "Purple", a mode the oldest copy of the collection didn't have yet. + node( + 1, + Some((0, "!")), + "CANVAS", + "Page", + vec![( + "variableModeBySetMap", + o(vec![("entries", arr(vec![o(vec![("variableSetID", by_asset("products", "10:1")), ("variableModeID", g(92))])]))]), + )], + ), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node( + 4, + Some((2, "!")), + "VARIABLE_SET", + "Products", + vec![("variableSetModes", arr(vec![mode(90, "Blue", "!")])), ("key", s("products")), ("version", s("10:1"))], + ), + node( + 6, + Some((2, "#")), + "VARIABLE_SET", + "Products", + vec![("variableSetModes", arr(vec![mode(90, "Blue", "!"), mode(92, "Purple", "\"")])), ("key", s("products")), ("version", s("20:1"))], + ), + node( + 5, + Some((2, "\"")), + "VARIABLE", + "button-bg", + vec![ + ("variableSetID", by_asset("products", "10:1")), + ("variableResolvedType", e("COLOR")), + ("variableDataValues", values(vec![(90, rgb(0.0, 0.0, 1.0))])), + ("key", s("button-bg")), + ("version", s("10:1")), + ], + ), + node( + 7, + Some((2, "$")), + "VARIABLE", + "button-bg", + vec![ + ("variableSetID", by_asset("products", "20:1")), + ("variableResolvedType", e("COLOR")), + ("variableDataValues", values(vec![(90, rgb(0.0, 0.0, 1.0)), (92, rgb(0.5, 0.0, 0.5))])), + ("key", s("button-bg")), + ("version", s("20:1")), + ], + ), + // The button names the older copy of the variable. + node( + 10, + Some((1, "!")), + "FRAME", + "Button", + vec![ + ("size", xy(100.0, 40.0)), + ( + "fillPaints", + arr(vec![o(vec![("type", e("SOLID")), ("color", rgb(0.0, 0.0, 1.0)), ("colorVar", asset_alias("button-bg", "10:1"))])]), + ), + ], + ), + ]; + let (doc, warnings) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + assert_eq!(doc.variables.collections.len(), 1, "{:?}", doc.variables.collections); + let products = &doc.variables.collections[0]; + assert_eq!(products.modes.iter().map(|m| m.name.as_str()).collect::>(), ["Blue", "Purple"]); + assert_eq!(doc.variables.variables.len(), 1); + let var = &doc.variables.variables[0]; + assert_eq!(var.collection, products.id); + assert_eq!(var.values.len(), 2, "the newest copy's values: {:?}", var.values); + let page = doc.nodes().find(|n| n.name == "Page").unwrap(); + assert_eq!(page.var_modes.get(&products.id).map(String::as_str), Some("1:92")); + let button = named(&doc, "Button"); + assert_eq!(button.bound.values().next(), Some(&var.id), "{:?}", button.bound); + assert!(!warnings.iter().any(|w| w.contains("variable modes of collections")), "{warnings:?}"); +} From f282a30164b642346e265fb412030d0ca66b0f69 Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 13:54:49 +0330 Subject: [PATCH 055/326] Delete map.rs --- map.rs | 490 --------------------------------------------------------- 1 file changed, 490 deletions(-) delete mode 100644 map.rs diff --git a/map.rs b/map.rs deleted file mode 100644 index 98239cd7b..000000000 --- a/map.rs +++ /dev/null @@ -1,490 +0,0 @@ -//! Decoded `.fig` message → REST API file JSON, which [`crate::rest`] then imports. -//! -//! The message lists node changes; each names its id (`guid`), its parent and its position among -//! the siblings (`parentIndex`). Nodes are read by field name, so files written with newer -//! schemas still import what is understood. Instances carry only their overrides: their layers -//! are expanded here from the main component (overrides and derived layout matched by id path, -//! component property values applied) so the import looks as saved. - -use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::rc::Rc; - -use figcraft_doc::VectorNetwork; -use figcraft_doc::geom::{Affine, Point}; -use figcraft_doc::proto::{MAX_ACTION_DEPTH, MAX_EXPR_DEPTH}; -use serde_json::{Map, Value, json}; - -use super::kiwi::Kv; -use super::network; - -mod component; -mod connector; -mod document; -mod layer; -mod layout; -mod paint; -mod proto; -mod text; -mod variables; - -use component::OverrideScope; -#[cfg(test)] -use paint::paint; - -type Obj = Map; - -/// Deepest nesting followed. -const MAX_DEPTH: usize = 256; -/// Most path commands read from one geometry blob. -const MAX_COMMANDS: usize = 200_000; -const MAX_GRID_TRACKS: usize = 1_000; -pub(super) const MAX_GRID_TRACK_VALUE: f64 = 1e6; -/// Id of "no style". -const NO_STYLE: &str = "4294967295:4294967295"; -/// Longest asset `key` or `version` kept for resolving references given as assets. -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`]). -pub(super) fn to_rest(msg: &Kv, name: &str, max_nodes: usize) -> (Value, Vec, Vec>) { - let mut m = Mapper::new(msg, max_nodes); - let _canon = VarCanon::install(&m); - let doc = m.document(); - // Large values are moved in, never passed through `json!`, which serialises its arguments: - // a deep copy of the whole tree, briefly holding it twice. - let mut out = json!({"name": name}); - out["document"] = doc; - if !m.library_contexts.is_empty() { - out[crate::rest::FIG_LIBRARY_CONTEXTS_FIELD] = Value::Array(std::mem::take(&mut m.library_contexts)); - } - // Mains in the file that the layer cap kept out: their instances are told apart from those of - // components the file doesn't have (#981). - if m.count >= m.max_nodes { - let capped: Vec = m.referenced_mains.difference(&m.mapped_mains).map(|id| json!(id)).collect(); - if !capped.is_empty() { - out[crate::rest::FIG_CAPPED_MAINS_FIELD] = Value::Array(capped); - } - } - if !m.styles.is_empty() { - out["styles"] = Value::Object(std::mem::take(&mut m.styles)); - } - if !m.components.is_empty() { - out["components"] = Value::Object(std::mem::take(&mut m.components)); - } - if !m.sets.is_empty() { - out["componentSets"] = Value::Object(std::mem::take(&mut m.sets)); - } - if let Some(vars) = m.variables() { - out["meta"] = vars; - } - let styles = m.style_definitions(); - if !styles.is_empty() { - out["styleDefinitions"] = Value::Array(styles); - } - (out, m.warnings.finish(), m.networks) -} - -#[cfg(test)] -mod image_filter_tests; - -/// REST importer warnings reworded for a `.fig` import (`None`: drop it). -pub(super) fn adapt_warning(w: String) -> Option { - if w.contains("geometry=paths") { - return None; - } - Some(w.replace("the variables JSON", "the file").replace("the file JSON", "the file")) -} - -// ---- small readers ---- - -/// A generated child is identified by one exact template GUID, not its array position. -fn generated_record<'a>(v: &View<'a>, field: &str, local_id: u32) -> Option<&'a Kv<'a>> { - v.get(field)?.get("overrides")?.list().iter().find(|row| { - row.get("guidPath").and_then(|path| path.get("guids")).map(Kv::list).is_some_and(|guids| { - guids.len() == 1 && num(&guids[0], "sessionID") == Some(40_000_000.0) && num(&guids[0], "localID") == Some(f64::from(local_id)) - }) - }) -} - -fn num(n: &Kv, k: &str) -> Option { - n.get(k).and_then(Kv::f64) -} - -fn guid(v: &Kv) -> Option { - Some(format!("{}:{}", num(v, "sessionID")? as u64, num(v, "localID")? as u64)) -} - -#[cfg(test)] -mod connector_snapshot_budget_tests; - -/// A `GUID`-holding reference (`StyleId`, `VariableID`, …): its `guid`. -fn ref_guid(v: &Kv) -> Option { - v.get("guid").and_then(guid).filter(|g| g != NO_STYLE) -} - -fn vec2(v: &Kv) -> Option { - Some(json!({"x": num(v, "x")?, "y": num(v, "y")?})) -} - -fn size(v: &Kv) -> Option<(f64, f64)> { - Some((num(v, "x")?, num(v, "y")?)) -} - -fn matrix(m: &Kv) -> Option { - let c = |k: &str| num(m, k); - let a = Affine::new([c("m00")?, c("m10")?, c("m01")?, c("m11")?, c("m02")?, c("m12")?]); - a.as_coeffs().iter().all(|x| x.is_finite()).then_some(a) -} - -fn rows(a: Affine) -> Value { - let [a, b, c, d, e, f] = a.as_coeffs(); - json!([[a, c, e], [b, d, f]]) -} - -fn copy_num(o: &mut Obj, n: &View, from: &str, to: &str) { - if let Some(x) = n.num(from) { - o.insert(to.into(), json!(x)); - } -} - -fn copy_str(o: &mut Obj, n: &View, from: &str, to: &str) { - if let Some(s) = n.str(from) { - o.insert(to.into(), json!(s)); - } -} - -/// A node seen through override layers: the last layer with a field wins. -#[derive(Clone)] -struct View<'a> { - layers: Vec<&'a Kv<'a>>, - /// Size and transform worked out from the constraints, over the layers' own. - fitted: Option<((f64, f64), Affine)>, -} - -impl<'a> View<'a> { - fn of(n: &'a Kv<'a>) -> Self { - Self { layers: vec![n], fitted: None } - } - - fn size(&self) -> Option<(f64, f64)> { - self.fitted.map(|f| f.0).or_else(|| self.get("size").and_then(size)) - } - - fn transform(&self) -> Option { - self.fitted.map(|f| f.1).or_else(|| self.get("transform").and_then(matrix)) - } - - fn with(&self, top: impl IntoIterator>) -> Self { - let mut v = self.clone(); - v.layers.extend(top); - v - } - - /// This view with `style` just above the layer that links it in `key` (or `legacy`): the style - /// beats that layer's and lower layers' copies of its fields (stale when the style changed - /// since, or written for the style linked before), and override rows above the link beat it. - fn styled(&self, style: Option<&'a Kv<'a>>, key: &str, legacy: &str) -> Self { - let mut v = self.clone(); - if let Some(s) = style { - let linked_in = |k: &str| v.layers.iter().rposition(|l| l.get(k).is_some()); - let at = linked_in(key).or_else(|| linked_in(legacy)).map_or(1, |i| i + 1); - v.layers.insert(at.min(v.layers.len()), s); - } - v - } - - fn get(&self, k: &str) -> Option<&'a Kv<'a>> { - self.layers.iter().rev().find_map(|l| l.get(k)) - } - - fn num(&self, k: &str) -> Option { - self.get(k).and_then(Kv::f64) - } - - fn str(&self, k: &str) -> Option<&'a str> { - self.get(k).and_then(Kv::str) - } - - fn flag(&self, k: &str) -> Option { - self.get(k).and_then(Kv::bool) - } - - fn list(&self, k: &str) -> &'a [Kv<'a>] { - self.get(k).map(Kv::list).unwrap_or_default() - } -} - -struct Mapper<'a> { - nodes: BTreeMap>, - kids: BTreeMap>, - blobs: Vec<&'a [u8]>, - /// Component property definitions: id → (REST name "Name#id", type). - prop_defs: BTreeMap, - /// The copies of a set's definitions each variant keeps (no name or type of their own; the - /// variant's layers and its instances' assignments use them): copy id → the definition's id. - prop_parents: BTreeMap, - /// File nodes by asset `key` and `version`: references can name a collection, variable or - /// style as the asset instead of the guid, and the file carries the resources to resolve - /// them (the collection node itself says the same `key`). - assets: BTreeMap>, - styles: Obj, - /// Descriptions of components and component sets (REST `components` / `componentSets`). - components: Obj, - sets: Obj, - /// Layers and keys of each main, built when an instance of it first needs them. - override_scopes: BTreeMap>, - /// Entries held by `override_scopes` (bounded by `max_nodes` together). - override_scope_entries: usize, - /// Component-bearing branches of the file's internal canvases (cached library definitions). - library_contexts: Vec, - /// Layers visited while scanning internal canvases, across all of them. - library_scan_count: usize, - warnings: crate::rest::Warnings, - count: usize, - /// The mains in the file that instances or instance swap defaults name, and the mains mapped - /// as layers: the difference is what the layer cap kept out. - referenced_mains: BTreeSet, - mapped_mains: BTreeSet, - /// Most layers produced or scanned, instance expansion included; the one place the cap comes - /// from (see [`super::layer_budget`]). - max_nodes: usize, - /// Layers kept back for the visible pages' top level while library copies are mapped, so the - /// copies can't take the whole budget and leave the pages empty. - reserved: usize, - /// Vector networks, each built once: the layers that show one (every instance of a main - /// holding it) name it by `vectorNetworkRef`. Kept out of the JSON, where a large file's - /// networks took gigabytes. - networks: Vec>, - /// Index in `networks` by what a network is made from: its blob, its scale and its style table. - network_ids: HashMap<(usize, u64, u64, usize), usize>, - /// 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, -} - -impl<'a> Mapper<'a> { - fn new(msg: &'a Kv<'a>, max_nodes: usize) -> Self { - let mut nodes = BTreeMap::new(); - let mut kids: BTreeMap> = BTreeMap::new(); - let mut prop_defs = BTreeMap::new(); - let mut prop_parents = BTreeMap::new(); - let changes = msg.get("nodeChanges").map(Kv::list).unwrap_or_default(); - // The last change of a GUID wins; a REMOVED change deletes what came before it. - for n in changes { - let Some(id) = n.get("guid").and_then(guid) else { continue }; - if n.get("phase").and_then(Kv::str) == Some("REMOVED") { - nodes.remove(&id); - } else { - nodes.insert(id, n); - } - } - for n in changes { - let Some(id) = n.get("guid").and_then(guid) else { continue }; - if !nodes.get(&id).is_some_and(|latest| std::ptr::eq(*latest, n)) { - continue; - } - // Variables and their collections are read from the node list (`of_type`), never - // as layers: out of the layer tree, an instance's expansion doesn't walk them again for - // every instance without counting them (#1077). - if let Some(p) = n.get("parentIndex") - && let Some(parent) = p.get("guid").and_then(guid) - && !matches!(n.get("type").and_then(Kv::str), Some("VARIABLE" | "VARIABLE_SET")) - { - kids.entry(parent).or_default().push((p.get("position").and_then(Kv::str).unwrap_or(""), id.clone())); - } - for d in n.get("componentPropDefs").map(Kv::list).unwrap_or_default() { - let Some(did) = d.get("id").and_then(guid) else { continue }; - if let (Some(name), Some(ty)) = (d.get("name").and_then(Kv::str), d.get("type").and_then(Kv::str)) { - prop_defs.insert(did.clone(), (format!("{name}#{did}"), ty)); - } else if let Some(parent) = d.get("parentPropDefId").and_then(guid) { - prop_parents.insert(did, parent); - } - } - } - for list in kids.values_mut() { - list.sort(); - list.dedup_by(|a, b| a.1 == b.1); - } - let blobs = - msg.get("blobs").map(Kv::list).unwrap_or_default().iter().map(|b| b.get("bytes").and_then(Kv::bytes).unwrap_or_default()).collect(); - let mut assets: BTreeMap> = BTreeMap::new(); - for n in msg.get("nodeChanges").map(Kv::list).unwrap_or_default() { - let (Some(key), Some(id)) = (n.get("key").and_then(Kv::str), n.get("guid").and_then(guid)) else { continue }; - if key.is_empty() || key.len() > MAX_ASSET_PART { - continue; - } - let version = n.get("version").and_then(Kv::str).filter(|v| !v.is_empty() && v.len() <= MAX_ASSET_PART).unwrap_or(""); - assets.entry(key.to_string()).or_default().entry(version.to_string()).or_insert(id); - } - Self { - nodes, - kids, - blobs, - prop_defs, - prop_parents, - assets, - styles: Obj::new(), - components: Obj::new(), - sets: Obj::new(), - override_scopes: BTreeMap::new(), - override_scope_entries: 0, - library_contexts: Vec::new(), - library_scan_count: 0, - warnings: crate::rest::Warnings::default(), - count: 0, - referenced_mains: BTreeSet::new(), - mapped_mains: BTreeSet::new(), - max_nodes, - reserved: 0, - networks: Vec::new(), - network_ids: HashMap::new(), - region_paint_elements: 0, - } - } - - /// The id of the resource a `VariableSetID` (or `VariableID`, `StyleId`) names: its `guid`, - /// else the file node its asset `key` and `version` names (a collection from a library is - /// referenced as the asset, and the file's own node for it says the same `key`). `None` when - /// the reference has neither or the asset names nothing (or ambiguously) in the file. - /// Original code for this importer: the field names are those of the schema each file embeds. - fn resource_id(&self, v: &Kv) -> Option { - // A guid names the resource when this file holds a node by it. One from another file (the - // library a style or collection came from, as a paste carries) names nothing here: the - // asset it also names finds the file's copy (#1638). - if let Some(g) = v.get("guid").and_then(guid).filter(|g| *g != NO_STYLE && self.nodes.contains_key(g)) { - return Some(g); - } - let asset = v.get("assetRef")?; - let key = asset.get("key").and_then(Kv::str)?; - let versions = self.assets.get(key)?; - let version = asset.get("version").and_then(Kv::str); - match version { - Some(v) => versions.get(v), - // Without a version: an unversioned record, else the file's only one. - None => versions.get("").or_else(|| (versions.len() == 1).then(|| versions.values().next()).flatten()), - } - .cloned() - } - - /// The collection a `VariableSetID` names, as one collection per library asset: a file that - /// took several updates of a library holds a copy of the collection for each version it met, - /// all with the same asset `key`. Variables and explicit modes may name any of those copies, - /// while the mode ids stay the same across them, so every copy maps to the newest one (the - /// one [`Self::variables`] keeps, with the modes of the others added). Without this, a page set - /// to a mode an older copy didn't have yet lost its mode, and the layers fell back to the - /// default mode of the newest copy. - pub(super) fn collection_id(&self, v: &Kv) -> Option { - let id = self.resource_id(v)?; - Some(self.canonical_collection(&id).unwrap_or(id)) - } - - /// The newest live copy of collection node `id`'s library asset, when it has a key. - pub(super) fn canonical_collection(&self, id: &str) -> Option { - let key = self.nodes.get(id)?.get("key").and_then(Kv::str).filter(|k| !k.is_empty())?; - let live_set = |n: &Kv| n.get("type").and_then(Kv::str) == Some("VARIABLE_SET") && n.get("isSoftDeleted").and_then(Kv::bool) != Some(true); - self.assets - .get(key)? - .iter() - .filter(|(_, nid)| self.nodes.get(nid.as_str()).is_some_and(|n| live_set(n))) - .max_by_key(|(ver, _)| version_rank(ver)) - .map(|(_, nid)| nid.clone()) - } - - /// A note about what this file's mapping left out or changed. Counted, as the REST importer - /// counts its own: these notes are met once per layer, so the kinds were named once each with - /// no sign of how much of the file they covered -- a file whose every text layer lost a - /// setting read the same as one where a single layer did (#467). The collector keeps the - /// first-seen order and the same cap, since some notes name fields of the file (image - /// filters). - fn warn(&mut self, w: impl Into) { - self.warnings.add(w.into()); - } - - fn children(&self, id: &str) -> Vec { - self.kids.get(id).map(|k| k.iter().map(|(_, c)| c.clone()).collect()).unwrap_or_default() - } - - /// How many layers may be produced now: the cap, less what is kept for the visible pages. - fn budget(&self) -> usize { - self.max_nodes.saturating_sub(self.reserved) - } -} - -/// A library version (`"40727:1183"`) as numbers to order by; unparsable parts rank lowest. -fn version_rank(v: &str) -> (u64, u64) { - let mut parts = v.split(':').map(|p| p.trim().parse::().unwrap_or(0)); - (parts.next().unwrap_or(0), parts.next().unwrap_or(0)) -} - -/// Library variables, one per asset. A file that took several updates of a library keeps a copy -/// of a variable for each version it met (same `key`, another `version`), and layers and other -/// variables name them by that asset (`assetRef {key, version}`) rather than by guid. Each -/// reference goes to the newest copy: it has the values of every mode the library has now, where -/// an older one lacks the modes added since (a layer under a page set to such a mode fell back to -/// the default one). Kept per thread while a file is mapped: the paint and variable readers that -/// meet references are free functions. -#[derive(Default)] -pub(super) struct VarCanon { - by_key: HashMap, - by_id: HashMap, -} - -thread_local! { - static VAR_CANON: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; -} - -/// Removes the thread's table when the mapping is done. -pub(super) struct VarCanonGuard; - -impl Drop for VarCanonGuard { - fn drop(&mut self) { - VAR_CANON.with(|c| c.borrow_mut().take()); - } -} - -impl VarCanon { - fn install(m: &Mapper) -> VarCanonGuard { - let mut newest: HashMap = HashMap::new(); - let mut copies: Vec<(String, String)> = Vec::new(); - for (id, n) in &m.nodes { - if n.get("type").and_then(Kv::str) != Some("VARIABLE") || n.get("isSoftDeleted").and_then(Kv::bool) == Some(true) { - continue; - } - let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) else { continue }; - let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or("")); - copies.push((id.clone(), key.to_string())); - let e = newest.entry(key.to_string()).or_insert_with(|| (rank, id.clone())); - if rank > e.0 || (rank == e.0 && *id > e.1) { - *e = (rank, id.clone()); - } - } - let mut t = VarCanon::default(); - for (id, key) in copies { - if let Some((_, canon)) = newest.get(&key) { - t.by_id.insert(id, canon.clone()); - } - } - t.by_key = newest.into_iter().map(|(k, (_, id))| (k, id)).collect(); - VAR_CANON.with(|c| *c.borrow_mut() = Some(t)); - VarCanonGuard - } - - /// The variable a reference (`{guid}` or `{assetRef}`) names, as its newest copy. - pub(super) fn resolve(r: &Kv) -> Option { - let by_guid = r.get("guid").and_then(guid).filter(|g| g != NO_STYLE); - VAR_CANON.with(|c| { - let c = c.borrow(); - let Some(t) = c.as_ref() else { return by_guid.clone() }; - if let Some(g) = &by_guid { - return Some(t.by_id.get(g).cloned().unwrap_or_else(|| g.clone())); - } - let key = r.get("assetRef")?.get("key").and_then(Kv::str)?; - t.by_key.get(key).cloned() - }) - } - - /// Whether variable node `id` is an older copy another one replaces. - pub(super) fn superseded(id: &str) -> bool { - VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.by_id.get(id)).is_some_and(|canon| canon != id)) - } -} From 08537cf425c201be99db433e9d5f2e909de87c8d Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 13:55:16 +0330 Subject: [PATCH 056/326] Delete tests.rs --- tests.rs | 1588 ------------------------------------------------------ 1 file changed, 1588 deletions(-) delete mode 100644 tests.rs diff --git a/tests.rs b/tests.rs deleted file mode 100644 index 0e2c5016e..000000000 --- a/tests.rs +++ /dev/null @@ -1,1588 +0,0 @@ -//! `.fig` import tests on fixtures built in code: a small schema written in a compact text form, -//! a message encoded with our own kiwi encoder, compressed (deflate and zstd), framed and zipped. - -use std::io::Write; - -use figcraft_doc::{NodeKind, VariableType}; -use serde_json::Value; - -use super::kiwi::{Def, Field, Kind, Kv, Schema, Type, encode}; -use super::*; - -/// The fixture schema: `enum Name A B …`, `struct|message Name type field, type field[] …`. -/// Message field ids count from 1; enum values from 0. -const SCHEMA: &str = " -enum NodeType NONE DOCUMENT CANVAS GROUP FRAME BOOLEAN_OPERATION VECTOR STAR LINE ELLIPSE RECTANGLE REGULAR_POLYGON ROUNDED_RECTANGLE TEXT SLICE SYMBOL INSTANCE STICKY VARIABLE VARIABLE_SET SHAPE_WITH_TEXT CONNECTOR TABLE -enum PaintType SOLID GRADIENT_LINEAR IMAGE EMOJI -enum ImageScaleMode STRETCH FIT FILL TILE -enum WindingRule NONZERO ODD -enum StyleType NONE FILL TEXT -enum StackMode NONE HORIZONTAL VERTICAL -enum PropType BOOL TEXT -enum VariableField MISSING VISIBLE TEXT_DATA -enum DataType BOOLEAN FLOAT STRING ALIAS COLOR PROP_REF EXPRESSION -enum ResolvedType BOOLEAN FLOAT STRING COLOR -enum InteractionType ON_CLICK ON_HOVER -enum ConnectionType NONE INTERNAL_NODE URL BACK CLOSE SET_VARIABLE CONDITIONAL SET_VARIABLE_MODE -enum StrokeCap NONE ROUND SQUARE ARROW_LINES ARROW_EQUILATERAL -enum StrokeJoin MITER BEVEL ROUND -enum VectorMirror NONE ANGLE ANGLE_AND_LENGTH -enum ShapeWithTextType SQUARE ELLIPSE -enum ConnectorLineStyle ELBOWED STRAIGHT CURVED -enum ExpressionFunction ADDITION SUBTRACTION RESOLVE_VARIANT MULTIPLY DIVIDE EQUALS -enum NavigationType NAVIGATE OVERLAY -enum TransitionType INSTANT_TRANSITION DISSOLVE SMART_ANIMATE -enum EasingType IN_CUBIC OUT_CUBIC -enum ConstraintType MIN CENTER MAX STRETCH SCALE -enum LeadingTrim NONE CAP_HEIGHT -struct GUID uint sessionID, uint localID -struct Color float r, float g, float b, float a -struct Vector float x, float y -struct Matrix float m00, float m01, float m02, float m10, float m11, float m12 -struct ColorStop Color color, float position -message Image byte[] hash, string name, uint dataBlob -message AssetRef string key, string version -message VariableID GUID guid, AssetRef assetRef -message PropRefValue GUID defId -message AnyValue bool boolValue, float floatValue, VariableID alias, Color colorValue, PropRefValue propRefValue, TextData textDataValue, string textValue, Expression expressionValue -message Expression ExpressionFunction expressionFunction, VariableData[] expressionArguments -message VariableTarget VariableID id -message VariableSetID GUID guid, AssetRef assetRef -message ConditionalActions Action[] actions, VariableData condition -message VectorData uint vectorNetworkBlob, Vector normalizedSize, NodeChange[] styleOverrideTable -message ConnectorEndpoint GUID endpointNodeID, Vector position, Vector relativePosition -message VariableData AnyValue value, DataType dataType -message Paint PaintType type, Color color, float opacity, bool visible, Image image, Matrix transform, ColorStop[] stops, VariableData colorVar, ImageScaleMode imageScaleMode -message ParentIndex GUID guid, string position -message FontName string family, string style, string postscript -message TextData string characters, uint[] characterStyleIDs, NodeChange[] styleOverrideTable -message Path WindingRule windingRule, uint commandsBlob -message GUIDPath GUID[] guids -message SymbolData GUID symbolID, NodeChange[] symbolOverrides -message StyleId GUID guid, AssetRef assetRef -message PropValue bool boolValue, TextData textValue -message PropDef GUID id, string name, PropValue initialValue, PropType type -message PropAssignment GUID defID, PropValue value -message MapEntry VariableData variableData, VariableField variableField -message VariableDataMap MapEntry[] entries -message SetMode GUID id, string name, string sortPosition -message ValuesEntry GUID modeID, VariableData variableData -message Values ValuesEntry[] entries -message ModeEntry VariableID variableSetID, GUID variableModeID -message ModeMap ModeEntry[] entries -message Event InteractionType interactionType -message Action GUID transitionNodeID, TransitionType transitionType, float transitionDuration, EasingType easingType, ConnectionType connectionType, NavigationType navigationType, VariableTarget targetVariable, VariableData targetVariableData, VariableSetID targetVariableSetID, GUID targetVariableModeID, ConditionalActions[] conditionalActions -message Interaction Event event, Action[] actions -message StartingPoint string name, string position -message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern -message Blob byte[] bytes -message Message NodeChange[] nodeChanges, Blob[] blobs -"; - -pub(super) fn schema() -> Schema { - Schema::parse(SCHEMA).unwrap() -} - -pub(super) fn o(fields: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { - Kv::Object(fields) -} -pub(super) fn f(x: f64) -> Kv<'static> { - Kv::Float(x as f32) -} -pub(super) fn u(x: u64) -> Kv<'static> { - Kv::Uint(x) -} -pub(super) fn e(n: &'static str) -> Kv<'static> { - Kv::Enum(n) -} -pub(super) fn s(x: impl Into) -> Kv<'static> { - Kv::Str(x.into()) -} -pub(super) fn g(l: u64) -> Kv<'static> { - o(vec![("sessionID", u(1)), ("localID", u(l))]) -} -pub(super) fn arr(v: Vec>) -> Kv<'static> { - Kv::Array(v) -} -pub(super) fn xy(x: f64, y: f64) -> Kv<'static> { - o(vec![("x", f(x)), ("y", f(y))]) -} -pub(super) fn at(x: f64, y: f64) -> Kv<'static> { - o(vec![("m00", f(1.0)), ("m01", f(0.0)), ("m02", f(x)), ("m10", f(0.0)), ("m11", f(1.0)), ("m12", f(y))]) -} -fn rgb(r: f64, gr: f64, b: f64) -> Kv<'static> { - o(vec![("r", f(r)), ("g", f(gr)), ("b", f(b)), ("a", f(1.0))]) -} -pub(super) fn solid(r: f64, gr: f64, b: f64) -> Kv<'static> { - o(vec![("type", e("SOLID")), ("color", rgb(r, gr, b)), ("opacity", f(1.0)), ("visible", Kv::Bool(true))]) -} -fn root_guid() -> Kv<'static> { - o(vec![("sessionID", u(0)), ("localID", u(0))]) -} -fn alias_data(l: u64) -> Kv<'static> { - o(vec![("value", o(vec![("alias", o(vec![("guid", g(l))]))])), ("dataType", e("ALIAS"))]) -} -fn prop_ref(def: u64, field: &'static str) -> Kv<'static> { - let data = o(vec![("value", o(vec![("propRefValue", o(vec![("defId", g(def))]))])), ("dataType", e("PROP_REF"))]); - o(vec![("entries", arr(vec![o(vec![("variableData", data), ("variableField", e(field))])]))]) -} - -/// A node: id (0: the document), parent (id, position), type, name and further fields. -pub(super) fn node(id: u64, par: Option<(u64, &str)>, ty: &'static str, name: &str, mut more: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { - let mut v = vec![("guid", if id == 0 { root_guid() } else { g(id) })]; - if let Some((p, pos)) = par { - v.push(("parentIndex", o(vec![("guid", if p == 0 { root_guid() } else { g(p) }), ("position", s(pos))]))); - } - v.push(("type", e(ty))); - v.push(("name", s(name))); - v.append(&mut more); - o(v) -} - -/// A path blob: a closed triangle. -fn triangle_blob() -> Vec { - let mut b = Vec::new(); - for (cmd, pts) in [(1u8, vec![0.0f32, 0.0]), (2, vec![10.0, 0.0]), (2, vec![5.0, 8.0]), (0, vec![])] { - b.push(cmd); - for p in pts { - b.extend_from_slice(&p.to_le_bytes()); - } - } - b -} - -/// A 2×1 PNG. -pub(super) fn png() -> Vec { - let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([255, 0, 0, 255])); - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out -} - -const HASH: [u8; 20] = [0xab; 20]; - -/// The fixture message: a page with a frame holding a rectangle (image fill, click interaction), -/// a two-style text, a group with a triangle vector and a star, a layer with a linked fill style, -/// one with a variable-bound fill, and an instance of a component with a boolean property -/// (property off, child renamed); a flow and an explicit variable mode; an unsupported sticky -/// note; styles and variables on the internal page. -fn message() -> Kv<'static> { - let modes = arr(vec![ - o(vec![("id", g(90)), ("name", s("Light")), ("sortPosition", s("!"))]), - o(vec![("id", g(91)), ("name", s("Dark")), ("sortPosition", s("\""))]), - ]); - let color_value = |c| o(vec![("value", o(vec![("colorValue", c)])), ("dataType", e("COLOR"))]); - let values = o(vec![( - "entries", - arr(vec![ - o(vec![("modeID", g(90)), ("variableData", color_value(rgb(1.0, 1.0, 1.0)))]), - o(vec![("modeID", g(91)), ("variableData", color_value(rgb(0.0, 0.0, 0.0)))]), - ]), - )]); - let click = o(vec![ - ("event", o(vec![("interactionType", e("ON_CLICK"))])), - ( - "actions", - arr(vec![o(vec![ - ("transitionNodeID", g(20)), - ("transitionType", e("SMART_ANIMATE")), - ("transitionDuration", f(0.25)), - ("easingType", e("OUT_CUBIC")), - ("connectionType", e("INTERNAL_NODE")), - ("navigationType", e("NAVIGATE")), - ])]), - ), - ]); - let font = |style: &str| o(vec![("family", s("Inter")), ("style", s(style)), ("postscript", s(""))]); - let text = o(vec![ - ("characters", s("Hi there")), - ("characterStyleIDs", arr(vec![u(0), u(0), u(0), u(5), u(5), u(5)])), - ("styleOverrideTable", arr(vec![o(vec![("fontName", font("Bold")), ("styleID", u(5))])])), - ]); - let nodes = vec![ - node(0, None, "DOCUMENT", "Document", vec![]), - node(1, Some((0, "!")), "CANVAS", "Page A", vec![]), - node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), - node(3, Some((2, "!")), "RECTANGLE", "Brand", vec![("styleType", e("FILL")), ("fillPaints", arr(vec![solid(0.0, 0.0, 1.0)]))]), - node(4, Some((2, "\"")), "VARIABLE_SET", "Theme", vec![("variableSetModes", modes)]), - node( - 5, - Some((2, "#")), - "VARIABLE", - "surface", - vec![("variableSetID", o(vec![("guid", g(4))])), ("variableResolvedType", e("COLOR")), ("variableDataValues", values)], - ), - // Listed before the frame, but its position puts it second. - node( - 20, - Some((1, "\"")), - "SYMBOL", - "Button", - vec![ - ("size", xy(100.0, 40.0)), - ("transform", at(500.0, 0.0)), - ("fillPaints", arr(vec![solid(0.0, 1.0, 0.0)])), - ( - "componentPropDefs", - arr(vec![o(vec![ - ("id", g(80)), - ("name", s("Show icon")), - ("initialValue", o(vec![("boolValue", Kv::Bool(true))])), - ("type", e("BOOL")), - ])]), - ), - ("stackMode", e("HORIZONTAL")), - ("stackSpacing", f(8.0)), - ("stackHorizontalPadding", f(12.0)), - ("stackVerticalPadding", f(4.0)), - ], - ), - node( - 21, - Some((20, "!")), - "ELLIPSE", - "Icon", - vec![("size", xy(16.0, 16.0)), ("transform", at(12.0, 12.0)), ("parameterConsumptionMap", prop_ref(80, "VISIBLE"))], - ), - node( - 10, - Some((1, "!")), - "FRAME", - "Screen", - vec![ - ("size", xy(400.0, 300.0)), - ("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)])), - ("prototypeStartingPoint", o(vec![("name", s("Main flow")), ("position", s("!"))])), - ( - "variableModeBySetMap", - o(vec![("entries", arr(vec![o(vec![("variableSetID", o(vec![("guid", g(4))])), ("variableModeID", g(91))])]))]), - ), - ], - ), - node( - 11, - Some((10, "!")), - "ROUNDED_RECTANGLE", - "Photo", - vec![ - ("size", xy(50.0, 40.0)), - ("transform", at(10.0, 20.0)), - ("cornerRadius", f(6.0)), - ("fillPaints", arr(vec![o(vec![("type", e("IMAGE")), ("image", o(vec![("hash", Kv::Bytes(HASH.to_vec()))]))])])), - ("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])), - ("strokeWeight", f(2.0)), - ("prototypeInteractions", arr(vec![click])), - ], - ), - node( - 12, - Some((10, "\"")), - "TEXT", - "Title", - vec![ - ("size", xy(120.0, 20.0)), - ("transform", at(10.0, 80.0)), - ("fillPaints", arr(vec![solid(0.0, 0.0, 0.0)])), - ("fontSize", f(16.0)), - ("fontName", font("Regular")), - ("leadingTrim", e("CAP_HEIGHT")), - ("textData", text), - ], - ), - node(13, Some((10, "#")), "FRAME", "Group", vec![("size", xy(30.0, 30.0)), ("transform", at(100.0, 100.0)), ("resizeToFit", Kv::Bool(true))]), - node( - 14, - Some((13, "!")), - "VECTOR", - "Tri", - vec![ - ("size", xy(10.0, 8.0)), - ("transform", at(5.0, 6.0)), - ("fillPaints", arr(vec![solid(1.0, 0.0, 0.0)])), - ("fillGeometry", arr(vec![o(vec![("windingRule", e("NONZERO")), ("commandsBlob", u(0))])])), - ], - ), - node( - 15, - Some((13, "\"")), - "STAR", - "Star", - vec![("size", xy(20.0, 20.0)), ("transform", at(10.0, 10.0)), ("count", u(6)), ("starInnerScale", f(0.5))], - ), - node( - 16, - Some((10, "$")), - "ROUNDED_RECTANGLE", - "Styled", - vec![ - ("size", xy(10.0, 10.0)), - ("transform", at(0.0, 200.0)), - // A stale copy of the style's paint: the style wins. - ("fillPaints", arr(vec![solid(0.5, 0.5, 0.5)])), - ("styleIdForFill", o(vec![("guid", g(3))])), - ], - ), - node( - 17, - Some((10, "%")), - "ROUNDED_RECTANGLE", - "Card", - vec![ - ("size", xy(10.0, 10.0)), - ("transform", at(20.0, 200.0)), - ("fillPaints", arr(vec![o(vec![("type", e("SOLID")), ("color", rgb(0.0, 0.0, 0.0)), ("colorVar", alias_data(5))])])), - ], - ), - node( - 18, - Some((10, "&")), - "INSTANCE", - "Button copy", - vec![ - ("size", xy(100.0, 40.0)), - ("transform", at(200.0, 200.0)), - ("fillPaints", arr(vec![solid(1.0, 0.0, 0.0)])), - ("stackMode", e("HORIZONTAL")), - ( - "symbolData", - o(vec![ - ("symbolID", g(20)), - ("symbolOverrides", arr(vec![o(vec![("guidPath", o(vec![("guids", arr(vec![g(21)]))])), ("name", s("Renamed icon"))])])), - ]), - ), - ("componentPropAssignments", arr(vec![o(vec![("defID", g(80)), ("value", o(vec![("boolValue", Kv::Bool(false))]))])])), - ], - ), - node(19, Some((10, "'")), "STICKY", "Note", vec![]), - ]; - o(vec![("nodeChanges", arr(nodes)), ("blobs", arr(vec![o(vec![("bytes", Kv::Bytes(triangle_blob()))])]))]) -} - -/// `canvas.fig`: magic, version, deflated schema, zstd message. -pub(super) fn canvas(schema: &Schema, msg: &Kv) -> Vec { - let root = schema.find("Message").unwrap(); - let mut z = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); - z.write_all(&encode::schema(schema)).unwrap(); - let schema_chunk = z.finish().unwrap(); - let msg_chunk = ruzstd::encoding::compress_to_vec(&encode::message(schema, root, msg).unwrap()[..], ruzstd::encoding::CompressionLevel::Fastest); - let mut out = b"fig-kiwi".to_vec(); - out.extend_from_slice(&101u32.to_le_bytes()); - for c in [schema_chunk, msg_chunk] { - out.extend_from_slice(&(c.len() as u32).to_le_bytes()); - out.extend_from_slice(&c); - } - out -} - -fn zip_file(canvas: &[u8]) -> Vec { - let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); - let image_name = format!("images/{}", HASH.iter().map(|b| format!("{b:02x}")).collect::()); - for (name, bytes) in [("canvas.fig", canvas.to_vec()), ("meta.json", br#"{"file_name":"Fixture"}"#.to_vec()), (image_name.as_str(), png())] { - z.start_file(name, stored).unwrap(); - z.write_all(&bytes).unwrap(); - } - z.finish().unwrap().into_inner() -} - -fn fixture() -> Vec { - zip_file(&canvas(&schema(), &message())) -} - -fn named<'d>(doc: &'d figcraft_doc::Document, name: &str) -> &'d figcraft_doc::Node { - doc.nodes().find(|n| n.name == name).unwrap_or_else(|| panic!("no layer {name}")) -} - -/// The shared schema plus the grid sizing definitions only these tests use. -fn grid_schema() -> Schema { - const NODE_FIELDS: &str = ", GridTrackMap gridColumns, GridTrackMap gridRows, GridTrackSizeMap gridColumnsSizing, GridTrackSizeMap gridRowsSizing, GUID gridColumnAnchor, GUID gridRowAnchor, uint gridColumnSpan, uint gridRowSpan, float gridColumnGap, float gridRowGap"; - const TYPES: &str = " -enum GridTrackSizingType FLEX FIXED HUG UNKNOWN -message GridTrackSizeFunction GridTrackSizingType type, float value -message GridTrackSize GridTrackSizeFunction minSizing, GridTrackSizeFunction maxSizing -message GridTrackSizeEntry GUID id, GridTrackSize trackSize -message GridTrackSizeMap GridTrackSizeEntry[] entries -message GridTrackEntry GUID id, string position -message GridTrackMap GridTrackEntry[] entries -message Blob "; - let text = SCHEMA.replace("enum StackMode NONE HORIZONTAL VERTICAL\n", "enum StackMode NONE HORIZONTAL VERTICAL GRID\n").replacen( - "\nmessage Blob ", - &format!("{NODE_FIELDS}{TYPES}"), - 1, - ); - Schema::parse(&text).unwrap() -} - -fn track_size(kind: &'static str, value: f64) -> Kv<'static> { - let sizing = || o(vec![("type", e(kind)), ("value", f(value))]); - o(vec![("minSizing", sizing()), ("maxSizing", sizing())]) -} - -fn ranged_track_size(min: Kv<'static>, max: Kv<'static>) -> Kv<'static> { - o(vec![("minSizing", min), ("maxSizing", max)]) -} - -fn track_map_entry(id: u64, size: Kv<'static>) -> Kv<'static> { - o(vec![("id", g(id)), ("trackSize", size)]) -} - -fn positioned_track(id: u64, position: &'static str) -> Kv<'static> { - o(vec![("id", g(id)), ("position", s(position))]) -} - -fn unpositioned_track(id: u64) -> Kv<'static> { - o(vec![("id", g(id))]) -} - -#[test] -fn grid_tracks_import_by_guid_and_keep_track_order() { - let cols = arr(vec![positioned_track(13, "$"), unpositioned_track(10), positioned_track(12, "#"), unpositioned_track(11)]); - let rows = arr(vec![positioned_track(21, "\""), positioned_track(20, "!")]); - // Sizing entries intentionally differ from track order. Their GUIDs define the join. - let col_sizes = arr(vec![ - track_map_entry(12, track_size("FLEX", 1.0)), - track_map_entry(10, track_size("FIXED", 120.0)), - track_map_entry(13, track_size("FLEX", 2.0)), - track_map_entry(11, track_size("HUG", 80.0)), - ]); - let row_sizes = arr(vec![track_map_entry(21, track_size("HUG", 30.0)), track_map_entry(20, track_size("FIXED", 50.0))]); - let nodes = vec![ - node(0, None, "DOCUMENT", "Document", vec![]), - node(1, Some((0, "!")), "CANVAS", "Page", vec![]), - node( - 2, - Some((1, "!")), - "FRAME", - "Grid", - vec![ - ("size", xy(600.0, 300.0)), - ("transform", at(0.0, 0.0)), - ("stackMode", e("GRID")), - ("gridColumns", o(vec![("entries", cols)])), - ("gridRows", o(vec![("entries", rows)])), - ("gridColumnsSizing", o(vec![("entries", col_sizes)])), - ("gridRowsSizing", o(vec![("entries", row_sizes)])), - ("gridColumnGap", f(10.0)), - ("gridRowGap", f(12.0)), - ], - ), - node( - 3, - Some((2, "!")), - "RECTANGLE", - "Hug child", - vec![ - ("size", xy(80.0, 30.0)), - ("transform", at(0.0, 0.0)), - ("gridColumnAnchor", g(11)), - ("gridRowAnchor", g(21)), - ("gridColumnSpan", u(2)), - ("gridRowSpan", u(1)), - ], - ), - ]; - let bytes = canvas(&grid_schema(), &o(vec![("nodeChanges", arr(nodes))])); - let (doc, warnings) = import(&bytes, "Grid tracks").unwrap(); - let grid = named(&doc, "Grid").layout.as_ref().unwrap(); - assert_eq!((grid.mode, grid.grid_columns, grid.grid_rows, grid.gap, grid.cross_gap), (figcraft_doc::LayoutMode::Grid, 4, 2, 10.0, 12.0)); - assert_eq!( - grid.column_tracks, - vec![ - figcraft_doc::GridTrack::fixed(120.0), - figcraft_doc::GridTrack::hug(), - figcraft_doc::GridTrack::fill(1.0), - figcraft_doc::GridTrack::fill(2.0), - ] - ); - assert_eq!(grid.row_tracks, vec![figcraft_doc::GridTrack::fixed(50.0), figcraft_doc::GridTrack::hug()]); - let child = &named(&doc, "Hug child").child_layout; - assert_eq!((child.grid_column, child.grid_row, child.grid_column_span, child.grid_row_span), (Some(1), Some(1), 2, 1)); - assert!(!warnings.iter().any(|w| w.contains("grid track")), "{warnings:?}"); -} - -#[test] -fn malformed_grid_tracks_warn_and_keep_equal_track_fallbacks() { - let tracks = arr(vec![positioned_track(30, "!"), positioned_track(31, "\""), positioned_track(32, "#"), positioned_track(33, "$")]); - let sizing = arr(vec![ - track_map_entry(30, track_size("FIXED", -1.0)), - track_map_entry(31, ranged_track_size(o(vec![("type", e("FLEX")), ("value", f(1.0))]), o(vec![("type", e("FLEX")), ("value", f(2.0))]))), - track_map_entry(33, track_size("UNKNOWN", 5.0)), - track_map_entry(34, track_size("FLEX", 3.0)), - ]); - let nodes = vec![ - node(0, None, "DOCUMENT", "Document", vec![]), - node(1, Some((0, "!")), "CANVAS", "Page", vec![]), - node( - 2, - Some((1, "!")), - "FRAME", - "Grid", - vec![ - ("size", xy(100.0, 100.0)), - ("transform", at(0.0, 0.0)), - ("stackMode", e("GRID")), - ("gridColumns", o(vec![("entries", tracks)])), - ("gridColumnsSizing", o(vec![("entries", sizing)])), - ], - ), - ]; - let bytes = canvas(&grid_schema(), &o(vec![("nodeChanges", arr(nodes))])); - let (doc, warnings) = import(&bytes, "Malformed grid tracks").unwrap(); - let layout = named(&doc, "Grid").layout.as_ref().unwrap(); - assert_eq!(layout.column_tracks, vec![figcraft_doc::GridTrack::default(); 4]); - assert!(warnings.iter().any(|w| w.contains("grid track sizing is unsupported or malformed")), "{warnings:?}"); - assert!(warnings.iter().any(|w| w.contains("stale or invalid grid track sizing entries")), "{warnings:?}"); -} - -#[test] -fn oversized_grid_track_lists_warn_and_use_default_tracks() { - let oversized: Vec> = (0..1_001).map(|i| unpositioned_track(100 + i)).collect(); - let sizing = vec![track_map_entry(100, track_size("FIXED", 40.0))]; - let nodes = vec![ - node(0, None, "DOCUMENT", "Document", vec![]), - node(1, Some((0, "!")), "CANVAS", "Page", vec![]), - node( - 2, - Some((1, "!")), - "FRAME", - "Grid", - vec![ - ("size", xy(100.0, 100.0)), - ("transform", at(0.0, 0.0)), - ("stackMode", e("GRID")), - ("gridColumns", o(vec![("entries", arr(oversized))])), - ("gridColumnsSizing", o(vec![("entries", arr(sizing))])), - ], - ), - ]; - let bytes = canvas(&grid_schema(), &o(vec![("nodeChanges", arr(nodes))])); - let (doc, warnings) = import(&bytes, "Oversized grid tracks").unwrap(); - let layout = named(&doc, "Grid").layout.as_ref().unwrap(); - assert!(layout.column_tracks.is_empty(), "{:?}", layout.column_tracks.len()); - assert!(warnings.iter().any(|w| w.contains("grid track list exceeds 1000 entries")), "{warnings:?}"); -} - -#[test] -fn kiwi_round_trip() { - let sc = schema(); - let back = Schema::decode(&encode::schema(&sc)).unwrap(); - assert_eq!(back.defs.len(), sc.defs.len()); - for (a, b) in sc.defs.iter().zip(&back.defs) { - assert_eq!((a.name.as_str(), a.kind), (b.name.as_str(), b.kind)); - let fields = |d: &Def| d.fields.iter().map(|f| (f.name.clone(), f.ty, f.array, f.value)).collect::>(); - assert_eq!(fields(a), fields(b)); - } - let msg = message(); - let root = sc.find("Message").unwrap(); - assert_eq!(back.decode_message(root, &encode::message(&sc, root, &msg).unwrap()).unwrap(), msg); -} - -#[test] -fn kiwi_scalars() { - let names = ["f", "i", "u", "i64", "u64", "s", "b"]; - let types = [Type::Float, Type::Int, Type::Uint, Type::Int64, Type::Uint64, Type::Str, Type::Bool]; - let fields = names - .iter() - .zip(types) - .enumerate() - .map(|(i, (n, t))| Field { name: n.to_string(), ty: Some(t), array: false, value: i as u32 + 1 }) - .collect(); - let sc = Schema { defs: vec![Def { name: "M".into(), kind: Kind::Message, fields }] }; - let cases = [ - (0.0f32, 0i32, 0u32, 0i64, 0u64), - (-1.5, -7, 300, i64::MIN, u64::MAX), - (3.25e7, i32::MAX, u32::MAX, i64::MAX, 1 << 60), - (1e-40, i32::MIN, 1, -1, 127), - ]; - for (fv, iv, uv, i64v, u64v) in cases { - // Written by hand: the generic encoder goes through f64, which can't hold every 64-bit value. - let mut w = encode::Writer::default(); - w.var_uint(1); - w.var_float(fv); - w.var_uint(2); - w.var_int(iv); - w.var_uint(3); - w.var_uint(uv); - w.var_uint(4); - w.var_int64(i64v); - w.var_uint(5); - w.var_uint64(u64v); - w.var_uint(6); - w.string("héllo"); - w.var_uint(7); - w.byte(1); - w.var_uint(0); - let got = sc.decode_message(0, &w.0).unwrap(); - // Denormals are stored as zero. - let want_f = if fv.abs() < f32::MIN_POSITIVE { 0.0 } else { fv }; - assert_eq!(got.get("f"), Some(&Kv::Float(want_f))); - assert_eq!(got.get("i"), Some(&Kv::Int(i64::from(iv)))); - assert_eq!(got.get("u"), Some(&Kv::Uint(u64::from(uv)))); - assert_eq!(got.get("i64"), Some(&Kv::Int(i64v))); - assert_eq!(got.get("u64"), Some(&Kv::Uint(u64v))); - assert_eq!(got.get("s"), Some(&s("héllo"))); - assert_eq!(got.get("b"), Some(&Kv::Bool(true))); - } -} - -#[test] -fn imports_the_fixture() { - let bytes = fixture(); - assert!(is_fig(&bytes)); - let (doc, warnings) = import(&bytes, "fallback").unwrap(); - assert_eq!(doc.name, "Fixture"); - assert_fixture_layers(&doc); - assert_fixture_styles(&doc); - assert_fixture_variables(&doc); - assert_fixture_components(&doc); - assert_fixture_prototype(&doc, &warnings); -} - -fn assert_fixture_layers(doc: &Document) { - // The internal page is skipped. - assert_eq!(doc.pages.len(), 1); - let page = doc.node(doc.pages[0]).unwrap(); - assert_eq!(page.name, "Page A"); - // Siblings by position: the frame comes first even though it's listed after the component. - assert_eq!(doc.node(page.children[0]).unwrap().name, "Screen"); - let screen = named(doc, "Screen"); - let names: Vec<&str> = screen.children.iter().map(|c| doc.node(*c).unwrap().name.as_str()).collect(); - assert_eq!(names, ["Photo", "Title", "Group", "Styled", "Card", "Button copy", "Note"]); - // Image fill from the archive. - let photo = named(doc, "Photo"); - let figcraft_doc::color::PaintKind::Image(img) = &photo.fills[0].kind else { panic!("not an image fill") }; - assert_eq!(doc.images.get(&img.image).map(|i| (i.width, i.height)), Some((2, 1))); - assert_eq!((photo.corners.radii[0], photo.stroke.weight), (6.0, 2.0)); - // Text with a bold run over "the". - let NodeKind::Text(t) = &named(doc, "Title").kind else { panic!("not text") }; - assert_eq!(t.characters, "Hi there"); - assert_eq!(t.style.font_size, 16.0); - assert_eq!(t.leading_trim, figcraft_doc::LeadingTrim::CapHeight, "vertical trim (#466)"); - assert_eq!(t.runs.len(), 1); - assert_eq!((t.runs[0].start, t.runs[0].end, t.runs[0].style.font_style.as_str()), (3, 6, "Bold")); - // The group's children keep their place on the page (group at 100, 100). - assert!(matches!(named(doc, "Group").kind, NodeKind::Group)); - let tri = named(doc, "Tri"); - assert!(matches!(&tri.kind, NodeKind::Vector { network } if !network.regions.is_empty())); - let abs = doc.world_transform(tri.id).translation(); - assert!((abs.x - 105.0).abs() < 1e-6 && (abs.y - 106.0).abs() < 1e-6, "{abs:?}"); - assert!(matches!(named(doc, "Star").kind, NodeKind::Star { count: 6, .. })); -} - -fn assert_fixture_styles(doc: &Document) { - let styled = named(doc, "Styled"); - assert_eq!(styled.styles.fill.as_deref(), Some("1:3")); - assert!(doc.styles.iter().any(|s| s.name == "Brand")); - let figcraft_doc::color::PaintKind::Solid { color } = styled.fills[0].kind else { panic!("not solid") }; - assert_eq!((color.r, color.g, color.b), (0.0, 0.0, 1.0)); -} - -fn assert_fixture_variables(doc: &Document) { - let screen = named(doc, "Screen"); - assert_eq!(doc.variables.collections.len(), 1); - assert_eq!(doc.variables.variables[0].kind, VariableType::Color); - assert_eq!(named(doc, "Card").bound.get("fill").map(String::as_str), Some("1:5")); - assert_eq!(screen.var_modes.get("1:4").map(String::as_str), Some("1:91")); -} - -fn assert_fixture_components(doc: &Document) { - let button = named(doc, "Button"); - assert!(matches!(&button.kind, NodeKind::Component { props, .. } if props.contains_key("Show icon"))); - let inst = named(doc, "Button copy"); - assert!( - matches!(&inst.kind, NodeKind::Instance { component, props } if *component == button.id && props.get("Show icon") == Some(&Value::Bool(false))) - ); - let icon = doc.node(inst.children[0]).unwrap(); - assert_eq!(icon.name, "Renamed icon"); - assert!(!icon.visible); -} - -fn assert_fixture_prototype(doc: &Document, warnings: &[String]) { - let button = named(doc, "Button"); - let screen = named(doc, "Screen"); - let it = &named(doc, "Photo").interactions[0]; - assert!(matches!(it.actions[0], figcraft_doc::proto::Action::Navigate { dest, .. } if dest == button.id)); - assert_eq!(it.duration_ms, 250); - let Some(NodeKind::Page { flows, .. }) = doc.node(doc.pages[0]).map(|p| &p.kind) else { panic!("no page") }; - assert_eq!((flows[0].name.as_str(), flows[0].start), ("Main flow", screen.id)); - // The sticky note comes in as a frame, with a warning. - assert!(matches!(named(doc, "Note").kind, NodeKind::Frame)); - assert!(warnings.iter().any(|w| w.contains("sticky layers import as frames")), "{warnings:?}"); -} - -#[test] -fn bare_canvas_and_zlib_chunks_open() { - let sc = schema(); - let c = canvas(&sc, &message()); - let (doc, w) = import(&c, "Bare").unwrap(); - assert_eq!(doc.name, "Bare"); - // Without the archive the image is a placeholder, reported. - assert!(w.iter().any(|w| w.contains("isn't in the file")), "{w:?}"); - // A zlib-wrapped schema chunk reads too. - let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); - z.write_all(&encode::schema(&sc)).unwrap(); - let zl = z.finish().unwrap(); - let parts = chunks(&c).unwrap(); - let mut out = c[..12].to_vec(); - for ch in [zl.as_slice(), parts[1]] { - out.extend_from_slice(&(ch.len() as u32).to_le_bytes()); - out.extend_from_slice(ch); - } - assert!(import(&out, "Z").is_ok()); -} - -/// The fixture message with the photo's image bytes in its own blobs, as copies written by plugins -/// and tools carry them: the PNG goes at the end of `blobs` and `image.dataBlob` points `shift` -/// places past it (0 is the PNG itself). -fn message_with_image_in_blobs(shift: u64) -> Kv<'static> { - fn point_images_at(value: &mut Kv<'static>, blob: u64) { - match value { - Kv::Object(fields) => { - for (name, field) in fields.iter_mut() { - match field { - Kv::Object(image) if *name == "image" => image.push(("dataBlob", u(blob))), - _ => point_images_at(field, blob), - } - } - } - Kv::Array(items) => items.iter_mut().for_each(|item| point_images_at(item, blob)), - _ => {} - } - } - let mut msg = message(); - let index = { - let Kv::Object(fields) = &mut msg else { panic!("the message is an object") }; - let Some((_, Kv::Array(blobs))) = fields.iter_mut().find(|(name, _)| *name == "blobs") else { panic!("no blobs") }; - blobs.push(o(vec![("bytes", Kv::Bytes(png()))])); - blobs.len() as u64 - 1 - }; - point_images_at(&mut msg, index + shift); - msg -} - -#[test] -fn a_bare_canvas_reads_images_carried_in_its_blobs() { - // The clipboard holds a bare canvas (no `images/`); the image comes from `image.dataBlob`. - let c = canvas(&schema(), &message_with_image_in_blobs(0)); - let (doc, warnings) = import(&c, "Pasted").unwrap(); - let photo = named(&doc, "Photo"); - let figcraft_doc::color::PaintKind::Image(img) = &photo.fills[0].kind else { panic!("not an image fill") }; - assert_eq!(doc.images.get(&img.image).map(|i| (i.width, i.height)), Some((2, 1))); - assert!(!warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); -} - -#[test] -fn a_data_blob_past_the_blobs_stays_a_placeholder() { - let c = canvas(&schema(), &message_with_image_in_blobs(5)); - let (_, warnings) = import(&c, "Pasted").unwrap(); - assert!(warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); -} - -/// A file can point any number of image hashes at one large blob; each used to get its own copy -/// of it (#1059). -#[test] -fn hashes_naming_one_blob_share_one_copy_of_it() { - let image = |hash: u8, blob: u64| o(vec![("image", o(vec![("hash", Kv::Bytes(vec![hash; 20])), ("dataBlob", u(blob))]))]); - let msg = o(vec![ - ("blobs", Kv::Array(vec![o(vec![("bytes", Kv::Bytes(png()))]), o(vec![("bytes", Kv::Bytes(vec![7; 16]))])])), - ("nodeChanges", Kv::Array((1..=50).map(|h| image(h, 0)).chain([image(99, 1), image(98, 2)]).collect())), - ]); - let copies = embedded_copies(&msg); - assert_eq!(copies.len(), 51, "the hash naming no blob is left out"); - let first = &copies[&"01".repeat(20)]; - assert_eq!(**first, *png()); - assert_eq!(copies.values().filter(|c| Arc::ptr_eq(c, first)).count(), 50); - assert_eq!(*copies[&"63".repeat(20)], [7; 16]); -} - -mod image_budget { - use super::*; - - fn image(hash: u8) -> Vec { - let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([hash, 0, 0, 255])); - let mut out = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out - } - - fn file(references: &[u8], members: &[(u8, Vec)]) -> Vec { - let mut nodes = vec![node(0, None, "DOCUMENT", "Document", vec![]), node(1, Some((0, "!")), "CANVAS", "Page", vec![])]; - for (i, hash) in references.iter().enumerate() { - nodes.push(node( - i as u64 + 2, - Some((1, &format!("{i:04}"))), - "RECTANGLE", - &format!("Image {i}"), - vec![ - ("size", xy(10.0, 10.0)), - ("fillPaints", arr(vec![o(vec![("type", e("IMAGE")), ("image", o(vec![("hash", Kv::Bytes(vec![*hash; 20]))]))])])), - ], - )); - } - let canvas = canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])); - let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let deflated = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); - z.start_file("canvas.fig", deflated).unwrap(); - z.write_all(&canvas).unwrap(); - for (hash, bytes) in members { - z.start_file(format!("images/{}", format!("{hash:02x}").repeat(20)), deflated).unwrap(); - z.write_all(bytes).unwrap(); - } - z.finish().unwrap().into_inner() - } - - fn bytes(doc: &Document, index: usize) -> &[u8] { - let node = named(doc, &format!("Image {index}")); - let figcraft_doc::color::PaintKind::Image(fill) = &node.fills[0].kind else { panic!("not an image fill") }; - &doc.images[&fill.image].bytes - } - - fn budget_warnings(warnings: &[String]) -> Vec<&str> { - warnings.iter().filter(|w| w.contains("total ZIP image byte budget")).map(String::as_str).collect() - } - - fn change_member_field(zip: &mut [u8], hash: u8, offset: usize, value: u32) { - let start = { - let mut z = zip::ZipArchive::new(std::io::Cursor::new(&*zip)).unwrap(); - z.by_name(&format!("images/{}", format!("{hash:02x}").repeat(20))).unwrap().central_header_start() as usize - }; - zip[start + offset..start + offset + 4].copy_from_slice(&value.to_le_bytes()); - } - - #[test] - fn exact_total_limit_keeps_all_images_and_each_import_gets_its_own_budget() { - let members = [(1, image(1)), (2, image(2))]; - let limit = members.iter().map(|(_, b)| b.len() as u64).sum(); - let zip = file(&[1, 2], &members); - for _ in 0..2 { - let (doc, warnings) = import_with_image_limit(&zip, "Images", limit).unwrap(); - assert_eq!(bytes(&doc, 0), members[0].1); - assert_eq!(bytes(&doc, 1), members[1].1); - assert!(warnings.is_empty(), "{warnings:?}"); - } - } - - #[test] - fn individually_acceptable_images_overflow_the_total_and_leave_placeholders() { - let members = [(1, image(1)), (2, image(2))]; - let limit = members.iter().map(|(_, b)| b.len() as u64).sum::() - 1; - assert!(members.iter().all(|(_, b)| b.len() as u64 <= limit)); - let (doc, warnings) = import_with_image_limit(&file(&[1, 2], &members), "Images", limit).unwrap(); - assert_eq!(bytes(&doc, 0), members[0].1); - assert_ne!(bytes(&doc, 1), members[1].1); - assert!(!doc.images.contains_key(&crate::image_hash(&members[1].1))); - let notes = budget_warnings(&warnings); - assert_eq!(notes.len(), 1, "{warnings:?}"); - assert!(notes[0].contains("1 ZIP image") && notes[0].contains(&limit.to_string()), "{warnings:?}"); - } - - #[test] - fn repeated_references_do_not_charge_or_count_a_rejection_twice() { - let members = [(1, image(1)), (2, image(2))]; - let (doc, warnings) = import_with_image_limit(&file(&[1, 1, 2, 2, 1], &members), "Images", members[0].1.len() as u64).unwrap(); - for i in [0, 1, 4] { - assert_eq!(bytes(&doc, i), members[0].1); - } - assert_eq!(bytes(&doc, 2), bytes(&doc, 3)); - assert_ne!(bytes(&doc, 2), members[1].1); - let notes = budget_warnings(&warnings); - assert_eq!(notes.len(), 1, "{warnings:?}"); - assert!(notes[0].contains("1 ZIP image"), "{warnings:?}"); - } - - #[test] - fn distinct_members_with_identical_contents_still_use_the_read_budget() { - let png = image(1); - let members = [(1, png.clone()), (2, png.clone())]; - let (doc, warnings) = import_with_image_limit(&file(&[1, 2], &members), "Images", png.len() as u64).unwrap(); - assert_eq!(bytes(&doc, 0), png); - assert_ne!(bytes(&doc, 1), png); - assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); - } - - #[test] - fn rejecting_a_member_before_reading_leaves_room_for_a_smaller_one() { - let png = image(1); - let members = [(1, vec![0; png.len() + 1]), (2, png.clone())]; - let (doc, warnings) = import_with_image_limit(&file(&[1, 2], &members), "Images", png.len() as u64).unwrap(); - assert_ne!(bytes(&doc, 0), members[0].1); - assert_eq!(bytes(&doc, 1), png); - assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); - } - - #[test] - fn failed_crc_reads_still_consume_the_bytes_read() { - let members = [(1, image(1)), (2, image(2))]; - let mut zip = file(&[1, 2], &members); - change_member_field(&mut zip, 1, 16, 0); - let (doc, warnings) = import_with_image_limit(&zip, "Images", members[0].1.len() as u64 + 1).unwrap(); - assert_ne!(bytes(&doc, 0), members[0].1); - assert_ne!(bytes(&doc, 1), members[1].1); - assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); - } - - #[test] - fn a_truncated_deflate_read_keeps_its_partial_charge() { - let members = [(1, image(1)), (2, image(2))]; - let mut zip = file(&[1, 2], &members); - // Shorten the first member's compressed size, cutting its deflate stream mid-image. - change_member_field(&mut zip, 1, 20, 15); - let limit = members[0].1.len() as u64; - let archive = Archive::open(&zip).unwrap(); - archive.image_budget.remaining.set(limit); - assert!(archive.image(&"01".repeat(20)).is_none()); - let remaining = archive.image_budget.remaining.get(); - assert!(remaining > 0 && remaining < limit, "partial read left {remaining} of {limit} bytes"); - assert!(archive.image(&"02".repeat(20)).is_none()); - assert_eq!(archive.image_budget.remaining.get(), remaining); - let (doc, warnings) = import_with_image_limit(&zip, "Images", limit).unwrap(); - assert_ne!(bytes(&doc, 1), members[1].1); - assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); - } - - #[test] - fn the_individual_image_cap_is_preserved_without_reading_a_large_member() { - let members = [(1, image(1)), (2, image(2))]; - let mut zip = file(&[1, 2], &members); - change_member_field(&mut zip, 1, 24, (MAX_IMAGE + 1) as u32); - let (doc, warnings) = import_with_image_limit(&zip, "Images", members[1].1.len() as u64).unwrap(); - assert_ne!(bytes(&doc, 0), members[0].1); - assert_eq!(bytes(&doc, 1), members[1].1); - assert!(budget_warnings(&warnings).is_empty(), "{warnings:?}"); - } - - #[test] - fn crc_is_checked_even_when_the_read_ends_exactly_at_the_budget() { - let members = [(1, image(1))]; - let mut zip = file(&[1], &members); - change_member_field(&mut zip, 1, 16, 0); - let (doc, warnings) = import_with_image_limit(&zip, "Images", members[0].1.len() as u64).unwrap(); - assert_ne!(bytes(&doc, 0), members[0].1); - assert!(warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); - assert!(budget_warnings(&warnings).is_empty(), "{warnings:?}"); - } - - #[test] - fn an_understated_size_cannot_read_past_the_remaining_budget() { - let members = [(1, image(1)), (2, image(2))]; - let mut zip = file(&[1, 2], &members); - change_member_field(&mut zip, 1, 24, 1); - let archive = Archive::open(&zip).unwrap(); - archive.image_budget.remaining.set(members[0].1.len() as u64 - 1); - assert!(archive.image(&"01".repeat(20)).is_none()); - assert_eq!(archive.image_budget.remaining.get(), 0); - assert_eq!(archive.image_budget.skipped.get(), 1); - assert!(archive.image(&"02".repeat(20)).is_none()); - assert_eq!(archive.image_budget.remaining.get(), 0); - assert_eq!(archive.image_budget.skipped.get(), 2); - } - - #[test] - fn invalid_image_contents_are_charged_before_image_validation() { - let members = [(1, vec![0; 8]), (2, image(2))]; - let limit = members[1].1.len() as u64 + 7; - let (doc, warnings) = import_with_image_limit(&file(&[1, 2], &members), "Images", limit).unwrap(); - assert_ne!(bytes(&doc, 1), members[1].1); - assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); - } - - #[test] - fn missing_and_unreferenced_members_do_not_consume_the_budget() { - let members = [(1, image(1)), (2, vec![0; 128])]; - let (doc, warnings) = import_with_image_limit(&file(&[9, 1], &members), "Images", members[0].1.len() as u64).unwrap(); - assert_eq!(bytes(&doc, 1), members[0].1); - assert!(warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); - assert!(budget_warnings(&warnings).is_empty(), "{warnings:?}"); - } - - #[test] - fn embedded_image_fallback_is_independent_of_the_zip_budget() { - let canvas = canvas(&schema(), &message_with_image_in_blobs(0)); - for bytes in [&canvas, &zip_file(&canvas)] { - let (doc, warnings) = import_with_image_limit(bytes, "Images", 0).unwrap(); - let photo = named(&doc, "Photo"); - let figcraft_doc::color::PaintKind::Image(fill) = &photo.fills[0].kind else { panic!("not an image fill") }; - assert_eq!(*doc.images[&fill.image].bytes, png()); - assert!(!warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); - assert_eq!(budget_warnings(&warnings).len(), usize::from(bytes.starts_with(b"PK")), "{warnings:?}"); - } - } - - #[test] - fn default_import_preserves_image_bytes_dimensions_and_existing_warnings() { - let members = [(1, image(1)), (2, image(2))]; - let (doc, warnings) = import(&file(&[1, 2], &members), "Images").unwrap(); - assert_eq!(bytes(&doc, 0), members[0].1); - assert_eq!(bytes(&doc, 1), members[1].1); - assert!(doc.images.values().all(|img| (img.width, img.height) == (2, 1))); - assert!(warnings.is_empty(), "{warnings:?}"); - let (doc, warnings) = import(&fixture(), "Fixture").unwrap(); - assert!(doc.images.values().any(|img| *img.bytes == png() && (img.width, img.height) == (2, 1))); - assert!(budget_warnings(&warnings).is_empty(), "{warnings:?}"); - } -} - -#[test] -fn other_files_are_not_fig() { - assert!(try_import(b"{\"document\": {}}", "x").is_none()); - assert!(try_import(b"", "x").is_none()); - let native = crate::save_bytes(&figcraft_doc::Document::new("N"), None).unwrap(); - assert!(try_import(&native, "x").is_none()); -} - -/// A cheap deterministic generator (mangled inputs, generated fixtures). -pub(super) struct Lcg(pub(super) u64); -impl Lcg { - pub(super) fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - self.0 >> 33 - } -} - -#[test] -fn mangled_files_never_panic() { - let bytes = fixture(); - let c = canvas(&schema(), &message()); - let mut r = Lcg(7); - for src in [&bytes, &c] { - for cut in (0..src.len()).step_by(37) { - let _ = import(&src[..cut], "x"); - } - for _ in 0..300 { - let mut m = src.clone(); - for _ in 0..1 + r.next() % 8 { - let i = (r.next() as usize) % m.len(); - m[i] ^= 1 << (r.next() % 8); - } - let _ = import(&m, "x"); - } - } -} - -#[test] -fn mangled_kiwi_never_panics() { - let sc = schema(); - let root = sc.find("Message").unwrap(); - let schema_bytes = encode::schema(&sc); - let msg = encode::message(&sc, root, &message()).unwrap(); - let mut r = Lcg(11); - for cut in 0..schema_bytes.len() { - let _ = Schema::decode(&schema_bytes[..cut]); - } - for cut in (0..msg.len()).step_by(3) { - if let Ok(kv) = sc.decode_message(root, &msg[..cut]) { - let _ = map::to_rest(&kv, "x", crate::rest::MAX_NODES); - } - } - for _ in 0..2000 { - let mut m = msg.clone(); - for _ in 0..1 + r.next() % 4 { - let i = (r.next() as usize) % m.len(); - m[i] = r.next() as u8; - } - if let Ok(kv) = sc.decode_message(root, &m) { - let (json, _, networks) = map::to_rest(&kv, "x", crate::rest::MAX_NODES); - let _ = crate::rest::import_with_networks(&json, &crate::rest::no_images, networks, crate::rest::MAX_NODES); - } - let mut sbytes = schema_bytes.clone(); - let i = (r.next() as usize) % sbytes.len(); - sbytes[i] = r.next() as u8; - if let Ok(s2) = Schema::decode(&sbytes) - && let Some(rt) = s2.find("Message") - { - let _ = s2.decode_message(rt, &msg); - } - } - // Pure junk, bare and framed. - for _ in 0..500 { - let junk: Vec = (0..(r.next() % 200)).map(|_| r.next() as u8).collect(); - let _ = Schema::decode(&junk); - let _ = sc.decode_message(root, &junk); - let mut framed = b"fig-kiwi\0\0\0\0".to_vec(); - framed.extend_from_slice(&junk); - let _ = import(&framed, "x"); - } -} - -#[test] -fn large_files_get_a_larger_value_budget() { - // Small files keep the fixed floor: a few bytes can't expand into a huge tree. - assert_eq!(kiwi::value_budget(0), 20_000_000); - assert_eq!(kiwi::value_budget(1 << 20), 20_000_000); - // A real 400 000-layer file: an 83.5 MB canvas whose message unpacks to 334 MB and holds - // 30.5 million values was refused as "too many values". - assert!(kiwi::value_budget(83_491_232) > 30_514_899); - // A real 194 MB design-system file (UX4G): a 39.5 MB canvas holding 29.7 million values. - assert!(kiwi::value_budget(39_528_420) > 29_703_730); - // Still bounded by the largest canvas read. - assert!(kiwi::value_budget(MAX_CANVAS as usize) <= 128 << 20); - // Counting every scalar field, a dense file may reach about 2.4 values per compressed byte (the - // 15 MB text-heavy fixture in `value_budget_tests` measures 1.8): below the ceiling the budget must - // cover that, the floor still holds up to 5 MB of canvas, and 32 MiB is enough for the ceiling. - assert!(kiwi::value_budget(8 << 20) >= (8 << 20) * 12 / 5); - #[cfg(not(target_pointer_width = "32"))] - assert!(kiwi::value_budget(30_000_000) >= 30_000_000 * 12 / 5); - assert_eq!(kiwi::value_budget(5_000_000), 20_000_000); - assert_eq!(kiwi::value_budget(32 << 20), kiwi::value_budget(MAX_CANVAS as usize)); -} - -#[test] -fn the_layer_cap_follows_the_file_size() { - // A small (or broken) file keeps the REST import's cap: instances expand into a layer per - // layer of their component, and a few bytes mustn't claim millions of layers. - assert_eq!(layer_budget(0), crate::rest::MAX_NODES); - assert_eq!(layer_budget(1 << 20), crate::rest::MAX_NODES); - // A real 894 004-layer file (an 83.5 MB canvas) stopped at 200 000 and came in with 27 of - // its 30 pages empty. - assert!(layer_budget(83_491_232) > 894_004); - // No file gets more than the ceiling. - assert_eq!(layer_budget(MAX_CANVAS as usize), MAX_FIG_NODES); -} - -#[test] -fn a_small_file_that_unpacks_large_gets_no_larger_budgets() { - // 40 MB of zeros in a blob pack into a few KB. Keyed to the unpacked message, they lifted the - // layer cap above the 231 231 layers its instances expand into; keyed to the file, the cap - // stays at the REST import's. - let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])]; - nodes.push(node(5, Some((1, "!")), "SYMBOL", "Main", vec![("size", xy(10.0, 10.0))])); - nodes.extend((10..1010).map(|i| node(i, Some((5, "!")), "RECTANGLE", "R", vec![("size", xy(1.0, 1.0))]))); - nodes.extend((2000..2230).map(|i| node(i, Some((1, "!")), "INSTANCE", "I", vec![("symbolData", o(vec![("symbolID", g(5))]))]))); - let blob = o(vec![("bytes", Kv::Bytes(vec![0; 40 << 20]))]); - let file = canvas(&schema(), &o(vec![("nodeChanges", arr(nodes)), ("blobs", arr(vec![blob]))])); - assert!(file.len() < 1 << 20, "{} bytes", file.len()); - let (doc, warnings) = import(&file, "x").unwrap(); - assert!(warnings.iter().any(|w| w.contains("more than 200000 layers")), "{warnings:?}"); - assert!(doc.node_count() <= crate::rest::MAX_NODES + 10); -} - -#[test] -fn the_mapper_stops_at_the_layer_cap_it_is_given() { - let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])]; - nodes.extend((2..12).map(|i| node(i, Some((1, "!")), "RECTANGLE", "R", vec![("size", xy(1.0, 1.0))]))); - let msg = o(vec![("nodeChanges", arr(nodes))]); - let (_, warnings, _) = map::to_rest(&msg, "x", 5); - assert!(warnings.iter().any(|w| w.contains("more than 5 layers")), "{warnings:?}"); - let (_, warnings, _) = map::to_rest(&msg, "x", crate::rest::MAX_NODES); - assert!(!warnings.iter().any(|w| w.contains("more than")), "{warnings:?}"); -} - -#[test] -fn scalar_fields_count_against_the_value_budget() { - // A message of 1000 scalar fields (id 1, `true`) is 1001 values: a budget of 10 refuses it. - let fields = vec![Field { name: "b".into(), ty: Some(Type::Bool), array: false, value: 1 }]; - let sc = Schema { defs: vec![Def { name: "Message".into(), kind: Kind::Message, fields }] }; - let mut data = [1u8, 1].repeat(1000); - data.push(0); - let e = sc.decode_message_within(0, &data, 10).unwrap_err(); - assert_eq!(e.0, "message: too many values"); - assert!(sc.decode_message_within(0, &data, 1001).is_ok()); -} - -#[test] -fn hostile_input_is_refused() { - // A message that contains itself, nested past the depth cap. - let field = |ty, array| vec![Field { name: "m".into(), ty: Some(ty), array, value: 1 }]; - let nested = Schema { defs: vec![Def { name: "Message".into(), kind: Kind::Message, fields: field(Type::Def(0), false) }] }; - assert!(nested.decode_message(0, &[1u8; 10_000]).is_err()); - // An array count larger than the data. - let array = Schema { defs: vec![Def { name: "Message".into(), kind: Kind::Message, fields: field(Type::Uint, true) }] }; - assert!(array.decode_message(0, &[1, 0xff, 0xff, 0xff, 0xff, 0x0f]).is_err()); - // A field type naming a missing definition. - let mut w = encode::Writer::default(); - w.var_uint(1); - w.string("Message"); - w.byte(2); - w.var_uint(1); - w.string("x"); - w.var_int(5); - w.byte(0); - w.var_uint(1); - assert!(Schema::decode(&w.0).is_err()); - // A schema without a Message definition. - let c = canvas(&Schema { defs: vec![Def { name: "Message".into(), kind: Kind::Message, fields: vec![] }] }, &Kv::Object(vec![])); - let renamed: Vec = { - let sc = Schema { defs: vec![Def { name: "Other".into(), kind: Kind::Message, fields: vec![] }] }; - let mut z = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); - z.write_all(&encode::schema(&sc)).unwrap(); - let sch = z.finish().unwrap(); - let mut out = c[..12].to_vec(); - out.extend_from_slice(&(sch.len() as u32).to_le_bytes()); - out.extend_from_slice(&sch); - out.extend_from_slice(&c[12 + 4 + chunks(&c).unwrap()[0].len()..]); - out - }; - assert!(import(&c, "x").is_ok()); - assert!(import(&renamed, "x").is_err()); -} - -#[test] -fn instances_inside_their_own_main_stop() { - let sym = node(5, Some((1, "!")), "SYMBOL", "Loop", vec![("size", xy(10.0, 10.0))]); - let inner = node(6, Some((5, "!")), "INSTANCE", "Self", vec![("symbolData", o(vec![("symbolID", g(5))]))]); - let doc_nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![]), sym, inner]; - let (doc, _) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(doc_nodes))])), "x").unwrap(); - assert!(doc.nodes().any(|n| n.name == "Self")); -} - -/// A collection from a library is named by its asset key, not a guid — also in the explicit mode -/// map of the frames, components and instances set it on, and in the variables' collection link. -#[test] -fn modes_of_collections_named_by_asset_import() { - let modes = arr(vec![ - o(vec![("id", g(90)), ("name", s("Dark")), ("sortPosition", s("!"))]), - o(vec![("id", g(91)), ("name", s("Light")), ("sortPosition", s("\""))]), - ]); - let color_value = |c| o(vec![("value", o(vec![("colorValue", c)])), ("dataType", e("COLOR"))]); - let values = o(vec![( - "entries", - arr(vec![ - o(vec![("modeID", g(90)), ("variableData", color_value(rgb(0.0, 0.0, 0.0)))]), - o(vec![("modeID", g(91)), ("variableData", color_value(rgb(1.0, 1.0, 1.0)))]), - ]), - )]); - let by_asset = |key: &'static str, version: Option<&'static str>| { - let mut r = vec![("key", s(key))]; - r.extend(version.map(|v| ("version", s(v)))); - o(vec![("assetRef", o(r))]) - }; - let mode_map = |set: Kv<'static>| o(vec![("entries", arr(vec![o(vec![("variableSetID", set), ("variableModeID", g(91))])]))]); - let nodes = vec![ - node(0, None, "DOCUMENT", "Document", vec![]), - node(1, Some((0, "!")), "CANVAS", "Page A", vec![]), - node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), - // The collection itself says the asset key its references name. - node(4, Some((2, "!")), "VARIABLE_SET", "Schema", vec![("variableSetModes", modes), ("key", s("schema-collection")), ("version", s("7"))]), - node( - 5, - Some((2, "\"")), - "VARIABLE", - "surface", - vec![("variableSetID", by_asset("schema-collection", Some("7"))), ("variableResolvedType", e("COLOR")), ("variableDataValues", values)], - ), - node( - 10, - Some((1, "!")), - "FRAME", - "Light section", - vec![("size", xy(400.0, 300.0)), ("variableModeBySetMap", mode_map(by_asset("schema-collection", Some("7"))))], - ), - node( - 20, - Some((1, "\"")), - "SYMBOL", - "Button", - vec![("size", xy(100.0, 40.0)), ("variableModeBySetMap", mode_map(by_asset("schema-collection", None)))], - ), - node( - 21, - Some((1, "#")), - "INSTANCE", - "Button copy", - vec![ - ("size", xy(100.0, 40.0)), - ("symbolData", o(vec![("symbolID", g(20))])), - ("variableModeBySetMap", mode_map(by_asset("schema-collection", Some("7")))), - ], - ), - // One names a collection that isn't in the file: its mode is skipped, with a warning. - node(11, Some((1, "$")), "FRAME", "Gone", vec![("size", xy(400.0, 300.0)), ("variableModeBySetMap", mode_map(by_asset("gone", None)))]), - ]; - let (doc, warnings) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); - assert_eq!(doc.variables.collections.len(), 1); - assert_eq!(doc.variables.variables.len(), 1); - assert_eq!(doc.variables.variables[0].collection, "1:4"); - for name in ["Light section", "Button", "Button copy"] { - let n = named(&doc, name); - assert_eq!(n.var_modes.get("1:4").map(String::as_str), Some("1:91"), "{name}"); - } - assert!(named(&doc, "Gone").var_modes.is_empty()); - assert!(warnings.iter().any(|w| w.contains("variable modes of collections that aren't in the file")), "{warnings:?}"); -} - -#[test] -fn resized_instances_lay_their_layers_out_by_their_constraints() { - let pin = |h: &'static str, v: &'static str| vec![("horizontalConstraint", e(h)), ("verticalConstraint", e(v))]; - let layer = |id, pos, ty, name, w, h, x, y, c: Vec<(&'static str, Kv<'static>)>| { - node(id, Some((5, pos)), ty, name, [vec![("size", xy(w, h)), ("transform", at(x, y))], c].concat()) - }; - let nodes = vec![ - node(0, None, "DOCUMENT", "D", vec![]), - node(1, Some((0, "!")), "CANVAS", "P", vec![]), - node(5, Some((1, "!")), "SYMBOL", "Logo", vec![("size", xy(132.0, 22.0)), ("transform", at(0.0, 0.0))]), - layer(6, "!", "ROUNDED_RECTANGLE", "Mark", 132.0, 22.0, 0.0, 0.0, pin("SCALE", "SCALE")), - layer(7, "\"", "ROUNDED_RECTANGLE", "Badge", 32.0, 10.0, 100.0, 12.0, pin("MAX", "MAX")), - layer(8, "#", "ROUNDED_RECTANGLE", "Bar", 112.0, 2.0, 10.0, 0.0, pin("STRETCH", "MIN")), - // A group scales its layers with it. - layer(11, "$", "FRAME", "Wordmark", 66.0, 22.0, 66.0, 0.0, [pin("SCALE", "SCALE"), vec![("resizeToFit", Kv::Bool(true))]].concat()), - node(12, Some((11, "!")), "ROUNDED_RECTANGLE", "Letter", vec![("size", xy(66.0, 22.0)), ("transform", at(0.0, 0.0))]), - node( - 9, - Some((1, "\"")), - "INSTANCE", - "Small logo", - vec![("size", xy(90.0, 15.0)), ("transform", at(0.0, 100.0)), ("symbolData", o(vec![("symbolID", g(5))]))], - ), - // Derived layout the file gives wins over the constraints. - node( - 10, - Some((1, "#")), - "INSTANCE", - "Derived logo", - vec![ - ("size", xy(90.0, 15.0)), - ("transform", at(0.0, 200.0)), - ("symbolData", o(vec![("symbolID", g(5))])), - ("derivedSymbolData", arr(vec![o(vec![("guidPath", o(vec![("guids", arr(vec![g(6)]))])), ("size", xy(50.0, 5.0))])])), - ], - ), - // A size the instance overrides: the place still follows the constraints. - node( - 13, - Some((1, "$")), - "INSTANCE", - "Resized badge", - vec![ - ("size", xy(90.0, 15.0)), - ("transform", at(0.0, 300.0)), - ( - "symbolData", - o(vec![ - ("symbolID", g(5)), - ("symbolOverrides", arr(vec![o(vec![("guidPath", o(vec![("guids", arr(vec![g(7)]))])), ("size", xy(20.0, 10.0))])])), - ]), - ), - ], - ), - ]; - let (doc, _) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); - let box_of = |inst: &str, name: &str| { - let i = named(&doc, inst); - let n = i.children.iter().map(|c| doc.node(*c).unwrap()).find(|n| n.name == name).unwrap(); - let t = n.transform.translation(); - [t.x, t.y, n.width, n.height].map(|x| (x * 1e3).round() / 1e3) - }; - assert_eq!(box_of("Small logo", "Mark"), [0.0, 0.0, 90.0, 15.0]); - assert_eq!(box_of("Small logo", "Badge"), [58.0, 5.0, 32.0, 10.0]); - assert_eq!(box_of("Small logo", "Bar"), [10.0, 0.0, 70.0, 2.0]); - // The main's own, then the instances'. - let mut letters: Vec<[f64; 2]> = - doc.nodes().filter(|n| n.name == "Letter").map(|n| [n.width, n.height].map(|x| (x * 1e3).round() / 1e3)).collect(); - letters.sort_by(|a, b| a[0].total_cmp(&b[0])); - assert_eq!(letters, [[45.0, 15.0], [45.0, 15.0], [45.0, 15.0], [66.0, 22.0]]); - assert_eq!(box_of("Derived logo", "Mark")[2..], [50.0, 5.0]); - assert_eq!(box_of("Resized badge", "Badge"), [58.0, 5.0, 20.0, 10.0]); -} - -#[test] -fn nested_instances_resized_again_drop_the_layout_derived_for_their_old_size() { - let stretch = || vec![("horizontalConstraint", e("STRETCH")), ("verticalConstraint", e("MIN"))]; - let nodes = vec![ - node(0, None, "DOCUMENT", "D", vec![]), - node(1, Some((0, "!")), "CANVAS", "P", vec![]), - node(20, Some((1, "!")), "SYMBOL", "Track", vec![("size", xy(100.0, 10.0)), ("transform", at(0.0, 0.0))]), - node(21, Some((20, "!")), "ROUNDED_RECTANGLE", "Fill", [vec![("size", xy(100.0, 10.0)), ("transform", at(0.0, 0.0))], stretch()].concat()), - node(30, Some((1, "\"")), "SYMBOL", "Slider", vec![("size", xy(200.0, 50.0)), ("transform", at(0.0, 100.0))]), - // The nested instance is 150 wide in its main, with the layout derived for that. - node( - 31, - Some((30, "!")), - "INSTANCE", - "Inner", - [ - vec![ - ("size", xy(150.0, 10.0)), - ("transform", at(0.0, 0.0)), - ("symbolData", o(vec![("symbolID", g(20))])), - ( - "derivedSymbolData", - arr(vec![o(vec![ - ("guidPath", o(vec![("guids", arr(vec![g(21)]))])), - ("size", xy(150.0, 10.0)), - ("fillPaints", arr(vec![solid(1.0, 0.0, 0.0)])), - ])]), - ), - ], - stretch(), - ] - .concat(), - ), - node( - 40, - Some((1, "#")), - "INSTANCE", - "Wide slider", - vec![("size", xy(300.0, 50.0)), ("transform", at(0.0, 200.0)), ("symbolData", o(vec![("symbolID", g(30))]))], - ), - ]; - let (doc, _) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); - let width = |outer: &str| { - let inner = doc.node(named(&doc, outer).children[0]).unwrap(); - (inner.width, doc.node(inner.children[0]).unwrap().width) - }; - // In its main the derived layout holds; stretched to 250 it no longer does. - assert_eq!(width("Slider"), (150.0, 150.0)); - assert_eq!(width("Wide slider"), (250.0, 250.0)); - // What else the derived data gives (the colour a variable resolves to, say) still holds. - let fill = doc.node(doc.node(named(&doc, "Wide slider").children[0]).unwrap().children[0]).unwrap(); - assert!(matches!(fill.fills.first().map(|p| &p.kind), Some(figcraft_doc::color::PaintKind::Solid { color }) if color.r == 1.0 && color.g == 0.0)); -} - -#[path = "tail_tests.rs"] -mod tail; - -#[path = "image_filter_tests.rs"] -mod image_filters; - -#[path = "text_list_tests.rs"] -mod text_list; - -/// `.fig` files in the folder `FIGCRAFT_FIG_SAMPLES` names (none when it's unset). -pub(super) fn samples() -> Vec { - let Some(dir) = std::env::var_os("FIGCRAFT_FIG_SAMPLES") else { return Vec::new() }; - let dir = std::fs::read_dir(dir).into_iter().flatten().flatten(); - dir.map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "fig")).collect() -} - -/// Local only (`FIGCRAFT_FIG_SAMPLES`): every file imports without warnings. -#[test] -fn local_samples_import() { - for p in samples() { - let bytes = std::fs::read(&p).unwrap(); - let (doc, warnings) = import(&bytes, "sample").unwrap_or_else(|e| panic!("{}: {e}", p.display())); - assert!(warnings.is_empty(), "{}: {warnings:?}", p.display()); - assert!(doc.node_count() > 5, "{}", p.display()); - } -} - -/// Local only: dumps each sample's schema, decoded message and REST JSON when `FIG_DUMP` names a -/// folder (for working on the importer). -#[test] -fn dump_samples() { - let Ok(out) = std::env::var("FIG_DUMP") else { return }; - for p in samples() { - let bytes = std::fs::read(&p).unwrap(); - let a = Archive::open(&bytes).unwrap(); - let (schema, message) = decode_canvas(&a.canvas).unwrap(); - let stem = p.file_stem().unwrap().to_string_lossy().to_string(); - let mut txt = String::new(); - for d in &schema.defs { - txt += &format!("{:?} {}\n", d.kind, d.name); - for f in &d.fields { - let ty = match f.ty { - Some(Type::Def(i)) => schema.defs[i].name.clone(), - Some(t) => format!("{t:?}"), - None => String::new(), - }; - txt += &format!(" {} {}{} = {}\n", f.name, ty, if f.array { "[]" } else { "" }, f.value); - } - } - 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())); - std::fs::write(format!("{out}/{stem}.rest.json"), serde_json::to_string_pretty(&rest).unwrap()).unwrap(); - } -} - -#[path = "board_import_tests.rs"] -mod board; - -/// A file that took several updates of a library holds a copy of its collection and of each of -/// its variables per version it met (same asset key, another version). Layers and modes name any -/// of them by asset, never by guid: they all become the newest copy, which has every mode — a page -/// set to a mode only the newer copies have keeps it, and fills bound to an older copy of a -/// variable follow its newest values. -#[test] -fn library_copies_of_several_versions_become_the_newest() { - let mode = |id, name: &'static str, pos: &'static str| o(vec![("id", g(id)), ("name", s(name)), ("sortPosition", s(pos))]); - let by_asset = |key: &'static str, version: &'static str| o(vec![("assetRef", o(vec![("key", s(key)), ("version", s(version))]))]); - let color_value = |c| o(vec![("value", o(vec![("colorValue", c)])), ("dataType", e("COLOR"))]); - let values = |pairs: Vec<(u64, Kv<'static>)>| { - o(vec![("entries", arr(pairs.into_iter().map(|(m, c)| o(vec![("modeID", g(m)), ("variableData", color_value(c))])).collect()))]) - }; - let asset_alias = - |key: &'static str, version: &'static str| o(vec![("value", o(vec![("alias", by_asset(key, version))])), ("dataType", e("ALIAS"))]); - let nodes = vec![ - node(0, None, "DOCUMENT", "Document", vec![]), - // The page is set to "Purple", a mode the oldest copy of the collection didn't have yet. - node( - 1, - Some((0, "!")), - "CANVAS", - "Page", - vec![( - "variableModeBySetMap", - o(vec![("entries", arr(vec![o(vec![("variableSetID", by_asset("products", "10:1")), ("variableModeID", g(92))])]))]), - )], - ), - node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), - node( - 4, - Some((2, "!")), - "VARIABLE_SET", - "Products", - vec![("variableSetModes", arr(vec![mode(90, "Blue", "!")])), ("key", s("products")), ("version", s("10:1"))], - ), - node( - 6, - Some((2, "#")), - "VARIABLE_SET", - "Products", - vec![("variableSetModes", arr(vec![mode(90, "Blue", "!"), mode(92, "Purple", "\"")])), ("key", s("products")), ("version", s("20:1"))], - ), - node( - 5, - Some((2, "\"")), - "VARIABLE", - "button-bg", - vec![ - ("variableSetID", by_asset("products", "10:1")), - ("variableResolvedType", e("COLOR")), - ("variableDataValues", values(vec![(90, rgb(0.0, 0.0, 1.0))])), - ("key", s("button-bg")), - ("version", s("10:1")), - ], - ), - node( - 7, - Some((2, "$")), - "VARIABLE", - "button-bg", - vec![ - ("variableSetID", by_asset("products", "20:1")), - ("variableResolvedType", e("COLOR")), - ("variableDataValues", values(vec![(90, rgb(0.0, 0.0, 1.0)), (92, rgb(0.5, 0.0, 0.5))])), - ("key", s("button-bg")), - ("version", s("20:1")), - ], - ), - // The button names the older copy of the variable. - node( - 10, - Some((1, "!")), - "FRAME", - "Button", - vec![ - ("size", xy(100.0, 40.0)), - ( - "fillPaints", - arr(vec![o(vec![("type", e("SOLID")), ("color", rgb(0.0, 0.0, 1.0)), ("colorVar", asset_alias("button-bg", "10:1"))])]), - ), - ], - ), - ]; - let (doc, warnings) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); - assert_eq!(doc.variables.collections.len(), 1, "{:?}", doc.variables.collections); - let products = &doc.variables.collections[0]; - assert_eq!(products.modes.iter().map(|m| m.name.as_str()).collect::>(), ["Blue", "Purple"]); - assert_eq!(doc.variables.variables.len(), 1); - let var = &doc.variables.variables[0]; - assert_eq!(var.collection, products.id); - assert_eq!(var.values.len(), 2, "the newest copy's values: {:?}", var.values); - let page = doc.nodes().find(|n| n.name == "Page").unwrap(); - assert_eq!(page.var_modes.get(&products.id).map(String::as_str), Some("1:92")); - let button = named(&doc, "Button"); - assert_eq!(button.bound.values().next(), Some(&var.id), "{:?}", button.bound); - assert!(!warnings.iter().any(|w| w.contains("variable modes of collections")), "{warnings:?}"); -} From 5d4a5082ec8188f03ea6107184c771fa0dc7e7c0 Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 14:54:48 +0330 Subject: [PATCH 057/326] Add files via upload --- crates/format/src/fig/map.rs | 16 +++++++++---- crates/format/src/fig/tests.rs | 42 +++++++++++++++++++++++++++++++--- 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index 98239cd7b..e24a93b2d 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -427,6 +427,8 @@ fn version_rank(v: &str) -> (u64, u64) { pub(super) struct VarCanon { by_key: HashMap, by_id: HashMap, + /// Every live variable node of the file, with a key or not. + local: BTreeSet, } thread_local! { @@ -446,10 +448,12 @@ impl VarCanon { fn install(m: &Mapper) -> VarCanonGuard { let mut newest: HashMap = HashMap::new(); let mut copies: Vec<(String, String)> = Vec::new(); + let mut local = BTreeSet::new(); for (id, n) in &m.nodes { if n.get("type").and_then(Kv::str) != Some("VARIABLE") || n.get("isSoftDeleted").and_then(Kv::bool) == Some(true) { continue; } + local.insert(id.clone()); let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) else { continue }; let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or("")); copies.push((id.clone(), key.to_string())); @@ -465,21 +469,25 @@ impl VarCanon { } } t.by_key = newest.into_iter().map(|(k, (_, id))| (k, id)).collect(); + t.local = local; VAR_CANON.with(|c| *c.borrow_mut() = Some(t)); VarCanonGuard } - /// The variable a reference (`{guid}` or `{assetRef}`) names, as its newest copy. + /// The variable a reference (`{guid}` or `{assetRef}`) names, as its newest copy. A guid + /// counts when this file holds a variable by it; one from another file (a paste carries the + /// library's own guids) names nothing here, so the asset it also names is tried before it is + /// kept as it is. pub(super) fn resolve(r: &Kv) -> Option { let by_guid = r.get("guid").and_then(guid).filter(|g| g != NO_STYLE); VAR_CANON.with(|c| { let c = c.borrow(); let Some(t) = c.as_ref() else { return by_guid.clone() }; - if let Some(g) = &by_guid { + if let Some(g) = by_guid.as_ref().filter(|g| t.local.contains(*g)) { return Some(t.by_id.get(g).cloned().unwrap_or_else(|| g.clone())); } - let key = r.get("assetRef")?.get("key").and_then(Kv::str)?; - t.by_key.get(key).cloned() + let by_asset = r.get("assetRef").and_then(|a| a.get("key")).and_then(Kv::str).and_then(|k| t.by_key.get(k)).cloned(); + by_asset.or(by_guid) }) } diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index 0e2c5016e..d0cea1932 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -1522,7 +1522,8 @@ fn library_copies_of_several_versions_become_the_newest() { Some((2, "!")), "VARIABLE_SET", "Products", - vec![("variableSetModes", arr(vec![mode(90, "Blue", "!")])), ("key", s("products")), ("version", s("10:1"))], + // "Legacy" was removed from the library since: only this older copy has it. + vec![("variableSetModes", arr(vec![mode(90, "Blue", "!"), mode(93, "Legacy", "\"")])), ("key", s("products")), ("version", s("10:1"))], ), node( 6, @@ -1557,6 +1558,37 @@ fn library_copies_of_several_versions_become_the_newest() { ("version", s("20:1")), ], ), + // A pasted layer names the variable by the library's own guid (not a node of this file) + // and by its asset: the asset wins. + node( + 11, + Some((1, "\"")), + "FRAME", + "Pasted button", + vec![ + ("size", xy(100.0, 40.0)), + ( + "fillPaints", + arr(vec![o(vec![ + ("type", e("SOLID")), + ("color", rgb(0.0, 0.0, 1.0)), + ( + "colorVar", + o(vec![ + ( + "value", + o(vec![( + "alias", + o(vec![("guid", g(777)), ("assetRef", o(vec![("key", s("button-bg")), ("version", s("20:1"))]))]), + )]), + ), + ("dataType", e("ALIAS")), + ]), + ), + ])]), + ), + ], + ), // The button names the older copy of the variable. node( 10, @@ -1575,14 +1607,18 @@ fn library_copies_of_several_versions_become_the_newest() { let (doc, warnings) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); assert_eq!(doc.variables.collections.len(), 1, "{:?}", doc.variables.collections); let products = &doc.variables.collections[0]; - assert_eq!(products.modes.iter().map(|m| m.name.as_str()).collect::>(), ["Blue", "Purple"]); + assert_eq!(products.modes.iter().map(|m| m.name.as_str()).collect::>(), ["Blue", "Purple", "Legacy"]); assert_eq!(doc.variables.variables.len(), 1); let var = &doc.variables.variables[0]; assert_eq!(var.collection, products.id); - assert_eq!(var.values.len(), 2, "the newest copy's values: {:?}", var.values); + // The newest copy's values: Purple included (a mode only it has), Legacy filled from the default. + assert_eq!(var.values.len(), 3, "{:?}", var.values); + assert!(matches!(var.values.get("1:92"), Some(figcraft_doc::VariableValue::Color(c)) if (c.r - 0.5).abs() < 1e-6), "{:?}", var.values); let page = doc.nodes().find(|n| n.name == "Page").unwrap(); assert_eq!(page.var_modes.get(&products.id).map(String::as_str), Some("1:92")); let button = named(&doc, "Button"); assert_eq!(button.bound.values().next(), Some(&var.id), "{:?}", button.bound); + let pasted = named(&doc, "Pasted button"); + assert_eq!(pasted.bound.values().next(), Some(&var.id), "{:?}", pasted.bound); assert!(!warnings.iter().any(|w| w.contains("variable modes of collections")), "{warnings:?}"); } From c411152b877508613bee62f332c91f77c0a480b0 Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 15:34:41 +0330 Subject: [PATCH 058/326] Add files via upload --- crates/format/src/fig/map.rs | 45 +++++++++++++++++++++------- crates/format/src/fig/tests.rs | 55 +++++++++++++++++++++++++++++++++- 2 files changed, 88 insertions(+), 12 deletions(-) diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index e24a93b2d..97e758e7f 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -372,22 +372,23 @@ impl<'a> Mapper<'a> { /// while the mode ids stay the same across them, so every copy maps to the newest one (the /// one [`Self::variables`] keeps, with the modes of the others added). Without this, a page set /// to a mode an older copy didn't have yet lost its mode, and the layers fell back to the - /// default mode of the newest copy. + /// default mode of the newest copy. A reference by asset that names no copy by itself (no + /// version, or a version the file doesn't hold, while it holds several) still names the asset: + /// its newest live copy. pub(super) fn collection_id(&self, v: &Kv) -> Option { - let id = self.resource_id(v)?; - Some(self.canonical_collection(&id).unwrap_or(id)) + let by_asset = || v.get("assetRef")?.get("key").and_then(Kv::str).and_then(VarCanon::newest_set); + match self.resource_id(v) { + Some(id) if self.nodes.contains_key(&id) => Some(self.canonical_collection(&id).unwrap_or(id)), + // The asset index can name a node a later change removed: the asset's live copy instead. + Some(id) => by_asset().or(Some(id)), + None => by_asset(), + } } /// The newest live copy of collection node `id`'s library asset, when it has a key. pub(super) fn canonical_collection(&self, id: &str) -> Option { let key = self.nodes.get(id)?.get("key").and_then(Kv::str).filter(|k| !k.is_empty())?; - let live_set = |n: &Kv| n.get("type").and_then(Kv::str) == Some("VARIABLE_SET") && n.get("isSoftDeleted").and_then(Kv::bool) != Some(true); - self.assets - .get(key)? - .iter() - .filter(|(_, nid)| self.nodes.get(nid.as_str()).is_some_and(|n| live_set(n))) - .max_by_key(|(ver, _)| version_rank(ver)) - .map(|(_, nid)| nid.clone()) + VarCanon::newest_set(key) } /// A note about what this file's mapping left out or changed. Counted, as the REST importer @@ -429,6 +430,10 @@ pub(super) struct VarCanon { by_id: HashMap, /// Every live variable node of the file, with a key or not. local: BTreeSet, + /// The newest live copy of each library collection, by asset key. Read from the file's live + /// nodes (the last change of each guid, REMOVED ones gone), not from the asset index, which + /// keeps the first node it met for a key and version even when a later change removed it. + sets_by_key: HashMap, } thread_local! { @@ -449,8 +454,20 @@ impl VarCanon { let mut newest: HashMap = HashMap::new(); let mut copies: Vec<(String, String)> = Vec::new(); let mut local = BTreeSet::new(); + let mut sets: HashMap = HashMap::new(); for (id, n) in &m.nodes { - if n.get("type").and_then(Kv::str) != Some("VARIABLE") || n.get("isSoftDeleted").and_then(Kv::bool) == Some(true) { + let ty = n.get("type").and_then(Kv::str); + if !matches!(ty, Some("VARIABLE" | "VARIABLE_SET")) || n.get("isSoftDeleted").and_then(Kv::bool) == Some(true) { + continue; + } + if ty == Some("VARIABLE_SET") { + if let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) { + let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or("")); + let e = sets.entry(key.to_string()).or_insert_with(|| (rank, id.clone())); + if rank > e.0 || (rank == e.0 && *id > e.1) { + *e = (rank, id.clone()); + } + } continue; } local.insert(id.clone()); @@ -470,6 +487,7 @@ impl VarCanon { } t.by_key = newest.into_iter().map(|(k, (_, id))| (k, id)).collect(); t.local = local; + t.sets_by_key = sets.into_iter().map(|(k, (_, id))| (k, id)).collect(); VAR_CANON.with(|c| *c.borrow_mut() = Some(t)); VarCanonGuard } @@ -491,6 +509,11 @@ impl VarCanon { }) } + /// The newest live copy of the library collection with asset key `key`. + pub(super) fn newest_set(key: &str) -> Option { + VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.sets_by_key.get(key).cloned())) + } + /// Whether variable node `id` is an older copy another one replaces. pub(super) fn superseded(id: &str) -> bool { VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.by_id.get(id)).is_some_and(|canon| canon != id)) diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index d0cea1932..d365ff9f7 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -28,6 +28,7 @@ enum StrokeCap NONE ROUND SQUARE ARROW_LINES ARROW_EQUILATERAL enum StrokeJoin MITER BEVEL ROUND enum VectorMirror NONE ANGLE ANGLE_AND_LENGTH enum ShapeWithTextType SQUARE ELLIPSE +enum NodePhase CREATED REMOVED enum ConnectorLineStyle ELBOWED STRAIGHT CURVED enum ExpressionFunction ADDITION SUBTRACTION RESOLVE_VARIANT MULTIPLY DIVIDE EQUALS enum NavigationType NAVIGATE OVERLAY @@ -74,7 +75,7 @@ message Event InteractionType interactionType message Action GUID transitionNodeID, TransitionType transitionType, float transitionDuration, EasingType easingType, ConnectionType connectionType, NavigationType navigationType, VariableTarget targetVariable, VariableData targetVariableData, VariableSetID targetVariableSetID, GUID targetVariableModeID, ConditionalActions[] conditionalActions message Interaction Event event, Action[] actions message StartingPoint string name, string position -message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern +message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern, NodePhase phase message Blob byte[] bytes message Message NodeChange[] nodeChanges, Blob[] blobs "; @@ -1589,6 +1590,23 @@ fn library_copies_of_several_versions_become_the_newest() { ), ], ), + // A page section set by a versionless reference, while the file holds several copies. + node( + 12, + Some((1, "#")), + "FRAME", + "Versionless", + vec![ + ("size", xy(100.0, 40.0)), + ( + "variableModeBySetMap", + o(vec![( + "entries", + arr(vec![o(vec![("variableSetID", o(vec![("assetRef", o(vec![("key", s("products"))]))])), ("variableModeID", g(92))])]), + )]), + ), + ], + ), // The button names the older copy of the variable. node( 10, @@ -1618,7 +1636,42 @@ fn library_copies_of_several_versions_become_the_newest() { assert_eq!(page.var_modes.get(&products.id).map(String::as_str), Some("1:92")); let button = named(&doc, "Button"); assert_eq!(button.bound.values().next(), Some(&var.id), "{:?}", button.bound); + assert_eq!(named(&doc, "Versionless").var_modes.get(&products.id).map(String::as_str), Some("1:92")); let pasted = named(&doc, "Pasted button"); assert_eq!(pasted.bound.values().next(), Some(&var.id), "{:?}", pasted.bound); assert!(!warnings.iter().any(|w| w.contains("variable modes of collections")), "{warnings:?}"); } + +/// A copy of a library collection that a later change removed, followed by a live node for the +/// same asset key and version: the live one is the collection, not the removed one the asset +/// index met first. +#[test] +fn removed_library_collection_copies_give_way_to_live_ones() { + let mode = |id, name: &'static str, pos: &'static str| o(vec![("id", g(id)), ("name", s(name)), ("sortPosition", s(pos))]); + let by_asset = |version: &'static str| o(vec![("assetRef", o(vec![("key", s("products")), ("version", s(version))]))]); + let set = |id, version: &'static str, modes: Vec>| { + node(id, Some((2, "!")), "VARIABLE_SET", "Products", vec![("variableSetModes", arr(modes)), ("key", s("products")), ("version", s(version))]) + }; + let removed = o(vec![("guid", g(8)), ("phase", e("REMOVED"))]); + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node( + 1, + Some((0, "!")), + "CANVAS", + "Page", + vec![("variableModeBySetMap", o(vec![("entries", arr(vec![o(vec![("variableSetID", by_asset("30:1")), ("variableModeID", g(92))])]))]))], + ), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + set(4, "10:1", vec![mode(90, "Blue", "!")]), + set(8, "30:1", vec![mode(90, "Blue", "!"), mode(92, "Purple", "\"")]), + removed, + set(9, "30:1", vec![mode(90, "Blue", "!"), mode(92, "Purple", "\"")]), + ]; + let (doc, warnings) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + assert_eq!(doc.variables.collections.len(), 1, "{:?}", doc.variables.collections); + let products = &doc.variables.collections[0]; + assert_eq!(products.id, "1:9"); + let page = doc.nodes().find(|n| n.name == "Page").unwrap(); + assert_eq!(page.var_modes.get("1:9").map(String::as_str), Some("1:92"), "{warnings:?}"); +} From 7f4b295983ab8527ae09e535aedc22a4fa411747 Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 16:17:10 +0330 Subject: [PATCH 059/326] Add files via upload --- crates/format/src/fig/map.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index 97e758e7f..e125028c8 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -444,12 +444,15 @@ thread_local! { pub(super) struct VarCanonGuard; impl Drop for VarCanonGuard { + /// Clears the thread's table, so a later file on this thread starts without it. fn drop(&mut self) { VAR_CANON.with(|c| c.borrow_mut().take()); } } impl VarCanon { + /// Builds the table from mapper `m`'s live nodes (newest copy per asset key, for variables and + /// for collections) and installs it for this thread until the returned guard is dropped. fn install(m: &Mapper) -> VarCanonGuard { let mut newest: HashMap = HashMap::new(); let mut copies: Vec<(String, String)> = Vec::new(); From ef52759ebc3c794b6c318a8aeff94613fd7f6b24 Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Sun, 1 Nov 2026 16:17:46 +0330 Subject: [PATCH 060/326] Add files via upload --- crates/format/src/fig/map/variables.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/format/src/fig/map/variables.rs b/crates/format/src/fig/map/variables.rs index 12b433fc0..0794ef155 100644 --- a/crates/format/src/fig/map/variables.rs +++ b/crates/format/src/fig/map/variables.rs @@ -2,6 +2,9 @@ use super::paint::color; use super::{Kv, MAX_EXPR_DEPTH, Mapper, Obj, Value, View, guid, json, num, ref_guid}; impl<'a> Mapper<'a> { + /// Layer `v`'s variable bindings (`boundVariables`, and the text style's) and its explicitly + /// set modes (`explicitVariableModes`) into `o`, in the REST shape. Variables and collections + /// named by library asset resolve to their newest copy in the file. pub(super) fn variable_bindings(&mut self, o: &mut Obj, v: &View<'a>) { let mut bound = Obj::new(); let mut text_bound = Obj::new(); @@ -137,7 +140,8 @@ pub(super) fn variable_data(d: &Kv, depth: usize) -> Option { Some(out) } -/// The variable an `ALIAS` variable data points at. +/// The variable an `ALIAS` variable data points at: by guid, or by library asset (the newest copy +/// of it in the file). pub(super) fn alias(d: Option<&Kv>) -> Option { let d = d?; if d.get("dataType").and_then(Kv::str) != Some("ALIAS") { From d72f0961867826c6bf9983b40734ada6e1dab70e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 11:54:35 -0500 Subject: [PATCH 061/326] M8: color-mix(): a none in color() is a missing component too Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import/css_color.rs | 5 ++++- crates/svg/src/import/css_color_tests.rs | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/import/css_color.rs b/crates/svg/src/import/css_color.rs index 9301275ed..715883de8 100644 --- a/crates/svg/src/import/css_color.rs +++ b/crates/svg/src/import/css_color.rs @@ -218,12 +218,15 @@ fn color_fn(args: &str, profile: ColorProfile) -> Eval { None => 1.0, }; let c = Color::new(value(r)?, value(g)?, value(b)?, a); + // A `none` is 0 here and missing in a mix: reds, greens and blues are analogous across the RGB + // spaces (CSS Color 4 section 12.2), so a missing channel stays missing through the conversion. + let missing = Missing { r: *r == "none", g: *g == "none", b: *b == "none", a: alpha == Some("none") }; let (from, why) = match *space { "srgb" => (ColorProfile::Srgb, None), "display-p3" => (ColorProfile::DisplayP3, None), _ => (ColorProfile::Srgb, Some("only the srgb and display-p3 spaces are read: its values were taken as sRGB")), }; - Ok((from.conversion_to(profile).apply(c), why, Missing::NONE)) + Ok((from.conversion_to(profile).apply(c), why, missing)) } /// A CSS number, a percentage (100% is 1) or `none` (0); finite only. diff --git a/crates/svg/src/import/css_color_tests.rs b/crates/svg/src/import/css_color_tests.rs index ee66b42da..c327fee01 100644 --- a/crates/svg/src/import/css_color_tests.rs +++ b/crates/svg/src/import/css_color_tests.rs @@ -86,6 +86,15 @@ fn color_mix_in_srgb_oklab_and_oklch() { assert_eq!(rgba8(fill("color-mix(in oklab, rgb(none 0 0), red)").0), rgba8(fill("color-mix(in oklab, black, red)").0)); // Missing in both stays missing through a nested mix and is carried in the outer one. assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, rgb(0 255 0 / none), rgb(0 255 0 / none)), red)").0), Some([128, 128, 0, 255])); + // `color()` gives its `none` values the same way, in either of its spaces (reds, greens and + // blues are analogous across RGB spaces, CSS Color 4 section 12.2). + assert_eq!(rgba8(fill("color-mix(in srgb, color(srgb 1 0 0 / none), blue)").0), Some([128, 0, 128, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, color(srgb none 0 0), red)").0), Some([255, 0, 0, 255])); + assert_eq!(rgba8(fill("color-mix(in srgb, color(display-p3 none 0 0), red)").0), Some([255, 0, 0, 255])); + assert_eq!( + rgba8(fill("color-mix(in srgb, color-mix(in srgb, color(srgb 0 1 0 / none), color(srgb 0 1 0 / none)), red)").0), + Some([128, 128, 0, 255]) + ); // Nested, with color() inside. assert_eq!(rgba8(fill("color-mix(in srgb, color-mix(in srgb, red, blue), color(srgb 0 1 0) 0%)").0), Some([128, 0, 128, 255])); } From 4e22873b44dfcf5ec6d5a8e7fd8b077501b07662 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 12:01:33 -0500 Subject: [PATCH 062/326] Page opacity test: a scrub on the field is live and one undo step Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 8802bb7e9..a6fd9830f 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1217,6 +1217,14 @@ fn the_page_background_opacity_field_sets_the_page_colour_alpha() { type_into(&mut u, "Opacity", "50", Key::Enter); assert!(near(page_bg(&u).a, 0.5), "{:?}", page_bg(&u)); assert_eq!(undo_steps(&u), steps + 1, "one undo step for the commit"); + // No label is drawn, so the field's leading strip scrubs it: a percent a point, live, and one + // undo step for the whole drag. + let edge = lead(&u, Id::unique("pagebg_a")); + drag(&mut u, edge, -25.0, Modifiers::NONE); + assert!(near(page_bg(&u).a, 0.25), "{:?}", page_bg(&u)); + assert_eq!(undo_steps(&u), steps + 2, "one undo step for the whole scrub"); + u.app.run("edit.undo", json!({})); + assert!(near(page_bg(&u).a, 0.5), "undo takes back the scrub alone"); // The hex field keeps the opacity when the typed colour has none, and takes one it carries. let hex = |u: &mut Ui| u.ctx.read_response(Id::unique("pagebg").with("click")).expect("the hex field").rect.center(); let at = hex(&mut u); From 8bc405edbccc73ed07f9373bf1c173a7e9b22bee Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 12:16:33 -0500 Subject: [PATCH 063/326] SVG import: the dash offset fix alone, with open-path, mixed-subpath and text tests The stretched-image fix moved to its own PR. Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import.rs | 12 +------ crates/svg/src/import/structure_tests.rs | 41 +++++++++++++----------- 2 files changed, 23 insertions(+), 30 deletions(-) diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index ed390ca4a..e154ab1c9 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -644,17 +644,7 @@ fn image(cx: &mut Ctx, img: &usvg::Image, id: &str, parent: NodeId, base: Affine let hash = add_image(cx.doc, bytes, iw, ih); let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Rectangle, layer_name(id, "Image"), w, h); n.transform = transform; - let mut fill = Paint::image(hash, ImageScaleMode::Fill); - // usvg sizes the box to the picture (`meet` and `slice` are in the transform), so a box of - // another shape is `preserveAspectRatio="none"`: the picture stretched edge to edge. A Fill - // would keep its shape and crop it; a crop of the whole picture stretches it. - if (w * ih - h * iw).abs() > 1e-6 * (w * ih).max(h * iw) - && let figcraft_color::PaintKind::Image(ip) = &mut fill.kind - { - ip.scale_mode = ImageScaleMode::Crop; - ip.crop = Some(Affine::IDENTITY.as_coeffs()); - } - n.fills = vec![fill]; + n.fills = vec![Paint::image(hash, ImageScaleMode::Fill)]; cx.add(n, parent); } diff --git a/crates/svg/src/import/structure_tests.rs b/crates/svg/src/import/structure_tests.rs index ee76c2238..500675fe4 100644 --- a/crates/svg/src/import/structure_tests.rs +++ b/crates/svg/src/import/structure_tests.rs @@ -146,26 +146,29 @@ fn a_closed_outline_keeps_a_dash_offset_of_half_a_dash() { assert_eq!(node(&d, f, "l").stroke.dashes, vec![4.0, 2.0], "an open line starts half a dash in anyway"); } -/// `preserveAspectRatio="none"` stretches a picture into its box edge to edge. usvg sizes the -/// box to the picture for `meet` and `slice` (the fit is in the transform), so a box of another -/// shape is a stretch: a Fill, which keeps the picture's shape and crops it, would show the -/// middle of the picture instead. +/// An open path is a line in this respect: half a dash in is where it starts anyway, so that +/// offset is left out, and any other is applied; an outline with an open subpath among closed +/// ones is open. #[test] -fn an_image_stretched_into_its_box_stays_stretched() { - use figcraft_color::{ImageScaleMode, PaintKind}; - let (d, f) = - import(&format!(r##""##)); - let n = node(&d, f, "pic"); - assert_eq!((n.width, n.height), (40.0, 40.0)); - let Some(PaintKind::Image(ip)) = n.fills.first().map(|p| &p.kind) else { panic!("{:?}", n.fills) }; - // The 4 × 2 picture's pixels map onto the whole 40 × 40 box: 10 across, 20 down. - let m = figcraft_render::paint::image_transform(ip, 4.0, 2.0, n.width, n.height); - assert_eq!((m.sx, m.ky, m.kx, m.sy, m.tx, m.ty), (10.0, 0.0, 0.0, 20.0, 0.0, 0.0), "{ip:?}"); - // With the aspect kept (the default) the box is the picture's own shape and a Fill is exact. - let (d, f) = import(&format!(r##""##)); - let n = node(&d, f, "pic"); - assert_eq!((n.width, n.height), (40.0, 20.0)); - assert!(matches!(n.fills.first().map(|p| &p.kind), Some(PaintKind::Image(i)) if i.scale_mode == ImageScaleMode::Fill), "{:?}", n.fills); +fn an_open_path_starts_half_a_dash_in_and_takes_other_offsets() { + let (d, f) = import( + r##""##, + ); + assert_eq!(node(&d, f, "half").stroke.dashes, vec![4.0, 2.0], "half a dash in is where an open path starts"); + assert_eq!(node(&d, f, "one").stroke.dashes, vec![3.0, 2.0, 1.0, 0.0], "one in: three of the first dash are left"); + assert_eq!(node(&d, f, "mixed").stroke.dashes, vec![4.0, 2.0], "an open subpath makes the outline open"); +} + +/// A text stroke runs along glyph contours, which close, so its offset is applied as on a shape. +#[test] +fn a_text_stroke_keeps_a_dash_offset_of_half_a_dash() { + if figcraft_text::fontdb::find_face("Inter", "Regular").is_none() { + return; + } + let (d, f) = import( + r##"T"##, + ); + assert_eq!(node(&d, f, "t").stroke.dashes, vec![2.0, 2.0, 2.0, 0.0]); } #[test] From 7b5f8c369988ad6b46946b91a95a87aa347f0e93 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 1 Nov 2026 12:30:08 -0500 Subject: [PATCH 064/326] docs: sync Craft App Suite list with ArtCraft Launcher --- README.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 63c8fb3d1..012ca857a 100644 --- a/README.md +++ b/README.md @@ -314,14 +314,22 @@ stand on its own. | | App | What it's for | Code | Learn more | |:-:|---|---|---|---| -| | **FigCraft** | **Interface design, components and prototypes · you are here** | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | -| | **PhotoCraft** | Image editing | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | +| | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | | | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | | | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | | | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. From e7a599baea9f3accbb9dd1ef561fc03566d1875a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sun, 1 Nov 2026 19:42:52 +0100 Subject: [PATCH 065/326] style(text): M2.1: clarify font filter precedence --- crates/text/src/fontdb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 6ebd7ec45..ac851647b 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -1304,7 +1304,7 @@ fn index_font_file(path: &std::path::Path, meta: &std::fs::Metadata, out: &mut B return; } let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).unwrap_or_default(); - if !(matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") || path.extension().is_none() && starts_like_a_font(path)) { + if !(matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") || (path.extension().is_none() && starts_like_a_font(path))) { return; } // Very large files are indexed all the same (Apple Color Emoji is ~180 MB and is where the From c41471d20bdde3e7308afce5fe92a884f1873a60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sun, 1 Nov 2026 19:54:54 +0100 Subject: [PATCH 066/326] build(pathops): M2.1: inherit workspace Rust version --- crates/pathops/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/pathops/Cargo.toml b/crates/pathops/Cargo.toml index 27e2b7200..207a79cdf 100644 --- a/crates/pathops/Cargo.toml +++ b/crates/pathops/Cargo.toml @@ -3,6 +3,7 @@ name = "figcraft-pathops" version.workspace = true edition.workspace = true license.workspace = true +rust-version.workspace = true description = "FigCraft path operations: booleans (union, subtract, intersect, exclude), outline stroke with inside/center/outside alignment, arrowheads" [lints] From 5fc2840d9089e0b21056b57c4dff9f795e38a4e3 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 1 Nov 2026 13:58:36 -0500 Subject: [PATCH 067/326] Release 0.14.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 44 ++++++++++++++++++++++---------------------- Cargo.toml | 2 +- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 797f6498d..888365316 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1763,7 +1763,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" [[package]] name = "figcraft" -version = "0.13.1" +version = "0.14.0" dependencies = [ "arboard", "craft-menu", @@ -1795,7 +1795,7 @@ dependencies = [ [[package]] name = "figcraft-cli" -version = "0.13.1" +version = "0.14.0" dependencies = [ "clap", "clap_complete", @@ -1813,7 +1813,7 @@ dependencies = [ [[package]] name = "figcraft-collab" -version = "0.13.1" +version = "0.14.0" dependencies = [ "base64 0.22.1", "chrono", @@ -1831,7 +1831,7 @@ dependencies = [ [[package]] name = "figcraft-collab-net" -version = "0.13.1" +version = "0.14.0" dependencies = [ "base64 0.22.1", "figcraft-collab", @@ -1854,7 +1854,7 @@ dependencies = [ [[package]] name = "figcraft-color" -version = "0.13.1" +version = "0.14.0" dependencies = [ "kurbo", "serde", @@ -1863,7 +1863,7 @@ dependencies = [ [[package]] name = "figcraft-doc" -version = "0.13.1" +version = "0.14.0" dependencies = [ "figcraft-color", "figcraft-geom", @@ -1876,7 +1876,7 @@ dependencies = [ [[package]] name = "figcraft-engine" -version = "0.13.1" +version = "0.14.0" dependencies = [ "base64 0.22.1", "craft-docpath", @@ -1910,7 +1910,7 @@ dependencies = [ [[package]] name = "figcraft-format" -version = "0.13.1" +version = "0.14.0" dependencies = [ "figcraft-doc", "figcraft-layout", @@ -1927,7 +1927,7 @@ dependencies = [ [[package]] name = "figcraft-geom" -version = "0.13.1" +version = "0.14.0" dependencies = [ "kurbo", "serde", @@ -1935,7 +1935,7 @@ dependencies = [ [[package]] name = "figcraft-layout" -version = "0.13.1" +version = "0.14.0" dependencies = [ "figcraft-doc", "figcraft-geom", @@ -1943,7 +1943,7 @@ dependencies = [ [[package]] name = "figcraft-mcp" -version = "0.13.1" +version = "0.14.0" dependencies = [ "base64 0.22.1", "figcraft-collab-net", @@ -1959,7 +1959,7 @@ dependencies = [ [[package]] name = "figcraft-pathops" -version = "0.13.1" +version = "0.14.0" dependencies = [ "figcraft-doc", "figcraft-geom", @@ -1968,7 +1968,7 @@ dependencies = [ [[package]] name = "figcraft-pdf" -version = "0.13.1" +version = "0.14.0" dependencies = [ "figcraft-color", "figcraft-doc", @@ -1985,7 +1985,7 @@ dependencies = [ [[package]] name = "figcraft-plugin" -version = "0.13.1" +version = "0.14.0" dependencies = [ "figcraft-color", "serde", @@ -1998,7 +1998,7 @@ dependencies = [ [[package]] name = "figcraft-render" -version = "0.13.1" +version = "0.14.0" dependencies = [ "crc32fast", "figcraft-color", @@ -2017,7 +2017,7 @@ dependencies = [ [[package]] name = "figcraft-server" -version = "0.13.1" +version = "0.14.0" dependencies = [ "chrono", "crc32fast", @@ -2042,7 +2042,7 @@ dependencies = [ [[package]] name = "figcraft-svg" -version = "0.13.1" +version = "0.14.0" dependencies = [ "base64 0.22.1", "figcraft-color", @@ -2058,7 +2058,7 @@ dependencies = [ [[package]] name = "figcraft-text" -version = "0.13.1" +version = "0.14.0" dependencies = [ "core-text", "craft-font-catalog", @@ -2076,7 +2076,7 @@ dependencies = [ [[package]] name = "figcraft-ui-egui" -version = "0.13.1" +version = "0.14.0" dependencies = [ "base64 0.22.1", "chrono", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "figcraft-vectordrawable" -version = "0.13.1" +version = "0.14.0" dependencies = [ "figcraft-color", "figcraft-doc", @@ -2118,7 +2118,7 @@ dependencies = [ [[package]] name = "figcraft-web" -version = "0.13.1" +version = "0.14.0" dependencies = [ "base64 0.22.1", "eframe", @@ -6739,7 +6739,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.13.1" +version = "0.14.0" dependencies = [ "figcraft-engine", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index a560971a8..c7a86dd21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ exclude = ["plugins"] # default-members = ["crates/*", "apps/figcraft", "apps/figcraft-cli", "xtask"] [workspace.package] -version = "0.13.1" +version = "0.14.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 83c28cf3aeb2df61c8c0c3941a3e7fbe6dbe5e1a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 14:12:18 -0500 Subject: [PATCH 068/326] M6: SVG import: a stretched image stays stretched (#1811) Co-authored-by: Claude Fable 5.1 --- crates/svg/src/import.rs | 12 +++++++++++- crates/svg/src/import/structure_tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 71c6c3b05..e3d9d8523 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -608,7 +608,17 @@ fn image(cx: &mut Ctx, img: &usvg::Image, id: &str, parent: NodeId, base: Affine let hash = add_image(cx.doc, bytes, iw, ih); let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Rectangle, layer_name(id, "Image"), w, h); n.transform = transform; - n.fills = vec![Paint::image(hash, ImageScaleMode::Fill)]; + let mut fill = Paint::image(hash, ImageScaleMode::Fill); + // usvg sizes the box to the picture (`meet` and `slice` are in the transform), so a box of + // another shape is `preserveAspectRatio="none"`: the picture stretched edge to edge. A Fill + // would keep its shape and crop it; a crop of the whole picture stretches it. + if (w * ih - h * iw).abs() > 1e-6 * (w * ih).max(h * iw) + && let figcraft_color::PaintKind::Image(ip) = &mut fill.kind + { + ip.scale_mode = ImageScaleMode::Crop; + ip.crop = Some(Affine::IDENTITY.as_coeffs()); + } + n.fills = vec![fill]; cx.add(n, parent); } diff --git a/crates/svg/src/import/structure_tests.rs b/crates/svg/src/import/structure_tests.rs index adeedb005..f16abb66a 100644 --- a/crates/svg/src/import/structure_tests.rs +++ b/crates/svg/src/import/structure_tests.rs @@ -129,6 +129,28 @@ fn strokes_scale_with_their_layer() { assert_eq!((l.width, l.stroke.weight, l.stroke.dashes.clone()), (30.0, 6.0, vec![12.0, 6.0])); } +/// `preserveAspectRatio="none"` stretches a picture into its box edge to edge. usvg sizes the +/// box to the picture for `meet` and `slice` (the fit is in the transform), so a box of another +/// shape is a stretch: a Fill, which keeps the picture's shape and crops it, would show the +/// middle of the picture instead. +#[test] +fn an_image_stretched_into_its_box_stays_stretched() { + use figcraft_color::{ImageScaleMode, PaintKind}; + let (d, f) = + import(&format!(r##""##)); + let n = node(&d, f, "pic"); + assert_eq!((n.width, n.height), (40.0, 40.0)); + let Some(PaintKind::Image(ip)) = n.fills.first().map(|p| &p.kind) else { panic!("{:?}", n.fills) }; + // The 4 × 2 picture's pixels map onto the whole 40 × 40 box: 10 across, 20 down. + let m = figcraft_render::paint::image_transform(ip, 4.0, 2.0, n.width, n.height); + assert_eq!((m.sx, m.ky, m.kx, m.sy, m.tx, m.ty), (10.0, 0.0, 0.0, 20.0, 0.0, 0.0), "{ip:?}"); + // With the aspect kept (the default) the box is the picture's own shape and a Fill is exact. + let (d, f) = import(&format!(r##""##)); + let n = node(&d, f, "pic"); + assert_eq!((n.width, n.height), (40.0, 20.0)); + assert!(matches!(n.fills.first().map(|p| &p.kind), Some(PaintKind::Image(i)) if i.scale_mode == ImageScaleMode::Fill), "{:?}", n.fills); +} + #[test] fn linked_files_are_never_read() { let dir = std::env::temp_dir().join("figcraft-svg-linked"); From 6b2e464361e84e3df28d33da5681ac08e9991763 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=82=BC=ED=98=84?= Date: Mon, 2 Nov 2026 04:12:23 +0900 Subject: [PATCH 069/326] M8: a scaled node's spread shadow keeps its room in SVG (#1803) The SVG export blurs a spread drop shadow in a filter whose region is the silhouette's page bounds grown by the spread's mitre and the blur. The spread grows the outline in the node's own units, though, and the transform then scales it: on a star scaled three times, a spread of 10 mitred out to some 97 units while the region only made room for 48, so SVG viewers cut the shadow's points off. The spread now grows the region as far across and down as the transform takes a local step of that length, as the paint bounds already do. Co-authored-by: Claude Opus 5.5 --- crates/svg/src/effects_tests.rs | 42 +++++++++++++++++++++++++++++++++ crates/svg/src/lib.rs | 10 +++++--- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/effects_tests.rs b/crates/svg/src/effects_tests.rs index 5177e992b..f81d8e04c 100644 --- a/crates/svg/src/effects_tests.rs +++ b/crates/svg/src/effects_tests.rs @@ -83,3 +83,45 @@ fn hostile_shadow_values_still_export() { assert!(export_svg(&d, &[n], &SvgOptions::default()).is_some()); } } + +/// The filter a spread shadow is blurred in makes room for the spread as the node's transform +/// draws it: on a star scaled three times, the spread's mitres reach three times as far, and on a +/// skewed one further across than down. +#[test] +fn a_scaled_spread_shadow_keeps_its_filter_room() { + use figcraft_doc::SPREAD_MITER_LIMIT; + use figcraft_geom::{Affine, kurbo}; + let star = NodeKind::Star { count: 5, inner_ratio: 0.4 }; + let s = + Shadow { color: Color::from_hex("000000").unwrap(), offset: (6.0, -9.0), radius: 4.0, spread: 10.0, show_behind: true, ..Default::default() }; + for (why, xf) in [ + ("scaled 3", Affine::scale(3.0)), + ("scaled (3, 1)", Affine::scale_non_uniform(3.0, 1.0)), + ("skewed", Affine::new([1.0, 0.0, 2.0, 1.0, 0.0, 0.0])), + ("turned and stretched", Affine::rotate(0.5) * Affine::scale_non_uniform(3.0, 1.0)), + ("as drawn", Affine::IDENTITY), + ] { + let (mut d, n) = with_effects(star.clone(), vec![EffectKind::DropShadow(s.clone())]); + let t = d.get(n).unwrap().transform; + d.get_mut(n).unwrap().transform = t * xf; + let svg = export(&d, n); + let tag = &svg[svg.find(" f64 { + let at = tag.find(&format!(" {name}=\"")).unwrap() + name.len() + 3; + tag[at..at + tag[at..].find('"').unwrap()].parse().unwrap() + }; + let region = kurbo::Rect::new(attr("x"), attr("y"), attr("x") + attr("width"), attr("y") + attr("height")); + // What the shadow paints, as the renderer draws it: the outline stroked twice the spread + // wide with mitred joins, through the node's transform, moved by the offset (in the + // export's frame, which starts at the node's export bounds) and blurred. + let bounds = figcraft_render::export_bounds(&d, n).unwrap(); + let at = Affine::translate((s.offset.0 - bounds.x0, s.offset.1 - bounds.y0)) * d.world_transform(n); + let shape = figcraft_render::node_outline(&d, d.get(n).unwrap()).unwrap(); + let stroke = kurbo::Stroke::new(s.spread * 2.0).with_join(kurbo::Join::Miter).with_miter_limit(SPREAD_MITER_LIMIT); + let mut grown = kurbo::stroke(shape.0.iter(), &stroke, &Default::default(), 0.01); + grown.apply_affine(at); + let blur = s.radius * 1.5; + let painted = figcraft_geom::Shape::bounding_box(&grown).inflate(blur, blur); + assert!(region.union(painted) == region, "{why}: the filter {region:?} cuts the shadow at {painted:?}"); + } +} diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index de98795d3..58d80ac91 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -1052,10 +1052,14 @@ impl W<'_> { else { continue; }; - let reach = s.spread.abs() * SPREAD_MITER_LIMIT + s.radius.abs() * 1.5 + 2.0; + // The spread grows the outline in its own units (mitres up to the limit), drawn through + // `xf`: as far across and down as a local step that long goes. The blur is in page units. + let spread = if s.spread.is_finite() { s.spread.abs() * SPREAD_MITER_LIMIT } else { 0.0 }; + let [a, b_, c, d, _, _] = xf.as_coeffs(); + let blur = s.radius.abs() * 1.5 + 2.0; + let region = b.inflate(spread * a.hypot(c) + blur, spread * b_.hypot(d) + blur); let cover = if s.show_behind { None } else { self.cover_input(n, xf) }; - let filter = - self.blur_filter(s.radius, b.inflate(reach, reach), cover.as_deref()).map(|f| format!(" filter=\"url(#{f})\"")).unwrap_or_default(); + let filter = self.blur_filter(s.radius, region, cover.as_deref()).map(|f| format!(" filter=\"url(#{f})\"")).unwrap_or_default(); let op = f64::from(s.color.a * n.opacity.clamp(0.0, 1.0)); let blend = if matches!(s.blend, figcraft_color::BlendMode::Normal | figcraft_color::BlendMode::PassThrough) { String::new() From 264bcb1c03219fe8785af50487d7b5a367a338c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=82=BC=ED=98=84?= Date: Mon, 2 Nov 2026 04:12:27 +0900 Subject: [PATCH 070/326] M8: an arc's spread shadow and mitred stroke get room for their corners (#1802) * M8: an arc's spread shadow gets room for its mitred corners Rectangles, frames and ellipses grow by exactly their spread, so their layers only make room for the spread itself; other shapes make room for the mitre at sharp corners (up to four times the spread). An ellipse with arc data (a pie slice, or a ring cut short) counted as an ellipse, but its ends meet its sides in sharp corners: a spread of 25 on a slice of 0.3 rad cut its shadow off at the layer's edge (up to 255 levels). Only an ellipse that goes all the way round now grows by exactly its spread. `figcraft_geom::full_sweep` is what `ellipse` already used to tell a whole ellipse or ring from an arc, so the two agree. Co-Authored-By: Claude Opus 5.5 * M8: an arc's mitred stroke gets room for its corners too Review: `outline_reach` counted every ellipse as an outline whose stroke mitres end on the grown box, the same mistake as the spread. A thin slice with a 20-unit mitred stroke and a spread of 10 still had its shadow cut off (255 levels). It now asks `grows_by_exactly_its_spread`, which picks the same shapes and leaves arcs out. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/node.rs | 17 +++++++---- crates/geom/src/lib.rs | 8 ++++- crates/render/src/spread_tests.rs | 50 +++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 6ec7e8245..3ac81afdb 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -942,9 +942,9 @@ impl Node { matches!(&self.kind, NodeKind::Vector { network } if network.vertices.iter().any(|v| v.cap.is_some_and(StrokeCap::is_arrow))); let caps = if self.stroke.cap_start.is_arrow() || self.stroke.cap_end.is_arrow() || point_arrows { w.max(self.stroke.weight) * 3.0 } else { w }; - // Right-angled or smooth outlines (boxes, ellipses) end their mitres on the grown box. - let boxy = matches!(self.kind, NodeKind::Rectangle | NodeKind::Ellipse { .. } | NodeKind::Section { .. }) || self.kind.is_frame_like(); - let miter = if boxy { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) }; + // Right-angled or smooth outlines (boxes, whole ellipses) end their mitres on the grown + // box; an arc's corners don't. + let miter = if self.grows_by_exactly_its_spread() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) }; base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * miter } else { 0.0 @@ -960,14 +960,19 @@ impl Node { !(matches!(self.kind, NodeKind::Group) || (matches!(self.kind, NodeKind::Text(_)) && self.has_visible_stroke())) } - /// Whether a spread grows this node's outline by exactly the spread (no sharp corners). + /// Whether a spread grows this node's outline by exactly the spread (no sharp corners). An arc + /// (an ellipse that doesn't go all the way round) has corners where its ends meet its sides. fn grows_by_exactly_its_spread(&self) -> bool { - matches!(self.kind, NodeKind::Rectangle | NodeKind::Ellipse { .. } | NodeKind::Section { .. }) || self.kind.is_frame_like() + match self.kind { + NodeKind::Rectangle | NodeKind::Section { .. } => true, + NodeKind::Ellipse { sweep, .. } => figcraft_geom::full_sweep(sweep), + _ => self.kind.is_frame_like(), + } } /// How much further than its spread a drop shadow can reach at the outline's sharp corners: /// spread moves the edges out in parallel and they meet in a mitre (see - /// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and ellipses grow by exactly the spread. + /// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread. fn spread_miter_reach(&self) -> f64 { if self.grows_by_exactly_its_spread() { return 0.0; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 012fca429..696a02e92 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -319,6 +319,12 @@ fn line_or_move(path: &mut BezPath, p: Point) { } } +/// Whether an ellipse of this `sweep` (radians) goes all the way round: a whole ellipse or ring, +/// without the sharp corners where an arc's ends meet its sides. +pub fn full_sweep(sweep: f64) -> bool { + finite(sweep).abs() >= TAU - 1e-9 +} + /// An ellipse in the `width`×`height` box; with arc data, a pie/arc/ring: `start` and `sweep` in /// radians (clockwise from 3 o'clock, y-down) and `inner` radius ratio 0..1. pub fn ellipse(width: f64, height: f64, start: f64, sweep: f64, inner: f64) -> BezPath { @@ -327,7 +333,7 @@ pub fn ellipse(width: f64, height: f64, start: f64, sweep: f64, inner: f64) -> B let sweep = finite(sweep).clamp(-TAU, TAU); let start = finite(start); let inner = finite(inner).clamp(0.0, 1.0); - let full = sweep.abs() >= TAU - 1e-9; + let full = full_sweep(sweep); let mut path = BezPath::new(); if full && inner <= 0.0 { return kurbo::Ellipse::new(c, (rx, ry), 0.0).to_path(0.01); diff --git a/crates/render/src/spread_tests.rs b/crates/render/src/spread_tests.rs index 00fbb6333..6b30766fc 100644 --- a/crates/render/src/spread_tests.rs +++ b/crates/render/src/spread_tests.rs @@ -142,3 +142,53 @@ fn spread_bands_are_cached_and_hostile_values_are_safe() { let _ = render(&d, n); } } + +/// An arc (a pie slice, or a ring cut short) has sharp corners where its ends meet its sides, and +/// a spread mitres them out past the spread: its layer makes room for that, as a star's does. A +/// clear shadow spread four times as far gives the same layer room to the full mitre: the shadow +/// it casts is the same. (Both layers end at the view here, so they line up pixel for pixel; +/// layers starting at different pixels can differ by a few levels at their edges.) +#[test] +fn arc_spread_mitres_are_not_cut_off() { + for kind in [ + NodeKind::Ellipse { start: 1.0, sweep: 0.3, inner: 0.0 }, + NodeKind::Ellipse { start: 0.0, sweep: 3.0, inner: 0.0 }, + NodeKind::Ellipse { start: 1.0, sweep: 2.0, inner: 0.8 }, + ] { + for spread in [25.0, 40.0] { + let (d, n) = shape(kind.clone(), vec![EffectKind::DropShadow(shadow(spread))]); + let clear = Shadow { color: Color::new(0.0, 0.0, 0.0, 0.0), ..shadow(spread * 4.0) }; + let (roomy, m) = shape(kind.clone(), vec![EffectKind::DropShadow(shadow(spread)), EffectKind::DropShadow(clear)]); + let (a, b) = (render(&d, n), render(&roomy, m)); + let worst = a.data().chunks(4).zip(b.data().chunks(4)).map(|(p, q)| p[3].abs_diff(q[3])).max().unwrap_or(0); + assert!(worst <= 2, "{kind:?}, a spread of {spread}: {worst} levels cut off"); + } + } +} + +/// A mitred stroke on an arc reaches out past its width at the arc's corners too, and a spread +/// grows from there: a thin slice with both keeps its whole shadow. +#[test] +fn arc_stroke_mitres_are_not_cut_off() { + use figcraft_doc::{StrokeAlign, StrokeJoin}; + let kind = NodeKind::Ellipse { start: std::f64::consts::FRAC_PI_2 - 0.015, sweep: 0.03, inner: 0.0 }; + for align in [StrokeAlign::Center, StrokeAlign::Outside] { + let make = |effects: Vec| { + let mut d = Document::new("arc"); + let p = d.first_page().unwrap(); + let n = d.create(p, kind.clone(), "S", 0.0, 190.0, 400.0, 20.0).unwrap(); + let node = d.get_mut(n).unwrap(); + node.fills = vec![Paint::solid(Color::WHITE)]; + node.strokes = vec![Paint::solid(Color::WHITE)]; + (node.stroke.weight, node.stroke.align, node.stroke.join, node.stroke.miter_limit) = (20.0, align, StrokeJoin::Miter, 4.0); + node.effects = effects.into_iter().map(|kind| Effect { kind, visible: true }).collect(); + (d, n) + }; + let (d, n) = make(vec![EffectKind::DropShadow(shadow(10.0))]); + let clear = Shadow { color: Color::new(0.0, 0.0, 0.0, 0.0), ..shadow(80.0) }; + let (roomy, m) = make(vec![EffectKind::DropShadow(shadow(10.0)), EffectKind::DropShadow(clear)]); + let (a, b) = (render(&d, n), render(&roomy, m)); + let worst = a.data().chunks(4).zip(b.data().chunks(4)).map(|(p, q)| p[3].abs_diff(q[3])).max().unwrap_or(0); + assert!(worst <= 2, "{align:?}: {worst} levels cut off"); + } +} From bd920fc7dec63ee8d433884a175f2f581cc9eb87 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 14:12:31 -0500 Subject: [PATCH 071/326] M8: .fig import: a routed connector takes its line style from the generated record (#1807) (#1813) * M8: .fig import: a routed connector takes its line style from the generated record (#1807) Co-Authored-By: Claude Fable 5.1 * M8: .fig import: a routed connector keeps its own empty paints and dash pattern CodeRabbit review on #1813: an explicit empty strokePaints (no stroke) or dashPattern (solid) on the connector no longer takes the generated record's. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- .../format/src/fig/connector_label_tests.rs | 58 +++++++++++++++++++ crates/format/src/fig/map/connector.rs | 26 +++++++++ docs/file-format-parity.md | 5 +- 3 files changed, 87 insertions(+), 2 deletions(-) diff --git a/crates/format/src/fig/connector_label_tests.rs b/crates/format/src/fig/connector_label_tests.rs index de0c4f2fb..ca76c0b29 100644 --- a/crates/format/src/fig/connector_label_tests.rs +++ b/crates/format/src/fig/connector_label_tests.rs @@ -218,6 +218,64 @@ fn connector_mut<'a, 's>(message: &'a mut Kv<'s>, local_id: u64) -> Option<&'a m }) } +fn set_connector_field(message: &mut Kv<'_>, key: &'static str, value: Kv<'static>) { + let connector = connector_mut(message, 123).expect("synthetic connector"); + let Kv::Object(fields) = connector else { panic!("connector object") }; + if let Some((_, current)) = fields.iter_mut().find(|(name, _)| *name == key) { + *current = value; + } else { + fields.push((key, value)); + } +} + +/// A connector without a saved snapshot (a curved or elbowed one is routed here) still draws its +/// line as the generated record says: the paint, weight, cap and dashes live there, not on the +/// connector (#1807). +#[test] +fn a_routed_connector_takes_its_line_style_from_the_generated_record() { + let mut message = synthetic_connector(1.0, false, 0.0); + set_connector_field(&mut message, "connectorLineStyle", Kv::Enum("CURVED")); + set_connector_field(&mut message, "connectorStart", obj(vec![("position", point(10.0, 10.0))])); + set_connector_field(&mut message, "connectorEnd", obj(vec![("position", point(110.0, 60.0))])); + set_override_field(&mut message, "nodeGenerationData", 0, "strokeWeight", scalar(4.0)); + set_override_field(&mut message, "nodeGenerationData", 0, "strokeCap", Kv::Enum("ROUND")); + set_override_field(&mut message, "nodeGenerationData", 0, "dashPattern", Kv::Array(vec![scalar(16.0), scalar(10.0)])); + let (rest, warnings, _) = map::to_rest(&message, "synthetic", crate::rest::MAX_NODES); + let connector = &rest["document"]["children"][0]["children"][0]; + assert_eq!(connector["type"], "VECTOR"); + assert!(connector.get("vectorNetwork").is_some(), "routed here: {connector}"); + assert_eq!(connector["strokes"].as_array().map(Vec::len), Some(1), "{connector}"); + assert!((connector["strokes"][0]["color"]["b"].as_f64().unwrap() - 0.8).abs() < 1e-6); + assert_eq!(connector["strokeWeight"], 4.0); + assert_eq!(connector["strokeDashes"], serde_json::json!([16.0, 10.0])); + assert_eq!(connector["strokeCapEnd"], "ARROW"); + assert!(warnings.iter().any(|warning| warning.contains("follow FigCraft's own routing")), "{warnings:?}"); + + let (native, _) = crate::rest::import_fig(&rest, &|_| None).unwrap(); + let node = find_node(&native, "synthetic connector"); + assert_eq!((node.strokes.len(), node.stroke.weight, node.stroke.dashes.clone()), (1, 4.0, vec![16.0, 10.0])); +} + +/// A routed connector that writes its own empty paints and dash pattern is meant to have no stroke +/// and a solid line: the generated record's paint and dashes don't replace them. +#[test] +fn a_routed_connector_keeps_its_own_empty_paints_and_dashes() { + let mut message = synthetic_connector(1.0, false, 0.0); + set_connector_field(&mut message, "connectorLineStyle", Kv::Enum("CURVED")); + set_connector_field(&mut message, "connectorStart", obj(vec![("position", point(10.0, 10.0))])); + set_connector_field(&mut message, "connectorEnd", obj(vec![("position", point(110.0, 60.0))])); + set_connector_field(&mut message, "strokePaints", Kv::Array(Vec::new())); + set_connector_field(&mut message, "dashPattern", Kv::Array(Vec::new())); + set_override_field(&mut message, "nodeGenerationData", 0, "strokeWeight", scalar(4.0)); + set_override_field(&mut message, "nodeGenerationData", 0, "dashPattern", Kv::Array(vec![scalar(16.0), scalar(10.0)])); + let (rest, _, _) = map::to_rest(&message, "synthetic", crate::rest::MAX_NODES); + let connector = &rest["document"]["children"][0]["children"][0]; + assert!(connector.get("vectorNetwork").is_some(), "routed here: {connector}"); + assert!(connector["strokes"].as_array().is_none_or(Vec::is_empty), "{connector}"); + assert!(connector.get("strokeDashes").is_none(), "{connector}"); + assert_eq!(connector["strokeWeight"], 4.0); +} + fn set_override_field(message: &mut Kv<'_>, field: &str, local_id: u64, key: &'static str, value: Kv<'static>) { let connector = connector_mut(message, 123).expect("synthetic connector"); let section = field_mut(connector, field).expect("connector override section"); diff --git a/crates/format/src/fig/map/connector.rs b/crates/format/src/fig/map/connector.rs index 7da7458b9..de2ff501c 100644 --- a/crates/format/src/fig/map/connector.rs +++ b/crates/format/src/fig/map/connector.rs @@ -1,4 +1,5 @@ use super::layer::{cap_name, own_text, svg_path, valid_size}; +use super::paint::{paint, stroke}; use super::{Affine, Kv, Mapper, NO_STYLE, Obj, Point, Value, View, generated_record, guid, json, matrix, network, num, rows}; use figcraft_doc::geom::kurbo::{BezPath, PathEl, Rect, Shape}; use figcraft_doc::{RouteEnd, Routing, Side, route_points}; @@ -29,6 +30,7 @@ impl<'a> Mapper<'a> { return Vec::new(); } let mid = self.connector(o, v, space); + self.connector_line_style(o, v); if shape.label { return self.connector_label(o, v, rest_id, mid); } @@ -122,6 +124,30 @@ impl<'a> Mapper<'a> { middle(&path).map(|m| m - b.origin().to_vec2()) } + /// The line's paint, weight, cap and dashes, which a connector keeps in its generated line + /// record rather than on itself: without a saved snapshot the routed line took none of them and + /// drew nothing (#1807). The connector's own values, when it has any, win. + fn connector_line_style(&mut self, o: &mut Obj, v: &View<'a>) { + let Some(line_style) = generated_record(v, "nodeGenerationData", 0) else { return }; + let style = View::of(line_style); + // A connector that writes its own (even empty) paints or dash pattern keeps them: an empty + // list is no stroke, or a solid line, not a missing value. + if v.get("strokePaints").is_none() && o.get("strokes").and_then(Value::as_array).is_none_or(Vec::is_empty) { + let strokes: Vec = style.list("strokePaints").iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect(); + if !strokes.is_empty() { + o.insert("strokes".into(), Value::Array(strokes)); + } + } + let mut line = Obj::new(); + stroke(&mut line, &style); + if v.get("dashPattern").is_some() { + line.remove("strokeDashes"); + } + for (key, value) in line { + o.entry(key).or_insert(value); + } + } + /// A connector with a label but no saved snapshot of it, as the frame a saved one imports as: /// `o` keeps the connector's place and size and gives its line to a vector child, and the /// label is a text child centred on `mid` (the line's middle; the frame's centre when the line diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 50805f39e..56cc701a2 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-10-31 · **Change:** minor (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-01 · **Change:** minor (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,7 +17,7 @@ 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), 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). 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, 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), 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), and 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, 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 | — | @@ -187,6 +187,7 @@ source paint coordinates. | Date | Change | Summary | |---|---|---| +| 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 | patch | M4: Dash and Custom strokes have a Dash cap (None, Round, Square) in the advanced stroke settings and `node.set {dashCap}`, on both ends of every dash on the canvas and in PNG, PDF and SVG. Unset, dashes keep taking the end point caps, so older files look the same; the saved file writes it only when set. Numbers unchanged | | 2026-10-30 | minor | `.fig` import: a connector's label without a saved snapshot was skipped; now the connector imports as a frame holding its line and the label, as a connector with a saved snapshot does, the label centred on the line's middle by length (in a 200-wide box, laid out again with the fonts at hand), in the connector's fill paints or black. Its background isn't known without the snapshot and is left out. Not checked on real files. Test: `fig::tests::tail::a_labelled_connector_without_a_snapshot_keeps_its_label` | | 2026-10-30 | minor | Pasted content row: an image the clipboard doesn't carry keeps its name and shows a placeholder that reads as missing; the paste names those layers in its message and opens the import report with its notes (#1646). Numbers unchanged | From cda326e24e8972eb2724f2456707562dd50cbcfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 20:54:42 +0100 Subject: [PATCH 072/326] fix(vectordrawable): M2.1: use inclusive range checks --- crates/vectordrawable/src/paint.rs | 2 +- crates/vectordrawable/src/tests/gradients.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/vectordrawable/src/paint.rs b/crates/vectordrawable/src/paint.rs index f66d0554a..0e8d01407 100644 --- a/crates/vectordrawable/src/paint.rs +++ b/crates/vectordrawable/src/paint.rs @@ -68,7 +68,7 @@ pub(crate) fn color_at(stops: &[(f64, Color)], t: f64) -> Color { /// the seam where the gradient starts over kept as a hard step. pub(crate) fn turn_stops(stops: &[(f64, Color)], shift: f64) -> Vec<(f64, Color)> { let d = shift.rem_euclid(1.0); - if !d.is_finite() || d < 1e-9 || d > 1.0 - 1e-9 || stops.is_empty() { + if !d.is_finite() || !(1e-9..=1.0 - 1e-9).contains(&d) || stops.is_empty() { return stops.to_vec(); } let seam = 1.0 - d; diff --git a/crates/vectordrawable/src/tests/gradients.rs b/crates/vectordrawable/src/tests/gradients.rs index ae58126e1..8f2a69edc 100644 --- a/crates/vectordrawable/src/tests/gradients.rs +++ b/crates/vectordrawable/src/tests/gradients.rs @@ -77,7 +77,7 @@ fn every_gradient_samples_where_figcraft_samples_it() { let stops: Vec<_> = g.sorted_stops().iter().map(|s| (f64::from(s.position), s.color)).collect(); let (a, b) = (color_at(&stops, want), color_at(&grad.stops, got)); // Away from the sweep's seam a turn's worth either side is the same colour. - let near_seam = kind == GradientKind::Angular && (want < 1e-3 || want > 1.0 - 1e-3); + let near_seam = kind == GradientKind::Angular && !want.is_nan() && !(1e-3..=1.0 - 1e-3).contains(&want); if !near_seam { assert!( (a.r - b.r).abs() < 1e-3 && (a.g - b.g).abs() < 1e-3 && (a.b - b.b).abs() < 1e-3, @@ -107,7 +107,7 @@ fn the_written_gradient_matches_the_rendered_pixels() { for x in (2..98).step_by(3) { let pt = Point::new(x as f64 + 0.5, y as f64 + 0.5); let ft = figcraft_t(kind, f, pt); - if kind == GradientKind::Angular && (ft < 0.03 || ft > 0.97 || (ft - 0.6).abs() < 0.01) { + if kind == GradientKind::Angular && !ft.is_nan() && (!(0.03..=0.97).contains(&ft) || (ft - 0.6).abs() < 0.01) { continue; } let (t, grad) = vd_t(&out, pt).unwrap(); @@ -149,7 +149,7 @@ fn turned_stops_keep_every_colour_where_it_was() { for i in 1..200 { let t = i as f64 / 200.0; let moved = (t + shift).rem_euclid(1.0); - if moved < 1e-6 || moved > 1.0 - 1e-6 { + if !moved.is_nan() && !(1e-6..=1.0 - 1e-6).contains(&moved) { continue; } let (a, b) = (color_at(&stops, t), color_at(&turned, moved)); From 6f7814c9d3c4c8d25d1750962e6e9603725d9d2b Mon Sep 17 00:00:00 2001 From: michaelgiraldo <1228401+michaelgiraldo@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:23:39 -0800 Subject: [PATCH 073/326] M9: document combined browser and collaboration hosting --- docs/server.md | 12 ++++++++++++ packaging/server/Caddyfile | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/docs/server.md b/docs/server.md index 9d42cb0fc..fddd5852e 100644 --- a/docs/server.md +++ b/docs/server.md @@ -753,6 +753,18 @@ sudo -u figcraft figcraft-server --config /etc/figcraft-server/server.toml key The other commands ([Managing files and links](#managing-files-and-links)) run the same way, as the `figcraft` user with `--config /etc/figcraft-server/server.toml`. +**Browser editor on the same hostname (optional).** The steps above install the collaboration +server. To also serve the editor, copy the complete contents of the matching +`figcraft-web-/` release directory into `/srv/figcraft-web`, with `index.html` directly +inside it; keep subdirectories such as `snippets/`. Use the commented browser-and-server block +in [`packaging/server/Caddyfile`](../packaging/server/Caddyfile) in place of its active server-only +block. Keep the loopback `listen`, `public_url` and `trusted_proxy` settings from steps 2 and 4. +The editor opens at `https://figcraft.example.com/app/`; the hostname root remains the +`wss://figcraft.example.com/` collaboration endpoint, not an editor homepage. Configure the +browser's `figcraft-server` meta tag as described in the +[web-hosting guide](../packaging/web/README.md#live-sessions), using the server address without a +publishing key. That guide also covers browser requirements, fonts and static-file delivery. + **In Docker instead of systemd.** [`packaging/server/Dockerfile`](../packaging/server/Dockerfile) builds a small image (the binary on a distroless base, no shell) that runs as an unprivileged user, keeps its files in the `/data` volume and stops gracefully on `docker stop`. Build it from diff --git a/packaging/server/Caddyfile b/packaging/server/Caddyfile index cd34394d0..e8ba7be8f 100644 --- a/packaging/server/Caddyfile +++ b/packaging/server/Caddyfile @@ -16,3 +16,35 @@ figcraft.example.com { # reverse_proxy 127.0.0.1:47900 # } # } + +# Browser editor and server on the same hostname instead. Use this block IN PLACE OF the +# active block above. Copy the complete browser release into /srv/figcraft-web, with index.html +# directly inside it and subdirectories such as snippets/ kept. See packaging/web/README.md for +# the browser's figcraft-server meta tag; never put a publishing key in public HTML. +# Open the editor at /app/. The hostname root remains the WSS endpoint, not an editor homepage. +# +# figcraft.example.com { +# encode gzip +# +# redir /app /app/?{query} 308 +# +# @entry path /app/ /app/index.html +# header @entry Cache-Control "no-cache" +# +# @release_assets path /app/figcraft-web-*.js /app/figcraft-web-*_bg.wasm +# header @release_assets Cache-Control "public, max-age=31536000, immutable" +# +# # No root favicon is configured: do not forward its implicit request to the WS server. +# handle /favicon.ico { +# respond 204 +# } +# +# handle_path /app/* { +# root * /srv/figcraft-web +# file_server +# } +# +# handle { +# reverse_proxy 127.0.0.1:47900 +# } +# } From 86e74a93f592050b72583ed928bd14eb6c381a0c Mon Sep 17 00:00:00 2001 From: michaelgiraldo <1228401+michaelgiraldo@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:54:10 -0800 Subject: [PATCH 074/326] M9: avoid immutable caching of missing browser assets --- packaging/server/Caddyfile | 5 +- packaging/server/caddy-test.sh | 119 +++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+), 1 deletion(-) create mode 100755 packaging/server/caddy-test.sh diff --git a/packaging/server/Caddyfile b/packaging/server/Caddyfile index e8ba7be8f..b36700b7e 100644 --- a/packaging/server/Caddyfile +++ b/packaging/server/Caddyfile @@ -32,7 +32,10 @@ figcraft.example.com { # header @entry Cache-Control "no-cache" # # @release_assets path /app/figcraft-web-*.js /app/figcraft-web-*_bg.wasm -# header @release_assets Cache-Control "public, max-age=31536000, immutable" +# # Defer so a missing asset does not receive the one-year cache header. +# header @release_assets Cache-Control "public, max-age=31536000, immutable" { +# defer +# } # # # No root favicon is configured: do not forward its implicit request to the WS server. # handle /favicon.ico { diff --git a/packaging/server/caddy-test.sh b/packaging/server/caddy-test.sh new file mode 100755 index 000000000..f2dd6b563 --- /dev/null +++ b/packaging/server/caddy-test.sh @@ -0,0 +1,119 @@ +#!/bin/sh +# Exercise the optional browser/server example with synthetic files over loopback HTTP. +# Requires caddy and nc; no backend, root access, public DNS or certificate is needed. +# Usage: packaging/server/caddy-test.sh +# Overrides: CADDY=/path/to/caddy CADDYFILE=/path/to/Caddyfile CADDY_TEST_PORT=18080 +set -eu + +HERE="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)" +CADDY="${CADDY:-caddy}" +CADDYFILE="${CADDYFILE:-$HERE/Caddyfile}" +PORT="${CADDY_TEST_PORT:-18080}" +case "$PORT" in ''|*[!0-9]*) echo 'CADDY_TEST_PORT must be a port number' >&2; exit 1 ;; esac +[ "$PORT" -gt 1023 ] && [ "$PORT" -lt 65536 ] || exit 1 +command -v "$CADDY" >/dev/null +command -v nc >/dev/null + +WORK="$(mktemp -d)" +PID='' +cleanup() { + status=$? + trap - 0 + if [ -n "$PID" ]; then + kill "$PID" 2>/dev/null || true + wait "$PID" 2>/dev/null || true + fi + rm -rf "$WORK" + exit "$status" +} +trap cleanup 0 +trap 'exit 1' HUP INT TERM +fail() { printf 'FAIL: %s\n' "$*" >&2; cat "$WORK/caddy.log" >&2; exit 1; } + +mkdir "$WORK/web" +printf 'synthetic editor\n' >"$WORK/web/index.html" +printf 'synthetic JavaScript asset\n' >"$WORK/web/figcraft-web-present.js" +printf 'synthetic WebAssembly asset\n' >"$WORK/web/figcraft-web-present_bg.wasm" + +# Extract the real commented block, changing only the hostname and filesystem root. +# The admin endpoint is disabled; state directories stay inside the temporary fixture. +printf '{\n\tadmin off\n}\n' >"$WORK/Caddyfile" +awk -v port="$PORT" -v root="$WORK/web" ' + $0 == "# figcraft.example.com {" { active = 1; found++; print "http://127.0.0.1:" port " {"; next } + active { + if ($0 !~ /^#/) exit 1 + if ($0 == "# }") { print "}"; active = 0; next } + sub(/^# ?/, "") + if ($1 == "root" && $2 == "*" && $3 == "/srv/figcraft-web") $0 = "\t\troot * \"" root "\"" + print + } + END { if (found != 1 || active) exit 1 } +' "$CADDYFILE" >>"$WORK/Caddyfile" + +XDG_CONFIG_HOME="$WORK/config" XDG_DATA_HOME="$WORK/data" \ + "$CADDY" validate --config "$WORK/Caddyfile" --adapter caddyfile >"$WORK/caddy.log" 2>&1 || + fail 'extracted example did not validate' +XDG_CONFIG_HOME="$WORK/config" XDG_DATA_HOME="$WORK/data" \ + "$CADDY" run --config "$WORK/Caddyfile" --adapter caddyfile >>"$WORK/caddy.log" 2>&1 & +PID=$! + +request() { + printf '%s %s HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n' "$1" "$2" | + nc -w 2 127.0.0.1 "$PORT" >"$WORK/response" || return 1 + tr -d '\r' <"$WORK/response" >"$WORK/clean" + awk 'BEGIN { headers = 1 } headers && /^$/ { headers = 0; next } !headers { print }' \ + "$WORK/clean" >"$WORK/body" +} +status() { awk 'NR == 1 { print $2 }' "$WORK/clean"; } +cache() { + awk '/^$/ { exit } tolower($0) ~ /^cache-control:/ { sub(/^[^:]*:[ \t]*/, ""); print }' "$WORK/clean" +} + +attempt=0 +until request GET /app/ 2>/dev/null && [ "$(status)" = 200 ]; do + kill -0 "$PID" 2>/dev/null || fail 'Caddy did not start (port may be in use)' + attempt=$((attempt + 1)) + [ "$attempt" -lt 30 ] || fail 'Caddy did not become ready' + sleep 0.1 +done +kill -0 "$PID" 2>/dev/null || fail 'Caddy exited during startup' + +IMMUTABLE='public, max-age=31536000, immutable' +checks=0 +check() { + method=$1 + name=$2 + expected=$3 + request "$method" "/app/$name" || fail "$method $name request failed" + [ "$(status)" = "$expected" ] || fail "$method $name: expected HTTP $expected, got $(status)" + if [ "$expected" = 200 ]; then + [ "$(cache)" = "$IMMUTABLE" ] || fail "$method $name: successful asset lost its cache policy" + if [ "$method" = GET ]; then + cmp -s "$WORK/body" "$WORK/web/$name" || fail "$method $name: wrong file contents" + fi + else + [ -z "$(cache)" ] || fail "$method $name: a missing asset received Cache-Control: $(cache)" + fi + if [ "$method" = HEAD ]; then + [ ! -s "$WORK/body" ] || fail "$method $name: HEAD returned a body" + fi + checks=$((checks + 1)) + printf 'PASS: %s %s -> %s\n' "$method" "$name" "$expected" +} + +for method in GET HEAD; do + check "$method" figcraft-web-present.js 200 + check "$method" figcraft-web-present_bg.wasm 200 + check "$method" figcraft-web-later.js 404 + check "$method" figcraft-web-later_bg.wasm 404 +done + +# The same URLs must work immediately when deployment supplies the previously missing files. +printf 'new JavaScript asset\n' >"$WORK/web/figcraft-web-later.js" +printf 'new WebAssembly asset\n' >"$WORK/web/figcraft-web-later_bg.wasm" +for method in GET HEAD; do + check "$method" figcraft-web-later.js 200 + check "$method" figcraft-web-later_bg.wasm 200 +done + +printf 'Caddy browser asset caching: %s checks passed (%s)\n' "$checks" "$("$CADDY" version)" From ecd900ab375cc75b533f29021a6e60c2181c8385 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:47:48 -0500 Subject: [PATCH 075/326] Control channel: ui.key arrows pan the view when nothing is selected, as the window does Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/control.rs | 5 ++++- crates/ui-egui/src/inspect_fields_tests.rs | 25 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index fd5a2a4e9..aa79bec78 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -996,7 +996,10 @@ fn ui_key(app: &mut FigApp, ctx: &Context, p: &Value) -> Result { "ArrowUp" => (0, -1), _ => (0, 1), }; - let (cmd, params) = if m.cmd || m.ctrl { + // With nothing selected the arrows pan the view, as the window's own key path does. + let (cmd, params) = if app.session.selection().is_empty() { + ("view.pan", json!({"dx": dx, "dy": dy, "big": m.shift})) + } else if m.cmd || m.ctrl { ("transform.nudgeSize", json!({"dw": dx, "dh": dy, "big": m.shift})) } else { ("transform.nudge", json!({"dx": dx, "dy": dy, "big": m.shift})) diff --git a/crates/ui-egui/src/inspect_fields_tests.rs b/crates/ui-egui/src/inspect_fields_tests.rs index 102e232b3..9ea3223fd 100644 --- a/crates/ui-egui/src/inspect_fields_tests.rs +++ b/crates/ui-egui/src/inspect_fields_tests.rs @@ -46,3 +46,28 @@ fn control_inspection_rejects_invalid_options_consistently() { } } } + +/// `ui.key` with an arrow and nothing selected pans the view, as the window's own key path does +/// (before, it answered that nothing was selected); with a selection it nudges (Shift: farther). +#[test] +fn control_key_arrows_pan_with_nothing_selected() { + let mut u = Ui::new(Session::new()); + let r = + call(&mut u, "engine.execute", json!({"command": "shape.rectangle", "params": {"x": 0, "y": 0, "width": 40, "height": 40}})).unwrap()["id"] + .clone(); + u.app.run("select.set", json!({"ids": []})); + u.app.run("view.set", json!({"zoom": 2.0, "cx": 0, "cy": 0})); + let view = |u: &Ui| { + let v = &u.app.session.ds().unwrap().view; + (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%"); + call(&mut u, "ui.key", json!({"key": "ArrowUp", "shift": true})).unwrap(); + assert_eq!(view(&u), (10.0, -100.0), "Shift: ten times as far"); + 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"); + 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"); +} From 9a1b33bbfdafd5938fb49cd1b7d22923b88c8357 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 2 Nov 2026 05:49:26 +0100 Subject: [PATCH 076/326] Reject signed major in plugin manifest api version string (#1853) Found while testing crates/plugin/src/manifest.rs:70 (api_from_number_or_string, the Api::Text arm) Co-authored-by: Claude Haiku 5.5 --- crates/plugin/src/manifest.rs | 1 + crates/plugin/src/tests.rs | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/crates/plugin/src/manifest.rs b/crates/plugin/src/manifest.rs index 6bca9aef2..269174e0f 100644 --- a/crates/plugin/src/manifest.rs +++ b/crates/plugin/src/manifest.rs @@ -77,6 +77,7 @@ fn api_from_number_or_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result Date: Mon, 2 Nov 2026 05:49:30 +0100 Subject: [PATCH 077/326] fix(cli): M2.1: scope dead-code expectation (#1816) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cédric Legrand --- apps/figcraft-cli/examples/man-and-completions.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/figcraft-cli/examples/man-and-completions.rs b/apps/figcraft-cli/examples/man-and-completions.rs index c67827477..2b119d6a8 100644 --- a/apps/figcraft-cli/examples/man-and-completions.rs +++ b/apps/figcraft-cli/examples/man-and-completions.rs @@ -6,7 +6,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #[path = "../src/args.rs"] -#[expect(dead_code, reason = "Generation uses clap's command metadata, not the parsed fields or runtime parser.")] +#[cfg_attr(not(test), expect(dead_code, reason = "Generation uses clap's command metadata, not the parsed fields or runtime parser."))] mod args; use std::path::Path; From fa8faf216d1ae9693332c49fecbc078e01b31293 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=82=BC=ED=98=84?= Date: Mon, 2 Nov 2026 13:49:34 +0900 Subject: [PATCH 078/326] M8: a whole ellipse starting anywhere stays whole through a .fig file (#1851) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A .fig file (and the REST JSON) holds an ellipse's start and end angles as 32-bit floats, and FigCraft writes them that way too. For a whole turn that starts anywhere but zero, end - start comes out a hair short of 2π as often as not (start 0.3: 6.283185184), which reads as an arc: the ellipse came back as a pie slice whose centred stroke draws a line from the centre to the edge. On import, a sweep within the angles' precision of a turn is now a turn. Co-authored-by: Claude Opus 5.5 --- crates/format/src/fig/export_tests.rs | 19 +++++++++++++++++++ crates/format/src/rest.rs | 7 ++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 5b4bcb991..b1b31262a 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -1592,3 +1592,22 @@ fn a_name_used_with_two_types_in_a_set_writes_both_definitions() { } } } + +/// A whole ellipse that starts anywhere round comes back whole: the file holds its start and end +/// angles as 32-bit floats, and their difference falls a hair short of a turn as often as not. +#[test] +fn a_whole_ellipse_starting_anywhere_comes_back_whole() { + let tau = std::f64::consts::TAU; + for start in [0.3, 2.0, -std::f64::consts::FRAC_PI_2, std::f64::consts::PI, 100.25] { + for sweep in [tau, -tau] { + let mut doc = Document::new("whole"); + let page = doc.first_page().unwrap(); + doc.create(page, NodeKind::Ellipse { start, sweep, inner: 0.0 }, "Ellipse", 0.0, 0.0, 100.0, 100.0).unwrap(); + let (bytes, _) = export(&doc, None).unwrap(); + let (back, _) = import(&bytes, "x").unwrap(); + let kinds: Vec = + back.ids().filter_map(|id| back.node(id)).map(|n| n.kind.clone()).filter(|k| matches!(k, NodeKind::Ellipse { .. })).collect(); + assert!(matches!(kinds.as_slice(), [NodeKind::Ellipse { sweep: s, .. }] if *s == sweep), "start {start}, sweep {sweep}: {kinds:?}"); + } + } +} diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 26ab3586a..4604b73a6 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -629,7 +629,12 @@ impl<'a> Ctx<'a> { let start = arc("startingAngle").unwrap_or(0.0).clamp(-1e3, 1e3); let end = arc("endingAngle").map_or(start + std::f64::consts::TAU, |e| e.clamp(-1e3, 1e3)); let tau = std::f64::consts::TAU; - NodeKind::Ellipse { start, sweep: (end - start).clamp(-tau, tau), inner: arc("innerRadius").unwrap_or(0.0).clamp(0.0, 1.0) } + // The angles are 32-bit floats: a whole turn from anywhere but zero comes out a + // hair short of 2π as often as not. Within their precision of a turn, it is one. + let precision = (start.abs() + end.abs() + tau) * f64::from(f32::EPSILON); + let sweep = end - start; + let sweep = if sweep.abs() >= tau - precision { tau.copysign(sweep) } else { sweep }; + NodeKind::Ellipse { start, sweep: sweep.clamp(-tau, tau), inner: arc("innerRadius").unwrap_or(0.0).clamp(0.0, 1.0) } } // Point counts aren't part of the documented JSON: the outline is exact when present. "REGULAR_POLYGON" | "STAR" if point_count().is_none() && has_geometry => NodeKind::Vector { network: VectorNetwork::default() }, From 702b0d78944e79fc3721261be3c495a08ef6730d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=82=BC=ED=98=84?= Date: Mon, 2 Nov 2026 13:49:38 +0900 Subject: [PATCH 079/326] M8: a whole ellipse drawn backwards keeps its simple stroke in SVG (#1848) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * M8: a whole ellipse drawn backwards keeps its simple stroke in SVG An ellipse with a sweep of -2π goes all the way round, as the renderer and the .fig export already read it. The SVG export's simple stroke checked `sweep >= 2π` only, so such an ellipse's inside or outside stroke was written as a filled even-odd ring instead of a stroke. All three places now ask `figcraft_geom::full_sweep`, as the geometry and the bounds do. Co-Authored-By: Claude Opus 5.5 * M8: a backwards whole ellipse's stroke ring in the renderer and .fig export, tested Review follow-up (#1848): the renderer's stroke ring and the .fig export's stroke geometry read a sweep of -2π as whole too, now through `full_sweep`. A test for each checks a backwards ellipse strokes the same ring as a forward one, and fails if either goes back to checking positive sweeps only. Co-Authored-By: Claude Opus 5.5 * M8: the .fig backwards-ellipse test compares the stroke ring itself Review follow-up (#1848): the test checked only that one stroke path was written. It now compares the path's commands and winding rule for the forward and backwards ellipse, and that the ring is even-odd. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/format/src/fig/export/shape.rs | 2 +- crates/format/src/fig/interop_tests.rs | 31 ++++++++++++++++++++++++++ crates/render/src/draw.rs | 2 +- crates/render/src/join_tests.rs | 20 +++++++++++++++++ crates/svg/src/lib.rs | 2 +- crates/svg/src/tests.rs | 21 +++++++++++++++++ 6 files changed, 75 insertions(+), 3 deletions(-) diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index 03c82cfb1..e4e2cae6b 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -282,7 +282,7 @@ impl<'d> Exporter<'d> { if !(plain && weight.is_finite() && weight > 0.0 && w.is_finite() && h.is_finite()) { return; } - let whole = matches!(n.kind, NodeKind::Ellipse { sweep, inner, .. } if inner == 0.0 && sweep.abs() >= std::f64::consts::TAU - 1e-9); + let whole = matches!(n.kind, NodeKind::Ellipse { sweep, inner, .. } if inner == 0.0 && figcraft_doc::geom::full_sweep(sweep)); if boxy || whole { let (out, inset) = match sp.align { StrokeAlign::Inside => (0.0, weight), diff --git a/crates/format/src/fig/interop_tests.rs b/crates/format/src/fig/interop_tests.rs index b51760c55..fa95d792b 100644 --- a/crates/format/src/fig/interop_tests.rs +++ b/crates/format/src/fig/interop_tests.rs @@ -449,3 +449,34 @@ fn local_samples_agree_with_the_written_schema() { } } } + +/// An ellipse drawn the other way round (a sweep of −2π) is whole: its inside stroke is written +/// as the same ring a forward one's is, path and winding rule alike. +#[test] +fn a_whole_ellipse_drawn_backwards_carries_its_stroke_ring() { + let ring = |sweep: f64| { + let mut doc = sample(); + let ids: Vec = doc.ids().collect(); + for id in ids { + if let Some(n) = doc.node_mut(id) + && let NodeKind::Ellipse { sweep: s, .. } = &mut n.kind + { + *s = sweep; + } + } + let out = std::cell::RefCell::new(None); + with_changes(&doc, |of, msg| { + let blobs = msg.get("blobs").unwrap().list(); + let geometry = of("ELLIPSE").get("strokeGeometry").map(|g| { + let p = g.list().first().unwrap().clone(); + let bytes = blobs.get(num(&p, "commandsBlob") as usize).and_then(|b| b.get("bytes")).and_then(Kv::bytes).unwrap(); + (name(&p, "windingRule").to_string(), bytes.to_vec()) + }); + *out.borrow_mut() = geometry; + }); + out.into_inner() + }; + let forwards = ring(std::f64::consts::TAU).expect("a forward ellipse writes its stroke ring"); + assert_eq!(forwards.0, "ODD"); + assert_eq!(ring(-std::f64::consts::TAU), Some(forwards)); +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index f48899aea..f0af6b6d0 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -217,7 +217,7 @@ pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc { p.apply_affine(Affine::translate((x0, y0))); Some(p) } - NodeKind::Ellipse { sweep, inner, .. } if sweep.abs() >= std::f64::consts::TAU - 1e-9 && inner == 0.0 => { + NodeKind::Ellipse { sweep, inner, .. } if figcraft_geom::full_sweep(sweep) && inner == 0.0 => { Some(figcraft_geom::kurbo::Ellipse::from_rect(Rect::new(x0, y0, x0 + ww, y0 + hh)).to_path(0.05)) } _ => None, diff --git a/crates/render/src/join_tests.rs b/crates/render/src/join_tests.rs index 9fbb4f870..42c931997 100644 --- a/crates/render/src/join_tests.rs +++ b/crates/render/src/join_tests.rs @@ -44,3 +44,23 @@ fn outside_bevel_join_cuts_outer_corner() { fn outside_miter_join_keeps_square_corner() { assert_ne!(covered(StrokeJoin::Miter), 0); } + +/// An ellipse drawn the other way round (a sweep of −2π) is whole: its inside stroke is the same +/// ring of two outlines as a forward one's. +#[test] +fn a_whole_ellipse_drawn_backwards_strokes_as_a_ring() { + let ring = |sweep: f64| { + let mut d = Document::new("ring"); + let p = d.first_page().unwrap(); + let id = d.create(p, NodeKind::Ellipse { start: 0.0, sweep, inner: 0.0 }, "E", 0.0, 0.0, 60.0, 40.0).unwrap(); + let n = d.get_mut(id).unwrap(); + n.strokes = vec![Paint::solid(Color::BLACK)]; + (n.stroke.weight, n.stroke.align) = (6.0, StrokeAlign::Inside); + let outline: BezPath = figcraft_geom::kurbo::Ellipse::from_rect(figcraft_geom::kurbo::Rect::new(0.0, 0.0, 60.0, 40.0)).to_path(0.1); + (*crate::draw::stroke_area(d.get(id).unwrap(), &outline, true)).clone() + }; + let forwards = ring(std::f64::consts::TAU); + let moves = forwards.elements().iter().filter(|e| matches!(e, figcraft_geom::kurbo::PathEl::MoveTo(_))).count(); + assert_eq!(moves, 2, "two outlines: {forwards:?}"); + assert_eq!(ring(-std::f64::consts::TAU), forwards); +} diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 58d80ac91..3158d1c0d 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -802,7 +802,7 @@ impl W<'_> { return None; } match n.kind { - NodeKind::Ellipse { sweep, inner, .. } if inner == 0.0 && sweep >= std::f64::consts::TAU - 1e-9 => { + NodeKind::Ellipse { sweep, inner, .. } if inner == 0.0 && figcraft_geom::full_sweep(sweep) => { figcraft_geom::kurbo::Shape::to_path(&figcraft_geom::kurbo::Ellipse::from_rect(r), 0.1) } NodeKind::Rectangle | NodeKind::Frame | NodeKind::Component { .. } | NodeKind::Instance { .. } if n.corners.smoothing == 0.0 => { diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index c3fb75f8e..ade0e3f30 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -429,3 +429,24 @@ fn an_exported_dashed_line_opens_as_the_same_line() { d.subtree(frame).iter().filter_map(|i| d.node(*i)).filter(|n| !n.stroke.dashes.is_empty()).map(|n| n.stroke.dashes.clone()).collect(); assert!(matches!(dashes.as_slice(), [d] if d.len() == 2 && d.iter().all(|v| (v - 10.7).abs() < 1e-4)), "{dashes:?}"); } + +/// An ellipse drawn the other way round (a sweep of −2π) is as whole as one drawn forwards: its +/// stroke inside or outside exports as a stroke, the same as the forward one's. +#[test] +fn a_whole_ellipse_drawn_backwards_keeps_its_simple_stroke() { + let export = |sweep: f64, align: figcraft_doc::StrokeAlign| { + let mut d = Document::new("backwards"); + let p = d.first_page().unwrap(); + let n = d.create(p, NodeKind::Ellipse { start: 0.0, sweep, inner: 0.0 }, "Ellipse", 0.0, 0.0, 100.0, 60.0).unwrap(); + let node = d.get_mut(n).unwrap(); + node.fills.clear(); + node.strokes = vec![Paint::solid(Color::from_hex("000000").unwrap())]; + (node.stroke.weight, node.stroke.align) = (8.0, align); + export_svg(&d, &[n], &SvgOptions { simplify_stroke: true, ..SvgOptions::default() }).unwrap() + }; + for align in [figcraft_doc::StrokeAlign::Inside, figcraft_doc::StrokeAlign::Outside] { + let (forwards, backwards) = (export(std::f64::consts::TAU, align), export(-std::f64::consts::TAU, align)); + assert!(forwards.contains("stroke-width=\"8\""), "{align:?}: {forwards}"); + assert_eq!(backwards, forwards, "{align:?}"); + } +} From fdd27a0b88ca597aac72260e18f077fc5c5dfe87 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:49:43 -0500 Subject: [PATCH 080/326] Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux (#1844) * Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux Co-Authored-By: Claude Fable 5.1 * Parity note: in the browser Ctrl+1 is the browser's tab key Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- crates/engine/src/keymap.rs | 3 ++- crates/engine/src/keymap_tests.rs | 12 ++++++++++++ crates/engine/src/shortcut_parity_tests.rs | 2 +- docs/ui-parity.md | 5 +++-- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index baa3885c5..65259755a 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -212,7 +212,8 @@ pub static KEYS: &[Binding] = &[ k(View, "view.comments", &["Shift+C"]), k(View, "view.multiplayerCursors", &["Alt+Cmd+\\"]), k(View, "view.snapPixel", &["Shift+Cmd+'"]), - k(View, "view.layers", &["Alt+1"]).label("Layers panel"), + // Windows: one help-center article writes Ctrl+1, another Alt+1; both open it there. + k(View, "view.layers", &["Alt+1"]).win(&["Alt+1", "Ctrl+1"]).label("Layers panel"), k(View, "view.assets", &["Alt+2"]).label("Assets panel"), k(View, "libraries.open", &["Alt+3"]), k(View, "view.design", &["Alt+8"]).label("Design panel"), diff --git a/crates/engine/src/keymap_tests.rs b/crates/engine/src/keymap_tests.rs index bdf57c9da..c7db0b16e 100644 --- a/crates/engine/src/keymap_tests.rs +++ b/crates/engine/src/keymap_tests.rs @@ -305,3 +305,15 @@ fn ctrl_tab_cycles_documents() { assert_eq!(lookup(Platform::Other, Context::Canvas, "Tab", mods(false, false, true, true)).map(|b| b.id), Some("doc.nextTab")); assert_eq!(lookup(Platform::Mac, Context::Canvas, "Tab", mods(true, false, false, true)).map(|b| b.id), Some("doc.previousTab")); } + +/// The Layers panel's Windows key is Ctrl+1 in one help-center article ("Mac: Option 1 Windows: +/// Ctrl 1", Select layers and objects) and Alt+1 in another (Explore the navigation bar and left +/// sidebar): both open it there. macOS keeps Option+1 alone; Cmd+1 is not documented. +#[test] +fn the_layers_panel_answers_both_of_its_documented_windows_keys() { + let (alt, ctrl, cmd) = (mods(false, true, false, false), mods(false, false, false, true), mods(false, false, true, false)); + assert_eq!(id_for(Platform::Other, Context::Canvas, "1", alt), Some("view.layers")); + assert_eq!(id_for(Platform::Other, Context::Canvas, "1", ctrl), Some("view.layers")); + assert_eq!(id_for(Platform::Mac, Context::Canvas, "1", alt), Some("view.layers")); + assert_eq!(id_for(Platform::Mac, Context::Canvas, "1", cmd), None); +} diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index 65e269982..6cf7c361d 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -146,7 +146,7 @@ static ROWS: &[Row] = &[ doc(View, "Pixel preview", &["Ctrl+P"], &["Ctrl+Alt+P"], Bound("view.pixelPreview"), ""), doc(View, "Others' cursors in a live session", &["Alt+Cmd+\\"], &["Ctrl+Alt+\\"], Bound("view.multiplayerCursors"), "new command"), doc(View, "Hide the side panels (minimize the interface)", &["Shift+Cmd+\\"], &[], Bound("view.leftSidebar"), ""), - doc(View, "Layers panel", &["Alt+1"], &[], Bound("view.layers"), "one article writes Ctrl+1 for Windows, another Alt+1; Alt+1 bound"), + doc(View, "Layers panel", &["Alt+1"], &["Alt+1", "Ctrl+1"], Bound("view.layers"), "one article writes Ctrl+1 for Windows, another Alt+1; both bound there"), doc(View, "Assets panel", &["Alt+2"], &[], Bound("view.assets"), ""), doc(View, "Libraries", &["Alt+3"], &[], Bound("libraries.open"), ""), doc(View, "Dev Mode on or off", &["Shift+D"], &[], Bound("view.devMode"), ""), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0286fd37d..a77f79348 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-10-30 · **Change:** minor (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-01 · **Change:** minor (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: @@ -150,7 +150,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look - **Where the documentation disagrees with itself** (noted per row): pixel grid (Shift+' or Cmd+'), letter spacing (Alt or Cmd with < >; Cmd would be the font size keys, Alt bound), Windows remove fill (Alt+/ or Alt+,; Alt+, is letter spacing), the Layers panel on Windows (Alt+1 - or Ctrl+1), send to back / bring to front (one table shows only the bracket). + or Ctrl+1; both bound there, though in the browser Ctrl+1 is the browser's own tab key and only Alt+1 reaches the app), send to back / bring to front (one table shows only the bracket). - **Platform keys:** macOS rows use Cmd and Option, Windows/Linux rows Ctrl and Alt (tested: no macOS glyph on Windows/Linux keycaps, no "Ctrl"/"Alt" words on macOS); no default binding uses a chord the system keeps (Cmd+H/M/Q/Tab/Space, Ctrl+Space and the screenshot keys on macOS; @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | | 2026-10-31 | minor | M1, #1682: as the help center describes the colour picker, choosing Image no longer opens a file dialog at once: the tab shows a checkered placeholder and Upload from computer until there is a file. An image paint shows its asset preview with the same button. A file dropped on the open picker replaces the image and keeps the fill mode, crop, position and adjustments; on the placeholder it becomes the paint's image, filling the layer. While a file is dragged the picker says it takes it instead of the window saying Drop to import. New command `image.replace {ids?, target?, index?, data | path}`, through the same size cap and decoder as `image.place`; one undo step. Dropped files in the browser arrive as `data`. A native window or a browser doesn't say where a dragged file is, so a drop with no known position goes to the open picker, and one known to be over the canvas imports as before. Left: the Fill and Stroke swatches in the Design panel don't take a drop, since their place can't be told during a drag; pasting into the picker isn't documented and isn't added. Tests: `colorpicker_image_tests`, `image_crop_tests::replacing_an_image_keeps_its_fill_mode_crop_and_adjustments`. Numbers unchanged | | 2026-10-30 | minor | Gap 4: the keyboard's Menu key opens the context menu, as Shift+F10 does (at the focused layer row or below the canvas selection, with the keyboard in the menu). egui already reported the key; FigCraft's keymap had no name or binding for it. `view.contextMenu` now takes `Menu` too, and the Context menus row is done (`layers_keyboard_tests`). Stale rows corrected: smart-selection spacing has had reorder rings since the "M1: smart-selection drag reordering" landing (the row is still partial: irregular grids and several marked layers aren't covered), and gap 4 and the parity summary quoted shortcut counts from before the last bindings (now 128 bound, none missing, 57 undocumented pinned, as `shortcut_parity_tests` counts). | | 2026-10-30 | minor | M4, gap 4: the eyedropper with Cmd/Ctrl+Shift held makes a colour style or variable of the colour it picks, as the reference app's eyedropper does, instead of filling the selection. It asks the UI for a Create from color window (`dialog.createFromColor`; the control channel never opens it). The window shows the colour and offers Style or Variable, a name (the next free "Color n") and, for a variable, a collection: the file's first, or a new one made with it in the same undo step. Create runs `style.create` or `variable.create`. Tests: `eyedropper_create_tests`, `sampled_color_tests`. | From 3b8ded69c00a01a10190d7eb73903bec78bcc043 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:49:48 -0500 Subject: [PATCH 081/326] M4: a link on text is underlined by default, and Underline takes it off (#1841) * M4: a link on text is underlined by default, and Underline takes it off Co-Authored-By: Claude Fable 5.1 * text.link: only a new link takes the default underline; Underline reads the texts inside a target Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- crates/engine/src/cmd/text.rs | 26 +++++++++++++---- crates/engine/src/text_behaviour_tests.rs | 34 +++++++++++++++++++++++ docs/target-app-parity.md | 3 +- 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index ec219db36..4fbb0fe1d 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -101,7 +101,9 @@ fn all_have(s: &Session, p: &Value, pred: impl Fn(&TextStyle) -> bool) -> bool { } return false; } - targets(s, p).iter().all(|i| matches!(doc.node(*i).map(|n| &n.kind), Some(NodeKind::Text(t)) if t.spans().iter().all(|(_, _, st)| pred(st)))) + // The texts `style` restyles: the targets and the texts inside them. + let texts: Vec<&TextData> = targets(s, p).iter().flat_map(|i| doc.subtree(*i)).filter_map(|d| doc.node(d).and_then(|n| n.kind.text())).collect(); + !texts.is_empty() && texts.iter().all(|t| t.spans().iter().all(|(_, _, st)| pred(st))) } fn toggle_bold(s: &mut Session, p: &Value) -> Result { @@ -217,10 +219,24 @@ pub fn specs() -> Vec { let on = all_have(s, p, |st| st.decoration == TextDecoration::Strikethrough); style(s, p, |st| st.decoration = if on { TextDecoration::None } else { TextDecoration::Strikethrough }) }), - spec!("text.link", "Create link", "{url, ids?}", true, |s, p| { - let url = req_string("text.link", p, "url")?; - style(s, p, |st| st.link = Some(url.clone())) - }), + spec!( + "text.link", + "Create link", + "{url, ids?} linked text is underlined unless it has a decoration of its own (Underline takes it off again)", + true, + |s, p| { + let url = req_string("text.link", p, "url")?; + style(s, p, |st| { + // "Links are styled with an underline by default" (Add links to text); Underline + // (Cmd/Ctrl+U) removes it, as documented there, and changing the URL of a link + // leaves its decoration as it is. + if st.link.is_none() && st.decoration == TextDecoration::None { + st.decoration = TextDecoration::Underline; + } + st.link = Some(url.clone()); + }) + } + ), spec!("text.bulletList", "Bulleted list", "{ids?} while editing: the selected paragraphs", true, |s, p| set_list( s, p, diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index b263211ee..ad476c364 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -550,3 +550,37 @@ fn css_font_family_escapes_backslash_and_newline() { let css = crate::codegen::css_decls(s.doc().unwrap(), s.doc().unwrap().node(t).unwrap(), &mut Default::default(), (true, true)); assert!(css.contains(r#"font-family: "Foo\"\3C /style>";"#), "{css}"); } + +/// "Links are styled with an underline by default. Use the keyboard shortcut to remove the +/// underline: Mac: Command U, Windows: Control U" (Add links to text). +#[test] +fn a_link_is_underlined_by_default_and_underline_takes_it_off() { + use figcraft_doc::TextDecoration; + let mut s = Session::new(); + let t = text(&mut s, "docs", json!({})); + let style = |s: &Session| s.doc().unwrap().node(t).unwrap().kind.text().unwrap().style.clone(); + s.execute("text.link", &json!({"ids": [t], "url": "https://example.com"})).unwrap(); + assert_eq!((style(&s).link.as_deref(), style(&s).decoration), (Some("https://example.com"), TextDecoration::Underline)); + s.execute("text.underline", &json!({"ids": [t]})).unwrap(); + assert_eq!( + (style(&s).link.as_deref(), style(&s).decoration), + (Some("https://example.com"), TextDecoration::None), + "the link stays, the underline goes" + ); + // Changing the URL of a link whose underline was taken off keeps it off. + s.execute("text.link", &json!({"ids": [t], "url": "https://example.org"})).unwrap(); + assert_eq!((style(&s).link.as_deref(), style(&s).decoration), (Some("https://example.org"), TextDecoration::None)); + // A decoration of the text's own is kept. + let u = text(&mut s, "struck", json!({"textDecoration": "strikethrough"})); + s.execute("text.link", &json!({"ids": [u], "url": "https://example.com"})).unwrap(); + assert_eq!(s.doc().unwrap().node(u).unwrap().kind.text().unwrap().style.decoration, TextDecoration::Strikethrough); + // On a frame, the link reaches the text inside, and Underline reads that text: it takes the + // underline off rather than putting it on again. + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 100, "width": 200, "height": 100})).unwrap()); + let inner = id(s.execute("text.create", &json!({"text": "inside", "x": 0, "y": 100, "parent": f})).unwrap()); + let inner_style = |s: &Session| s.doc().unwrap().node(inner).unwrap().kind.text().unwrap().style.clone(); + s.execute("text.link", &json!({"ids": [f], "url": "https://example.com"})).unwrap(); + assert_eq!((inner_style(&s).link.as_deref(), inner_style(&s).decoration), (Some("https://example.com"), TextDecoration::Underline)); + s.execute("text.underline", &json!({"ids": [f]})).unwrap(); + assert_eq!(inner_style(&s).decoration, TextDecoration::None, "Underline on the frame reads the text inside it"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 489c0e7da..06cf024f0 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-10-31 · **Change:** minor (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-01 · **Change:** minor (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 @@ -648,6 +648,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | M4: a link made with `text.link` (Cmd/Ctrl+K, Shift+Cmd/Ctrl+U) underlines the linked text unless it has a decoration of its own ("Links are styled with an underline by default. Use the keyboard shortcut to remove the underline", Add links to text); Underline (Cmd/Ctrl+U) takes the underline off and the link stays. Found by a documentation audit of the text rules. Test: `text_behaviour_tests::a_link_is_underlined_by_default_and_underline_takes_it_off`. Numbers unchanged | | 2026-10-31 | patch | M4: Dash and Custom strokes have a Dash cap (None, Round, Square) in the advanced stroke settings and `node.set {dashCap}`, on both ends of every dash on the canvas and in PNG, PDF and SVG. Unset, dashes keep taking the end point caps, so older files look the same; the saved file writes it only when set. Numbers unchanged | | 2026-10-31 | minor | M11, gap 6: widgets draw lines and SVG pictures, as a Figma widget's `Line` and `SVG` do (plugin API 6; older plugins unchanged). A line is 100 long, black and 1 thick unless told otherwise, and turns around its top-left corner. An SVG comes in as locked layers, scaled to fit a size, within the widget's 256 layers. The Counter example uses both. Numbers unchanged. Tests: `widget_shapes_tests`, `widget_tests`. | | 2026-10-30 | minor | M11, gap 6: a widget can open its plugin's panel, as a Figma widget's click handler shows a plugin window (plugin API 5). A widget callback's `ui_show` (click, field edit or menu item) opens the plugin's one panel and keeps the module loaded; each panel callback gets the widget's id and current state as well as the panel's event and values, and its `widget_render` redraws the widget in the same undo step. A widget removed meanwhile isn't redrawn (the callback rolls back, the panel stays); an API 3 or 4 plugin's `ui_show` from a widget still opens nothing; a presented prototype opens no panel. The Counter example (API 5) gets Set count… in its menu: a panel whose Set button redraws it with the count entered. Tests: `widget_panel_tests` (engine), the Counter's unit test. Numbers unchanged | From 2abd8c5f52ae76e1269833fa4351662e45f78cfa Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:49:53 -0500 Subject: [PATCH 082/326] M2: Remove all auto layout takes it off a frame and every frame nested in it (#1833) Co-authored-by: Claude Fable 5.1 --- crates/engine/src/al_nesting_tests.rs | 27 +++++++++++++++++++++++++++ crates/engine/src/cmd/structure.rs | 26 ++++++++++++++++++++++++++ crates/ui-egui/locales/en.toml | 1 + crates/ui-egui/src/menus.rs | 1 + docs/auto-layout-parity.md | 4 +++- 5 files changed, 58 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/al_nesting_tests.rs b/crates/engine/src/al_nesting_tests.rs index 6ebcc295b..f5d607ecf 100644 --- a/crates/engine/src/al_nesting_tests.rs +++ b/crates/engine/src/al_nesting_tests.rs @@ -318,3 +318,30 @@ fn fill_text_in_a_hugging_card_sets_the_height_in_one_step() { // Whatever the fonts, the card hugs the wrapped text exactly. assert!((cb.height() - (tb.height() + 20.0)).abs() < 1e-6, "card {cb:?} text {tb:?}"); } + +/// "To remove auto layout from a frame and all of its nested objects at once, right-click on the +/// frame and go to More layout options > Remove all auto layout." (Toggle on auto layout in designs) +#[test] +fn remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it() { + let mut s = Session::new(); + let outer = frame(&mut s, None, 0.0, 0.0, 300.0, 100.0); + let inner = frame(&mut s, Some(outer), 0.0, 0.0, 100.0, 50.0); + let deep = frame(&mut s, Some(inner), 0.0, 0.0, 40.0, 20.0); + rect(&mut s, Some(deep), 0.0, 0.0, 10.0, 10.0); + for (f, dir) in [(outer, "horizontal"), (inner, "vertical"), (deep, "horizontal")] { + s.execute("node.set", &json!({"id": f, "props": {"layout": dir}})).unwrap(); + } + let laid_out = |s: &Session| [outer, inner, deep].map(|n| s.doc().unwrap().node(n).unwrap().layout.is_some()); + // Remove auto layout takes it off the frame alone. + s.execute("layout.remove", &json!({"ids": [outer]})).unwrap(); + assert_eq!(laid_out(&s), [false, true, true]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(laid_out(&s), [true, true, true]); + let steps = s.ds().unwrap().history.undo.len(); + let r = s.execute("layout.removeAll", &json!({"ids": [outer]})).unwrap(); + assert_eq!(laid_out(&s), [false, false, false], "every nested frame too"); + assert_eq!(r["removed"].as_array().map(Vec::len), Some(3)); + assert_eq!(s.ds().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(laid_out(&s), [true, true, true]); +} diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index 52b4a415d..693465d81 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -83,6 +83,32 @@ pub fn specs() -> Vec { } ok() }), + spec!( + "layout.removeAll", + "Remove all auto layout", + "{ids?} takes the auto layout off the frames and every frame nested in them at once (More layout options ▸ Remove all auto layout); instances and the layers inside them keep theirs", + true, + |s, p| { + let ids = req_targets("layout.removeAll", s, p)?; + let doc = s.doc_mut()?; + let mut removed = Vec::new(); + for root in ids { + for i in doc.subtree(root) { + let strip = doc.node(i).is_some_and(|n| n.layout.is_some() && !matches!(n.kind, figcraft_doc::NodeKind::Instance { .. })) + && !crate::assets::components::inside_instance(doc, i); + if !strip { + continue; + } + let n = doc.get_mut(i)?; + n.layout = None; + super::props::drop_layout_bindings(n); + figcraft_layout::coherent_sizing(doc, i); + removed.push(i); + } + } + Ok(json!({"removed": removed})) + } + ), spec!("layout.suggest", "Suggest auto layout", "{ids?, direction? (horizontal|vertical|grid)}", true, layout_add), spec!("object.moveToPage", "Move to page", "{ids?, page}", true, move_to_page), spec!("object.setThumbnail", "Set as thumbnail", "{id?}", true, |s, p| { diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index ba567dd81..9150cc32b 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1187,6 +1187,7 @@ name = "English" "Remove" = "Remove" "Remove all" = "Remove all" "Remove annotation" = "Remove annotation" +"Remove all auto layout" = "Remove all auto layout" "Remove auto layout" = "Remove auto layout" "Remove column" = "Remove column" "Remove dev resource" = "Remove dev resource" diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 76f220f4f..299d2a20f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -502,6 +502,7 @@ pub fn popups(app: &mut FigApp, ctx: &egui::Context) { (tr("Use as mask"), "object.mask"), ("-", ""), (tr("Add auto layout"), "layout.add"), + (tr("Remove all auto layout"), "layout.removeAll"), (tr("Create component"), "component.create"), (tr("Detach instance"), "component.detach"), ("-", ""), diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index b38829368..feb476a1a 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-30 · **Change:** minor (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-01 · **Change:** minor (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%, @@ -42,6 +42,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Hug only on auto layout frames (and text); Fill only in an auto layout flow, never on a top-level frame | pass | `al_behaviour_tests::hug_and_fill_only_where_they_apply` | | Min/max width and height bound Hug, Fill and Fixed sizes, on frames and children | pass | `sizing_rules`; a fill child at its max leaves the rest to the other fill children (silent on redistribution: CSS flexbox) | | A hugging text wider than its max width wraps at the max | pass | `sizing_rules` | +| Remove all auto layout: a frame and all of its nested objects lose their auto layout at once (More layout options) | **added** | `layout.removeAll {ids?}`, one undo step, in the canvas context menu beside Add auto layout; instances and the layers inside them keep theirs; `al_nesting_tests::remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it` | | Text filling a width wraps and its hugging frame grows with it | pass | `sizing_rules` | | A hugging frame follows a child that grows, through nested levels, in one edit and one undo step | pass | `al_behaviour_tests::a_hugging_frame_follows_its_children_through_nested_levels` | | Padding per side (uniform, vertical/horizontal, individual) | pass | `padding_and_stroke_rules` | @@ -95,6 +96,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | M2: Remove all auto layout ("To remove auto layout from a frame and all of its nested objects at once, right-click on the frame and go to More layout options > Remove all auto layout", Toggle on auto layout in designs): `layout.removeAll {ids?}` strips the frames and every frame nested in them in one undo step, leaving instances and their layers alone; in the canvas context menu beside Add auto layout and in the Actions palette. Found by a documentation audit of this page. Test: `al_nesting_tests::remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it`. Numbers unchanged | | 2026-10-30 | minor | M8, #1083: grid placement finds free cells on a bitmap, a word at a time, with the same placements; crafted grids of wide children no longer stall a layout pass. Numbers unchanged. | | 2026-10-29 | minor | M2 review fixes: conversion preserves mask runs and Fill sizing per axis; layout inference uses visible, non-absolute flow children; the sidebar hides Add for mixed selections containing existing auto layout. Regression coverage includes rendered mask pixels, visible-child positions, parent layout stability and the sidebar accessibility tree. Numbers unchanged | | 2026-10-29 | minor | M2: the Layout sidebar exposes Add auto layout (+) for groups. `layout.add` converts one selected group into a frame in place rather than wrapping it: same id, name and direct children; the layout arranges those children, and one undo restores the group. Sidebar, menu, shortcut and API calls all use the corrected command. This follows the contributor’s observed Figma behavior and the workflow familiar to users of similar design tools. Tests cover direct-child reflow, stable hierarchy, undo/redo and wrapping a multi-group selection. Numbers unchanged | From 65bd00f739601e257150275347cc816b0d68f098 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:49:58 -0500 Subject: [PATCH 083/326] M3: Delete on a layer inside an instance hides it instead of being refused (#1834) * M3: Delete on a layer inside an instance hides it instead of being refused Co-Authored-By: Claude Fable 5.1 * The components structure test: Delete inside an instance hides Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- crates/engine/src/assets/components/tests.rs | 6 ++++- crates/engine/src/cmd/edit.rs | 11 ++++++++- .../engine/src/components_behaviour_tests.rs | 24 ++++++++++++++++++- docs/components-parity.md | 5 ++-- 4 files changed, 41 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/assets/components/tests.rs b/crates/engine/src/assets/components/tests.rs index 82aabc63f..ffaac176f 100644 --- a/crates/engine/src/assets/components/tests.rs +++ b/crates/engine/src/assets/components/tests.rs @@ -144,7 +144,6 @@ fn instances_refuse_structure_edits() { let before = s.doc().unwrap().clone(); let undo = s.ds().unwrap().history.undo.len(); let refused = [ - ("edit.delete", json!({"ids": [ibg]})), ("shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5, "parent": i})), ("node.reorder", json!({"id": idot, "index": 0})), ("object.group", json!({"ids": [ibg, idot]})), @@ -158,6 +157,11 @@ fn instances_refuse_structure_edits() { assert_eq!(*s.doc().unwrap(), before, "{cmd} rolled back"); } assert_eq!(s.ds().unwrap().history.undo.len(), undo); + // Delete on a layer inside hides it instead (an override), as the reference tool does. + ex(&mut s, "edit.delete", json!({"ids": [ibg]})); + assert!(s.doc().unwrap().node(ibg).is_some_and(|n| !n.visible), "hidden, not removed"); + assert_eq!(s.doc().unwrap().node(i).unwrap().children, before.node(i).unwrap().children, "the structure is intact"); + healthy(&s); // Deleting the whole instance is fine. ex(&mut s, "edit.delete", json!({"ids": [i]})); healthy(&s); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3f72e429e..700fa7414 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -544,6 +544,15 @@ fn delete(s: &mut Session, p: &Value) -> Result { let ids = req_targets("edit.delete", s, p)?; let doc = s.doc_mut()?; let ids = roots(doc, &ids); + // A layer inside an instance can't be removed: Delete hides it instead, an override ("Figma + // will only toggle the layer's visibility instead of removing it", Guide to auto layout). + let (hidden, ids): (Vec<_>, Vec<_>) = ids.into_iter().partition(|i| crate::assets::components::inside_instance(doc, *i)); + for i in &hidden { + doc.get_mut(*i)?.visible = false; + } + if ids.is_empty() { + return Ok(json!({"deleted": [], "hidden": hidden})); + } let mut parents = Vec::new(); for i in &ids { if doc.node(*i).is_some_and(Node::is_page) { @@ -556,7 +565,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { } // Select the parent frame like Figma? Figma clears the selection. s.set_selection(vec![]); - Ok(json!({"deleted": ids})) + Ok(json!({"deleted": ids, "hidden": hidden})) } /// Layers duplicated last (Duplicate or Alt-drag) and their copies, in the same order. While the diff --git a/crates/engine/src/components_behaviour_tests.rs b/crates/engine/src/components_behaviour_tests.rs index a95e1268c..6d5a7ebcb 100644 --- a/crates/engine/src/components_behaviour_tests.rs +++ b/crates/engine/src/components_behaviour_tests.rs @@ -512,7 +512,6 @@ fn what_instances_cannot_override_is_refused() { ), ("remove auto layout", "layout.remove", json!({"ids": ["$"]}), Layer::Row, "structure of the instance"), ("reorder layers", "node.reorder", json!({"id": "$", "index": 3}), Layer::Bg, "\"the order, or z-index, of any layers within the instance\""), - ("delete a layer", "edit.delete", json!({"ids": ["$"]}), Layer::Bg, "layers can only be hidden"), ( "add a layer", "shape.rectangle", @@ -969,3 +968,26 @@ fn a_new_component_set_is_named_after_its_first_variant() { assert_eq!(node(&s, c).name, "State=Default"); healthy(&s); } + +/// "You can't delete a layer or object from an instance. If you try, Figma will only toggle the +/// layer's visibility instead of removing it." (Guide to auto layout; the flows article says the +/// same). Delete hides the layer, an override; the main component is untouched. +#[test] +fn deleting_a_layer_inside_an_instance_hides_it_instead() { + let mut s = Session::new(); + let k = kit(&mut s); + let target = k.copy(&s, Layer::Bg); + let steps = undo_len(&s); + let r = s.execute("edit.delete", &json!({"ids": [target]})).unwrap(); + assert_eq!((r["hidden"].clone(), r["deleted"].clone()), (json!([target]), json!([]))); + let doc = s.doc().unwrap(); + assert!(doc.node(target).is_some_and(|n| !n.visible), "hidden, not removed"); + assert!(doc.node(k.bg).is_some_and(|n| n.visible), "the main is untouched"); + assert_eq!(doc.node(k.inst).unwrap().children.len(), doc.node(k.card).unwrap().children.len(), "the structure is intact"); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().node(target).is_some_and(|n| n.visible)); + // The instance itself still goes away. + s.execute("edit.delete", &json!({"ids": [k.inst]})).unwrap(); + assert!(s.doc().unwrap().node(k.inst).is_none()); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 051730215..0e3248248 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-10-31 · **Change:** minor (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-01 · **Change:** minor (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 @@ -15,7 +15,7 @@ accounts). | Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main | | Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances | | What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | -| What it doesn't: position, rotation, constraints and absolute or grid placement of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out; the instance itself resizes and its layers follow the main's constraints | +| What it doesn't: position, rotation, constraints and absolute or grid placement of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out (Delete on a layer inside an instance hides it instead of removing it, as the help center says it does); the instance itself resizes and its layers follow the main's constraints | | Component sets / variants, add variant, switch | done | Combine as variants is in the Object menu, and the canvas and layers context menu and the Design panel offer it when two or more main components are selected; Add variant on a main component not in a set yet makes it a set of itself and the new variant, one undo step (#903); components that are variants already aren't combined again (it used to put a set inside a set) | | A main's copy within its file is an instance of it: Duplicate, Alt-drag, Copy then Paste | done | a variant duplicated in its set stays a new variant and a whole set copies as a new set; only the copied roots become instances (a main inside a copied frame is copied as a main); Cut then Paste and pastes into other files keep the component (#892) | | A component can't contain its own instance, directly or through other components | done | refused with the loop named (creating, placing, swapping, switching variants, moving, pasting, an instance-swap value); each variant counts as its own component, so a variant may hold a sibling variant's instance unless that one leads back to it; a dropped instance lands on the page; a file holding a loop opens with one instance detached and a note, any other file unchanged; a loop merged in a live session stops expanding where an instance would show itself again (#1084) | @@ -78,6 +78,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | M3: Delete on a layer inside an instance hides it (an override) instead of being refused ("You can't delete a layer or object from an instance. If you try, Figma will only toggle the layer's visibility instead of removing it", Guide to auto layout); `edit.delete` reports those ids under `hidden`, the structure and the main component stay as they were, one undo step; deleting the instance itself still removes it. Found by a documentation audit of the auto layout page. Test: `components_behaviour_tests::deleting_a_layer_inside_an_instance_hides_it_instead` (the refusal row for it is gone from `what_instances_cannot_override_is_refused`). Numbers unchanged | | 2026-10-31 | minor | M3, gap 10: library analytics cover styles and variables. A file reports how many of its layers use each of a library's styles and variables, and Show usage (`library.usage`) lists them beside the components, by a Type choice, with their layers and files. Layers inside instances count for their component. Insertions, detachments and modes aren't counted for them yet. Numbers unchanged. Tests: `library_assets_tests`. | | 2026-10-31 | minor | M6: as the help center describes code syntax, Dev Mode's SwiftUI and Compose code now writes a bound variable's iOS or Android code syntax in place of its value, as CSS already wrote the Web one: fills, strokes and their weight, sizes, corner radius, gaps, padding, opacity, the font family and size and the characters. A variable with no code syntax for the platform keeps the value, since a name made up here wouldn't exist in the code it lands in. ArkUI and Flutter have no code syntax platform and are unchanged. Test: `variables_behaviour_tests::swiftui_and_compose_name_variables_by_their_code_syntax`. Numbers unchanged. Grade unchanged | | 2026-10-31 | minor | M3, gap 10: library analytics over time. A file counts the instances of library components it inserts (placed, created, pasted or duplicated, Alt-dragged copies too; not those nested in another instance) and reports them like its detaches (`ReportInserted`). The server counts what a file's insertion and detach totals grow past their highest in the current week, a Monday at 00:00 UTC, so an undo and a redo count once, and keeps a year of weeks in `actions.json` (`Actions`). `library.usage {days?}` adds `insertions`, `detachments` and `weeks`, and per component `insertions` and `detachments`; Show usage has a 30 days, 90 days or 1 year choice, the period's totals, and each component's counts on a line of their own. The new variants are appended, so older messages keep their bytes; an older server refuses them and Show usage says it doesn't count insertions. A file's first report after this counts its total in that week. Tests: `library_actions_tests`, `inserting_library_instances_counts_them`. Grade unchanged | From 5050631bcf0679ac01f53c073a0b6310d2084ce9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:50:03 -0500 Subject: [PATCH 084/326] M5: Hide UI in the presenter: the bars go away and Cmd/Ctrl+\ brings them back (#1820) (#1826) Co-authored-by: Claude Fable 5.1 --- crates/engine/src/cmd/proto.rs | 6 ++-- crates/ui-egui/locales/en.toml | 2 ++ crates/ui-egui/src/app/commands.rs | 4 +++ crates/ui-egui/src/app/control.rs | 2 +- crates/ui-egui/src/present.rs | 5 ++- crates/ui-egui/src/present/chrome.rs | 16 ++++++++- crates/ui-egui/src/present/navigate.rs | 1 + crates/ui-egui/src/present/player.rs | 12 +++++-- crates/ui-egui/src/proto_editor_tests.rs | 45 +++++++++++++++++++++++- docs/control-protocol.md | 4 +-- docs/mcp.md | 2 +- docs/prototyping-parity.md | 4 ++- 12 files changed, 90 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/proto.rs b/crates/engine/src/cmd/proto.rs index df80764a3..dc30e933b 100644 --- a/crates/engine/src/cmd/proto.rs +++ b/crates/engine/src/cmd/proto.rs @@ -137,7 +137,7 @@ pub fn specs() -> Vec { spec!( "proto.presentOptions", "Presentation options", - "{scale? fit|fitWidth|fill|actual, deviceFrame? bool, hotspotHints? bool, inspect? bool} how the presenter sizes the prototype (Fit scales down to fit, Fit width fills the width, Fill covers the window, Actual shows it at 100%), whether it draws the device, whether a click where nothing reacts flashes the hotspots (on by default) and whether the Inspect panel shows the properties of the layer under the pointer; kept for later presentations", + "{scale? fit|fitWidth|fill|actual, deviceFrame? bool, hotspotHints? bool, inspect? bool, hideUi? bool} how the presenter sizes the prototype (Fit scales down to fit, Fit width fills the width, Fill covers the window, Actual shows it at 100%), whether it draws the device, whether a click where nothing reacts flashes the hotspots (on by default), whether the Inspect panel shows the properties of the layer under the pointer, and whether the bars are hidden (Hide UI: the prototype alone; Cmd/Ctrl+\\ shows them again); kept for later presentations", false, |s, p| { let cmd = "proto.presentOptions"; @@ -146,13 +146,13 @@ pub fn specs() -> Vec { let scale = v.as_str().filter(|x| PRESENT_SCALES.contains(x)).ok_or_else(|| bad(cmd, "scale: fit|fitWidth|fill|actual"))?; data.insert("scale".into(), json!(scale)); } - for key in ["deviceFrame", "hotspotHints", "inspect"] { + for key in ["deviceFrame", "hotspotHints", "inspect", "hideUi"] { if let Some(v) = p.get(key).filter(|v| !v.is_null()) { data.insert(key.into(), json!(v.as_bool().ok_or_else(|| bad(cmd, format!("{key}: true|false")))?)); } } if data.is_empty() { - return Err(bad(cmd, "nothing to set: scale, deviceFrame, hotspotHints or inspect")); + return Err(bad(cmd, "nothing to set: scale, deviceFrame, hotspotHints, inspect or hideUi")); } s.request_ui("present.options", Value::Object(data)); ok() diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 9150cc32b..38f2d4970 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -656,6 +656,7 @@ name = "English" "Help page" = "Help page" "Here: {names}" = "Here: {names}" "Hidden" = "Hidden" +"Hide UI" = "Hide UI" "Hide contents" = "Hide contents" "Hide from publishing" = "Hide from publishing" "Hide section contents" = "Hide section contents" @@ -1385,6 +1386,7 @@ name = "English" "Show device frame" = "Show device frame" "Show dimensions on objects" = "Show dimensions on objects" "Show hotspot hints" = "Show hotspot hints" +"The bars are hidden. {shortcut} shows them again" = "The bars are hidden. {shortcut} shows them again" "Show in Explorer" = "Show in Explorer" "Show in Finder" = "Show in Finder" "Show in folder" = "Show in folder" diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 69b60c5ed..0e34f437a 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -210,10 +210,14 @@ impl FigApp { if let Some(i) = r.data.get("inspect").and_then(|i| i.as_bool()) { v.inspect = i; } + if let Some(h) = r.data.get("hideUi").and_then(|h| h.as_bool()) { + v.hide_ui = h; + } if let Some(p) = self.ui.present.as_mut() { p.view.device_frame = v.device_frame; p.view.hotspot_hints = v.hotspot_hints; p.view.inspect = v.inspect; + p.view.hide_ui = v.hide_ui; p.set_scale(v.scale); } } diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 10baf76e8..72435673c 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -53,7 +53,7 @@ impl FigApp { "reduceMotion": self.reduce_motion(), "presenting": self.ui.present.is_some(), "presenter": tabs::shown_or_paused(self).map(present::Presenter::inspect), - "presentOptions": {"scale": self.ui.present_view.scale.id(), "deviceFrame": self.ui.present_view.device_frame, "comments": self.ui.present_view.comments, "hotspotHints": self.ui.present_view.hotspot_hints, "inspect": self.ui.present_view.inspect}, + "presentOptions": {"scale": self.ui.present_view.scale.id(), "deviceFrame": self.ui.present_view.device_frame, "comments": self.ui.present_view.comments, "hotspotHints": self.ui.present_view.hotspot_hints, "inspect": self.ui.present_view.inspect, "hideUi": self.ui.present_view.hide_ui}, "preview": self.ui.preview.as_ref().map(|p| p.player.inspect()), "mainMenu": self.ui.main_menu, "palette": self.ui.palette.is_some(), diff --git a/crates/ui-egui/src/present.rs b/crates/ui-egui/src/present.rs index 11c4466df..8f23069f2 100644 --- a/crates/ui-egui/src/present.rs +++ b/crates/ui-egui/src/present.rs @@ -216,11 +216,14 @@ pub struct PresentView { pub hotspot_hints: bool, /// A panel beside the prototype shows the Inspect properties of the layer under the pointer. pub inspect: bool, + /// Hide UI: the bar above the prototype and the navigation bar under it are gone, so the + /// prototype shows alone (Cmd/Ctrl+\, the editor's Show/Hide UI key, brings them back). + pub hide_ui: bool, } impl Default for PresentView { fn default() -> Self { - Self { scale: PresentScale::Fit, device_frame: true, comments: false, hotspot_hints: true, inspect: false } + Self { scale: PresentScale::Fit, device_frame: true, comments: false, hotspot_hints: true, inspect: false, hide_ui: false } } } diff --git a/crates/ui-egui/src/present/chrome.rs b/crates/ui-egui/src/present/chrome.rs index 4b477ec9f..4fc57ff0f 100644 --- a/crates/ui-egui/src/present/chrome.rs +++ b/crates/ui-egui/src/present/chrome.rs @@ -21,6 +21,8 @@ pub(super) enum BarAction { Comments, /// Show or hide the Inspect panel. Inspect, + /// Hide UI: hide or show the bars (the Options menu, Cmd/Ctrl+\). + HideUi, } pub struct PresentTab { @@ -53,6 +55,10 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) { if !typing && ctx.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::C)) { action = Some(BarAction::Comments); } + // Cmd/Ctrl+\ hides and shows the bars, as it hides and shows the editor's UI. + if !typing && ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Backslash)) { + action = Some(BarAction::HideUi); + } if pres.view.inspect { let t = Tokens::get(&ctx); egui::Panel::right("present_inspect") @@ -64,7 +70,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) { egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { action = player(&mut pres, ui, ui.max_rect(), now, Chrome { keys: !typing, ..FULL }).or(action); }); - let picked_device = navigation_bar(&mut pres, &ctx, now); + let picked_device = if pres.view.hide_ui { None } else { navigation_bar(&mut pres, &ctx, now) }; // Keys the prototype left alone: C shows the comments, F fills the screen. if !typing { if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::C)) { @@ -78,6 +84,14 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) { match action { Some(BarAction::Comments) => pres.view.comments = !pres.view.comments, Some(BarAction::Inspect) => pres.view.inspect = !pres.view.inspect, + Some(BarAction::HideUi) => { + pres.view.hide_ui = !pres.view.hide_ui; + // As the reference tool does, say how the bars come back. + if pres.view.hide_ui { + let shortcut = crate::toolbar::pretty_shortcut("Cmd+\\"); + app.toast(crate::i18n::trf("The bars are hidden. {shortcut} shows them again", &[("shortcut", &shortcut)])); + } + } _ => {} } if live diff --git a/crates/ui-egui/src/present/navigate.rs b/crates/ui-egui/src/present/navigate.rs index 34e76ea80..b5ae19cec 100644 --- a/crates/ui-egui/src/present/navigate.rs +++ b/crates/ui-egui/src/present/navigate.rs @@ -130,6 +130,7 @@ impl Presenter { "waiting": self.waiting.len(), "inspect": self.view.inspect, "inspected": self.inspected, + "hideUi": self.view.hide_ui, "deviceColor": doc.and_then(|d| page_settings(d, self.current).device_color()).map(|c| c.name), "responsive": self.fit.map(|f| [f.0, f.1]), "frameSize": doc.and_then(|d| d.node(self.current)).map(|n| [n.width, n.height]), diff --git a/crates/ui-egui/src/present/player.rs b/crates/ui-egui/src/present/player.rs index 006d95214..8bcbea09d 100644 --- a/crates/ui-egui/src/present/player.rs +++ b/crates/ui-egui/src/present/player.rs @@ -16,12 +16,14 @@ use super::{ pub(super) fn player(p: &mut Presenter, ui: &mut Ui, rect: Rect, now: f64, chrome: Chrome) -> Option { let ctx = ui.ctx().clone(); p.clock = now; - let bar = Rect::from_min_size(rect.min, vec2(rect.width(), chrome.bar_h)); + // Hide UI (the full-window presenter only): no bar, the prototype takes the whole window. + let hidden = p.view.hide_ui && !chrome.pane; + let bar = Rect::from_min_size(rect.min, vec2(rect.width(), if hidden { 0.0 } else { chrome.bar_h })); let area = Rect::from_min_max(pos2(rect.min.x, bar.max.y), rect.max); let bg = crate::theme::doc_c32(ui.ctx(), p.doc.as_ref().map(|d| page_settings(d, p.current)).unwrap_or_default().background); let r = chrome.round; ui.painter().rect_filled(area, CornerRadius { nw: 0, ne: 0, sw: r, se: r }, bg); - let action = top_bar(p, ui, bar, now, chrome); + let action = if hidden { None } else { top_bar(p, ui, bar, now, chrome) }; if action == Some(BarAction::Restart) { p.restart(p.start, now); } @@ -280,6 +282,12 @@ fn options_menu(p: &mut Presenter, ui: &mut Ui, device: Option, responsi p.view.hotspot_hints = !p.view.hotspot_hints; ui.close(); } + // Hide UI, as the reference tool's Options menu has it (#1820): the bars go away, the key + // (the editor's Show/Hide UI key) brings them back. + if menu_check(ui, p.view.hide_ui, tr("Hide UI"), &crate::toolbar::pretty_shortcut("Cmd+\\")) { + action = Some(BarAction::HideUi); + ui.close(); + } if menu_check(ui, false, tr("Restart"), "R") { p.restart(p.start, now); ui.close(); diff --git a/crates/ui-egui/src/proto_editor_tests.rs b/crates/ui-egui/src/proto_editor_tests.rs index 63c152e14..b16894425 100644 --- a/crates/ui-egui/src/proto_editor_tests.rs +++ b/crates/ui-egui/src/proto_editor_tests.rs @@ -1,10 +1,11 @@ //! The interaction editor's conditionals and the presenter's hotspot hints, driven headless //! through egui (the harness is `present_tests`'). -use egui::{Pos2, Rect, pos2}; +use egui::{Event, Key, Modifiers, Pos2, Rect, pos2}; use figcraft_doc::proto::{Action, Expr, ExprOp}; use figcraft_doc::{NodeId, VariableValue}; use figcraft_engine::Session; +use figcraft_engine::keymap::Platform; use serde_json::{Value, json}; use crate::present_tests::{Ui, id}; @@ -42,6 +43,48 @@ fn click(u: &mut Ui, p: Pos2) { u.button(p, false); } +fn press(u: &mut Ui, key: Key, modifiers: Modifiers) { + let ev = |pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }; + u.frame(vec![ev(true), ev(false)]); +} + +/// Cmd on macOS, Ctrl elsewhere, as egui reports it. +fn cmd() -> Modifiers { + if crate::shortcuts::platform() == Platform::Mac { Modifiers::MAC_CMD | Modifiers::COMMAND } else { Modifiers::CTRL | Modifiers::COMMAND } +} + +/// Hide UI (the Options menu, or Cmd/Ctrl+\ as in the editor) hides the bar above the prototype and +/// the navigation bar under it, so the prototype alone shows and takes the bar's room; the key shows +/// them again; the option carries over like the others, and the prototype still reacts meanwhile. +#[test] +fn hide_ui_hides_the_bars_and_the_key_shows_them_again() { + let (s, a, b, _) = setup(); + let mut u = Ui::new(s); + u.run("proto.present", json!({"start": a})); + u.frame(vec![]); + assert_eq!(presenter(&u)["hideUi"], json!(false), "shown by default"); + let top = |u: &Ui| rect_of(&presenter(u)["hotspots"][0]["rect"]).min.y; + let with_bars = top(&u); + u.run("proto.presentOptions", json!({"hideUi": true})); + u.frame(vec![]); + assert_eq!(presenter(&u)["hideUi"], json!(true)); + assert_eq!(u.app.inspect()["presentOptions"]["hideUi"], json!(true), "kept for the next presentation"); + let without = top(&u); + assert!(without < with_bars, "the prototype moves up into the bar's room: {with_bars} then {without}"); + press(&mut u, Key::Backslash, cmd()); + u.frame(vec![]); + assert_eq!(presenter(&u)["hideUi"], json!(false), "the key shows the bars again"); + assert_eq!(top(&u), with_bars); + press(&mut u, Key::Backslash, cmd()); + u.frame(vec![]); + assert_eq!(presenter(&u)["hideUi"], json!(true), "and hides them once more"); + assert!(u.app.ui.present_view.hide_ui, "kept for the next presentation"); + // The prototype keeps reacting with the bars hidden. + let at = rect_of(&presenter(&u)["hotspots"][0]["rect"]).center(); + click(&mut u, at); + assert_eq!(presenter(&u)["current"], json!(b)); +} + #[test] fn a_click_where_nothing_reacts_flashes_the_hotspots() { let (s, a, b, btn) = setup(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b2a455e0f..82ba08bd1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -250,9 +250,9 @@ far the view is panned (`pan`, `panRange`), whether a scroll is still coasting ( active screen's `hotspots` (`[{id, rect: [x0, y0, x1, y1]}]` in window points, bottom-most first), whether a click where nothing reacts flashes them (`hotspotHints`) and they are flashing now (`hotspotFlash`), and whether the Inspect panel shows (`inspect`) with the layer it shows -(`inspected`), and the link an Open link notice waits to open (`linkNotice`, else `null`) (`null` +(`inspected`), whether its bars are hidden (`hideUi`), and the link an Open link notice waits to open (`linkNotice`, else `null`) (`null` when nothing plays). `presentOptions` holds the options the next presentation -starts with (`scale`, `deviceFrame`, `comments`, `hotspotHints`, `inspect`). +starts with (`scale`, `deviceFrame`, `comments`, `hotspotHints`, `inspect`, `hideUi`). `textPreview` is true while a live text preview shows on the canvas (a hovered text style or named instance, a dragged axis slider; see `text.preview` in [mcp.md](mcp.md)). `focus` is keyboard navigation's state: the `region` with the keyboard (`toolbar`, `layers`, diff --git a/docs/mcp.md b/docs/mcp.md index 0e9f4f497..b5e49e749 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -859,7 +859,7 @@ in the file) the presented frame is instead resized to the device's screen, or w the presenter's window at 100%, and its constraints and auto layout respond as when it is resized in the editor (an axis it hugs keeps hugging its content); the file's frames don't change. `proto.present {start?}` plays the prototype full-window and `proto.preview {start?}` in a resizable pane over the canvas that follows edits live; `proto.closePreview` closes -it. `proto.presentOptions {scale?, deviceFrame?, hotspotHints?, inspect?}` sets how the +it. `proto.presentOptions {scale?, deviceFrame?, hotspotHints?, inspect?, hideUi?}` sets how the full-window presenter sizes the prototype (`fit` scales it down to fit, `fitWidth` fills the width, `fill` covers the window, `actual` shows it at 100%; what overflows pans), whether it draws the device, whether a click where nothing reacts briefly flashes the screen's hotspots (the layers with diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 345d08753..826b6780d 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-31 · **Change:** minor (the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) **Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except media control, every transition and easing exist; key/gamepad triggers take controller buttons, @@ -44,6 +44,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Nested layers with the same trigger: the top-most layer's interaction wins; a layer without that trigger lets it through to the one under it | pass | `nested_hotspots_and_click_through`, `hotspots_priority_and_click_through` | | A layer without interactions over a hotspot | silent | it doesn't block it: clicks reach the hotspot under it | | Hidden layers aren't hotspots; clipping frames cut their hotspots | pass | same | +| Hide UI (Options menu): "Hide the toolbar and footer on your current view" and "Remind you how to restore the toolbar and footer" | **added** | the Options menu's Hide UI and Cmd/Ctrl+\ (the editor's Show/Hide UI key, as the reference tool's) hide the bar above the prototype and the navigation bar under it, and a toast names the key that shows them again; `hide_ui_hides_the_bars_and_the_key_shows_them_again` (#1820) | | Navigate to: replaces the screen; from an overlay it closes the overlays; preserve scroll position keeps the offset (as far as the destination scrolls) | pass | `overlays_stack_swap_close_and_go_with_navigation`, `navigating_resets_scroll_unless_it_preserves_it` | | Back: closes the top overlay first, else returns to the previous screen playing its animation backwards; restart empties the history | pass | `back_plays_the_way_in_backwards_and_restart_starts_over`, `back_and_reverting_play_the_animation_the_other_way` | | Scroll to: every frame around the layer scrolls to bring it in, animated with the interaction's animation | pass | `scroll_to_moves_every_scrolling_frame_around_the_layer` | @@ -92,6 +93,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Drag-driven animations that follow the pointer, in their direction | done | | | Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537). Devices not compared with Figma's | | Hotspot hints, inspect panel in the presenter, comments in the presenter | done | | +| Hide UI in the presenter (Options menu, Cmd/Ctrl+\) | done | the bar above the prototype and the navigation bar under it go away and the prototype takes their room; a toast names the key that brings them back; `proto.presentOptions {hideUi}`, kept for later presentations (#1820) | | Preview pane following edits live | done | | | Edit interactions on several layers at once | done | | | Open link: a notice before a link opens, with a checkbox to skip it on this device | done | every openable link — `http`, `https` and `mailto` — and whatever fired it, a click, a delay, a key (a further link that fires while the notice shows is dropped); skipping it opens at once only a link the viewer's own click, press, drag or key fired, one per frame and never while a notice shows — a delay, the pointer passing over a layer or a timed mouse trigger still shows the notice, without the checkbox; a press under way when the notice appears ends there, so its release doesn't reach the prototype behind it; Open link opens it, Cancel or Escape drops it; the desktop app saves the checkbox with its preferences, and the web build keeps it until the page reloads; `proto.linkNotice {show}` turns it on or off (`present_links_tests`) | From 15bd733886ee1978e35aeb5ec831057596b61f9e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:51:07 -0500 Subject: [PATCH 085/326] Number fields: Alt held over the field scrubs it, as the label does Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 23 +++++++++++++++++++ .../ui-egui/src/panels/typography/spacing.rs | 2 +- crates/ui-egui/src/widgets.rs | 23 +++++++++++++------ docs/ui-parity.md | 5 ++-- 4 files changed, 43 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 566f0828b..91fbae2b2 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1194,3 +1194,26 @@ fn sidebar_field_text_stays_in_place_on_focus() { assert!((before.center().y - after.center().y).abs() <= 0.5, "numeric={numeric}: before={before:?}, after={after:?}"); } } + +/// "You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option +/// Windows: Alt" to scrub it (Adjust alignment, rotation, position, and dimensions). Alt is what +/// makes the drag a scrub there, not the fine rate: a point moves a step, as on the label. Without +/// Alt a drag on the field is no click, so it neither edits nor moves anything. +#[test] +fn alt_held_over_a_field_scrubs_it() { + let (mut u, a, _) = setup(); + let (at, _) = field(&mut u, "X"); + let steps = undo_steps(&u); + // Alt is held as the pointer arrives over the field, a frame before the press (the field takes + // a drag only once it has seen Alt; egui assigns a press by the frame before it). + let alt = Modifiers { alt: true, ..Modifiers::NONE }; + u.frame_with(vec![Event::PointerMoved(at)], alt); + drag(&mut u, at, 25.0, alt); + assert_eq!(geom(&u, a).0, 35.0, "a step a point: X from 10"); + assert_eq!(undo_steps(&u), steps + 1, "one undo step for the whole scrub"); + assert_eq!(field(&mut u, "X").1, "35", "the field shows it and isn't editing"); + let (at, _) = field(&mut u, "X"); + drag(&mut u, at, 25.0, Modifiers::NONE); + assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub"); + assert_eq!(undo_steps(&u), steps + 1); +} diff --git a/crates/ui-egui/src/panels/typography/spacing.rs b/crates/ui-egui/src/panels/typography/spacing.rs index 5ffaf22a2..2adc119df 100644 --- a/crates/ui-egui/src/panels/typography/spacing.rs +++ b/crates/ui-egui/src/panels/typography/spacing.rs @@ -58,7 +58,7 @@ pub(super) fn spacing_input(ui: &mut Ui, field: &SpacingField, value: &str, widt ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } let numeric = value.trim_end_matches('%').parse::().ok(); - match widgets::scrub(ui, field.id, &response, numeric, 1.0) { + match widgets::scrub(ui, field.id, &response, numeric, 1.0, true) { Some(FieldEdit::Scrub(v, done)) => Some(SpacingEdit::Scrub(v, done)), _ => typed.map(SpacingEdit::Typed), } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index c7e20bb1d..4ed92eb0d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -132,8 +132,9 @@ pub fn scrubbed(from: f64, amount: f64, quantum: f64) -> f64 { } /// The shared label-scrub gesture, including changing modifier rates and raw edge motion. -/// Callers supply the hit area and apply live values until the final `Scrub(_, true)`. -pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option, step: f64) -> Option { +/// Callers supply the hit area and apply live values until the final `Scrub(_, true)`. `fine_on_alt`: +/// Alt gives tenths (off where Alt is what makes the drag a scrub at all). +pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option, step: f64, fine_on_alt: bool) -> Option { let v = value?; // Where the scrub began and how far it has taken the value (the modifiers can change on // the way: each stretch counts at its own rate). @@ -150,7 +151,7 @@ pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option, st // does too. Elsewhere the scrub just stops there. let raw = p.motion().map_or(0.0, |m| m.x / i.pixels_per_point); let at_edge = moved == 0.0 && p.hover_pos().is_none_or(|at| at.x <= 1.0 || at.x >= i.content_rect().max.x - 1.0); - (f64::from(if at_edge { raw } else { moved }), i.modifiers.shift, i.modifiers.alt) + (f64::from(if at_edge { raw } else { moved }), i.modifiers.shift, i.modifiers.alt && fine_on_alt) }); // The frame the button goes up moves nothing: the scrub ends where the last one left it. if response.dragged() { @@ -265,7 +266,12 @@ fn number_field_impl( let edit_rect = Rect::from_min_max(pos2(rect.min.x + lead_w, rect.min.y), rect.max); let editing_id = id.with("editing"); let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); - let field_resp = ui.interact(edit_rect, id.with("field"), Sense::click()); + // Alt held over the field scrubs it too, as the label always does: "hover the input field + // itself and hold down the modifier key" (Adjust alignment, rotation, position, and + // dimensions). The drag sense stays on until a scrub begun that way is let go. + let field_id = id.with("field"); + let alt_scrub = editing.is_none() && (ui.input(|i| i.modifiers.alt) || ui.ctx().is_being_dragged(field_id)); + let field_resp = ui.interact(edit_rect, field_id, if alt_scrub { Sense::CLICK | Sense::DRAG } else { Sense::click() }); a11y::number(&field_resp, lead.name(), value, suffix, empty.text()); a11y::ring_around(ui, rect, &field_resp); // The label scrubs with the pointer; the keyboard stops at the value only. @@ -291,10 +297,13 @@ fn number_field_impl( } Lead::None | Lead::Named(_) => {} } - if lead_resp.hovered() || lead_resp.dragged() { + if lead_resp.hovered() || lead_resp.dragged() || (alt_scrub && (field_resp.hovered() || field_resp.dragged())) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } - if let Some(edit) = scrub(ui, id, &lead_resp, value, step) { + // On the field, Alt is what makes the drag a scrub, so it is not the fine rate there. + if let Some(edit) = + scrub(ui, id, &lead_resp, value, step, true).or_else(|| alt_scrub.then(|| scrub(ui, id, &field_resp, value, step, false)).flatten()) + { out = Some(Edit::All(edit)); } let (key_step, key_big) = key_steps(ui.ctx(), suffix, step); @@ -340,7 +349,7 @@ fn number_field_impl( } // Typing on a field the keyboard reached (Tab) edits it: the editor takes the typed text. let typed_now = editing.is_none() && on_field && ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_)))); - let started = editing.is_none() && (field_resp.clicked() || typed_now); + let started = editing.is_none() && ((field_resp.clicked() && !alt_scrub) || typed_now); // The text the field would commit to no effect: what it showed when the edit began, or the // value the arrows last stepped it to. let kept_id = id.with("kept"); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0286fd37d..6f453111b 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-10-30 · **Change:** minor (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-01 · **Change:** minor (a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; 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: @@ -70,7 +70,7 @@ interaction feel not yet compared. | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | | Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) | | Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; the pixel grid shows from 400% (`view_behaviour_tests`) | -| Numeric fields: arithmetic, scrubbing by dragging the label, mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: a step a point (1 px; 1% of opacity, 1° of rotation), ten with Shift, a tenth with Alt, each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; rates not compared with Figma's | +| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: a step a point (1 px; 1% of opacity, 1° of rotation), ten with Shift, a tenth with Alt, each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; rates not compared with Figma's | | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | 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) | @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 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-10-31 | minor | M1, #1682: as the help center describes the colour picker, choosing Image no longer opens a file dialog at once: the tab shows a checkered placeholder and Upload from computer until there is a file. An image paint shows its asset preview with the same button. A file dropped on the open picker replaces the image and keeps the fill mode, crop, position and adjustments; on the placeholder it becomes the paint's image, filling the layer. While a file is dragged the picker says it takes it instead of the window saying Drop to import. New command `image.replace {ids?, target?, index?, data | path}`, through the same size cap and decoder as `image.place`; one undo step. Dropped files in the browser arrive as `data`. A native window or a browser doesn't say where a dragged file is, so a drop with no known position goes to the open picker, and one known to be over the canvas imports as before. Left: the Fill and Stroke swatches in the Design panel don't take a drop, since their place can't be told during a drag; pasting into the picker isn't documented and isn't added. Tests: `colorpicker_image_tests`, `image_crop_tests::replacing_an_image_keeps_its_fill_mode_crop_and_adjustments`. Numbers unchanged | | 2026-10-30 | minor | Gap 4: the keyboard's Menu key opens the context menu, as Shift+F10 does (at the focused layer row or below the canvas selection, with the keyboard in the menu). egui already reported the key; FigCraft's keymap had no name or binding for it. `view.contextMenu` now takes `Menu` too, and the Context menus row is done (`layers_keyboard_tests`). Stale rows corrected: smart-selection spacing has had reorder rings since the "M1: smart-selection drag reordering" landing (the row is still partial: irregular grids and several marked layers aren't covered), and gap 4 and the parity summary quoted shortcut counts from before the last bindings (now 128 bound, none missing, 57 undocumented pinned, as `shortcut_parity_tests` counts). | | 2026-10-30 | minor | M4, gap 4: the eyedropper with Cmd/Ctrl+Shift held makes a colour style or variable of the colour it picks, as the reference app's eyedropper does, instead of filling the selection. It asks the UI for a Create from color window (`dialog.createFromColor`; the control channel never opens it). The window shows the colour and offers Style or Variable, a name (the next free "Color n") and, for a variable, a collection: the file's first, or a new one made with it in the same undo step. Create runs `style.create` or `variable.create`. Tests: `eyedropper_create_tests`, `sampled_color_tests`. | From f58e022ed7cd48d9a2bb883cbcf3c9e27888a7b2 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:56:06 -0500 Subject: [PATCH 086/326] Shortcuts: Cmd/Ctrl+Alt+arrows rotate a degree at a time, 15 with Shift (#1845) * Shortcuts: Cmd/Ctrl+Alt+arrows rotate a degree at a time, 15 with Shift Co-Authored-By: Claude Fable 5.1 * The rotate gesture's label in the English catalog Co-Authored-By: Claude Fable 5.1 * Rotate keys: about the selection's rotation origin, not while editing points, Dev Mode refusal on the control path too Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/keymap.rs | 1 + crates/engine/src/shortcut_parity_tests.rs | 4 +- crates/ui-egui/locales/en.toml | 3 ++ crates/ui-egui/src/control.rs | 15 ++++++- crates/ui-egui/src/shortcut_keys_tests.rs | 49 ++++++++++++++++++++++ crates/ui-egui/src/shortcuts.rs | 15 +++++++ docs/ui-parity.md | 7 ++-- 7 files changed, 89 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index 65259755a..d21864762 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -346,6 +346,7 @@ pub static KEYS: &[Binding] = &[ pub static GESTURES: &[(Group, &str, &str, &str)] = &[ (Tools, "Pan the canvas", "Space drag", "Space+drag"), (Tools, "Pan with nothing selected (Shift: farther)", "← ↑ → ↓", "← ↑ → ↓"), + (Transform, "Rotate a degree (Shift: 15)", "⌥⌘ ← ↑ → ↓", "Ctrl+Alt+← ↑ → ↓"), (Tools, "Place a shape or frame (its tool chosen)", "↵", "Enter"), (Zoom, "Zoom tool: click to zoom in, drag an area", "Hold Z", "Hold Z"), (Zoom, "Zoom tool: zoom out", "Hold ⌥Z", "Hold Alt+Z"), diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index 6cf7c361d..c650f121e 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -255,6 +255,8 @@ static ROWS: &[Row] = &[ doc(Transform, "Use as mask (again: release)", &["Ctrl+Cmd+M"], &["Ctrl+Alt+M"], Bound("object.mask"), ""), doc(Transform, "Resize a frame to fit its contents", &["Alt+Shift+Cmd+R"], &["Ctrl+Alt+Shift+R"], Bound("object.resizeToFit"), ""), doc(Transform, "Nudge (Shift: big nudge)", &["ArrowRight"], &[], Gesture("Nudge (Shift: big nudge)"), ""), + doc(Transform, "Rotate a degree (Shift: 15 degrees)", &["Alt+Cmd+ArrowDown"], &[], Gesture("Rotate a degree (Shift: 15)"), + "Accessibility at Figma; down and right turn clockwise, up and left back (silent on the direction)"), doc(Transform, "Suspend snapping while dragging", &["Ctrl"], &[], Gesture("Suspend snapping while dragging"), "Control on macOS (Cmd keeps working); Ctrl elsewhere"), doc(Transform, "Show the rotation origin to move it", &["Alt+R"], &[], Bound("transform.rotationOrigin"), @@ -407,7 +409,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), (129, 128, 1, 0, 2, 57)); + assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (130, 129, 1, 0, 2, 57)); } #[test] diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 38f2d4970..c44635a2a 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -994,6 +994,9 @@ name = "English" "Nov" = "Nov" "Now" = "Now" "Nudge (Shift: big nudge)" = "Nudge (Shift: big nudge)" +"Rotate a degree (Shift: 15)" = "Rotate a degree (Shift: 15)" +"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓" +"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓" "Nudge amount" = "Nudge amount" "Number" = "Number" "Number ↑" = "Number ↑" diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index fd5a2a4e9..58c454bc3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -996,11 +996,24 @@ fn ui_key(app: &mut FigApp, ctx: &Context, p: &Value) -> Result { "ArrowUp" => (0, -1), _ => (0, 1), }; - let (cmd, params) = if m.cmd || m.ctrl { + let (cmd, params) = if (m.cmd || m.ctrl) && m.alt { + // Rotate a degree, 15 with Shift: down and right clockwise, up and left back, about + // the selection's rotation origin; nothing while points are being edited. + if app.session.ds().is_ok_and(|d| d.vector_edit.is_some()) { + return Ok(json!({})); + } + let step = if m.shift { 15.0 } else { 1.0 }; + let origin = app.session.ds().ok().and_then(|d| d.origin_point()); + ("transform.rotate", json!({"degrees": if dx + dy < 0 { -step } else { step }, "cx": origin.map(|o| o.x), "cy": origin.map(|o| o.y)})) + } else if m.cmd || m.ctrl { ("transform.nudgeSize", json!({"dw": dx, "dh": dy, "big": m.shift})) } else { ("transform.nudge", json!({"dx": dx, "dy": dy, "big": m.shift})) }; + // Dev Mode only inspects, as the window's key path says. + if crate::menus::dev_mode_refuses(app, cmd) { + return Err("Dev Mode only inspects: switch to Design to edit".into()); + } app.session.execute(cmd, ¶ms).map_err(|e| e.to_string()) } _ => { diff --git a/crates/ui-egui/src/shortcut_keys_tests.rs b/crates/ui-egui/src/shortcut_keys_tests.rs index 42413a4fb..6907cac5a 100644 --- a/crates/ui-egui/src/shortcut_keys_tests.rs +++ b/crates/ui-egui/src/shortcut_keys_tests.rs @@ -228,3 +228,52 @@ fn cmd_plus_and_minus_zoom_the_canvas_not_the_interface() { assert!(view(&u).2 < 1.0, "Cmd/Ctrl+- zooms the canvas out: {}", view(&u).2); assert_eq!(u.ctx.zoom_factor(), 1.0); } + +/// "Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one +/// degree at a time" and with Shift "15 degrees at a time" (Accessibility at Figma). The keys +/// turned the selection's size before; Cmd/Ctrl+arrows without Alt still resize. +#[test] +fn cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift() { + let mut s = Session::new(); + let r = id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap()); + let mut u = Ui::new(s); + u.app.run("select.set", json!({"ids": [r]})); + let rot = |u: &Ui| figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().node(r).unwrap().transform); + let size = |u: &Ui| { + let n = u.app.session.doc().unwrap().node(r).unwrap().clone(); + (n.width, n.height) + }; + press(&mut u, Key::ArrowDown, cmd() | Modifiers::ALT); + assert!((rot(&u) - 1.0).abs() < 1e-6, "one degree: {}", rot(&u)); + press(&mut u, Key::ArrowDown, cmd() | Modifiers::ALT | Modifiers::SHIFT); + assert!((rot(&u) - 16.0).abs() < 1e-6, "fifteen more: {}", rot(&u)); + press(&mut u, Key::ArrowUp, cmd() | Modifiers::ALT); + assert!((rot(&u) - 15.0).abs() < 1e-6, "one back: {}", rot(&u)); + assert_eq!(size(&u), (40.0, 40.0), "no resize"); + press(&mut u, Key::ArrowDown, cmd()); + assert_eq!(size(&u), (40.0, 41.0), "Cmd/Ctrl+arrows alone still resize"); + // Two layers turned together: the turns go about the rotated selection box's centre, so a + // degree down and a degree up leave both where they were. + let c = id(u.app.session.execute("shape.rectangle", &json!({"x": 200, "y": 0, "width": 40, "height": 40})).unwrap()); + let d = id(u.app.session.execute("shape.rectangle", &json!({"x": 300, "y": 60, "width": 30, "height": 20})).unwrap()); + u.app.run("select.set", json!({"ids": [c, d]})); + u.app.run("transform.rotate", json!({"degrees": 30})); + let bounds = |u: &Ui| [c, d].map(|n| u.app.session.doc().unwrap().world_bounds(n).unwrap()); + let before = bounds(&u); + press(&mut u, Key::ArrowDown, cmd() | Modifiers::ALT); + press(&mut u, Key::ArrowUp, cmd() | Modifiers::ALT); + let after = bounds(&u); + for (x, y) in before.iter().zip(&after) { + assert!( + (x.x0 - y.x0).abs() < 1e-6 && (x.y0 - y.y0).abs() < 1e-6 && (x.x1 - y.x1).abs() < 1e-6 && (x.y1 - y.y1).abs() < 1e-6, + "{x:?} then {y:?}" + ); + } + // While points are being edited the chord does nothing to the layer. + u.app.run("select.set", json!({"ids": [r]})); + let rot_before = rot(&u); + u.app.run("vector.edit.begin", json!({"id": r})); + press(&mut u, Key::ArrowDown, cmd() | Modifiers::ALT); + assert!((rot(&u) - rot_before).abs() < 1e-6, "no turn while editing points"); + u.app.run("vector.edit.end", json!({})); +} diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index a6006976d..f44adb68e 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -484,6 +484,21 @@ fn key_event(app: &mut FigApp, key: Key, physical: Option, m: Modifiers, re app.run("view.pan", json!({"dx": dx, "dy": dy, "big": m.shift})); } else if crate::menus::dev_mode_refuses(app, "transform.nudge") { // Dev Mode: said so, nothing moves. + } else if m.command && m.alt { + // Cmd/Ctrl+Alt+arrows rotate a degree at a time, 15 with Shift (Accessibility at + // Figma); down and right turn clockwise, up and left back (the documentation doesn't + // say which way). Not while points are being edited: the layer must not turn under + // the editor, and no key rotates points. About the selection's rotation origin (the + // moved one, else the centre of the rotated selection box), so repeated turns stay put. + if app.session.ds().is_ok_and(|d| d.vector_edit.is_some()) { + return true; + } + let step = if m.shift { 15.0 } else { 1.0 }; + let origin = app.session.ds().ok().and_then(|d| d.origin_point()); + app.run( + "transform.rotate", + json!({"degrees": if dx + dy < 0.0 { -step } else { step }, "cx": origin.map(|o| o.x), "cy": origin.map(|o| o.y)}), + ); } else if m.command { // Cmd/Ctrl+arrows resize: right/down grow, left/up shrink. app.run("transform.nudgeSize", json!({"dw": dx, "dh": dy, "big": m.shift})); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a77f79348..de15b2bd2 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-01 · **Change:** minor (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-01 · **Change:** minor (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: @@ -128,8 +128,8 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | | Count | Notes | |---|---|---| -| Documented shortcuts (rows) | 129 | each with macOS and Windows/Linux keys | -| Bound as documented | 128 (110 before this suite) | 108 keymap bindings, 14 held keys, gestures and presentation keys, 6 vector edit tool keys | +| Documented shortcuts (rows) | 130 | each with macOS and Windows/Linux keys | +| Bound as documented | 129 (110 before this suite) | 108 keymap bindings, 15 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 | @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | | 2026-10-31 | minor | M1, #1682: as the help center describes the colour picker, choosing Image no longer opens a file dialog at once: the tab shows a checkered placeholder and Upload from computer until there is a file. An image paint shows its asset preview with the same button. A file dropped on the open picker replaces the image and keeps the fill mode, crop, position and adjustments; on the placeholder it becomes the paint's image, filling the layer. While a file is dragged the picker says it takes it instead of the window saying Drop to import. New command `image.replace {ids?, target?, index?, data | path}`, through the same size cap and decoder as `image.place`; one undo step. Dropped files in the browser arrive as `data`. A native window or a browser doesn't say where a dragged file is, so a drop with no known position goes to the open picker, and one known to be over the canvas imports as before. Left: the Fill and Stroke swatches in the Design panel don't take a drop, since their place can't be told during a drag; pasting into the picker isn't documented and isn't added. Tests: `colorpicker_image_tests`, `image_crop_tests::replacing_an_image_keeps_its_fill_mode_crop_and_adjustments`. Numbers unchanged | | 2026-10-30 | minor | Gap 4: the keyboard's Menu key opens the context menu, as Shift+F10 does (at the focused layer row or below the canvas selection, with the keyboard in the menu). egui already reported the key; FigCraft's keymap had no name or binding for it. `view.contextMenu` now takes `Menu` too, and the Context menus row is done (`layers_keyboard_tests`). Stale rows corrected: smart-selection spacing has had reorder rings since the "M1: smart-selection drag reordering" landing (the row is still partial: irregular grids and several marked layers aren't covered), and gap 4 and the parity summary quoted shortcut counts from before the last bindings (now 128 bound, none missing, 57 undocumented pinned, as `shortcut_parity_tests` counts). | From a953a04e33a51e5112f7f35511cea21399f271ad Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 23:59:08 -0500 Subject: [PATCH 087/326] Shortcuts: Cmd/Ctrl+Shift+Alt+= / - / 0 make the interface larger, smaller and default-sized (#1846) * Shortcuts: Cmd/Ctrl+Shift+Alt+= / - / 0 make the interface larger, smaller and default-sized Co-Authored-By: Claude Fable 5.1 * Interface size keys: live while editing text too, and the new size draws on the next frame Co-Authored-By: Claude Fable 5.1 * A preference set during a frame repaints this window too, so the interface size applies on the next frame Co-Authored-By: Claude Fable 5.1 * Control channel: a preference changed by a hidden window's command repaints every window Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/view.rs | 31 ++++++++++++++++ crates/engine/src/keymap.rs | 5 +++ crates/engine/src/keymap_tests.rs | 41 ++++++++++++++++++++++ crates/engine/src/lib.rs | 2 +- crates/engine/src/prefs.rs | 4 +++ crates/engine/src/shortcut_parity_tests.rs | 5 ++- crates/ui-egui/src/app.rs | 8 +++++ crates/ui-egui/src/control.rs | 8 +++++ crates/ui-egui/src/ui_scale.rs | 5 +-- crates/ui-egui/src/windows.rs | 2 ++ docs/ui-parity.md | 7 ++-- 11 files changed, 111 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index c7fea9f92..1fc2ef22a 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -194,6 +194,22 @@ fn region(s: &mut Session, step: i64) -> Result { ok() } +/// Step the interface size through the Preferences sizes: `dir` 1 up, -1 down, 0 back to the +/// system's size (1). At an end it stays. Kept at once, as a size picked in Preferences is. +fn ui_scale_step(s: &mut Session, dir: i32) -> Result { + let now = s.prefs.ui_scale; + let next = match dir { + 0 => 1.0, + 1 => crate::UI_SCALE_SIZES.iter().copied().find(|v| *v > now + 1e-9).unwrap_or(now), + _ => crate::UI_SCALE_SIZES.iter().rev().copied().find(|v| *v < now - 1e-9).unwrap_or(now), + }; + if (next - now).abs() > 1e-9 { + s.prefs.ui_scale = next; + s.prefs_unsaved = true; + } + Ok(json!({"scale": s.prefs.ui_scale})) +} + fn pref(s: &mut Session, p: &Value, f: fn(&mut crate::Prefs) -> &mut bool) -> Result { let slot = f(&mut s.prefs); *slot = boolean(p, "on").unwrap_or(!*slot); @@ -395,6 +411,21 @@ pub fn specs() -> Vec { Ok(json!({"scale": s.prefs.ui_scale})) } ), + spec!( + "pref.uiScaleUp", + "Larger interface", + "{} the next of the Preferences sizes above the current one (the interface size keys of Accessibility at Figma); at the largest it stays → {scale}", + false, + |s, _| ui_scale_step(s, 1) + ), + spec!( + "pref.uiScaleDown", + "Smaller interface", + "{} the next of the Preferences sizes below the current one; at the smallest it stays → {scale}", + false, + |s, _| ui_scale_step(s, -1) + ), + spec!("pref.uiScaleReset", "Default interface size", "{} back to the system's own size (1) → {scale}", false, |s, _| ui_scale_step(s, 0)), spec!("pref.autoSave", "Save files automatically", "{on?}", false, |s, p| pref(s, p, |x| &mut x.auto_save)), spec!("pref.startOnHome", "Start on the Home screen", "{on?}", false, |s, p| pref(s, p, |x| &mut x.start_on_home)), spec!("pref.nudge", "Nudge amount", "{small?, big?}", false, |s, p| { diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index d21864762..a0f0bc4b6 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -214,6 +214,11 @@ pub static KEYS: &[Binding] = &[ k(View, "view.snapPixel", &["Shift+Cmd+'"]), // Windows: one help-center article writes Ctrl+1, another Alt+1; both open it there. k(View, "view.layers", &["Alt+1"]).win(&["Alt+1", "Ctrl+1"]).label("Layers panel"), + // The interface size (Accessibility at Figma): Cmd/Ctrl+Shift+Alt with =, - and 0, while + // editing text too. + k(View, "pref.uiScaleUp", &["Alt+Shift+Cmd+="]).both(), + k(View, "pref.uiScaleDown", &["Alt+Shift+Cmd+-"]).both(), + k(View, "pref.uiScaleReset", &["Alt+Shift+Cmd+0"]).both(), k(View, "view.assets", &["Alt+2"]).label("Assets panel"), k(View, "libraries.open", &["Alt+3"]), k(View, "view.design", &["Alt+8"]).label("Design panel"), diff --git a/crates/engine/src/keymap_tests.rs b/crates/engine/src/keymap_tests.rs index c7db0b16e..67c5bf258 100644 --- a/crates/engine/src/keymap_tests.rs +++ b/crates/engine/src/keymap_tests.rs @@ -306,6 +306,47 @@ fn ctrl_tab_cycles_documents() { assert_eq!(lookup(Platform::Mac, Context::Canvas, "Tab", mods(true, false, false, true)).map(|b| b.id), Some("doc.previousTab")); } +/// "Adjust the scale of the Figma UI [...] Windows: Reset to Default: Control ⇧Shift Alt 0; Make +/// Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -" (Accessibility at Figma; ⌘ on +/// a Mac). The steps go through the sizes Preferences offers, stop at the ends, and are kept at once. +#[test] +fn the_interface_size_keys_step_through_the_preferences_sizes() { + let m = mods(true, true, true, false); + for p in PLATFORMS { + for c in [Context::Canvas, Context::Text] { + assert_eq!(id_for(p, c, "=", m), Some("pref.uiScaleUp"), "{p:?} {c:?}"); + assert_eq!(id_for(p, c, "-", m), Some("pref.uiScaleDown"), "{p:?} {c:?}"); + assert_eq!(id_for(p, c, "0", m), Some("pref.uiScaleReset"), "{p:?} {c:?}"); + } + } + let mut s = Session::new(); + let scale = |s: &Session| s.prefs.ui_scale; + ex(&mut s, "pref.uiScale", json!({"scale": 1})); + s.prefs_unsaved = false; + ex(&mut s, "pref.uiScaleUp", json!({})); + assert_eq!(scale(&s), 1.1); + assert!(s.prefs_unsaved, "kept at once"); + ex(&mut s, "pref.uiScaleUp", json!({})); + assert_eq!(scale(&s), 1.25); + ex(&mut s, "pref.uiScaleDown", json!({})); + assert_eq!(scale(&s), 1.1); + assert_eq!(ex(&mut s, "pref.uiScaleReset", json!({}))["scale"], json!(1.0)); + assert_eq!(scale(&s), 1.0); + // Between two sizes a step lands on the next one; at an end it stays. + ex(&mut s, "pref.uiScale", json!({"scale": 1.3})); + ex(&mut s, "pref.uiScaleUp", json!({})); + assert_eq!(scale(&s), 1.5); + ex(&mut s, "pref.uiScale", json!({"scale": 1.3})); + ex(&mut s, "pref.uiScaleDown", json!({})); + assert_eq!(scale(&s), 1.25); + ex(&mut s, "pref.uiScale", json!({"scale": 2})); + ex(&mut s, "pref.uiScaleUp", json!({})); + assert_eq!(scale(&s), 2.0); + ex(&mut s, "pref.uiScale", json!({"scale": 0.75})); + ex(&mut s, "pref.uiScaleDown", json!({})); + assert_eq!(scale(&s), 0.75); +} + /// The Layers panel's Windows key is Ctrl+1 in one help-center article ("Mac: Option 1 Windows: /// Ctrl 1", Select layers and objects) and Alt+1 in another (Explore the navigation bar and left /// sidebar): both open it there. macOS keeps Option+1 alone; Cmd+1 is not documented. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1c0b7e39a..0da532b25 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -110,7 +110,7 @@ mod view_state; pub use derived::{changed_nodes, normalize}; pub use doc_state::{DocState, History, HistoryEntry, Interaction, PREVIEW_READ_ONLY, Preedit, TextEdit, VersionPreview}; pub use error::{EngineError, Result, bad}; -pub use prefs::{Clipboard, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UiRequest, clamp_ui_scale}; +pub use prefs::{Clipboard, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UI_SCALE_SIZES, UiRequest, clamp_ui_scale}; pub use session::Forward; pub use view_state::ViewState; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 709482218..5c455aa35 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -7,6 +7,10 @@ pub const UI_SCALE_MIN: f64 = 0.75; pub const UI_SCALE_MAX: f64 = 3.0; /// `scale` kept between [`UI_SCALE_MIN`] and [`UI_SCALE_MAX`]; not a finite number: `None`. +/// The interface sizes Preferences offers, relative to the system's scale (the keys step through +/// them; `pref.uiScale` takes any size up to [`UI_SCALE_MAX`]). +pub const UI_SCALE_SIZES: [f64; 8] = [0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0]; + pub fn clamp_ui_scale(scale: f64) -> Option { scale.is_finite().then(|| scale.clamp(UI_SCALE_MIN, UI_SCALE_MAX)) } diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index c650f121e..0b9b573af 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -147,6 +147,9 @@ static ROWS: &[Row] = &[ doc(View, "Others' cursors in a live session", &["Alt+Cmd+\\"], &["Ctrl+Alt+\\"], Bound("view.multiplayerCursors"), "new command"), doc(View, "Hide the side panels (minimize the interface)", &["Shift+Cmd+\\"], &[], Bound("view.leftSidebar"), ""), doc(View, "Layers panel", &["Alt+1"], &["Alt+1", "Ctrl+1"], Bound("view.layers"), "one article writes Ctrl+1 for Windows, another Alt+1; both bound there"), + doc(View, "Interface scale: make larger", &["Alt+Shift+Cmd+="], &[], Bound("pref.uiScaleUp"), "Accessibility at Figma, Adjust the scale of the Figma UI"), + doc(View, "Interface scale: make smaller", &["Alt+Shift+Cmd+-"], &[], Bound("pref.uiScaleDown"), "Accessibility at Figma"), + doc(View, "Interface scale: reset to default", &["Alt+Shift+Cmd+0"], &[], Bound("pref.uiScaleReset"), "Accessibility at Figma"), doc(View, "Assets panel", &["Alt+2"], &[], Bound("view.assets"), ""), doc(View, "Libraries", &["Alt+3"], &[], Bound("libraries.open"), ""), doc(View, "Dev Mode on or off", &["Shift+D"], &[], Bound("view.devMode"), ""), @@ -409,7 +412,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), (130, 129, 1, 0, 2, 57)); + assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (133, 132, 1, 0, 2, 57)); } #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d130daaea..c625f342a 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -117,6 +117,11 @@ impl FigApp { if ctx.viewport_id() == egui::ViewportId::ROOT { ctx.set_zoom_factor(plan.zoom); } + // A size that just changed (a key, Preferences, a command) draws at the new size from + // the next frame: ask for it rather than wait for the next input. + if plan != self.ui.ui_scale { + ctx.request_repaint(); + } self.ui.ui_scale = plan; } let dark = match self.session.prefs.theme.as_str() { @@ -177,6 +182,9 @@ impl FigApp { self.frame(ui); windows::settle(self, &ctx, files); if self.session.prefs != prefs { + // This window too: a preference set during the frame (the interface size, the theme) + // is applied as the next frame begins, so ask for it now rather than wait for input. + ctx.request_repaint(); windows::repaint_others(self, &ctx); } windows::show(self, &ctx); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 58c454bc3..322d9032c 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -545,6 +545,7 @@ pub fn background(app: &mut FigApp, ctx: &Context) { } // Outside a frame, so outside the frame's guard: within the window's swap, a panic still // ends in recovery copies and leaves every window its own state. + let prefs = app.session.prefs.clone(); let res = crate::windows::as_window(app, target, |app| { let mut res = Err("internal error".to_string()); // Every control-channel gesture is fenced from the user's system clipboard. @@ -554,6 +555,13 @@ pub fn background(app: &mut FigApp, ctx: &Context) { app.control_synthetic = before; res }); + // A preference the command changed (the interface size, the theme) applies as each + // window's next frame begins; no frame's end-of-frame check ran here, so ask every window. + if app.session.prefs != prefs { + for id in std::iter::once(0).chain(app.windows.list.iter().map(|w| w.id)) { + ctx.request_repaint_of(crate::windows::viewport(id)); + } + } let _ = r.reply.send(ControlReply { id: r.id, result: res.unwrap_or_else(|| Err(format!("no window {target}"))) }); } request_paint(app, ctx); diff --git a/crates/ui-egui/src/ui_scale.rs b/crates/ui-egui/src/ui_scale.rs index 6b275a078..3a407dcf8 100644 --- a/crates/ui-egui/src/ui_scale.rs +++ b/crates/ui-egui/src/ui_scale.rs @@ -47,8 +47,9 @@ pub fn percent(scale: f32) -> u32 { (scale * 100.0).round().clamp(0.0, 100_000.0) as u32 } -/// The sizes Preferences offers, relative to the system's scale (`pref.uiScale` takes up to 3). -pub const SIZES: [f64; 8] = [0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0]; +/// The sizes Preferences offers, relative to the system's scale (`pref.uiScale` takes up to 3); +/// the interface size keys step through the same list. +pub const SIZES: [f64; 8] = figcraft_engine::UI_SCALE_SIZES; #[cfg(test)] mod tests { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index b9e7e997d..f9f6067d7 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -718,6 +718,8 @@ fn draw(app: &mut FigApp, id: u64, ui: &mut egui::Ui) { adopt(app, &e); settle(app, &ctx, files_before); if app.session.prefs != prefs { + // This window too (see the root's frame): the next frame applies the preference. + ctx.request_repaint(); repaint_others(app, &ctx); } let (outer, inner) = ctx.input(|i| (i.viewport().outer_rect, i.viewport().inner_rect)); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index de15b2bd2..3963e4624 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-01 · **Change:** minor (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-01 · **Change:** minor (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: @@ -128,8 +128,8 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | | Count | Notes | |---|---|---| -| Documented shortcuts (rows) | 130 | each with macOS and Windows/Linux keys | -| Bound as documented | 129 (110 before this suite) | 108 keymap bindings, 15 held keys, gestures and presentation keys, 6 vector edit tool keys | +| Documented shortcuts (rows) | 133 | each with macOS and Windows/Linux keys | +| Bound as documented | 132 (110 before this suite) | 111 keymap bindings, 15 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 | @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | | 2026-10-31 | minor | M1, #1682: as the help center describes the colour picker, choosing Image no longer opens a file dialog at once: the tab shows a checkered placeholder and Upload from computer until there is a file. An image paint shows its asset preview with the same button. A file dropped on the open picker replaces the image and keeps the fill mode, crop, position and adjustments; on the placeholder it becomes the paint's image, filling the layer. While a file is dragged the picker says it takes it instead of the window saying Drop to import. New command `image.replace {ids?, target?, index?, data | path}`, through the same size cap and decoder as `image.place`; one undo step. Dropped files in the browser arrive as `data`. A native window or a browser doesn't say where a dragged file is, so a drop with no known position goes to the open picker, and one known to be over the canvas imports as before. Left: the Fill and Stroke swatches in the Design panel don't take a drop, since their place can't be told during a drag; pasting into the picker isn't documented and isn't added. Tests: `colorpicker_image_tests`, `image_crop_tests::replacing_an_image_keeps_its_fill_mode_crop_and_adjustments`. Numbers unchanged | From 9c3ec8c1d1c0f7457c990700c4f8c77677420aef Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 00:00:19 -0500 Subject: [PATCH 088/326] M4: typing 1) and a space starts a numbered list, as 1. does (#1842) * M4: typing 1) and a space starts a numbered list, as 1. does Co-Authored-By: Claude Fable 5.1 * Parity: the Text area row names the list creation characters Co-Authored-By: Claude Fable 5.1 * Parity: the list creation characters without spaces inside the code spans Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/canvas/textedit.rs | 5 +++-- crates/engine/src/text_tail_tests.rs | 27 +++++++++++++++++++++++++++ docs/target-app-parity.md | 5 +++-- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index 91e411e54..d7a70e5c7 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -277,14 +277,15 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result = t.characters.chars().collect(); let start = line_start(&chars, a); let typed: String = chars.get(start..a).unwrap_or(&[]).iter().collect(); let list = match typed.as_str() { "-" | "*" => ListStyle::Bulleted, - "1." => ListStyle::Numbered, + "1." | "1)" => ListStyle::Numbered, _ => ListStyle::None, }; if list != ListStyle::None { diff --git a/crates/engine/src/text_tail_tests.rs b/crates/engine/src/text_tail_tests.rs index 81d05ed23..a94852093 100644 --- a/crates/engine/src/text_tail_tests.rs +++ b/crates/engine/src/text_tail_tests.rs @@ -318,3 +318,30 @@ fn rest_import_lists_and_decorations() { (DecorationStyle::Wavy, DecorationLength::Pixels(2.0), DecorationLength::Auto, true, Some(Color::new(0.0, 0.0, 1.0, 1.0))) ); } + +/// "From within the text layer, there are a couple of ways to start a numbered list: Enter one of +/// the creation characters below followed by a Space: 1. 1)" (Create bulleted and numbered lists); +/// "-" and "*" start a bulleted one the same way. +#[test] +fn typing_a_creation_character_and_a_space_starts_a_list() { + for (start, want) in [("1.", N), ("1)", N), ("-", B), ("*", B)] { + let mut s = Session::new(); + let t = text(&mut s, "x"); + s.execute("node.set", &json!({"id": t, "props": {"characters": ""}})).unwrap(); + begin(&mut s, t, Some(0), false).unwrap(); + for c in start.chars() { + insert(&mut s, &c.to_string()).unwrap(); + } + insert(&mut s, " ").unwrap(); + assert_eq!((data(&s, t).characters.as_str(), lists(&s, t)), ("", vec![(want, 0)]), "{start}"); + } + // "2)" is not a creation character: it stays text. + let mut s = Session::new(); + let t = text(&mut s, "x"); + s.execute("node.set", &json!({"id": t, "props": {"characters": ""}})).unwrap(); + begin(&mut s, t, Some(0), false).unwrap(); + for c in ["2", ")", " "] { + insert(&mut s, c).unwrap(); + } + assert_eq!((data(&s, t).characters.as_str(), lists(&s, t)), ("2) ", vec![(P, 0)])); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 06cf024f0..69ea86cca 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-01 · **Change:** minor (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-01 · **Change:** minor (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 @@ -105,7 +105,7 @@ Breadth: does it exist. Ready: depth, correctness and fidelity for real projects | 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 | | 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 | -| 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, hanging punctuation and lists, decoration style, thickness, offset, skip ink and colour landed) | 3–7 | +| 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 | | 13 | Prototyping | 6 | 92% | 74% | Video triggers and media actions, controllers on macOS, Linux and FreeBSD, real prototype QA (behaviour suite from the documentation, delays on mouse triggers, manual overlay offsets, key combinations, controller buttons on key/gamepad triggers (Windows and the browser), widgets reacting in prototypes, interactive components playing their variants, drag-driven animations, physical springs landed) ([prototyping-parity](prototyping-parity.md)) | 2–5 | @@ -648,6 +648,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | M4: typing `1)` followed by a space at the start of a plain paragraph starts a numbered list, as `1.` already did ("Enter one of the creation characters below followed by a Space: 1. 1)", Create bulleted and numbered lists). Found by a documentation audit of the text rules. Test: `text_tail_tests::typing_a_creation_character_and_a_space_starts_a_list`. Numbers unchanged | | 2026-11-01 | patch | M4: a link made with `text.link` (Cmd/Ctrl+K, Shift+Cmd/Ctrl+U) underlines the linked text unless it has a decoration of its own ("Links are styled with an underline by default. Use the keyboard shortcut to remove the underline", Add links to text); Underline (Cmd/Ctrl+U) takes the underline off and the link stays. Found by a documentation audit of the text rules. Test: `text_behaviour_tests::a_link_is_underlined_by_default_and_underline_takes_it_off`. Numbers unchanged | | 2026-10-31 | patch | M4: Dash and Custom strokes have a Dash cap (None, Round, Square) in the advanced stroke settings and `node.set {dashCap}`, on both ends of every dash on the canvas and in PNG, PDF and SVG. Unset, dashes keep taking the end point caps, so older files look the same; the saved file writes it only when set. Numbers unchanged | | 2026-10-31 | minor | M11, gap 6: widgets draw lines and SVG pictures, as a Figma widget's `Line` and `SVG` do (plugin API 6; older plugins unchanged). A line is 100 long, black and 1 thick unless told otherwise, and turns around its top-left corner. An SVG comes in as locked layers, scaled to fit a size, within the widget's 256 layers. The Counter example uses both. Numbers unchanged. Tests: `widget_shapes_tests`, `widget_tests`. | From 8174dd5b7438bf900ab2af194f381c249f6ca5f9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 00:01:29 -0500 Subject: [PATCH 089/326] M4: bulleted lists keep the same bullet at every level of indentation (#1843) * M4: bulleted lists keep the same bullet at every level of indentation Co-Authored-By: Claude Fable 5.1 * list_markers: the comment says bullets are the same at every level Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/text/src/layout.rs | 9 ++++++--- crates/text/src/tail_tests.rs | 4 ++-- docs/target-app-parity.md | 3 ++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 3ae4997ab..7f5872fdf 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -1165,9 +1165,12 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) /// The markers of a text's paragraphs ("" for plain ones). Numbers count the items of one list at /// one level, restarting after a plain paragraph, a shallower item or the other kind of list, -/// from the first item's start number; levels go 1. a. i. and • ◦ ▪, then round again. +/// from the first item's start number; levels go 1. a. i., then round again; bullets are • at +/// every level. pub(crate) fn list_markers(lists: &[ParaList]) -> Vec { - const BULLETS: [&str; 3] = ["\u{2022}", "\u{25E6}", "\u{25AA}"]; + // "Figma bullets will keep the same styling at all levels of indentation." (Create bulleted + // and numbered lists) + const BULLET: &str = "\u{2022}"; let mut count = [(ListStyle::None, 0usize); figcraft_doc::MAX_LIST_INDENT as usize + 1]; lists .iter() @@ -1187,7 +1190,7 @@ pub(crate) fn list_markers(lists: &[ParaList]) -> Vec { (ListStyle::Numbered, 1) => format!("{}.", alpha(c.1)), (ListStyle::Numbered, 2) => format!("{}.", roman(c.1)), (ListStyle::Numbered, _) => format!("{}.", c.1), - _ => BULLETS.get(d % 3).copied().unwrap_or("\u{2022}").to_string(), + _ => BULLET.to_string(), } }) .collect() diff --git a/crates/text/src/tail_tests.rs b/crates/text/src/tail_tests.rs index 712ff6aa8..805f744d8 100644 --- a/crates/text/src/tail_tests.rs +++ b/crates/text/src/tail_tests.rs @@ -90,8 +90,8 @@ fn list_numbering_by_level() { ), ( vec![pl(B, 0), pl(B, 1), pl(B, 2), pl(B, 3)], - vec!["\u{2022}", "\u{25E6}", "\u{25AA}", "\u{2022}"], - "silent: bullets change shape per level, round again", + vec!["\u{2022}", "\u{2022}", "\u{2022}", "\u{2022}"], + "bullets keep the same styling at all levels of indentation", ), (vec![pl(N, 0), pl(N, 0), pl(P, 0), pl(N, 0)], vec!["1.", "2.", "", "1."], "silent: a plain paragraph ends a list, the next starts at 1"), (vec![pl(N, 0), pl(B, 0), pl(N, 0)], vec!["1.", "\u{2022}", "1."], "silent: the other kind of list at the same level starts the count again"), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 69ea86cca..75a426231 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-01 · **Change:** minor (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-01 · **Change:** minor (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 @@ -648,6 +648,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | M4: bulleted lists draw the same bullet at every level of indentation ("Figma bullets will keep the same styling at all levels of indentation", Create bulleted and numbered lists); the deeper levels drew a white bullet and a small square, pinned as silent before. Numbered levels (1., a., i.) are unchanged. Found by a documentation audit of the text rules. Test: `tail_tests::list_numbering_by_level` (the bullets row). Numbers unchanged | | 2026-11-01 | patch | M4: typing `1)` followed by a space at the start of a plain paragraph starts a numbered list, as `1.` already did ("Enter one of the creation characters below followed by a Space: 1. 1)", Create bulleted and numbered lists). Found by a documentation audit of the text rules. Test: `text_tail_tests::typing_a_creation_character_and_a_space_starts_a_list`. Numbers unchanged | | 2026-11-01 | patch | M4: a link made with `text.link` (Cmd/Ctrl+K, Shift+Cmd/Ctrl+U) underlines the linked text unless it has a decoration of its own ("Links are styled with an underline by default. Use the keyboard shortcut to remove the underline", Add links to text); Underline (Cmd/Ctrl+U) takes the underline off and the link stays. Found by a documentation audit of the text rules. Test: `text_behaviour_tests::a_link_is_underlined_by_default_and_underline_takes_it_off`. Numbers unchanged | | 2026-10-31 | patch | M4: Dash and Custom strokes have a Dash cap (None, Round, Square) in the advanced stroke settings and `node.set {dashCap}`, on both ends of every dash on the canvas and in PNG, PDF and SVG. Unset, dashes keep taking the end point caps, so older files look the same; the saved file writes it only when set. Numbers unchanged | From f9b56936219857cfbbe82d0c6b6c19eb7a7850f9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 00:02:56 -0500 Subject: [PATCH 090/326] M2: a text keeps a max height or a number of max lines, not both (#1832) Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/props.rs | 19 +++++++++++++- crates/engine/src/cmd/text.rs | 22 +++++++++++++++-- crates/engine/src/text_behaviour_tests.rs | 30 +++++++++++++++++++++++ docs/auto-layout-parity.md | 4 ++- 4 files changed, 71 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index fe7fdcd74..fbf80fc1b 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -759,6 +759,14 @@ fn apply_sizing(cmd: &str, doc: &mut Document, id: NodeId, k: &str, v: &Value) - other => Some(f64_of(other).ok_or_else(|| bad(cmd, format!("`{k}` must be a number or null")))?.clamp(0.0, 1e7)), }; set_limit(&mut doc.get_mut(id)?.child_layout, k, val); + // A text has a max height or a number of max lines, not both: a max height sets the + // lines back to Auto (Guide to auto layout). + if k == "maxHeight" + && val.is_some() + && let Some(t) = doc.get_mut(id)?.kind.text_mut() + { + t.max_lines = 0; + } } "columnTracks" | "gridColumnTracks" | "rowTracks" | "gridRowTracks" => { let a = v.as_array().ok_or_else(|| bad(cmd, format!("`{k}` must be an array of tracks")))?; @@ -900,7 +908,16 @@ 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"))?, - "maxLines" => text_mut(cmd, doc.get_mut(id)?)?.max_lines = f64_of(v).unwrap_or(0.0).clamp(0.0, 10_000.0) as u32, + "maxLines" => { + let lines = f64_of(v).unwrap_or(0.0).clamp(0.0, 10_000.0) as u32; + let n = doc.get_mut(id)?; + text_mut(cmd, n)?.max_lines = lines; + // A text has a max height or a number of max lines, not both: a number of lines takes + // the max height away (Guide to auto layout). + if lines > 0 { + n.child_layout.max_h = None; + } + } "features" | "textFeatures" | "fontFeatures" | "openTypeFeatures" => { let f = features_of(cmd, v)?; let t = text_mut(cmd, doc.get_mut(id)?)?; diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 4fbb0fe1d..b507afd6b 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -323,12 +323,30 @@ pub fn specs() -> Vec { true, |s, p| { let v = finite(req_num("text.maxLines", p, "lines")?).clamp(0.0, 10_000.0) as u32; - para(s, p, |t| { + let r = para(s, p, |t| { t.max_lines = v; if v > 0 && t.auto_resize != TextAutoResize::Height { t.auto_resize = TextAutoResize::Truncate; } - }) + })?; + // A text has a max height or a number of max lines, not both (Guide to auto layout). + if v > 0 { + let ids = match textedit::selected_range(s) { + Some((id, _, _)) => vec![id], + None => targets(s, p), + }; + let doc = s.doc_mut()?; + for i in ids { + for d in doc.subtree(i) { + if let Some(n) = doc.node_mut(d) + && n.kind.text().is_some() + { + n.child_layout.max_h = None; + } + } + } + } + Ok(r) } ), spec!( diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index ad476c364..9ae7dd62c 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -551,6 +551,36 @@ fn css_font_family_escapes_backslash_and_newline() { assert!(css.contains(r#"font-family: "Foo\"\3C /style>";"#), "{css}"); } +/// "Text layers cannot have both a max height and a set number of max lines. Adding a max height +/// will set max lines to Auto. Setting max lines to a number will remove the layer's max height +/// setting." (Guide to auto layout) +#[test] +fn a_text_has_a_max_height_or_max_lines_not_both() { + let mut s = Session::new(); + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 100})).unwrap()); + s.execute("node.set", &json!({"id": f, "props": {"layout": "vertical"}})).unwrap(); + let t = id(s.execute("text.create", &json!({"text": "Hello there world", "x": 0, "y": 0, "parent": f, "width": 60})).unwrap()); + let state = |s: &Session| { + let n = s.doc().unwrap().node(t).unwrap().clone(); + (n.kind.text().unwrap().max_lines, n.child_layout.max_h) + }; + s.execute("node.set", &json!({"id": t, "props": {"maxLines": 2}})).unwrap(); + assert_eq!(state(&s), (2, None)); + s.execute("node.set", &json!({"id": t, "props": {"maxHeight": 40}})).unwrap(); + assert_eq!(state(&s), (0, Some(40.0)), "a max height sets max lines to Auto"); + s.execute("node.set", &json!({"id": t, "props": {"maxLines": 3}})).unwrap(); + assert_eq!(state(&s), (3, None), "max lines take the max height away"); + s.execute("node.set", &json!({"id": t, "props": {"maxHeight": 50}})).unwrap(); + s.execute("text.maxLines", &json!({"ids": [t], "lines": 1})).unwrap(); + assert_eq!(state(&s), (1, None), "the Max lines command too"); + // Auto (0) leaves a max height alone, and a frame's max height has no lines to clear. + s.execute("node.set", &json!({"id": t, "props": {"maxHeight": 50}})).unwrap(); + s.execute("node.set", &json!({"id": t, "props": {"maxLines": 0}})).unwrap(); + assert_eq!(state(&s), (0, Some(50.0))); + s.execute("node.set", &json!({"id": f, "props": {"maxHeight": 80}})).unwrap(); + assert_eq!(s.doc().unwrap().node(f).unwrap().child_layout.max_h, Some(80.0)); +} + /// "Links are styled with an underline by default. Use the keyboard shortcut to remove the /// underline: Mac: Command U, Windows: Control U" (Add links to text). #[test] diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index feb476a1a..f481fc7ab 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (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-01 · **Change:** minor (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%, @@ -42,6 +42,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Hug only on auto layout frames (and text); Fill only in an auto layout flow, never on a top-level frame | pass | `al_behaviour_tests::hug_and_fill_only_where_they_apply` | | Min/max width and height bound Hug, Fill and Fixed sizes, on frames and children | pass | `sizing_rules`; a fill child at its max leaves the rest to the other fill children (silent on redistribution: CSS flexbox) | | A hugging text wider than its max width wraps at the max | pass | `sizing_rules` | +| A text has a max height or a number of max lines, not both: a max height sets max lines to Auto, a number of max lines removes the max height | **fixed** | both coexisted; `node.set {maxHeight}` and `{maxLines}` and `text.maxLines` keep one of the two (a frame's max height is untouched); `text_behaviour_tests::a_text_has_a_max_height_or_max_lines_not_both` | | Remove all auto layout: a frame and all of its nested objects lose their auto layout at once (More layout options) | **added** | `layout.removeAll {ids?}`, one undo step, in the canvas context menu beside Add auto layout; instances and the layers inside them keep theirs; `al_nesting_tests::remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it` | | Text filling a width wraps and its hugging frame grows with it | pass | `sizing_rules` | | A hugging frame follows a child that grows, through nested levels, in one edit and one undo step | pass | `al_behaviour_tests::a_hugging_frame_follows_its_children_through_nested_levels` | @@ -96,6 +97,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | M2: a text layer keeps a max height or a number of max lines, not both ("Text layers cannot have both a max height and a set number of max lines", Guide to auto layout): `node.set {maxHeight}` on a text sets its max lines to Auto, and `node.set {maxLines}` or `text.maxLines` with a number removes its max height. Found by a documentation audit of this page. Test: `text_behaviour_tests::a_text_has_a_max_height_or_max_lines_not_both`. Numbers unchanged | | 2026-11-01 | minor | M2: Remove all auto layout ("To remove auto layout from a frame and all of its nested objects at once, right-click on the frame and go to More layout options > Remove all auto layout", Toggle on auto layout in designs): `layout.removeAll {ids?}` strips the frames and every frame nested in them in one undo step, leaving instances and their layers alone; in the canvas context menu beside Add auto layout and in the Actions palette. Found by a documentation audit of this page. Test: `al_nesting_tests::remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it`. Numbers unchanged | | 2026-10-30 | minor | M8, #1083: grid placement finds free cells on a bitmap, a word at a time, with the same placements; crafted grids of wide children no longer stall a layout pass. Numbers unchanged. | | 2026-10-29 | minor | M2 review fixes: conversion preserves mask runs and Fill sizing per axis; layout inference uses visible, non-absolute flow children; the sidebar hides Add for mixed selections containing existing auto layout. Regression coverage includes rendered mask pixels, visible-child positions, parent layout stability and the sidebar accessibility tree. Numbers unchanged | From 55821565ac0a3ecc36268a72fa5a2aec9430bb53 Mon Sep 17 00:00:00 2001 From: samhyun Date: Mon, 2 Nov 2026 09:58:03 +0900 Subject: [PATCH 091/326] M8: a spread round a stroke with corners keeps its whole shadow A dashed stroke is cut into dashes with corners wherever they fall round the outline, and a width profile or a brush can give the stroke corners of its own. A drop shadow's spread mitres those corners out, but a whole ellipse or a box still counted as growing by exactly its spread, so the shadow was cut off at the layer's edge (up to 255 levels). Such a node now gets the room a star does. Whether the outline's own mitres end on its box is a check of its own, which the stroke's reach keeps using, so a node with no spread keeps its bounds. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/node.rs | 22 ++++++++++--- crates/render/src/spread_tests.rs | 55 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 3ac81afdb..e24057f7b 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -944,7 +944,7 @@ impl Node { if self.stroke.cap_start.is_arrow() || self.stroke.cap_end.is_arrow() || point_arrows { w.max(self.stroke.weight) * 3.0 } else { w }; // Right-angled or smooth outlines (boxes, whole ellipses) end their mitres on the grown // box; an arc's corners don't. - let miter = if self.grows_by_exactly_its_spread() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) }; + let miter = if self.outline_mitres_end_on_its_box() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) }; base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * miter } else { 0.0 @@ -960,9 +960,10 @@ impl Node { !(matches!(self.kind, NodeKind::Group) || (matches!(self.kind, NodeKind::Text(_)) && self.has_visible_stroke())) } - /// Whether a spread grows this node's outline by exactly the spread (no sharp corners). An arc - /// (an ellipse that doesn't go all the way round) has corners where its ends meet its sides. - fn grows_by_exactly_its_spread(&self) -> bool { + /// Whether this node's outline has no sharp corners (right-angled ones aside), so mitres along + /// it end on its box grown by as much: a box or a whole ellipse. An arc (an ellipse that doesn't + /// go all the way round) has corners where its ends meet its sides. + fn outline_mitres_end_on_its_box(&self) -> bool { match self.kind { NodeKind::Rectangle | NodeKind::Section { .. } => true, NodeKind::Ellipse { sweep, .. } => figcraft_geom::full_sweep(sweep), @@ -970,9 +971,20 @@ impl Node { } } + /// Whether a spread grows this node by exactly the spread: its outline mitres end on its box + /// (see [`Node::outline_mitres_end_on_its_box`]), and so does its stroke. A dashed stroke is + /// cut into dashes with corners wherever they fall round the outline, and a width profile or a + /// brush can give the stroke corners of its own, which the spread mitres out. + fn grows_by_exactly_its_spread(&self) -> bool { + let s = &self.stroke; + let cornered = self.has_visible_stroke() && (!s.dashes.is_empty() || s.profile().is_some() || s.brush.is_some()); + !cornered && self.outline_mitres_end_on_its_box() + } + /// How much further than its spread a drop shadow can reach at the outline's sharp corners: /// spread moves the edges out in parallel and they meet in a mitre (see - /// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread. + /// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread, + /// unless their stroke has corners (see [`Node::grows_by_exactly_its_spread`]). fn spread_miter_reach(&self) -> f64 { if self.grows_by_exactly_its_spread() { return 0.0; diff --git a/crates/render/src/spread_tests.rs b/crates/render/src/spread_tests.rs index 6b30766fc..ec41dd8dd 100644 --- a/crates/render/src/spread_tests.rs +++ b/crates/render/src/spread_tests.rs @@ -192,3 +192,58 @@ fn arc_stroke_mitres_are_not_cut_off() { assert!(worst <= 2, "{align:?}: {worst} levels cut off"); } } + +/// A dashed stroke is cut into separate dashes with square ends, a width profile can step its +/// width and a brush lays down shapes of its own: round a whole ellipse or a rounded box, a spread +/// mitres out at their corners, past the box grown by the spread, and keeps its whole shadow. +#[test] +fn stroke_corners_spread_mitres_are_not_cut_off() { + use figcraft_doc::{Brush, Node, StrokeAlign, StrokeCap, WidthProfile}; + type Style = fn(&mut Node); + let strokes: [(&str, Style); 4] = [ + ("dashed", |n| n.stroke.dashes = vec![30.0, 30.0]), + ("dashed with square caps", |n| (n.stroke.dashes, n.stroke.dash_cap) = (vec![30.0, 30.0], Some(StrokeCap::Square))), + ("stepped", |n| n.stroke.width_profile = Some(WidthProfile::new([(0.0, 1.0), (0.25, 4.0), (0.26, 0.2), (0.75, 4.0)]))), + ("starry", |n| n.stroke.brush = Some(Brush::new("stars"))), + ]; + let shapes = [(NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, 0.0), (NodeKind::Rectangle, 100.0)]; + for (kind, radius) in shapes { + for (name, style) in strokes { + for align in [StrokeAlign::Outside, StrokeAlign::Center] { + let make = |effects: Vec| { + let (mut d, n) = shape(kind.clone(), effects); + let node = d.get_mut(n).unwrap(); + node.corners.radii = [radius; 4]; + node.strokes = vec![Paint::solid(Color::WHITE)]; + (node.stroke.weight, node.stroke.align) = (20.0, align); + style(node); + (d, n) + }; + let (d, n) = make(vec![EffectKind::DropShadow(shadow(30.0))]); + let clear = Shadow { color: Color::new(0.0, 0.0, 0.0, 0.0), ..shadow(120.0) }; + let (roomy, m) = make(vec![EffectKind::DropShadow(shadow(30.0)), EffectKind::DropShadow(clear)]); + let (a, b) = (render(&d, n), render(&roomy, m)); + let worst = a.data().chunks(4).zip(b.data().chunks(4)).map(|(p, q)| p[3].abs_diff(q[3])).max().unwrap_or(0); + // The stroke lands a little differently on a layer of another size, even when + // both have room to spare: up to 16 levels at a pixel or two. Cut off is 255. + assert!(worst <= 16, "{kind:?} radius {radius}, {name} {align:?}: {worst} levels cut off"); + } + } + } +} + +/// Without a spread, a dashed stroke reaches no further than a solid one: the bounds an export +/// goes by stay the box grown by the stroke. +#[test] +fn a_dashed_stroke_without_a_spread_keeps_its_bounds() { + use figcraft_doc::StrokeAlign; + for kind in [NodeKind::Rectangle, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }] { + let (mut d, n) = shape(kind.clone(), vec![]); + let node = d.get_mut(n).unwrap(); + node.strokes = vec![Paint::solid(Color::WHITE)]; + (node.stroke.weight, node.stroke.align) = (20.0, StrokeAlign::Outside); + node.stroke.dashes = vec![30.0, 30.0]; + let b = crate::export_bounds(&d, n).unwrap(); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (80.0, 80.0, 320.0, 320.0), "{kind:?}"); + } +} From ed2747e9a4a4487c2e0202386b0e3c51c030ea31 Mon Sep 17 00:00:00 2001 From: samhyun Date: Mon, 2 Nov 2026 10:36:05 +0900 Subject: [PATCH 092/326] M8: a stroke's square dash ends and brush shapes paint within its bounds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three ways a stroke painted past the bounds an export and a redraw go by, with no effects at all: - A dash's square end stands out along the path as far as the band does across it, so its corners reach √2 times as far from the path. Round a curve that is past the box grown by the stroke. - The ink brush's ragged edges reach 0.54 of the weight from the path, not 0.5. - A scatter brush's copies stray by the weight whatever a width profile does, but the profile's scale was applied to the stray as well, so a thinning profile left them out. `outline_reach` now counts square dash ends as √2 at least, and `Brush::reach_factor` takes the profile's scale for the shapes only and counts the shapes' reach (`Brush::SHAPE_REACH`), which a test checks every preset against. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/node.rs | 6 ++- crates/doc/src/props.rs | 15 +++++-- crates/pathops/src/brush_tests.rs | 21 +++++++--- crates/render/src/lib.rs | 2 + crates/render/src/stroke_reach_tests.rs | 54 +++++++++++++++++++++++++ 5 files changed, 88 insertions(+), 10 deletions(-) create mode 100644 crates/render/src/stroke_reach_tests.rs diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index e24057f7b..ce7d75ec3 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -945,7 +945,11 @@ impl Node { // Right-angled or smooth outlines (boxes, whole ellipses) end their mitres on the grown // box; an arc's corners don't. let miter = if self.outline_mitres_end_on_its_box() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) }; - base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * miter + // A dash's square end stands out along the path as far as the band does across it: + // its corners reach √2 times as far from the path, past the box round a curve. + let square_dashes = !self.stroke.dashes.is_empty() && self.stroke.band_caps().contains(&StrokeCap::Square); + let corners = if square_dashes { miter.max(std::f64::consts::SQRT_2) } else { miter }; + base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * corners } else { 0.0 }; diff --git a/crates/doc/src/props.rs b/crates/doc/src/props.rs index 0c78681f2..1c6cd6e3e 100644 --- a/crates/doc/src/props.rs +++ b/crates/doc/src/props.rs @@ -146,10 +146,16 @@ impl Brush { } } - /// How much wider than the stroke weight the brush can paint (larger copies, strays). - pub fn reach_factor(&self) -> f64 { + /// The farthest a built-in brush shape reaches from the path, in stroke weights: the ink + /// brush's ragged edges stand a little past half the weight. + pub const SHAPE_REACH: f64 = 0.54; + + /// How much wider than the stroke weight the brush can paint where a width profile scales it + /// at most `scale`: its shapes' edges and larger copies, which the profile scales, and strays, + /// which it doesn't. + pub fn reach_factor(&self, scale: f64) -> f64 { let b = self.sanitized(); - 1.0 + b.size_jitter + 2.0 * b.scatter + 2.0 * Self::SHAPE_REACH * (1.0 + b.size_jitter) * scale + 2.0 * b.scatter } } @@ -188,7 +194,8 @@ impl StrokeProps { /// The widest the stroke gets anywhere along the path (the weight, scaled by a width profile /// and widened by a brush's reach). pub fn max_weight(&self) -> f64 { - self.profile().map_or(self.weight, |p| self.weight * p.max_scale()) * self.brush.as_ref().map_or(1.0, Brush::reach_factor) + let scale = self.profile().map_or(1.0, WidthProfile::max_scale); + self.weight * self.brush.as_ref().map_or(scale, |b| b.reach_factor(scale)) } /// The miter limit as the angle (degrees) below which joins bevel: limit = 1 / sin(angle / 2), diff --git a/crates/pathops/src/brush_tests.rs b/crates/pathops/src/brush_tests.rs index 403935ddd..b97356362 100644 --- a/crates/pathops/src/brush_tests.rs +++ b/crates/pathops/src/brush_tests.rs @@ -21,14 +21,25 @@ fn props(weight: f64, b: &Brush) -> StrokeProps { StrokeProps { weight, align: StrokeAlign::Center, brush: Some(b.clone()), ..Default::default() } } +/// What a brush paints stays within half [`StrokeProps::max_weight`] of the path, which the +/// stroke's bounds go by: plain, with copies grown, turned and strayed all they can, and with a +/// width profile thinning or widening it (strays keep their distance, whatever the profile). #[test] fn every_preset_draws_inside_its_reach() { for p in PRESETS { - let b = brush(p.id); - let out = outline(&line(200.0), 10.0, &props(10.0, &b), &b).unwrap(); - let bb = out.bounding_box(); - assert!(!out.elements().is_empty(), "{}", p.id); - assert!(bb.y0 >= -5.5 && bb.y1 <= 5.5 && bb.x0 >= -5.5 && bb.x1 <= 205.5, "{}: {bb:?}", p.id); + let wild = Brush { size_jitter: 1.0, rotation_jitter: 1.0, scatter: 4.0, ..brush(p.id) }; + for (b, profile) in [(brush(p.id), None), (wild.clone(), None), (wild.clone(), Some(0.2)), (wild, Some(2.0))] { + let k = StrokeProps { width_profile: profile.map(|s| WidthProfile::new([(0.0, s), (1.0, s)])), ..props(10.0, &b) }; + let out = outline(&line(200.0), 10.0, &k, &b).unwrap(); + let bb = out.bounding_box(); + let reach = k.max_weight() / 2.0; + assert!(!out.elements().is_empty(), "{}", p.id); + assert!( + bb.y0 >= -reach && bb.y1 <= reach && bb.x0 >= -reach && bb.x1 <= 200.0 + reach, + "{} {b:?} {profile:?}: {bb:?}, reach {reach}", + p.id + ); + } } assert!(outline(&line(10.0), 1.0, &props(1.0, &brush("nope")), &brush("nope")).is_none()); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f1ab0ea5f..5276d2e64 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -564,6 +564,8 @@ mod solo_tests; #[cfg(test)] mod spread_tests; #[cfg(test)] +mod stroke_reach_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod width_tests; diff --git a/crates/render/src/stroke_reach_tests.rs b/crates/render/src/stroke_reach_tests.rs new file mode 100644 index 000000000..f447e93bd --- /dev/null +++ b/crates/render/src/stroke_reach_tests.rs @@ -0,0 +1,54 @@ +//! What a stroke paints stays within the bounds an export and a redraw go by: square dash ends +//! that stand out round a curve, brush shapes past half the weight and brush copies that stray +//! further than a width profile thins them included. + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Brush, Document, Node, NodeKind, StrokeAlign, StrokeCap, StrokeJoin, WidthProfile}; + +use super::*; + +/// How many pixels `kind` (at (200, 200), `size` square) with a 40-unit stroke styled by `style` +/// paints more than a pixel outside its export bounds, on a 600 × 600 view. +fn painted_outside(kind: &NodeKind, size: f64, align: StrokeAlign, miter_limit: f64, style: fn(&mut Node)) -> usize { + let mut d = Document::new("reach"); + let p = d.first_page().unwrap(); + let n = d.create(p, kind.clone(), "S", 200.0, 200.0, size, size).unwrap(); + let node = d.get_mut(n).unwrap(); + node.fills.clear(); + node.corners.radii = [30.0; 4]; + node.strokes = vec![Paint::solid(Color::WHITE)]; + (node.stroke.weight, node.stroke.align, node.stroke.join, node.stroke.miter_limit) = (40.0, align, StrokeJoin::Miter, miter_limit); + style(node); + let b = crate::export_bounds(&d, n).unwrap(); + let mut pix = Pixmap::new(600, 600).unwrap(); + render_nodes_into(&d, &[n], &View { origin: (0.0, 0.0), scale: 1.0, width: 600, height: 600 }, &mut pix); + let (xs, ys) = (b.x0 - 1.0..=b.x1 + 1.0, b.y0 - 1.0..=b.y1 + 1.0); + let inside = |i: usize| xs.contains(&((i % 600) as f64 + 0.5)) && ys.contains(&((i / 600) as f64 + 0.5)); + pix.data().chunks(4).enumerate().filter(|(i, p)| p[3] > 0 && !inside(*i)).count() +} + +#[test] +fn a_stroke_with_corners_paints_within_its_bounds() { + type Style = fn(&mut Node); + let strokes: [(&str, Style); 4] = [ + ("square dash ends", |n| (n.stroke.dashes, n.stroke.dash_cap) = (vec![30.0, 30.0], Some(StrokeCap::Square))), + ("short square dashes", |n| (n.stroke.dashes, n.stroke.dash_cap) = (vec![1.0, 7.0], Some(StrokeCap::Square))), + ("the ink brush", |n| n.stroke.brush = Some(Brush::new("ink"))), + ("a thinned scatter brush", |n| { + n.stroke.brush = Some(Brush { scatter: 1.0, ..Brush::new("dots") }); + n.stroke.width_profile = Some(WidthProfile::new([(0.0, 0.5), (1.0, 0.5)])); + }), + ]; + let circle = NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }; + let shapes = [(&circle, 200.0), (&circle, 30.0), (&NodeKind::Rectangle, 200.0), (&NodeKind::Star { count: 5, inner_ratio: 0.4 }, 200.0)]; + for (kind, size) in shapes { + for (name, style) in strokes { + for align in [StrokeAlign::Center, StrokeAlign::Outside] { + for miter_limit in [4.0, 1.0] { + let outside = painted_outside(kind, size, align, miter_limit, style); + assert_eq!(outside, 0, "{kind:?} {size}, {name}, {align:?}, mitre limit {miter_limit}"); + } + } + } + } +} From 3c9d943ff21c3d7b8fb40b1f5cb1a85539bd7205 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 00:42:22 -0500 Subject: [PATCH 093/326] Field scrub: the field always senses drags; Alt as the drag begins makes it a scrub until the button is let go Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 13 +++++++++++++ crates/ui-egui/src/widgets.rs | 16 +++++++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 91fbae2b2..4e3dfb35d 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1216,4 +1216,17 @@ fn alt_held_over_a_field_scrubs_it() { drag(&mut u, at, 25.0, Modifiers::NONE); assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub"); assert_eq!(undo_steps(&u), steps + 1); + // Alt and the press in the same frame still scrub, and Alt let go before the button still + // ends the scrub with its undo step. + let (at, _) = field(&mut u, "X"); + let press = |pressed: bool, m: Modifiers, p: Pos2| Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; + u.frame_with(vec![Event::PointerMoved(at), press(true, alt, at)], alt); + for k in 1..=10 { + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 2.0 * k as f32, at.y))], alt); + } + let to = pos2(at.x + 20.0, at.y); + u.frame_with(vec![Event::PointerMoved(to), press(false, Modifiers::NONE, to)], Modifiers::NONE); + u.frame(vec![]); + assert_eq!(geom(&u, a).0, 55.0, "twenty more"); + assert_eq!(undo_steps(&u), steps + 2, "committed when the button went up, without Alt"); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 4ed92eb0d..7db22abc0 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -268,10 +268,16 @@ fn number_field_impl( let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); // Alt held over the field scrubs it too, as the label always does: "hover the input field // itself and hold down the modifier key" (Adjust alignment, rotation, position, and - // dimensions). The drag sense stays on until a scrub begun that way is let go. + // dimensions). The field always senses drags (egui assigns a press by the frame before it, so + // a sense that waits for Alt would miss a press that arrives with it); Alt as the drag begins + // is what makes it a scrub, and that holds until the button is let go, Alt released or not. let field_id = id.with("field"); - let alt_scrub = editing.is_none() && (ui.input(|i| i.modifiers.alt) || ui.ctx().is_being_dragged(field_id)); - let field_resp = ui.interact(edit_rect, field_id, if alt_scrub { Sense::CLICK | Sense::DRAG } else { Sense::click() }); + let field_resp = ui.interact(edit_rect, field_id, Sense::click_and_drag()); + let alt_now = ui.input(|i| i.modifiers.alt); + let scrubbing_id = id.with("altscrub"); + let alt_scrub = + editing.is_none() && if field_resp.drag_started() { alt_now } else { ui.data(|d| d.get_temp::(scrubbing_id)).unwrap_or(false) }; + ui.data_mut(|d| d.insert_temp(scrubbing_id, alt_scrub && field_resp.dragged() && !field_resp.drag_stopped())); a11y::number(&field_resp, lead.name(), value, suffix, empty.text()); a11y::ring_around(ui, rect, &field_resp); // The label scrubs with the pointer; the keyboard stops at the value only. @@ -297,7 +303,7 @@ fn number_field_impl( } Lead::None | Lead::Named(_) => {} } - if lead_resp.hovered() || lead_resp.dragged() || (alt_scrub && (field_resp.hovered() || field_resp.dragged())) { + if lead_resp.hovered() || lead_resp.dragged() || (alt_now && editing.is_none() && field_resp.hovered()) || (alt_scrub && field_resp.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } // On the field, Alt is what makes the drag a scrub, so it is not the fine rate there. @@ -349,7 +355,7 @@ fn number_field_impl( } // Typing on a field the keyboard reached (Tab) edits it: the editor takes the typed text. let typed_now = editing.is_none() && on_field && ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_)))); - let started = editing.is_none() && ((field_resp.clicked() && !alt_scrub) || typed_now); + let started = editing.is_none() && ((field_resp.clicked() && !alt_now) || typed_now); // The text the field would commit to no effect: what it showed when the edit began, or the // value the arrows last stepped it to. let kept_id = id.with("kept"); From abf2eb9b3a19692e0296297e6f1b7d69bc48ea6b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 01:24:32 -0500 Subject: [PATCH 094/326] M1: the Fill section shows a text's characters' fills, mixed when they differ, and a layer fill edit reaches every character (#1856) Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/edit/props.rs | 6 ++ crates/engine/src/cmd/lists.rs | 51 +++++++++- crates/engine/src/cmd/props.rs | 3 + crates/engine/src/text_fill_tests.rs | 67 +++++++++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/right/paints.rs | 3 +- crates/ui-egui/src/text_mixed_fill_tests.rs | 107 ++++++++++++++++++++ crates/ui-egui/src/widgets/colorpicker.rs | 3 +- docs/ui-parity.md | 4 +- 9 files changed, 240 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/text_mixed_fill_tests.rs diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index da19b1eec..b31312a01 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -267,6 +267,9 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> let doc = s.doc_mut()?; for i in ids { let n = doc.get_mut(i)?; + if fills { + crate::cmd::lists::take_character_fills(n); + } let frameish = n.kind.is_frame_like(); let list = if fills { &mut n.fills } else { &mut n.strokes }; if add { @@ -298,6 +301,9 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result Option> { + let NodeKind::Text(t) = &n.kind else { return Some(n.fills.clone()) }; + let mut spans = t.spans().into_iter().map(|(_, _, st)| st.fills.as_ref().unwrap_or(&n.fills)); + let first = spans.next().unwrap_or(&n.fills).clone(); + spans.all(|f| *f == first).then_some(first) +} + +/// Before a layer-level edit of a text's fills (the Fill section, `fill.*`, `node.set`): the +/// characters' own fills go, so the edit shows on every one of them. One list they all shared +/// becomes the layer's first, so the edit starts from what the characters showed; characters +/// that differed fall back to the layer's fills, which the edit then replaces ("Click + to +/// replace mixed content"). Not a text, or no character with fills of its own: nothing changes. +pub(crate) fn take_character_fills(n: &mut Node) { + let NodeKind::Text(t) = &n.kind else { return }; + if t.style.fills.is_none() && t.runs.iter().all(|r| r.style.fills.is_none()) { + return; + } + if let Some(shared) = character_fills(n) + && shared != n.fills + { + let old = std::mem::replace(&mut n.fills, shared); + for (i, p) in old.iter().enumerate() { + rebind_edited_paint(n, true, i, p); + } + } + if let NodeKind::Text(t) = &mut n.kind { + t.style.fills = None; + for r in &mut t.runs { + r.style.fills = None; + } + t.normalize(); + } +} + /// Where item `k` lands when the item at `from` moves to `to`. pub fn moved_index(k: usize, from: usize, to: usize) -> usize { if k == from { @@ -250,11 +289,19 @@ fn move_item(s: &mut Session, p: &Value, cmd: &str, list: BoundList) -> Result= len || to >= len || from == to { continue; } let n = s.doc_mut()?.get_mut(id)?; + if list == BoundList::Fills { + take_character_fills(n); + } let moved = match list { BoundList::Fills => reorder(&mut n.fills, from, to), BoundList::Strokes => reorder(&mut n.strokes, from, to), diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index fbf80fc1b..670ee73ab 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -376,6 +376,9 @@ fn layout_mut<'a>(cmd: &str, k: &str, n: &'a mut Node) -> Result<&'a mut AutoLay /// Replace a node's fills (or strokes). Bindings on the paints whose bound values the new list /// changed let go, as an explicit edit does (see `lists::rebind_edited_paint`). fn set_paints(n: &mut Node, fills: bool, paints: Vec) { + if fills { + super::lists::take_character_fills(n); + } let old = std::mem::replace(if fills { &mut n.fills } else { &mut n.strokes }, paints); for (i, p) in old.iter().enumerate() { super::lists::rebind_edited_paint(n, fills, i, p); diff --git a/crates/engine/src/text_fill_tests.rs b/crates/engine/src/text_fill_tests.rs index 8501a6ce5..6ef49b9e3 100644 --- a/crates/engine/src/text_fill_tests.rs +++ b/crates/engine/src/text_fill_tests.rs @@ -1,10 +1,75 @@ -//! Range fills on text: set on a range, cleared back to the layer's fill. +//! Range fills on text: set on a range, cleared back to the layer's fill; a layer-level fill edit +//! reaches every character. use serde_json::json; use crate::Session; +use crate::cmd::lists::character_fills; use crate::params::id_of; +/// The fill each character of `t` shows, as hex. +fn fills_shown(s: &Session, t: figcraft_doc::NodeId) -> Vec { + let n = s.doc().unwrap().node(t).unwrap().clone(); + let tx = n.kind.text().unwrap().clone(); + (0..tx.char_count()) + .map(|i| { + tx.style_at(i) + .fills + .clone() + .unwrap_or_else(|| n.fills.clone()) + .iter() + .map(|p| p.solid_color().unwrap().to_hex()) + .collect::>() + .join("+") + }) + .collect() +} + +/// A text styled on a range, or on all of its characters, keeps those fills until the layer's +/// fill is edited: then every character takes the layer's fills, in one undo step (#1856). +#[test] +fn a_layer_fill_edit_reaches_every_character() { + let mut s = Session::new(); + let t = id_of(&s.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap()["id"]).unwrap(); + s.execute("fill.set", &json!({"ids": [t], "color": "#FF0000"})).unwrap(); + let node = |s: &Session| s.doc().unwrap().node(t).unwrap().clone(); + assert_eq!(character_fills(&node(&s)).map(|f| f.len()), Some(1), "one shared list"); + // "ello" yellow: the characters differ, the layer's fill is mixed, the canvas keeps both. + s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); + assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"]); + assert_eq!(character_fills(&node(&s)), None, "mixed"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "reselecting changes nothing"); + // The layer's fill set: every character takes it, their own fills are gone. + let steps = s.ds().unwrap().history.undo.len(); + s.execute("fill.set", &json!({"ids": [t], "color": "#0000FF"})).unwrap(); + assert_eq!(fills_shown(&s, t), ["0000FF"; 5]); + assert!(node(&s).kind.text().unwrap().runs.is_empty(), "no character keeps fills of its own"); + assert_eq!(s.ds().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.undo().unwrap(); + assert_eq!(fills_shown(&s, t), ["FF0000", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "undo puts the characters' fills back"); + s.redo().unwrap(); + // All of the characters styled while editing: they share a list the layer doesn't have yet. + // A fill added at the layer goes on top of that list, not the layer's old one. + s.execute("text.style", &json!({"id": t, "start": 0, "end": 5, "textFills": ["#00FF00"]})).unwrap(); + assert_eq!(fills_shown(&s, t), ["00FF00"; 5]); + assert_eq!(character_fills(&node(&s)).map(|f| f.len()), Some(1), "one shared list, the characters'"); + assert_eq!(node(&s).fills[0].solid_color().unwrap().to_hex(), "0000FF", "the layer's own list is older"); + s.execute("fill.add", &json!({"ids": [t], "color": "#FF00FF"})).unwrap(); + assert_eq!(fills_shown(&s, t), ["00FF00+FF00FF"; 5]); + assert!(node(&s).kind.text().unwrap().runs.is_empty()); + assert_eq!(node(&s).fills.len(), 2, "the layer's list is the characters' now"); + // `node.set` with a fill, and a mixed text again: both reach every character. + s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); + s.execute("node.set", &json!({"id": t, "props": {"fill": "#123456"}})).unwrap(); + assert_eq!(fills_shown(&s, t), ["123456"; 5]); + // A rectangle is left alone by all of this. + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"]).unwrap(); + s.execute("fill.set", &json!({"ids": [r], "color": "#ABCDEF"})).unwrap(); + assert_eq!(character_fills(s.doc().unwrap().node(r).unwrap()).map(|f| f.len()), Some(1)); +} + #[test] fn range_fill_sets_and_clears() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7ecb64d22..4186ba7c5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -243,6 +243,8 @@ mod table_paste_tests; #[cfg(test)] mod text_enter_tests; #[cfg(test)] +mod text_mixed_fill_tests; +#[cfg(test)] mod titlebar_tests; #[cfg(test)] mod ui_params_tests; diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 58423d252..06e23eaf7 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -293,7 +293,8 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI } let t = Tokens::get(ui.ctx()); let ids = sel.to_vec(); - let list = common(doc, sel, |n| if fills { n.fills.clone() } else { n.strokes.clone() }); + // A text's fills are what its characters show: one list they share, or mixed (#1856). + let list = common(doc, sel, |n| if fills { figcraft_engine::cmd::lists::character_fills(n) } else { Some(n.strokes.clone()) }).flatten(); let title = if fills { tr("Fill") } else { tr("Stroke") }; let empty = list.as_ref().is_none_or(|l| l.is_empty()); let slot = if fills { StyleSlot::Fill } else { StyleSlot::Stroke }; diff --git a/crates/ui-egui/src/text_mixed_fill_tests.rs b/crates/ui-egui/src/text_mixed_fill_tests.rs new file mode 100644 index 000000000..b494c267d --- /dev/null +++ b/crates/ui-egui/src/text_mixed_fill_tests.rs @@ -0,0 +1,107 @@ +//! The Fill section on a text whose characters were coloured while editing (#1856), driven +//! through egui headless: characters with different fills show as mixed content and + replaces +//! them on every character; characters that all share fills the layer doesn't have show those. + +use egui::accesskit::Role; +use egui::{Pos2, pos2}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; + +const NOTE: &str = "Click + to replace mixed content"; + +/// A red "Hello" with its characters from `from` on coloured yellow while editing, selected. +fn ui(from: usize) -> (Ui, NodeId) { + let mut s = Session::new(); + let t = NodeId(s.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap()["id"].as_u64().unwrap()); + s.execute("fill.set", &json!({"ids": [t], "color": "#FF0000"})).unwrap(); + s.execute("text.style", &json!({"id": t, "start": from, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + (u, t) +} + +/// The accessible controls after a frame: role, label, value and centre. +fn controls(u: &mut Ui) -> Vec<(Role, String, String, Pos2)> { + u.frame(vec![]); + let out = u.frame_output(vec![]); + let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; + nodes + .iter() + .map(|(_, n)| { + let at = n.bounds().map_or(pos2(0.0, 0.0), |b| pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)); + (n.role(), n.label().unwrap_or_default().to_string(), n.value().unwrap_or_default().to_string(), at) + }) + .collect() +} + +/// What the Fill section shows: its hex rows top first, whether the mixed-content note is there +/// (only a paint section shows it, and the strokes here are never mixed), and its + button. The +/// section's rows lie between its + and the Stroke section's; Selection colors is further down. +fn fill_section(c: &[(Role, String, String, Pos2)]) -> (Vec, bool, Pos2) { + let button = |name: &str| { + c.iter().find(|(r, l, _, _)| *r == Role::Button && l == name).map(|(_, _, _, p)| *p).unwrap_or_else(|| panic!("no {name} button: {c:?}")) + }; + let (top, bottom) = (button("Add fill"), button("Add stroke")); + let mut rows: Vec<(f32, String)> = + c.iter().filter(|(r, _, _, p)| *r == Role::TextInput && p.y > top.y && p.y < bottom.y).map(|(_, _, v, p)| (p.y, v.clone())).collect(); + rows.sort_by(|a, b| a.0.total_cmp(&b.0)); + let note = c.iter().any(|(_, l, v, _)| l == NOTE || v == NOTE); + (rows.into_iter().map(|(_, v)| v).collect(), note, top) +} + +fn fills_shown(u: &Ui, t: NodeId) -> Vec { + let n = u.app.session.doc().unwrap().node(t).unwrap().clone(); + let tx = n.kind.text().unwrap().clone(); + (0..tx.char_count()) + .map(|i| { + tx.style_at(i) + .fills + .clone() + .unwrap_or_else(|| n.fills.clone()) + .iter() + .map(|p| p.solid_color().unwrap().to_hex()) + .collect::>() + .join("+") + }) + .collect() +} + +#[test] +fn differently_coloured_characters_show_as_mixed_content_and_plus_replaces_them() { + let (mut u, t) = ui(1); + let c = controls(&mut u); + let (rows, note, plus) = fill_section(&c); + assert!(note, "the Fill section shows the note: {c:?}"); + assert!(rows.is_empty(), "no row for the layer's own red: {rows:?}"); + // + adds a fill on top of the layer's: every character shows the layer's fills now. + let steps = u.app.session.ds().unwrap().history.undo.len(); + u.button(plus, true); + u.button(plus, false); + u.frame(vec![]); + let n = u.app.session.doc().unwrap().node(t).unwrap().clone(); + assert_eq!(n.fills.len(), 2, "the new fill on the layer's: {:?}", n.fills); + assert!(n.kind.text().unwrap().runs.is_empty(), "no character keeps fills of its own"); + assert!(fills_shown(&u, t).iter().all(|f| f == "FF0000+D9D9D9"), "{:?}", fills_shown(&u, t)); + assert_eq!(u.app.session.ds().unwrap().history.undo.len(), steps + 1, "one undo step"); + let c = controls(&mut u); + let (rows, note, _) = fill_section(&c); + assert!(!note, "no note once the characters agree: {c:?}"); + assert_eq!(rows, ["D9D9D9", "FF0000"], "the new fill above the layer's red: {c:?}"); +} + +#[test] +fn characters_sharing_fills_the_layer_lacks_show_theirs() { + let (mut u, t) = ui(0); + let n = u.app.session.doc().unwrap().node(t).unwrap().clone(); + assert_eq!(n.fills[0].solid_color().unwrap().to_hex(), "FF0000", "the layer still has its old fill"); + assert_eq!(fills_shown(&u, t), ["FFFF00"; 5]); + let c = controls(&mut u); + let (rows, note, _) = fill_section(&c); + assert_eq!(rows, ["FFFF00"], "the characters' yellow is the row, not the layer's red: {c:?}"); + assert!(!note, "{c:?}"); +} diff --git a/crates/ui-egui/src/widgets/colorpicker.rs b/crates/ui-egui/src/widgets/colorpicker.rs index 5fbcc7b40..3bd322031 100644 --- a/crates/ui-egui/src/widgets/colorpicker.rs +++ b/crates/ui-egui/src/widgets/colorpicker.rs @@ -92,7 +92,8 @@ fn current_paint(app: &FigApp, target: &PickerTarget) -> Option { }, PickerTarget::Paint { fills, index, ids } => { let n = doc.node(*ids.first()?)?; - let list = if *fills { &n.fills } else { &n.strokes }; + // A text's fills are its characters' (none to pick while they differ). + let list = if *fills { figcraft_engine::cmd::lists::character_fills(n)? } else { n.strokes.clone() }; list.get(*index).cloned() } PickerTarget::Effect { ids, index, secondary } => doc.node(*ids.first()?)?.effects.get(*index)?.color(*secondary).map(Paint::solid), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3963e4624..0f1b5f3f2 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-01 · **Change:** minor (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-02 · **Change:** patch (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); 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: @@ -33,6 +33,7 @@ interaction feel not yet compared. | 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. | | 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 (`text_mixed_fill_tests`, engine `text_fill_tests`; #1856). A range selected while editing keeps its own Fill 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 @@ -176,6 +177,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 2026-11-02 | patch | Fill section: a text whose characters were coloured differently while editing shows mixed content, as a mixed selection does ("Text nodes can have multiple sets of fills if some characters are colored differently than others", the developer documentation's `fills`); characters that all share fills the layer doesn't have (all of them styled while editing) show those instead of the layer's older list; and a layer-level fill edit (a row, its picker, +, reordering, `fill.*`, `node.set`) reaches every character, their own fills going in the same undo step. The section used to show the layer's own fill, a single colour the canvas no longer showed (#1856). Tests: `text_mixed_fill_tests`, engine `text_fill_tests`. Numbers unchanged | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From 9783af934712ed03a9d4ccfcc8df8ac17a32dd7b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 01:27:48 -0500 Subject: [PATCH 095/326] Field scrub: the field senses drags only with Alt held or a scrub going on, so a touch swipe stays the scroll area's Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/field_tests.rs | 26 +++++++++++++++++++++++--- crates/ui-egui/src/widgets.rs | 14 ++++++++------ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 4e3dfb35d..e9aabcacb 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1216,11 +1216,11 @@ fn alt_held_over_a_field_scrubs_it() { drag(&mut u, at, 25.0, Modifiers::NONE); assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub"); assert_eq!(undo_steps(&u), steps + 1); - // Alt and the press in the same frame still scrub, and Alt let go before the button still - // ends the scrub with its undo step. + // Alt let go before the button still ends the scrub with its undo step. let (at, _) = field(&mut u, "X"); let press = |pressed: bool, m: Modifiers, p: Pos2| Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; - u.frame_with(vec![Event::PointerMoved(at), press(true, alt, at)], alt); + u.frame_with(vec![Event::PointerMoved(at)], alt); + u.frame_with(vec![press(true, alt, at)], alt); for k in 1..=10 { u.frame_with(vec![Event::PointerMoved(pos2(at.x + 2.0 * k as f32, at.y))], alt); } @@ -1229,4 +1229,24 @@ fn alt_held_over_a_field_scrubs_it() { u.frame(vec![]); assert_eq!(geom(&u, a).0, 55.0, "twenty more"); assert_eq!(undo_steps(&u), steps + 2, "committed when the button went up, without Alt"); + // Without Alt the field doesn't take the drag at all (a touch swipe over it is the panel's to + // scroll): the press is a click of the field's, not a drag. + let (at, _) = field(&mut u, "X"); + let field_id = Id::unique("pos_x").with("field"); + u.frame_with(vec![Event::PointerMoved(at)], Modifiers::NONE); + u.frame_with(vec![press(true, Modifiers::NONE, at)], Modifiers::NONE); + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y))], Modifiers::NONE); + assert!(!u.ctx.is_being_dragged(field_id), "a plain press on the field isn't a drag of the field's"); + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, Modifiers::NONE, pos2(at.x + 10.0, at.y))], Modifiers::NONE); + u.frame(vec![]); + assert_eq!(geom(&u, a).0, 55.0, "nothing scrubbed"); + // With Alt held over it, the field does take the drag. + let (at, _) = field(&mut u, "X"); + u.frame_with(vec![Event::PointerMoved(at)], alt); + u.frame_with(vec![press(true, alt, at)], alt); + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y))], alt); + assert!(u.ctx.is_being_dragged(field_id), "with Alt the drag is the field's"); + u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, alt, pos2(at.x + 10.0, at.y))], alt); + u.frame(vec![]); + assert_eq!(geom(&u, a).0, 65.0, "ten more"); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 7db22abc0..58733ce79 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -268,15 +268,17 @@ fn number_field_impl( let mut editing: Option = ui.data(|d| d.get_temp(editing_id)); // Alt held over the field scrubs it too, as the label always does: "hover the input field // itself and hold down the modifier key" (Adjust alignment, rotation, position, and - // dimensions). The field always senses drags (egui assigns a press by the frame before it, so - // a sense that waits for Alt would miss a press that arrives with it); Alt as the drag begins - // is what makes it a scrub, and that holds until the button is let go, Alt released or not. + // dimensions). The field senses drags only while Alt is held, or while a scrub begun that way + // goes on (Alt released or not), so a plain press or a touch swipe on it stays the scroll + // area's; egui assigns a press by the frame before it, so Alt is held over the field before + // the press, as a hand does. Alt as the drag begins is what makes it a scrub. let field_id = id.with("field"); - let field_resp = ui.interact(edit_rect, field_id, Sense::click_and_drag()); let alt_now = ui.input(|i| i.modifiers.alt); let scrubbing_id = id.with("altscrub"); - let alt_scrub = - editing.is_none() && if field_resp.drag_started() { alt_now } else { ui.data(|d| d.get_temp::(scrubbing_id)).unwrap_or(false) }; + let scrubbing = ui.data(|d| d.get_temp::(scrubbing_id)).unwrap_or(false); + let field_sense = if editing.is_none() && (alt_now || scrubbing) { Sense::click_and_drag() } else { Sense::click() }; + let field_resp = ui.interact(edit_rect, field_id, field_sense); + let alt_scrub = editing.is_none() && if field_resp.drag_started() { alt_now } else { scrubbing }; ui.data_mut(|d| d.insert_temp(scrubbing_id, alt_scrub && field_resp.dragged() && !field_resp.drag_stopped())); a11y::number(&field_resp, lead.name(), value, suffix, empty.text()); a11y::ring_around(ui, rect, &field_resp); From 8fb53baa64c73aa3721e636e944a1e9b5db67da9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 02:02:35 -0500 Subject: [PATCH 096/326] SVG import: a filled and stroked path with an open subpath is tested through its split Co-Authored-By: Claude Fable 5.1 --- crates/svg/src/import/structure_tests.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/svg/src/import/structure_tests.rs b/crates/svg/src/import/structure_tests.rs index a44590470..fbc9976ae 100644 --- a/crates/svg/src/import/structure_tests.rs +++ b/crates/svg/src/import/structure_tests.rs @@ -159,6 +159,27 @@ fn an_open_path_starts_half_a_dash_in_and_takes_other_offsets() { assert_eq!(node(&d, f, "mixed").stroke.dashes, vec![4.0, 2.0], "an open subpath makes the outline open"); } +/// A filled and stroked path with an open subpath becomes a fill layer and a stroke layer: the +/// stroke layer is open, so it starts half a dash in like any open path and that offset is left +/// out; a filled and stroked path that closes stays one layer whose offset is applied. +#[test] +fn a_filled_and_stroked_open_path_splits_and_its_stroke_layer_is_open() { + let (d, f) = import( + r##""##, + ); + for id in ["both", "bothmixed"] { + let stroke_layer = node(&d, f, id); + assert!(stroke_layer.fills.is_empty() && !stroke_layer.strokes.is_empty(), "{id}: the stroke layer carries the stroke alone"); + assert_eq!(stroke_layer.stroke.dashes, vec![4.0, 2.0], "{id}: an open stroke layer starts half a dash in by itself"); + let fill_layer = node(&d, f, &format!("{id} fill")); + assert!(!fill_layer.fills.is_empty() && fill_layer.strokes.is_empty(), "{id}: the fill layer carries the fill alone"); + } + let one = node(&d, f, "bothclosed"); + assert!(!one.fills.is_empty() && !one.strokes.is_empty(), "a closed path keeps fill and stroke on one layer"); + assert_eq!(one.stroke.dashes, vec![2.0, 2.0, 2.0, 0.0], "and its offset rotates the pattern"); + assert!(d.subtree(f).into_iter().filter_map(|i| d.node(i)).all(|n| n.name != "bothclosed fill"), "no split for a closed path"); +} + /// A text stroke runs along glyph contours, which close, so its offset is applied as on a shape. #[test] fn a_text_stroke_keeps_a_dash_offset_of_half_a_dash() { From 5c9bb79b1abe44e57ec919499127b37138a9d14a Mon Sep 17 00:00:00 2001 From: mortezanaeemi-ops Date: Mon, 2 Nov 2026 10:34:09 +0330 Subject: [PATCH 097/326] Add files via upload --- crates/format/src/fig/map.rs | 6 +++++ crates/format/src/fig/tests.rs | 48 ++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index e125028c8..927c233a2 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -517,6 +517,12 @@ impl VarCanon { VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.sets_by_key.get(key).cloned())) } + /// Whether a table is installed on this thread (for tests: none outlives the mapping). + #[cfg(test)] + pub(crate) fn installed() -> bool { + VAR_CANON.with(|c| c.borrow().is_some()) + } + /// Whether variable node `id` is an older copy another one replaces. pub(super) fn superseded(id: &str) -> bool { VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.by_id.get(id)).is_some_and(|canon| canon != id)) diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index d365ff9f7..787c70865 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -1675,3 +1675,51 @@ fn removed_library_collection_copies_give_way_to_live_ones() { let page = doc.nodes().find(|n| n.name == "Page").unwrap(); assert_eq!(page.var_modes.get("1:9").map(String::as_str), Some("1:92"), "{warnings:?}"); } + +/// Two copies of a library collection with the same version: the choice doesn't depend on the order +/// of the node changes (the higher guid wins), and the thread's lookup table is gone after the import. +#[test] +fn same_version_library_copies_resolve_deterministically_and_leave_no_table() { + let mode = |id, name: &'static str| o(vec![("id", g(id)), ("name", s(name)), ("sortPosition", s("!"))]); + let set = |id, modes: Vec>| { + node(id, Some((2, "!")), "VARIABLE_SET", "Products", vec![("variableSetModes", arr(modes)), ("key", s("products")), ("version", s("20:1"))]) + }; + let page = node( + 1, + Some((0, "!")), + "CANVAS", + "Page", + vec![( + "variableModeBySetMap", + o(vec![( + "entries", + arr(vec![o(vec![("variableSetID", o(vec![("assetRef", o(vec![("key", s("products"))]))])), ("variableModeID", g(90))])]), + )]), + )], + ); + let base = || { + vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + page.clone(), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + ] + }; + let mut picked = Vec::new(); + for swap in [false, true] { + let (a, b) = (set(4, vec![mode(90, "Blue")]), set(6, vec![mode(90, "Blue")])); + let mut nodes = base(); + if swap { + nodes.extend([b, a]); + } else { + nodes.extend([a, b]); + } + let (doc, _) = import(&canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + assert_eq!(doc.variables.collections.len(), 1, "{:?}", doc.variables.collections); + let id = doc.variables.collections[0].id.clone(); + let page = doc.nodes().find(|n| n.name == "Page").unwrap(); + assert_eq!(page.var_modes.get(&id).map(String::as_str), Some("1:90")); + picked.push(id); + assert!(!super::map::VarCanon::installed()); + } + assert_eq!(picked, ["1:6", "1:6"]); +} From 50eb28e0acee993183379c1dd293f978091117ee Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 02:06:57 -0500 Subject: [PATCH 098/326] M2: a Cmd/Ctrl-click on a padding field sets all four sides with the value typed Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/keymap.rs | 1 + crates/engine/src/shortcut_parity_tests.rs | 3 +- crates/ui-egui/locales/en.toml | 3 ++ .../ui-egui/src/padding_individual_tests.rs | 48 +++++++++++++++++++ crates/ui-egui/src/panels/layout_panel.rs | 22 ++++++--- crates/ui-egui/src/widgets.rs | 12 +++++ docs/auto-layout-parity.md | 5 +- docs/ui-parity.md | 7 +-- 8 files changed, 89 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index a0f0bc4b6..9afce8341 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -364,6 +364,7 @@ pub static GESTURES: &[(Group, &str, &str, &str)] = &[ (Transform, "Opacity 10%…90%, 0: 100%", "1…9, 0", "1…9, 0"), (Transform, "Exact opacity (4 then 5: 45%)", "Two digits", "Two digits"), (Transform, "Suspend snapping while dragging", "Hold ⌃ or ⌘", "Hold Ctrl"), + (Arrange, "Edit padding on all sides", "⌘ click a padding field", "Ctrl+click a padding field"), (Prototype, "Presenting: next frame", "→, Space or N", "→, Space or N"), (Prototype, "Presenting: previous frame", "←", "←"), (Prototype, "Presenting: restart", "R", "R"), diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index 0b9b573af..3165cb4f1 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -278,6 +278,7 @@ static ROWS: &[Row] = &[ doc(Arrange, "Add auto layout", &["Shift+A"], &[], Bound("layout.add"), ""), doc(Arrange, "Remove auto layout", &["Alt+Shift+A"], &[], Bound("layout.remove"), ""), doc(Arrange, "Suggest auto layout", &["Ctrl+Shift+A"], &["Ctrl+Alt+Shift+A"], Bound("layout.suggest"), "was unbound"), + doc(Arrange, "Edit padding on all sides (from right panel)", &["Cmd"], &[], Gesture("Edit padding on all sides"), "held while clicking a padding field: the value typed goes to every side"), pin(Arrange, "distribute.horizontal", &["Ctrl+Alt+H"], &["Alt+Shift+H"]), pin(Arrange, "distribute.vertical", &["Ctrl+Alt+V"], &["Alt+Shift+V"]), pin(Arrange, "arrange.tidy", &["Ctrl+Alt+T"], &["Ctrl+Alt+Shift+T"]), @@ -412,7 +413,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), (133, 132, 1, 0, 2, 57)); + assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (134, 133, 1, 0, 2, 57)); } #[test] diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index c44635a2a..2207b61ca 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -388,6 +388,8 @@ name = "English" "Crop marks" = "Crop marks" "Ctrl+arrows" = "Ctrl+arrows" "Ctrl+click" = "Ctrl+click" +"Ctrl+click a padding field" = "Ctrl+click a padding field" +"⌘ click a padding field" = "⌘ click a padding field" "Ctrl+scroll" = "Ctrl+scroll" "Current name" = "Current name" "Current version" = "Current version" @@ -494,6 +496,7 @@ name = "English" "Edit dev resource" = "Edit dev resource" "Edit link" = "Edit link" "Edit link copied" = "Edit link copied" +"Edit padding on all sides" = "Edit padding on all sides" "Edit style" = "Edit style" "Edit variable" = "Edit variable" "Edit with the builder" = "Edit with the builder" diff --git a/crates/ui-egui/src/padding_individual_tests.rs b/crates/ui-egui/src/padding_individual_tests.rs index bf076d487..2b493ca7f 100644 --- a/crates/ui-egui/src/padding_individual_tests.rs +++ b/crates/ui-egui/src/padding_individual_tests.rs @@ -112,3 +112,51 @@ fn shut_pair_fields_edit_their_own_axis() { u.frame(vec![]); assert_eq!(padding(&u, f), [7.0, 20.0, 7.0, 20.0]); } + +/// A press and release at `p` with Cmd/Ctrl held (Alt is the field's own scrub modifier). +fn command_click(u: &mut Ui, p: Pos2) { + let m = Modifiers::COMMAND; + let press = |pressed: bool| Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; + u.frame_with(vec![Event::PointerMoved(p)], m); + u.frame_with(vec![press(true)], m); + u.frame_with(vec![press(false)], m); + u.frame(vec![]); +} + +/// "Edit padding on all sides (from right panel): ⌘ Command + Click padding input field / Ctrl + +/// Click padding input field" (Guide to auto layout, Keyboard shortcut guide): a value typed +/// after a Cmd/Ctrl-click on any padding field goes to all four sides in one undo step; a plain +/// click keeps editing that side or axis alone. +#[test] +fn a_command_click_on_a_padding_field_edits_all_sides() { + let (mut u, f) = scene(); + u.app.run("node.set", json!({"ids": [f], "props": {"paddingLeft": 16.0, "paddingRight": 54.0}})); + assert_eq!(padding(&u, f), [10.0, 54.0, 10.0, 16.0]); + // The shut pair: Cmd/Ctrl-click Vertical padding and type 7: every side is 7. + let history = u.app.session.undo_depth().0; + let v = named_field(&mut u, "Vertical padding"); + command_click(&mut u, v); + u.frame(vec![Event::Text("7".into())]); + enter(&mut u); + u.frame(vec![]); + assert_eq!(padding(&u, f), [7.0; 4]); + assert_eq!(u.app.session.undo_depth().0, history + 1, "one undo step"); + // A plain click afterwards edits its own axis again. + let v = named_field(&mut u, "Vertical padding"); + click(&mut u, v); + u.frame(vec![Event::Text("9".into())]); + enter(&mut u); + u.frame(vec![]); + assert_eq!(padding(&u, f), [9.0, 7.0, 9.0, 7.0]); + // Individual padding open: Cmd/Ctrl-click the left field and type 3: every side is 3. + let t = named_button(&mut u, "Individual padding"); + click(&mut u, t); + let left = u.ctx.read_response(Id::unique(("padding", 3)).with("field")).expect("left field shows").rect.center(); + command_click(&mut u, left); + u.frame(vec![Event::Text("3".into())]); + enter(&mut u); + u.frame(vec![]); + assert_eq!(padding(&u, f), [3.0; 4]); + u.app.run("edit.undo", json!({})); + assert_eq!(padding(&u, f), [9.0, 7.0, 9.0, 7.0], "undone as one step"); +} diff --git a/crates/ui-egui/src/panels/layout_panel.rs b/crates/ui-egui/src/panels/layout_panel.rs index 4762bdd08..81e406a51 100644 --- a/crates/ui-egui/src/panels/layout_panel.rs +++ b/crates/ui-egui/src/panels/layout_panel.rs @@ -16,7 +16,7 @@ use crate::i18n::{tr, tr_noop}; use crate::icons::{self, Icon}; use crate::right::{block, common, menu_item, menu_popup, row}; use crate::theme::{ACCENT, Tokens, regular}; -use crate::widgets::{self, FIELD_H, Lead}; +use crate::widgets::{self, FIELD_H, FieldEdit, Lead}; /// Most tracks listed in the panel (the rest are still laid out; edit them through commands). const MAX_TRACK_ROWS: usize = 24; @@ -416,6 +416,16 @@ fn alignment(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) { } } +/// Commit a padding field's edit: a value typed after a Cmd/Ctrl-click goes to all four sides +/// ("Edit padding on all sides (from right panel): ⌘ Command + Click padding input field / Ctrl + +/// Click padding input field", Guide to auto layout); otherwise to the field's own side or axis. +fn padding_field(app: &mut FigApp, ui: &Ui, ids: &[NodeId], key: &str, id: Id, e: Option) { + match e { + Some(FieldEdit::Set(v)) if widgets::edit_began_with_command(ui, id) => app.set_props(ids, json!({"padding": v.max(0.0)})), + e => app.field(ids, key, e, |v| json!(v.max(0.0))), + } +} + /// The Spacing row: the H/V padding pair, or, with Individual padding on, two rows of one field /// per side (like Individual corners). fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) { @@ -439,9 +449,9 @@ fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) { for (r, pair) in sides.chunks(2).enumerate() { row(ui, 32.0, |ui| { for (key, name, icon, v, k) in pair { - let e = - crate::variable_ui::number_field(app, ui, ids, key, Id::unique(("padding", *k)), Lead::Icon(*icon, name), Some(*v), "", col); - app.field(ids, key, e, |v| json!(v.max(0.0))); + let id = Id::unique(("padding", *k)); + let e = crate::variable_ui::number_field(app, ui, ids, key, id, Lead::Icon(*icon, name), Some(*v), "", col); + padding_field(app, ui, ids, key, id, e); } if r == 0 { toggle(ui); @@ -461,7 +471,7 @@ fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) { "", col, ); - app.field(ids, "paddingHorizontal", e, |v| json!(v.max(0.0))); + padding_field(app, ui, ids, "paddingHorizontal", Id::unique("al_padh"), e); let e = crate::variable_ui::number_field( app, ui, @@ -473,7 +483,7 @@ fn spacing(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], l: &AutoLayout) { "", col, ); - app.field(ids, "paddingVertical", e, |v| json!(v.max(0.0))); + padding_field(app, ui, ids, "paddingVertical", Id::unique("al_padv"), e); toggle(ui); }); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index c7e20bb1d..2a32ffd13 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -185,6 +185,14 @@ pub fn number_field(ui: &mut Ui, id: Id, lead: Lead, value: Option, suffix: number_field_mixed(ui, id, lead, value, suffix, width, step)?.settled() } +/// Whether the edit of number field `id` began with a Cmd/Ctrl-click. A padding field edited +/// that way sets every side: "Edit padding on all sides (from right panel): ⌘ Command + Click +/// padding input field / Ctrl + Click padding input field" (Guide to auto layout, Keyboard +/// shortcut guide). +pub fn edit_began_with_command(ui: &Ui, id: Id) -> bool { + ui.data(|d| d.get_temp::(id.with("cmdstart"))).unwrap_or(false) +} + /// [`number_field`] over several layers: without a single value (`value` None, "Mixed") a relative /// edit comes back as one for each layer ([`Edit::Each`]). pub fn number_field_mixed(ui: &mut Ui, id: Id, lead: Lead, value: Option, suffix: &str, width: f32, step: f64) -> Option { @@ -346,10 +354,14 @@ fn number_field_impl( let kept_id = id.with("kept"); if started { editing = Some(if typed_now { String::new() } else { value.map(fmt_num).unwrap_or_default() }); + // Whether Cmd/Ctrl was held on the click that began the edit: a padding field then sets + // every side ([`edit_began_with_command`]). + let with_command = !typed_now && ui.input(|i| i.modifiers.command); ui.data_mut(|d| { d.insert_temp(editing_id, editing.clone().unwrap_or_default()); d.insert_temp(kept_id, value.map(fmt_num).unwrap_or_default()); d.insert_temp(id.with("selectall"), !typed_now); + d.insert_temp(id.with("cmdstart"), with_command); }); ui.memory_mut(|m| m.request_focus(id.with("te"))); } diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index f481fc7ab..22d956ae0 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (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-02 · **Change:** patch (a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; 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%, @@ -77,7 +77,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver |---|---|---| | 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` | -| Gap, auto gap (between / evenly / around), padding (per side), alignment 3×3 | done | | +| 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 ("Edit padding on all sides (from right panel): ⌘ Command + Click padding input field / Ctrl + Click padding input field", 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` | | Min/max width and height, redistribution | done | hugging text wraps at its max | @@ -97,6 +97,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 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 ("Edit padding on all sides (from right panel): ⌘ Command + Click padding input field / Ctrl + Click padding input field", 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-01 | patch | M2: a text layer keeps a max height or a number of max lines, not both ("Text layers cannot have both a max height and a set number of max lines", Guide to auto layout): `node.set {maxHeight}` on a text sets its max lines to Auto, and `node.set {maxLines}` or `text.maxLines` with a number removes its max height. Found by a documentation audit of this page. Test: `text_behaviour_tests::a_text_has_a_max_height_or_max_lines_not_both`. Numbers unchanged | | 2026-11-01 | minor | M2: Remove all auto layout ("To remove auto layout from a frame and all of its nested objects at once, right-click on the frame and go to More layout options > Remove all auto layout", Toggle on auto layout in designs): `layout.removeAll {ids?}` strips the frames and every frame nested in them in one undo step, leaving instances and their layers alone; in the canvas context menu beside Add auto layout and in the Actions palette. Found by a documentation audit of this page. Test: `al_nesting_tests::remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it`. Numbers unchanged | | 2026-10-30 | minor | M8, #1083: grid placement finds free cells on a bitmap, a word at a time, with the same placements; crafted grids of wide children no longer stall a layout pass. Numbers unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3963e4624..6273975d8 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-01 · **Change:** minor (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-02 · **Change:** patch (Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; 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: @@ -128,8 +128,8 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | | Count | Notes | |---|---|---| -| Documented shortcuts (rows) | 133 | each with macOS and Windows/Linux keys | -| Bound as documented | 132 (110 before this suite) | 111 keymap bindings, 15 held keys, gestures and presentation keys, 6 vector edit tool keys | +| Documented shortcuts (rows) | 134 | each with macOS and Windows/Linux keys | +| Bound as documented | 133 (110 before this suite) | 111 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 | @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 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 ("Edit padding on all sides (from right panel): ⌘ Command + Click padding input field / Ctrl + Click padding input field", 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 | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From badbe64440f3c033d7929e63eabf54f7a0e3d51d Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 03:23:36 -0500 Subject: [PATCH 099/326] Fill section: a removal that names no paint leaves the characters' fills, and Copy fill and Crop image use the list the rows show Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/edit/props.rs | 10 +++++++++- crates/engine/src/cmd/image.rs | 4 ++++ crates/engine/src/cmd/lists.rs | 11 +++++++++-- crates/engine/src/text_fill_tests.rs | 9 +++++++++ 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index b31312a01..9b6921d3f 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -267,6 +267,13 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> let doc = s.doc_mut()?; for i in ids { let n = doc.get_mut(i)?; + // A removal that names no paint changes nothing, the characters' own fills included. + if !add { + let shown = if fills { crate::cmd::lists::character_fills(n).map_or(n.fills.len(), |f| f.len()) } else { n.strokes.len() }; + if index.unwrap_or(shown.saturating_sub(1)) >= shown { + continue; + } + } if fills { crate::cmd::lists::take_character_fills(n); } @@ -350,7 +357,8 @@ pub(super) fn paint_copy(s: &mut Session, p: &Value, fills: bool) -> Result Result { // A selection with nothing to crop is refused as unavailable, not as bad input. let refuse = |why: &str| EngineError::Disabled(cmd.into(), why.into()); let [id] = ids[..] else { return Err(refuse("select one layer to crop its image")) }; + // A text's fills are its characters' (the Design panel's rows): the crop edits that list. + if crate::cmd::lists::has_character_fills(s.doc()?.get(id)?) { + crate::cmd::lists::take_character_fills(s.doc_mut()?.get_mut(id)?); + } let doc = s.doc()?; let n = doc.get(id)?; let index = match get(p, "index") { diff --git a/crates/engine/src/cmd/lists.rs b/crates/engine/src/cmd/lists.rs index 8f4cb37b3..455a02567 100644 --- a/crates/engine/src/cmd/lists.rs +++ b/crates/engine/src/cmd/lists.rs @@ -201,14 +201,21 @@ pub fn character_fills(n: &Node) -> Option> { spans.all(|f| *f == first).then_some(first) } +/// Whether any character of a text carries fills of its own (on its base style or a run). +pub(crate) fn has_character_fills(n: &Node) -> bool { + match &n.kind { + NodeKind::Text(t) => t.style.fills.is_some() || t.runs.iter().any(|r| r.style.fills.is_some()), + _ => false, + } +} + /// Before a layer-level edit of a text's fills (the Fill section, `fill.*`, `node.set`): the /// characters' own fills go, so the edit shows on every one of them. One list they all shared /// becomes the layer's first, so the edit starts from what the characters showed; characters /// that differed fall back to the layer's fills, which the edit then replaces ("Click + to /// replace mixed content"). Not a text, or no character with fills of its own: nothing changes. pub(crate) fn take_character_fills(n: &mut Node) { - let NodeKind::Text(t) = &n.kind else { return }; - if t.style.fills.is_none() && t.runs.iter().all(|r| r.style.fills.is_none()) { + if !has_character_fills(n) { return; } if let Some(shared) = character_fills(n) diff --git a/crates/engine/src/text_fill_tests.rs b/crates/engine/src/text_fill_tests.rs index 6ef49b9e3..3e77b47d8 100644 --- a/crates/engine/src/text_fill_tests.rs +++ b/crates/engine/src/text_fill_tests.rs @@ -64,6 +64,15 @@ fn a_layer_fill_edit_reaches_every_character() { s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); s.execute("node.set", &json!({"id": t, "props": {"fill": "#123456"}})).unwrap(); assert_eq!(fills_shown(&s, t), ["123456"; 5]); + // A removal that names no paint leaves the characters' own fills alone; a copy takes the fill + // the characters show, the list the Design panel's rows are. + s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); + s.execute("fill.remove", &json!({"ids": [t], "index": 7})).unwrap(); + assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "nothing removed, nothing taken"); + s.execute("text.style", &json!({"id": t, "start": 0, "end": 5, "textFills": ["#00FF00"]})).unwrap(); + s.execute("fill.copy", &json!({"id": t})).unwrap(); + let copied = s.clipboard.paint.clone().and_then(|(_, p)| p.solid_color()).map(|c| c.to_hex()); + assert_eq!(copied.as_deref(), Some("00FF00"), "the characters' fill is copied, not the layer's older one"); // A rectangle is left alone by all of this. let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"]).unwrap(); s.execute("fill.set", &json!({"ids": [r], "color": "#ABCDEF"})).unwrap(); From a4b07876a3285a9a3ae41a43b7757dc7016bef27 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 03:32:39 -0500 Subject: [PATCH 100/326] M2: a Cmd/Ctrl-click on a padding field reads the modifier at the press, clears its mark when no edit follows and commits a retyped value to all sides Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/shortcut_parity_tests.rs | 2 +- crates/ui-egui/src/widgets.rs | 18 +++++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index 3165cb4f1..7d145db39 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -278,7 +278,7 @@ static ROWS: &[Row] = &[ doc(Arrange, "Add auto layout", &["Shift+A"], &[], Bound("layout.add"), ""), doc(Arrange, "Remove auto layout", &["Alt+Shift+A"], &[], Bound("layout.remove"), ""), doc(Arrange, "Suggest auto layout", &["Ctrl+Shift+A"], &["Ctrl+Alt+Shift+A"], Bound("layout.suggest"), "was unbound"), - doc(Arrange, "Edit padding on all sides (from right panel)", &["Cmd"], &[], Gesture("Edit padding on all sides"), "held while clicking a padding field: the value typed goes to every side"), + doc(Arrange, "Edit padding on all sides (from right panel)", &["Cmd"], &["Ctrl"], Gesture("Edit padding on all sides"), "held while clicking a padding field: the value typed goes to every side"), pin(Arrange, "distribute.horizontal", &["Ctrl+Alt+H"], &["Alt+Shift+H"]), pin(Arrange, "distribute.vertical", &["Ctrl+Alt+V"], &["Alt+Shift+V"]), pin(Arrange, "arrange.tidy", &["Ctrl+Alt+T"], &["Ctrl+Alt+Shift+T"]), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 2a32ffd13..08d919781 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -352,11 +352,17 @@ fn number_field_impl( // The text the field would commit to no effect: what it showed when the edit began, or the // value the arrows last stepped it to. let kept_id = id.with("kept"); + // Whether Cmd/Ctrl was held while the button was down on the field: a click's modifier is + // read on its press, so letting go of the key before the release still counts. + let cmd_press_id = id.with("cmdpress"); + let cmd_held_before = ui.data(|d| d.get_temp::(cmd_press_id)).unwrap_or(false); + let (cmd_pressed, any_down) = ui.input(|i| (field_resp.is_pointer_button_down_on() && i.modifiers.command, i.pointer.any_down())); + ui.data_mut(|d| d.insert_temp(cmd_press_id, cmd_pressed || (cmd_held_before && any_down))); if started { editing = Some(if typed_now { String::new() } else { value.map(fmt_num).unwrap_or_default() }); // Whether Cmd/Ctrl was held on the click that began the edit: a padding field then sets - // every side ([`edit_began_with_command`]). - let with_command = !typed_now && ui.input(|i| i.modifiers.command); + // every side ([`edit_began_with_command`]). The flag lives as long as the edit. + let with_command = !typed_now && (cmd_pressed || cmd_held_before || ui.input(|i| i.modifiers.command)); ui.data_mut(|d| { d.insert_temp(editing_id, editing.clone().unwrap_or_default()); d.insert_temp(kept_id, value.map(fmt_num).unwrap_or_default()); @@ -364,6 +370,9 @@ fn number_field_impl( d.insert_temp(id.with("cmdstart"), with_command); }); ui.memory_mut(|m| m.request_focus(id.with("te"))); + } else if editing.is_none() { + // No edit under way: an arrow step on the focused field is its own side's. + ui.data_mut(|d| d.remove::(id.with("cmdstart"))); } match editing { Some(mut text) => { @@ -418,7 +427,10 @@ fn number_field_impl( // Enter, Tab or a click elsewhere commits what was typed (a field left as it was // commits nothing: no undo step, and a rounded display isn't written back). let kept: String = ui.data(|d| d.get_temp(kept_id)).unwrap_or_default(); - if text != kept + // An edit begun with Cmd/Ctrl commits the value even retyped as it was: the other + // sides are to take it ([`edit_began_with_command`]). + let for_all = ui.data(|d| d.get_temp::(id.with("cmdstart"))).unwrap_or(false); + if (text != kept || for_all) && let Some(e) = typed(&text) { out = Some(e); From 96cd54b5568ccbd45f572f8dceaafe416424f162 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 04:09:51 -0500 Subject: [PATCH 101/326] Fill section: mixed text has no fill rows to remove or crop, and a crop lifts the characters' fills only when it edits Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/edit/props.rs | 6 ++++-- crates/engine/src/cmd/image.rs | 17 ++++++++++------- crates/engine/src/text_fill_tests.rs | 10 ++++++++++ 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index 9b6921d3f..2ec716818 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -267,9 +267,11 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> let doc = s.doc_mut()?; for i in ids { let n = doc.get_mut(i)?; - // A removal that names no paint changes nothing, the characters' own fills included. + // A removal that names no paint among the rows shown changes nothing, the characters' own + // fills included; characters coloured differently show no rows at all ("Click + to + // replace mixed content"). if !add { - let shown = if fills { crate::cmd::lists::character_fills(n).map_or(n.fills.len(), |f| f.len()) } else { n.strokes.len() }; + let shown = if fills { crate::cmd::lists::character_fills(n).map_or(0, |f| f.len()) } else { n.strokes.len() }; if index.unwrap_or(shown.saturating_sub(1)) >= shown { continue; } diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index 9f6b942a4..865e4d19a 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -184,9 +184,10 @@ fn replace(s: &mut Session, p: &Value) -> Result { Ok(json!({"image": image, "width": width, "height": height, "changed": changed})) } -/// The index of a layer's top visible image fill (fills paint bottom to top). +/// The index of a layer's top visible image fill among the fills it shows (fills paint bottom to +/// top): a text's characters' shared list, so none while they are coloured differently. pub fn top_image_fill(n: &Node) -> Option { - n.fills.iter().rposition(|f| f.visible && matches!(f.kind, PaintKind::Image(_))) + crate::cmd::lists::character_fills(n)?.iter().rposition(|f| f.visible && matches!(f.kind, PaintKind::Image(_))) } fn crop(s: &mut Session, p: &Value) -> Result { @@ -195,17 +196,17 @@ fn crop(s: &mut Session, p: &Value) -> Result { // A selection with nothing to crop is refused as unavailable, not as bad input. let refuse = |why: &str| EngineError::Disabled(cmd.into(), why.into()); let [id] = ids[..] else { return Err(refuse("select one layer to crop its image")) }; - // A text's fills are its characters' (the Design panel's rows): the crop edits that list. - if crate::cmd::lists::has_character_fills(s.doc()?.get(id)?) { - crate::cmd::lists::take_character_fills(s.doc_mut()?.get_mut(id)?); - } let doc = s.doc()?; let n = doc.get(id)?; + // A text's fills are its characters' (the Design panel's rows): the crop edits that list, and + // characters coloured differently have no row to crop ("Click + to replace mixed content"). + let shown = + crate::cmd::lists::character_fills(n).ok_or_else(|| refuse("the characters have different fills, so there is no one fill to crop"))?; let index = match get(p, "index") { None | Some(Value::Null) => top_image_fill(n).ok_or_else(|| refuse("the layer has no image fill to crop"))?, Some(_) => req_index(cmd, p, "index")?, }; - let mut paint = n.fills.get(index).cloned().ok_or_else(|| bad(cmd, "no fill at that index"))?; + let mut paint = shown.get(index).cloned().ok_or_else(|| bad(cmd, "no fill at that index"))?; let PaintKind::Image(img) = &mut paint.kind else { return Err(bad(cmd, "that fill is not an image")) }; // An image already in Crop mode only enters crop mode: no edit, no undo step. if img.scale_mode != ImageScaleMode::Crop { @@ -213,6 +214,8 @@ fn crop(s: &mut Session, p: &Value) -> Result { img.crop = Some(img.placement_crop(f64::from(data.width), f64::from(data.height), n.width, n.height)); img.scale_mode = ImageScaleMode::Crop; let n = s.doc_mut()?.get_mut(id)?; + // The characters' shared list becomes the layer's, so the crop shows on every one of them. + crate::cmd::lists::take_character_fills(n); if let Some(f) = n.fills.get_mut(index) { *f = paint; } diff --git a/crates/engine/src/text_fill_tests.rs b/crates/engine/src/text_fill_tests.rs index 3e77b47d8..348fcc9e7 100644 --- a/crates/engine/src/text_fill_tests.rs +++ b/crates/engine/src/text_fill_tests.rs @@ -69,6 +69,16 @@ fn a_layer_fill_edit_reaches_every_character() { s.execute("text.style", &json!({"id": t, "start": 1, "end": 5, "textFills": ["#FFFF00"]})).unwrap(); s.execute("fill.remove", &json!({"ids": [t], "index": 7})).unwrap(); assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "nothing removed, nothing taken"); + // Characters coloured differently show no fill rows at all: a removal with or without an + // index leaves the layer's hidden fill and the characters' own alone, and there is no row to + // crop (the command is unavailable, as the menu has it). + s.execute("fill.remove", &json!({"ids": [t], "index": 0})).unwrap(); + s.execute("fill.remove", &json!({"ids": [t]})).unwrap(); + assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "mixed: nothing to remove"); + assert_eq!(node(&s).fills.len(), 1, "the layer's own fill stays"); + assert!(matches!(s.execute("image.crop", &json!({"ids": [t]})), Err(crate::EngineError::Disabled(..))), "mixed: nothing to crop"); + assert_eq!(fills_shown(&s, t), ["123456", "FFFF00", "FFFF00", "FFFF00", "FFFF00"], "and nothing taken"); + assert_eq!(crate::cmd::image::top_image_fill(&node(&s)), None, "the menu finds no image to crop either"); s.execute("text.style", &json!({"id": t, "start": 0, "end": 5, "textFills": ["#00FF00"]})).unwrap(); s.execute("fill.copy", &json!({"id": t})).unwrap(); let copied = s.clipboard.paint.clone().and_then(|(_, p)| p.solid_color()).map(|c| c.to_hex()); From 367f188b348f0e575b30b804665d3451c416839b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 04:39:07 -0500 Subject: [PATCH 102/326] M6: the arrows show and move a placement crosshair with a shape or frame tool chosen, and Enter places there (#1839) Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/tools.rs | 4 ++ crates/engine/src/canvas/tools/keys.rs | 15 +++++++- crates/engine/src/canvas/tools/pointer.rs | 1 + crates/engine/src/cmd/view.rs | 25 ++++++++++++ crates/engine/src/keymap.rs | 1 + crates/engine/src/lib.rs | 2 + crates/engine/src/place_crosshair_tests.rs | 45 ++++++++++++++++++++++ crates/ui-egui/locales/en.toml | 1 + crates/ui-egui/src/canvas/overlays.rs | 13 +++++++ crates/ui-egui/src/control.rs | 6 +++ crates/ui-egui/src/shortcut_keys_tests.rs | 22 +++++++++++ crates/ui-egui/src/shortcuts.rs | 6 ++- docs/ui-parity.md | 5 ++- 13 files changed, 141 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/place_crosshair_tests.rs diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index c68276fd3..cf8fb30b4 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -589,6 +589,10 @@ pub struct ToolState { pub picked: Option, /// The widget layers whose hover styles show while the pointer is over them (a live preview). pub(crate) widget_hover: Vec, + /// The placement crosshair: where Enter puts the next shape or frame once the arrows have + /// shown it (in the middle of the view) and moved it (`tool.crosshair`), in page coordinates. + /// Placing, Escape and a tool change take it away. + pub place_at: Option, } impl ToolState { diff --git a/crates/engine/src/canvas/tools/keys.rs b/crates/engine/src/canvas/tools/keys.rs index 21606b222..4f4d58915 100644 --- a/crates/engine/src/canvas/tools/keys.rs +++ b/crates/engine/src/canvas/tools/keys.rs @@ -84,8 +84,11 @@ impl Session { if self.tool.busy() { return refuse("finish the drag first"); } + // The crosshair the arrows moved goes with the placement, which lands on it when no point + // is given. + let crosshair = self.tool.place_at.take(); let v = &self.ds()?.view; - let (c, zoom) = (at.unwrap_or(Point::new(v.cx, v.cy)), v.zoom); + let (c, zoom) = (at.or(crosshair).unwrap_or(Point::new(v.cx, v.cy)), v.zoom); let (w, h) = tool.click_size(); let ev = |kind| PointerEvent::at(kind, c.x - w / 2.0, c.y - h / 2.0, zoom); let r = self.pointer(&ev(PointerKind::Down)).and_then(|()| self.pointer(&ev(PointerKind::Up))); @@ -111,6 +114,13 @@ impl Session { self.tool.overlay = Overlay::default(); return self.cancel_interaction(); } + // The placement crosshair goes first; the tool stays. + if self.tool.place_at.take().is_some() { + if let Ok(ds) = self.ds_mut() { + ds.revision += 1; + } + return Ok(()); + } if self.end_origin_edit() { return Ok(()); } @@ -174,6 +184,7 @@ impl Session { /// Snapshot of tool state for the UI / inspect. pub fn tool_info(&self) -> serde_json::Value { let shapes: Vec = self.shape_handles().into_iter().map(|(h, at)| json!({"handle": h, "at": at})).collect(); - json!({"tool": self.tool.tool.id(), "busy": self.tool.busy(), "overlay": self.tool.overlay, "arcHandles": self.arc_handles(), "shapeHandles": shapes}) + let crosshair = self.tool.place_at.map(|p| [p.x, p.y]); + json!({"tool": self.tool.tool.id(), "busy": self.tool.busy(), "overlay": self.tool.overlay, "arcHandles": self.arc_handles(), "shapeHandles": shapes, "crosshair": crosshair}) } } diff --git a/crates/engine/src/canvas/tools/pointer.rs b/crates/engine/src/canvas/tools/pointer.rs index 1493604dc..90dc1540b 100644 --- a/crates/engine/src/canvas/tools/pointer.rs +++ b/crates/engine/src/canvas/tools/pointer.rs @@ -79,6 +79,7 @@ impl Session { self.tool.tool = t; self.tool.gesture = Gesture::None; self.tool.pick_only = false; + self.tool.place_at = None; // The tool's cursor shows before the pointer moves. self.tool.overlay = Overlay { builder_remove: self.tool.builder_remove && t == ToolId::ShapeBuilder, cursor: t.cursor(), ..Overlay::default() }; diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 1fc2ef22a..20379a7ba 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -522,6 +522,31 @@ pub fn specs() -> Vec { tool(s, t) } ), + spec!( + "tool.crosshair", + "Move the placement crosshair", + "{dx?, dy? (arrow-key steps, e.g. 1 or -1), big? (the large nudge, like Shift)} — the arrows with a shape or frame tool chosen and nothing selected: the first shows the crosshair in the middle of the view, the next move it by the nudge amount; Enter (`tool.place`) puts the object there", + false, + |s, p| { + if !s.tool.tool.draws_shape() { + return Err(EngineError::Disabled("tool.crosshair".into(), "choose a shape or frame tool first".into())); + } + let step = if boolean(p, "big").unwrap_or(false) { s.prefs.nudge_big } else { s.prefs.nudge_small }; + 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 = &s.ds()?.view; + // "It will appear in the middle of the viewport": the first arrow shows it there. + let at = match s.tool.place_at { + Some(c) => figcraft_geom::Point::new(c.x + dx, c.y + dy), + None => figcraft_geom::Point::new(v.cx, v.cy), + }; + s.tool.place_at = Some(at); + if let Ok(ds) = s.ds_mut() { + ds.revision += 1; + } + Ok(json!({"x": at.x, "y": at.y})) + } + ), spec!( "tool.place", "Place with the tool", diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index a0f0bc4b6..77b6f7efe 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -353,6 +353,7 @@ pub static GESTURES: &[(Group, &str, &str, &str)] = &[ (Tools, "Pan with nothing selected (Shift: farther)", "← ↑ → ↓", "← ↑ → ↓"), (Transform, "Rotate a degree (Shift: 15)", "⌥⌘ ← ↑ → ↓", "Ctrl+Alt+← ↑ → ↓"), (Tools, "Place a shape or frame (its tool chosen)", "↵", "Enter"), + (Tools, "Show and move the placement crosshair (its tool chosen, nothing selected)", "← ↑ → ↓", "← ↑ → ↓"), (Zoom, "Zoom tool: click to zoom in, drag an area", "Hold Z", "Hold Z"), (Zoom, "Zoom tool: zoom out", "Hold ⌥Z", "Hold Alt+Z"), (Zoom, "Zoom around the pointer", "⌘ scroll", "Ctrl+scroll"), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0da532b25..e4bf41d26 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -463,6 +463,8 @@ mod penpot_export_tests; #[cfg(test)] mod pixel_preview_tests; #[cfg(test)] +mod place_crosshair_tests; +#[cfg(test)] mod placed_image_size_tests; #[cfg(test)] mod playground_tests; diff --git a/crates/engine/src/place_crosshair_tests.rs b/crates/engine/src/place_crosshair_tests.rs new file mode 100644 index 000000000..a2aafba10 --- /dev/null +++ b/crates/engine/src/place_crosshair_tests.rs @@ -0,0 +1,45 @@ +//! The placement crosshair: the arrows with a shape or frame tool chosen show it in the middle of +//! the view and move it, and Enter places the object there ("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." / "Use the arrow keys to move the crosshair around the canvas or board, then +//! press Return/Enter to place the object.", Accessibility at Figma, #1839). + +use serde_json::json; + +use crate::Session; + +#[test] +fn the_arrows_show_and_move_the_crosshair_and_enter_places_there() { + let mut s = Session::new(); + s.execute("view.set", &json!({"zoom": 1.0, "cx": 300, "cy": 200})).unwrap(); + assert!(s.execute("tool.crosshair", &json!({"dx": 1})).is_err(), "a shape or frame tool first"); + s.execute("tool.rectangle", &json!({})).unwrap(); + // The first arrow shows the crosshair in the middle of the view, unmoved; the next move it by + // the nudge amounts. + let r = s.execute("tool.crosshair", &json!({"dx": 1, "dy": 0})).unwrap(); + assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(300.0), Some(200.0))); + s.execute("tool.crosshair", &json!({"dx": 1, "dy": 0})).unwrap(); + let r = s.execute("tool.crosshair", &json!({"dx": 0, "dy": -1, "big": true})).unwrap(); + assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(301.0), Some(190.0)), "a nudge, then a big nudge"); + assert_eq!(s.tool_info()["crosshair"], json!([301.0, 190.0])); + let v = &s.ds().unwrap().view; + assert_eq!((v.cx, v.cy), (300.0, 200.0), "the view hasn't panned"); + // Enter: the rectangle is centred on the crosshair, which goes. + let placed = s.execute("tool.place", &json!({})).unwrap(); + let id = crate::params::id_of(&placed["ids"][0]).unwrap(); + let b = s.doc().unwrap().world_bounds(id).unwrap(); + assert_eq!((b.center().x, b.center().y), (301.0, 190.0)); + assert_eq!(s.tool.place_at, None); + assert!(s.tool_info()["crosshair"].is_null()); + // Escape takes a shown crosshair away before anything else, the tool staying; a tool change + // takes it away too. + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({})).unwrap(); + assert!(s.tool.place_at.is_some()); + s.escape().unwrap(); + assert_eq!((s.tool.place_at, s.tool.tool), (None, crate::ToolId::Rectangle)); + s.execute("tool.crosshair", &json!({})).unwrap(); + s.execute("tool.ellipse", &json!({})).unwrap(); + assert_eq!(s.tool.place_at, None); +} diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index c44635a2a..89cee56eb 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1073,6 +1073,7 @@ name = "English" "Pages: {pages}" = "Pages: {pages}" "Paint bucket" = "Paint bucket" "Pan the canvas" = "Pan the canvas" +"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Show and move the placement crosshair (its tool chosen, nothing selected)" "Pan with nothing selected (Shift: farther)" = "Pan with nothing selected (Shift: farther)" "Panels" = "Panels" "Paper" = "Paper" diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 483a180b9..efdf3ad63 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -145,6 +145,7 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec } // Pen path. pen_overlay(app, painter, zoom); + crosshair_overlay(app, painter); // Eraser brush (vector edit mode). if let Some([x, y, r]) = ov.brush { let c = app.to_screen(x, y); @@ -416,6 +417,18 @@ fn attach_points(app: &FigApp, painter: &egui::Painter, points: &[([f64; 2], boo } } +/// The placement crosshair the arrows showed and moved: where Enter puts the next shape or frame. +fn crosshair_overlay(app: &FigApp, painter: &egui::Painter) { + let Some(p) = app.session.tool.place_at.filter(|_| app.session.tool.tool.draws_shape()) else { return }; + let c = app.to_screen(p.x, p.y); + let col = accent(painter); + for d in [vec2(1.0, 0.0), vec2(0.0, 1.0)] { + painter.line_segment([c - d * 12.0, c - d * 3.0], stroke(col, 1.5)); + painter.line_segment([c + d * 3.0, c + d * 12.0], stroke(col, 1.5)); + } + painter.circle_stroke(c, 3.0, stroke(col, 1.5)); +} + fn pen_overlay(app: &FigApp, painter: &egui::Painter, zoom: f64) { let ov = &app.session.tool.overlay; if !ov.pen.is_empty() { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 322d9032c..405d6dfa7 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1004,6 +1004,12 @@ fn ui_key(app: &mut FigApp, ctx: &Context, p: &Value) -> Result { "ArrowUp" => (0, -1), _ => (0, 1), }; + // A shape or frame tool chosen and nothing selected: the arrows show and move the + // placement crosshair, as the window's key path does. + if app.session.selection().is_empty() && app.session.tool.tool.draws_shape() && !app.session.tool.dev_mode && !(m.cmd || m.ctrl || m.alt) + { + return app.session.execute("tool.crosshair", &json!({"dx": dx, "dy": dy, "big": m.shift})).map_err(|e| e.to_string()); + } let (cmd, params) = if (m.cmd || m.ctrl) && m.alt { // Rotate a degree, 15 with Shift: down and right clockwise, up and left back, about // the selection's rotation origin; nothing while points are being edited. diff --git a/crates/ui-egui/src/shortcut_keys_tests.rs b/crates/ui-egui/src/shortcut_keys_tests.rs index 6907cac5a..dbe6ab3b9 100644 --- a/crates/ui-egui/src/shortcut_keys_tests.rs +++ b/crates/ui-egui/src/shortcut_keys_tests.rs @@ -54,6 +54,28 @@ fn arrows_pan_the_view_when_nothing_is_selected() { assert_eq!(u.app.session.doc().unwrap().world_bounds(r).unwrap().x0, 1.0); } +/// With a shape or frame tool chosen and nothing selected, the arrows show the placement crosshair +/// in the middle of the view and move it (Shift: the large nudge) instead of panning, and Enter +/// places the object there (Accessibility at Figma, #1839). +#[test] +fn arrows_show_and_move_the_placement_crosshair_with_a_shape_tool() { + let mut u = Ui::new(Session::new()); + u.app.run("select.set", json!({"ids": []})); + u.app.run("view.set", json!({"zoom": 2.0, "cx": 100, "cy": 50})); + u.app.run("tool.rectangle", json!({})); + press(&mut u, Key::ArrowRight, Modifiers::NONE); + assert_eq!(view(&u), (100.0, 50.0, 2.0), "no pan: the crosshair shows instead"); + assert_eq!(u.app.session.tool.place_at.map(|p| (p.x, p.y)), Some((100.0, 50.0)), "in the middle of the view"); + press(&mut u, Key::ArrowDown, Modifiers::SHIFT); + assert_eq!(u.app.session.tool.place_at.map(|p| (p.x, p.y)), Some((100.0, 60.0)), "moved by the large nudge"); + press(&mut u, Key::Enter, Modifiers::NONE); + let sel = u.app.session.selection(); + let b = u.app.session.doc().unwrap().world_bounds(sel[0]).unwrap(); + assert_eq!((b.center().x, b.center().y), (100.0, 60.0), "placed at the crosshair"); + assert!(u.app.session.tool.place_at.is_none(), "which goes with the placement"); + assert_eq!(view(&u), (100.0, 50.0, 2.0)); +} + #[test] fn keyboard_box_selection_key_and_cmd_arrows() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index f44adb68e..5f756e160 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -480,7 +480,11 @@ fn key_event(app: &mut FigApp, key: Key, physical: Option, m: Modifiers, re _ => (0.0, 0.0), }; if (dx, dy) != (0.0, 0.0) { - if app.session.selection().is_empty() { + if app.session.selection().is_empty() && app.session.tool.tool.draws_shape() && !app.session.tool.dev_mode && !m.command && !m.alt { + // A shape or frame tool chosen: the arrows show the placement crosshair in the middle + // of the view and move it; Enter places there (Accessibility at Figma). + app.run("tool.crosshair", json!({"dx": dx, "dy": dy, "big": m.shift})); + } else if app.session.selection().is_empty() { app.run("view.pan", json!({"dx": dx, "dy": dy, "big": m.shift})); } else if crate::menus::dev_mode_refuses(app, "transform.nudge") { // Dev Mode: said so, nothing moves. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3963e4624..87af3f3e3 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-01 · **Change:** minor (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-02 · **Change:** patch (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); 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: @@ -61,7 +61,7 @@ interaction feel not yet compared. | Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation | | 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. No crosshair to move with the arrows first | +| Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | Scale tool (K): handles about an anchor, live factor, panel | done | | @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 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). Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From 56ad0ba14fa299885fcc2bbdd345f13f9f7e2a9a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:08:41 -0500 Subject: [PATCH 103/326] Placement crosshair: kept with its page and document, gone with a pointer placement, kept when the same tool is chosen again Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/tools.rs | 7 ++-- crates/engine/src/canvas/tools/draw.rs | 2 ++ crates/engine/src/canvas/tools/keys.rs | 19 ++++++++--- crates/engine/src/canvas/tools/pointer.rs | 5 ++- crates/engine/src/cmd/view.rs | 13 +++++--- crates/engine/src/place_crosshair_tests.rs | 37 ++++++++++++++++++++++ crates/ui-egui/src/canvas/overlays.rs | 2 +- 7 files changed, 73 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index cf8fb30b4..9bc4bef2a 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -590,9 +590,12 @@ pub struct ToolState { /// The widget layers whose hover styles show while the pointer is over them (a live preview). pub(crate) widget_hover: Vec, /// The placement crosshair: where Enter puts the next shape or frame once the arrows have - /// shown it (in the middle of the view) and moved it (`tool.crosshair`), in page coordinates. - /// Placing, Escape and a tool change take it away. + /// shown it (in the middle of the view) and moved it (`tool.crosshair`), in page coordinates + /// of the document and page in `place_on` (elsewhere it isn't shown: `Session::crosshair`). + /// Placing, Escape and a change of tool take it away. pub place_at: Option, + /// The document (uid) and page the crosshair was shown on. + pub(crate) place_on: Option<(u64, NodeId)>, } impl ToolState { diff --git a/crates/engine/src/canvas/tools/draw.rs b/crates/engine/src/canvas/tools/draw.rs index d59a2b904..7831c6fad 100644 --- a/crates/engine/src/canvas/tools/draw.rs +++ b/crates/engine/src/canvas/tools/draw.rs @@ -209,6 +209,8 @@ impl Session { crate::normalize(ds.doc_mut(), &before); } self.commit_interaction()?; + // A placement by the pointer takes the placement crosshair with it, as Enter does. + self.tool.place_at = None; if !self.prefs.keep_tool { self.set_tool(ToolId::Move); } diff --git a/crates/engine/src/canvas/tools/keys.rs b/crates/engine/src/canvas/tools/keys.rs index 4f4d58915..07a91557b 100644 --- a/crates/engine/src/canvas/tools/keys.rs +++ b/crates/engine/src/canvas/tools/keys.rs @@ -86,7 +86,8 @@ impl Session { } // The crosshair the arrows moved goes with the placement, which lands on it when no point // is given. - let crosshair = self.tool.place_at.take(); + let crosshair = self.crosshair(); + self.tool.place_at = None; let v = &self.ds()?.view; let (c, zoom) = (at.or(crosshair).unwrap_or(Point::new(v.cx, v.cy)), v.zoom); let (w, h) = tool.click_size(); @@ -114,8 +115,11 @@ impl Session { self.tool.overlay = Overlay::default(); return self.cancel_interaction(); } - // The placement crosshair goes first; the tool stays. - if self.tool.place_at.take().is_some() { + // The placement crosshair goes first; the tool stays. One left on another page or + // document goes quietly. + let shown = self.crosshair().is_some(); + self.tool.place_at = None; + if shown { if let Ok(ds) = self.ds_mut() { ds.revision += 1; } @@ -184,7 +188,14 @@ impl Session { /// Snapshot of tool state for the UI / inspect. pub fn tool_info(&self) -> serde_json::Value { let shapes: Vec = self.shape_handles().into_iter().map(|(h, at)| json!({"handle": h, "at": at})).collect(); - let crosshair = self.tool.place_at.map(|p| [p.x, p.y]); + let crosshair = self.crosshair().map(|p| [p.x, p.y]); json!({"tool": self.tool.tool.id(), "busy": self.tool.busy(), "overlay": self.tool.overlay, "arcHandles": self.arc_handles(), "shapeHandles": shapes, "crosshair": crosshair}) } + + /// The placement crosshair, while the document and page it was shown on are the ones in + /// front (`ToolState::place_at`). + pub fn crosshair(&self) -> Option { + let here = self.ds().ok().map(|d| (d.uid, d.page)); + self.tool.place_at.filter(|_| here.is_some() && here == self.tool.place_on) + } } diff --git a/crates/engine/src/canvas/tools/pointer.rs b/crates/engine/src/canvas/tools/pointer.rs index 90dc1540b..5696832ab 100644 --- a/crates/engine/src/canvas/tools/pointer.rs +++ b/crates/engine/src/canvas/tools/pointer.rs @@ -76,10 +76,13 @@ impl Session { if !matches!(t, ToolId::Move | ToolId::Scale | ToolId::Hand) && self.ds().is_ok_and(|d| d.vector_edit.is_some()) { let _ = crate::vectoredit::end(self); } + // The placement crosshair goes with a change of tool, not with the same tool chosen again. + if self.tool.tool != t { + self.tool.place_at = None; + } self.tool.tool = t; self.tool.gesture = Gesture::None; self.tool.pick_only = false; - self.tool.place_at = None; // The tool's cursor shows before the pointer moves. self.tool.overlay = Overlay { builder_remove: self.tool.builder_remove && t == ToolId::ShapeBuilder, cursor: t.cursor(), ..Overlay::default() }; diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 20379a7ba..e2f8d575b 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -534,13 +534,18 @@ pub fn specs() -> Vec { let step = if boolean(p, "big").unwrap_or(false) { s.prefs.nudge_big } else { s.prefs.nudge_small }; 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 = &s.ds()?.view; - // "It will appear in the middle of the viewport": the first arrow shows it there. - let at = match s.tool.place_at { + let (uid, page, centre) = { + let ds = s.ds()?; + (ds.uid, ds.page, figcraft_geom::Point::new(ds.view.cx, ds.view.cy)) + }; + // "It will appear in the middle of the viewport": the first arrow shows it there (a + // crosshair left on another page or document starts over). + let at = match s.crosshair() { Some(c) => figcraft_geom::Point::new(c.x + dx, c.y + dy), - None => figcraft_geom::Point::new(v.cx, v.cy), + None => centre, }; s.tool.place_at = Some(at); + s.tool.place_on = Some((uid, page)); if let Ok(ds) = s.ds_mut() { ds.revision += 1; } diff --git a/crates/engine/src/place_crosshair_tests.rs b/crates/engine/src/place_crosshair_tests.rs index a2aafba10..9bd89dc90 100644 --- a/crates/engine/src/place_crosshair_tests.rs +++ b/crates/engine/src/place_crosshair_tests.rs @@ -7,6 +7,7 @@ use serde_json::json; use crate::Session; +use crate::tools::{PointerEvent, PointerKind}; #[test] fn the_arrows_show_and_move_the_crosshair_and_enter_places_there() { @@ -43,3 +44,39 @@ fn the_arrows_show_and_move_the_crosshair_and_enter_places_there() { s.execute("tool.ellipse", &json!({})).unwrap(); assert_eq!(s.tool.place_at, None); } + +#[test] +fn the_crosshair_keeps_its_page_and_goes_with_a_pointer_placement_but_not_the_same_tool_again() { + let mut s = Session::new(); + s.execute("view.set", &json!({"zoom": 1.0, "cx": 300, "cy": 200})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({"dx": 1})).unwrap(); + s.execute("tool.crosshair", &json!({"dx": 1})).unwrap(); + // The tool already chosen named again keeps the crosshair: `tool.place {tool}` lands on it. + let placed = s.execute("tool.place", &json!({"tool": "rectangle"})).unwrap(); + let id = crate::params::id_of(&placed["ids"][0]).unwrap(); + assert_eq!(s.doc().unwrap().world_bounds(id).unwrap().center().x, 301.0); + // A click places too (the tool kept by the preference) and takes the crosshair with it. + s.prefs.keep_tool = true; + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({})).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Down, 600.0, 600.0, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Up, 600.0, 600.0, 1.0)).unwrap(); + assert_eq!((s.tool.tool, s.tool.place_at), (crate::ToolId::Rectangle, None), "placed by the pointer: the crosshair goes, the tool stays"); + // Another page in front: the crosshair shown on the first isn't there, Escape has nothing to + // take, and the next arrow starts over in the middle of this page's view. + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("tool.crosshair", &json!({"dx": 5})).unwrap(); + s.execute("page.add", &json!({})).unwrap(); + s.execute("page.select", &json!({"index": 1})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + assert_eq!(s.crosshair(), None); + assert!(s.tool_info()["crosshair"].is_null()); + s.escape().unwrap(); + assert_eq!(s.tool.tool, crate::ToolId::Move, "Escape went on to the tool"); + s.execute("tool.rectangle", &json!({})).unwrap(); + let r = s.execute("tool.crosshair", &json!({"dx": 1})).unwrap(); + let v = &s.ds().unwrap().view; + assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(v.cx), Some(v.cy)), "shown afresh in the middle of this page's view"); +} diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index efdf3ad63..6079fabfa 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -419,7 +419,7 @@ fn attach_points(app: &FigApp, painter: &egui::Painter, points: &[([f64; 2], boo /// The placement crosshair the arrows showed and moved: where Enter puts the next shape or frame. fn crosshair_overlay(app: &FigApp, painter: &egui::Painter) { - let Some(p) = app.session.tool.place_at.filter(|_| app.session.tool.tool.draws_shape()) else { return }; + let Some(p) = app.session.crosshair().filter(|_| app.session.tool.tool.draws_shape()) else { return }; let c = app.to_screen(p.x, p.y); let col = accent(painter); for d in [vec2(1.0, 0.0), vec2(0.0, 1.0)] { From 779a5c982e2888d6487cfb3db5a984ad232cf5b6 Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Mon, 2 Nov 2026 11:29:02 +0100 Subject: [PATCH 104/326] i18n(sv): translate 21 new strings (#1870) Brings the Swedish catalog up to date with upstream main (f9b56936). Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/locales/sv.toml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index 748518fff..1c9cf0ee2 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -13,7 +13,10 @@ name = "Svenska" "({n} warnings: some entries were skipped)" = { one = "({n} varning: vissa poster hoppades över)", other = "({n} varningar: vissa poster hoppades över)" } "+ Create variable" = "+ Skapa variabel" ".fig (experimental)" = ".fig (experimentell)" +"1 year" = "1 år" "1…9, 0" = "1…9, 0" +"30 days" = "30 dagar" +"90 days" = "90 dagar" "@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{bin_added} / −{bin_deleted} binary assets, {first} – {last}" = "@{login}: {prs} PR:er, {commits} commits, +{added} / −{deleted} rader (Δ {delta}), +{bin_added} / −{bin_deleted} binära resurser, {first} – {last}" "A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "En samling i den här filen med dessa lägen och variabler: ange overrides för deras värden per läge och lägg till egna variabler" "A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "Det finns redan en .figcraft-fil med det här namnet. Välj dess fullständiga namn för att bekräfta att den ersätts." @@ -477,6 +480,7 @@ name = "Svenska" "Drop to import" = "Släpp för att importera" "Drop to open" = "Släpp för att öppna" "Drop shadow" = "Slagskugga" +"Drop to use this image" = "Släpp för att använda bilden" "Dual-licensed MIT OR Apache-2.0. Made by the ArtCraft team and community." = "Dubbellicensierad under MIT OR Apache-2.0. Skapad av ArtCraft-teamet och gemenskapen." "Duo" = "Duo" "Duplicate" = "Duplicera" @@ -652,6 +656,7 @@ name = "Svenska" "Help page" = "Hjälpsida" "Here: {names}" = "Här: {names}" "Hidden" = "Dold" +"Hide UI" = "Dölj gränssnitt" "Hide contents" = "Dölj innehåll" "Hide from publishing" = "Dölj vid publicering" "Hide section contents" = "Dölj avsnittets innehåll" @@ -832,6 +837,9 @@ name = "Svenska" "Make slot" = "Gör till plats" "New collection" = "Ny samling" "Nobody shares a file there now." = "Ingen delar någon fil där just nu." +"Past 30 days" = "Senaste 30 dagarna" +"Past 90 days" = "Senaste 90 dagarna" +"Past year" = "Senaste året" "Pasted design layers" = "Inklistrade designlager" "Pasted design layers; the clipboard didn't carry the images of: {layers}" = "Designlager inklistrade; urklippet innehöll inte bilderna för: {layers}" "Remove these results from the file" = "Ta bort de här resultaten från filen" @@ -977,6 +985,7 @@ name = "Svenska" "Not read yet" = "Inte läst än" "Not shared" = "Inte delad" "Note {n}" = "Anteckning {n}" +"Nothing counted yet" = "Inget har räknats ännu" "Nothing changed since this version." = "Ingenting har ändrats sedan den här versionen." "Nothing changed since this was marked ready for dev." = "Inget har ändrats sedan detta markerades som klart för utveckling." "Nothing here yet. Set a frame's status to list it." = "Inget här än. Ange en frames status för att lista den." @@ -985,6 +994,9 @@ name = "Svenska" "Nov" = "nov" "Now" = "Nu" "Nudge (Shift: big nudge)" = "Flytta stegvis (Shift: stort steg)" +"Rotate a degree (Shift: 15)" = "Rotera en grad (Shift: 15)" +"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓" +"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓" "Nudge amount" = "Steglängd" "Number" = "Nummer" "Number ↑" = "Nummer ↑" @@ -1179,6 +1191,7 @@ name = "Svenska" "Remove" = "Ta bort" "Remove all" = "Ta bort alla" "Remove annotation" = "Ta bort anteckning" +"Remove all auto layout" = "Ta bort all auto layout" "Remove auto layout" = "Ta bort auto layout" "Remove column" = "Ta bort kolumn" "Remove dev resource" = "Ta bort utvecklarresurs" @@ -1309,8 +1322,11 @@ name = "Svenska" "Search files and templates" = "Sök efter filer och mallar" "Search results" = "Sökresultat" "Search fonts" = "Sök typsnitt" +"This server doesn't count insertions" = "Den här servern räknar inte infogningar" +"This server doesn't count styles and variables" = "Den här servern räknar inte stilar och variabler" "Someone who left" = "Någon som har lämnat" "Take the results off the board; they stay in the file" = "Ta bort resultaten från tavlan; de finns kvar i filen" +"Upload from computer" = "Ladda upp från datorn" "Use fonts installed on this computer…" = "Använd typsnitt som är installerade på den här datorn…" "Search layers" = "Sök lager" "Search pages" = "Sök sidor" @@ -1373,6 +1389,7 @@ name = "Svenska" "Show device frame" = "Visa enhetsram" "Show dimensions on objects" = "Visa dimensioner på objekt" "Show hotspot hints" = "Visa tips om aktiva punkter" +"The bars are hidden. {shortcut} shows them again" = "Fälten är dolda. {shortcut} visar dem igen" "Show in Explorer" = "Visa i Utforskaren" "Show in Finder" = "Visa i Finder" "Show in folder" = "Visa i mapp" @@ -1864,6 +1881,7 @@ name = "Svenska" "video triggers are not supported and were skipped" = "videoutlösare stöds inte och hoppades över" "yesterday" = "i går" "{count} in it now · Changed {date}" = "{count} i den nu · Ändrad {date}" +"{insertions} · {detachments}" = "{insertions} · {detachments}" "{instances} in {files}" = "{instances} i {files}" "{language}: draft translation, waiting for a native speaker's review." = "{language}: utkast till översättning, väntar på granskning av en modersmålstalare." "{length} bleed" = "{length} utfall" @@ -1902,6 +1920,7 @@ name = "Svenska" "{n} detached" = { one = "{n} bortkopplad", other = "{n} bortkopplade" } "{n} files" = { one = "{n} fil", other = "{n} filer" } "{n} hours ago" = { one = "för {n} timme sedan", other = "för {n} timmar sedan" } +"{n} inserted" = { one = "{n} infogad", other = "{n} infogade" } "{n} instances" = { one = "{n} instans", other = "{n} instanser" } "{n} layers" = { one = "{n} lager", other = "{n} lager" } "{n} layers as one file" = { one = "{n} lager som en fil", other = "{n} lager som en fil" } @@ -1932,6 +1951,7 @@ name = "Svenska" "{n}w" = "{n} v" "{page}, nothing selected" = "{page}, inget markerat" "{percent}%" = "{percent} %" +"{period}: {counts}" = "{period}: {counts}" "{profile} (current)" = "{profile} (aktuell)" "{property} is its value; {property ? \"a\" : \"b\"} picks a string. Other {…} stays as written." = "{property} är dess värde; {property ? \"a\" : \"b\"} väljer en sträng. Andra {…} lämnas som de är skrivna." "{server} can't say what became of your files (it is older than this app)." = "{server} kan inte säga vad som hände med dina filer (den är äldre än den här appen)." @@ -1939,6 +1959,7 @@ name = "Svenska" "{server} · {shared} · Opened {date}" = "{server} · {shared} · Öppnad {date}" "{tool} hold {key}" = "{tool} håll ned {key}" "{used} · {detached}" = "{used} · {detached}" +"{used} · {inserted}" = "{used} · {inserted}" "{value} isn't a colour" = "{value} är inte en färg" "{when} · edited" = "{when} · ändrad" "← ↑ → ↓" = "← ↑ → ↓" From ebe60a4924a09bcc1ee3e5b5ec3a12d400cee9c6 Mon Sep 17 00:00:00 2001 From: Jonas <124611557+MrChocolate12@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:29:12 +0100 Subject: [PATCH 105/326] Complete German translation (192 missing entries) (#1863) I completed all missing translations and checked them in de.toml. Co-authored-by: Brandon Thomas --- crates/ui-egui/locales/de.toml | 192 +++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index e6d13bbea..b088b2d32 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -1781,6 +1781,198 @@ status = "draft — needs native review" "⌘ click" = "⌘ Klick" "⌘ scroll" = "⌘ Scrollen" "⌥ drag" = "⌥ Ziehen" +"1 year" = "1 Jahr" +"30 days" = "30 Tage" +"90 days" = "90 Tage" +"A responsive product page: hero, features, figures, a quote and a footer" = "Eine responsive Produktseite: Hero-Bereich, Funktionen, Kennzahlen, ein Zitat und eine Fußzeile" +"A title, an agenda, a big figure, a chart and a closing slide" = "Ein Titel, eine Agenda, eine große Kennzahl, ein Diagramm und eine Abschlussfolie" +"A to Z" = "A bis Z" +"All the fonts this file uses are installed" = "Alle Schriften dieser Datei sind installiert" +"Allow and download" = "Erlauben und herunterladen" +"Allow downloading fonts?" = "Herunterladen von Schriften erlauben?" +"Alphabetical" = "Alphabetisch" +"An analytics screen on a grid: figures, charts drawn from vectors and a table" = "Ein Analytics-Bildschirm auf einem Raster: Kennzahlen, aus Vektoren gezeichnete Diagramme und eine Tabelle" +"Android Vector Drawable" = "Android Vector Drawable" +"Apps" = "Apps" +"Apr" = "Apr." +"Aug" = "Aug." +"Best effort" = "Bestmöglich" +"Board grid" = "Boardraster" +"Bottom padding" = "Innenabstand unten" +"Bound to {name}. Click to detach the variable." = "An {name} gebunden. Klicken Sie, um die Variable zu lösen." +"Check for Updates" = "Nach Updates suchen" +"Check for updates…" = "Nach Updates suchen…" +"Checking the fonts installed on this computer…" = "Auf diesem Computer installierte Schriften werden geprüft…" +"Colour and text styles, Light and Dark variables, buttons, inputs and cards" = "Farb- und Textstile, Variablen für Hell und Dunkel, Buttons, Eingabefelder und Karten" +"Compatibility" = "Kompatibilität" +"Convert to frame" = "In Rahmen umwandeln" +"Convert to section" = "In Abschnitt umwandeln" +"Dart constants for Flutter…" = "Dart-Konstanten für Flutter…" +"Calculated from other variables; it follows them" = "Aus anderen Variablen berechnet; folgt ihnen" +"Copied comments for AI" = "Kommentare für KI kopiert" +"Copy effect" = "Effekt kopieren" +"Copy fill" = "Füllung kopieren" +"Copy for AI" = "Für KI kopieren" +"Copy stroke" = "Kontur kopieren" +"Couldn't download {name}" = "{name} konnte nicht heruntergeladen werden" +"Created" = "Erstellt" +"Crop image" = "Bild zuschneiden" +"Dashboard" = "Dashboard" +"Date created" = "Erstellungsdatum" +"Dec" = "Dez." +"Design system starter" = "Designsystem-Starter" +"Detach calculation" = "Berechnung lösen" +"Don't show this again" = "Nicht mehr anzeigen" +"Download" = "Herunterladen" +"Downloading… {percent}%" = "Wird heruntergeladen… {percent} %" +"Draw a frame" = "Rahmen zeichnen" +"Drop to use this image" = "Loslassen, um dieses Bild zu verwenden" +"Edited {when}" = "Bearbeitet {when}" +"Exact only" = "Nur exakt" +"Export frames and layers as PNG, JPG, SVG or PDF" = "Rahmen und Ebenen als PNG, JPG, SVG oder PDF exportieren" +"Exported {name}; {n} kinds of content were changed or left out" = { one = "{name} exportiert; {n} Inhaltsart wurde geändert oder ausgelassen", other = "{name} exportiert; {n} Inhaltsarten wurden geändert oder ausgelassen" } +"Exported {n} files; some content was changed or left out" = { one = "{n} Datei exportiert; einige Inhalte wurden geändert oder ausgelassen", other = "{n} Dateien exportiert; einige Inhalte wurden geändert oder ausgelassen" } +"Feb" = "Feb." +"FigCraft stopped because of an internal error." = "FigCraft wurde wegen eines internen Fehlers beendet." +"File not found" = "Datei nicht gefunden" +"Format" = "Format" +"Four screens of a trail app with components and a prototype flow" = "Vier Bildschirme einer Wander-App mit Komponenten und einem Prototyp-Ablauf" +"Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "Kostenlose Schriften stammen von Google Fonts und Noto und werden über jsDelivr und GitHub geladen. Jede Datei wird anhand des Schriftenindex geprüft, bevor sie in den Schriftenordner installiert wird, den die Craft-Apps gemeinsam nutzen. Nichts wird heruntergeladen, bevor Sie es erlauben." +"Getting started" = "Erste Schritte" +"Graph paper" = "Rasterpapier" +"Greyscale components and two example screens to sketch a flow with" = "Komponenten in Graustufen und zwei Beispielbildschirme, um einen Ablauf zu skizzieren" +"Hide UI" = "Oberfläche ausblenden" +"Hide these tips (Getting started in the Help menu shows them again)" = "Diese Tipps ausblenden („Erste Schritte“ im Hilfemenü zeigt sie wieder an)" +"Hide when publishing" = "Beim Veröffentlichen ausblenden" +"Icon components on a 24 px grid with keylines and a size preview" = "Icon-Komponenten auf einem 24-px-Raster mit Keylines und einer Größenvorschau" +"Icon set starter" = "Icon-Set-Starter" +"Ignore unsupported" = "Nicht unterstützte ignorieren" +"Individual padding" = "Einzelne Innenabstände" +"Interface size" = "Größe der Oberfläche" +"Jan" = "Jan." +"Joining live session…" = "Live-Sitzung wird beigetreten…" +"Jul" = "Jul." +"Jun" = "Jun." +"Kits" = "Kits" +"Landing page" = "Landingpage" +"Last modified" = "Zuletzt geändert" +"Leaving the prototype" = "Prototyp wird verlassen" +"Left padding" = "Innenabstand links" +"Link frames on the Prototype tab, then present the flow" = "Verknüpfen Sie Rahmen im Tab „Prototyp“ und präsentieren Sie dann den Ablauf" +"Make a component" = "Komponente erstellen" +"Past 30 days" = "Letzte 30 Tage" +"Past 90 days" = "Letzte 90 Tage" +"Past year" = "Letztes Jahr" +"Mar" = "Mär." +"May" = "Mai" +"Missing fonts" = "Fehlende Schriften" +"Mobile app" = "Mobile App" +"Newest first" = "Neueste zuerst" +"No comments to copy" = "Keine Kommentare zum Kopieren" +"No files or templates match your search" = "Keine Dateien oder Vorlagen passen zu Ihrer Suche" +"No other pages" = "Keine weiteren Seiten" +"No templates match your search" = "Keine Vorlagen passen zu Ihrer Suche" +"Not now" = "Nicht jetzt" +"Nothing counted yet" = "Noch nichts gezählt" +"Nov" = "Nov." +"Rotate a degree (Shift: 15)" = "Um ein Grad drehen (Umschalt: 15)" +"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓" +"Ctrl+Alt+← ↑ → ↓" = "Strg+Alt+← ↑ → ↓" +"Oct" = "Okt." +"Oldest first" = "Älteste zuerst" +"One announcement in five common sizes: square, portrait, story, link and banner" = "Eine Ankündigung in fünf gängigen Größen: Quadrat, Hochformat, Story, Link und Banner" +"Order" = "Reihenfolge" +"Other" = "Sonstige" +"Paste effect" = "Effekt einfügen" +"Paste fill" = "Füllung einfügen" +"Paste stroke" = "Kontur einfügen" +"Pick the Frame tool, then drag on the canvas or choose a device size" = "Wählen Sie das Rahmen-Werkzeug und ziehen Sie auf der Arbeitsfläche oder wählen Sie eine Gerätegröße" +"Plugin" = "Plugin" +"Plugins & widgets" = "Plugins & Widgets" +"Presentation slides" = "Präsentationsfolien" +"Playground" = "Testumgebung" +"Relative to your system's display scaling (100% is the system's own size). Document zoom is separate." = "Relativ zur Anzeigeskalierung Ihres Systems (100 % ist die Größe des Systems). Der Dokumentzoom ist davon unabhängig." +"Reload the page to get back the unsaved files the browser had room for." = "Laden Sie die Seite neu, um die ungespeicherten Dateien zurückzuerhalten, für die der Browser Platz hatte." +"Reload the page to get your unsaved files back." = "Laden Sie die Seite neu, um Ihre ungespeicherten Dateien zurückzuerhalten." +"Reload the page to start again." = "Laden Sie die Seite neu, um von vorn zu beginnen." +"Remove all auto layout" = "Gesamtes Auto-Layout entfernen" +"Remove from recents" = "Aus „Zuletzt verwendet“ entfernen" +"Reorder selection" = "Auswahl neu anordnen" +"Reset grid" = "Raster zurücksetzen" +"Right padding" = "Innenabstand rechts" +"Search templates" = "Vorlagen suchen" +"See all templates" = "Alle Vorlagen ansehen" +"Select layers and they space themselves as their content changes" = "Wählen Sie Ebenen aus, und ihre Abstände passen sich an, wenn sich der Inhalt ändert" +"Search files and templates" = "Dateien und Vorlagen suchen" +"Search results" = "Suchergebnisse" +"This server doesn't count insertions" = "Dieser Server zählt keine Einfügungen" +"This server doesn't count styles and variables" = "Dieser Server zählt keine Stile und Variablen" +"Upload from computer" = "Vom Computer hochladen" +"Search pages" = "Seiten suchen" +"Sep" = "Sep." +"Server key" = "Serverschlüssel" +"Set corner smoothing to 60%" = "Eckenglättung auf 60 % setzen" +"Share with a code" = "Mit einem Code teilen" +"Show all templates" = "Alle Vorlagen anzeigen" +"The bars are hidden. {shortcut} shows them again" = "Die Leisten sind ausgeblendet. {shortcut} blendet sie wieder ein" +"Show in Explorer" = "Im Explorer anzeigen" +"Show in Finder" = "Im Finder anzeigen" +"Show in folder" = "Im Ordner anzeigen" +"Social and slides" = "Social Media und Folien" +"Social post sizes" = "Größen für Social-Media-Beiträge" +"Sort by" = "Sortieren nach" +"Sort by {column}" = "Nach {column} sortieren" +"Start from a template" = "Mit einer Vorlage beginnen" +"Start sharing with the Share button, then pass on the code it gives" = "Starten Sie das Teilen mit der Schaltfläche „Teilen“ und geben Sie dann den angezeigten Code weiter" +"Strong line every" = "Starke Linie alle" +"Text on a path" = "Text auf Pfad" +"The window is too small for {size}%, so the interface is drawn at {drawn}%. Make the window larger to use {size}%." = "Das Fenster ist zu klein für {size} %, daher wird die Oberfläche mit {drawn} % dargestellt. Vergrößern Sie das Fenster, um {size} % zu verwenden." +"This file is too large to join here (up to {mb} MB)" = "Diese Datei ist zu groß, um hier beizutreten (bis zu {mb} MB)" +"This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Diese Datei verwendet Schriften, die auf diesem Computer nicht installiert sind. Ihr Text wird in einer Ersatzschrift dargestellt, bis Sie sie installieren." +"This link opens a website outside the prototype:" = "Dieser Link öffnet eine Website außerhalb des Prototyps:" +"This link opens your mail app to write a message:" = "Dieser Link öffnet Ihre Mail-App, um eine Nachricht zu schreiben:" +"This server doesn't count detached instances" = "Dieser Server zählt keine gelösten Instanzen" +"Top padding" = "Innenabstand oben" +"Try another search, or browse templates." = "Versuchen Sie eine andere Suche oder stöbern Sie in den Vorlagen." +"Try another word, or look at every kind." = "Versuchen Sie ein anderes Wort oder sehen Sie sich alle Arten an." +"Turn a layer into a component, reuse it, and change every copy at once" = "Wandeln Sie eine Ebene in eine Komponente um, verwenden Sie sie wieder und ändern Sie alle Kopien auf einmal" +"Update check is not supported in the web browser." = "Die Update-Suche wird im Webbrowser nicht unterstützt." +"Use your browser's zoom to change the interface size." = "Ändern Sie die Größe der Oberfläche mit dem Zoom Ihres Browsers." +"Uses variables: each layer shows them in its own mode" = "Verwendet Variablen: Jede Ebene zeigt sie in ihrem eigenen Modus" +"Websites" = "Websites" +"What you try here changes this preview and the code below, not the file" = "Was Sie hier ausprobieren, ändert diese Vorschau und den Code darunter, nicht die Datei" +"Widget" = "Widget" +"Wireframe kit" = "Wireframe-Kit" +"Your unsaved files were too large for the browser to keep." = "Ihre ungespeicherten Dateien waren zu groß, als dass der Browser sie behalten konnte." +"Z to A" = "Z bis A" +"connector labels without a saved snapshot are centred on the line, without their background" = "Verbinder-Beschriftungen ohne gespeicherten Schnappschuss werden mittig auf der Linie und ohne Hintergrund dargestellt" +"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "Abgewinkelte und gebogene Verbinder ohne gespeicherten Pfad folgen dem eigenen Routing von FigCraft" +"instance swap properties whose default component was past the layer limit were skipped" = "Instanztausch-Eigenschaften, deren Standardkomponente über dem Ebenenlimit lag, wurden übersprungen" +"instances whose component was past the layer limit were imported as frames" = "Instanzen, deren Komponente über dem Ebenenlimit lag, wurden als Rahmen importiert" +"invalid vector region fill paint list; layer fill used" = "Ungültige Füllungsliste der Vektorregion; Füllung der Ebene verwendet" +"invalid vector region paints were skipped" = "Ungültige Füllungen der Vektorregion wurden übersprungen" +"just now" = "gerade eben" +"linked vector region fill styles keep resolved appearance; live style links were left out" = "Verknüpfte Füllstile von Vektorregionen behalten ihr aufgelöstes Aussehen; Live-Stilverknüpfungen wurden ausgelassen" +"note or shape generated child has invalid bounds; child skipped" = "Vom Notiz- oder Formgenerator erzeugtes Kindobjekt hat ungültige Grenzen; Kindobjekt übersprungen" +"note or shape generated child is missing its style or bounds; child skipped" = "Dem vom Notiz- oder Formgenerator erzeugten Kindobjekt fehlen Stil oder Grenzen; Kindobjekt übersprungen" +"note or shape generated children exceed the layer or nesting limit; remaining children skipped" = "Vom Notiz- oder Formgenerator erzeugte Kindobjekte überschreiten das Ebenen- oder Verschachtelungslimit; übrige Kindobjekte übersprungen" +"note or shape generated layout is missing or unsupported; using its outer frame" = "Das vom Notiz- oder Formgenerator erzeugte Layout fehlt oder wird nicht unterstützt; äußerer Rahmen verwendet" +"only in a text style or variable" = "nur in einem Textstil oder einer Variable" +"shape generated outline is missing or damaged; using its rectangle" = "Die vom Formgenerator erzeugte Kontur fehlt oder ist beschädigt; Rechteck verwendet" +"slot layers without a matching slot property were imported as frames" = "Slot-Ebenen ohne passende Slot-Eigenschaft wurden als Rahmen importiert" +"variable-bound vector region paints keep resolved appearance; live bindings were left out" = "An Variablen gebundene Füllungen von Vektorregionen behalten ihr aufgelöstes Aussehen; Live-Bindungen wurden ausgelassen" +"vector region paint data exceeded import limits and was skipped" = "Füllungsdaten der Vektorregion überschritten die Importgrenzen und wurden übersprungen" +"vector region references a missing fill style; layer fill used" = "Vektorregion verweist auf einen fehlenden Füllstil; Füllung der Ebene verwendet" +"yesterday" = "gestern" +"{insertions} · {detachments}" = "{insertions} · {detachments}" +"{month} {day}, {year}" = "{day}. {month} {year}" +"{n} detached" = { one = "{n} gelöst", other = "{n} gelöst" } +"{n} inserted" = { one = "{n} eingefügt", other = "{n} eingefügt" } +"{n} text layers" = { one = "{n} Textebene", other = "{n} Textebenen" } +"{percent}%" = "{percent} %" +"{period}: {counts}" = "{period}: {counts}" +"{used} · {detached}" = "{used} · {detached}" +"{used} · {inserted}" = "{used} · {inserted}" [commands] "align.bottom" = "Unten ausrichten" From 5d387bb3b482f749c279af960eec1e9069f63927 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:29:23 -0500 Subject: [PATCH 106/326] M2: fill container children share the free space by their content area, border-box fashion (#1824) (#1861) * M2: fill container children share the free space by their content area, border-box fashion (#1824) Co-Authored-By: Claude Fable 5.1 * Layout: rustfmt's line for the frozen-share closure Co-Authored-By: Claude Fable 5.1 * M2: one doc comment on distribute (review) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/layout/src/lib.rs | 43 +++++++++++++++++++++++-------- crates/layout/src/nested_tests.rs | 42 ++++++++++++++++++++++++++++++ docs/auto-layout-parity.md | 4 ++- 3 files changed, 77 insertions(+), 12 deletions(-) diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index f13339c6f..56f4bf625 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -327,6 +327,10 @@ struct Item { max_main: Option, min_cross: Option, max_cross: Option, + /// The item's own insets along the main axis (an auto layout frame's padding and included + /// inside stroke): fill children share the free space by their content area, border-box + /// fashion, so these come on top of each one's share. + inset_main: f64, /// Baseline alignment: distance from the item's top to its first baseline. baseline: Option, /// Baseline alignment: offset from the line's top (computed per line). @@ -414,6 +418,10 @@ fn flow_items(doc: &Document, kids: &[NodeId], horizontal: bool, hug_main: bool, let (sm, sc) = if horizontal { (cl.sizing_h, cl.sizing_v) } else { (cl.sizing_v, cl.sizing_h) }; let (min_main, max_main, min_cross, max_cross) = if horizontal { (cl.min_w, cl.max_w, cl.min_h, cl.max_h) } else { (cl.min_h, cl.max_h, cl.min_w, cl.max_w) }; + let inset_main = node.layout.as_ref().map_or(0.0, |al| { + let (pt, pr, pb, pl) = insets(node, al); + if horizontal { pl + pr } else { pt + pb } + }); items.push(Item { id: *child, main: if horizontal { w } else { h }, @@ -425,6 +433,7 @@ fn flow_items(doc: &Document, kids: &[NodeId], horizontal: bool, hug_main: bool, max_main, min_cross, max_cross, + inset_main, baseline: None, base_off: 0.0, }); @@ -596,19 +605,31 @@ pub fn layout_frame(doc: &mut Document, frame: NodeId, m: &dyn Measure) { } } -/// Share `free` main-axis space among the fill items `open` like CSS flexbox: each takes an equal -/// share within its min/max; when clamping adds more than it removes, the items held at their min -/// keep it (otherwise those held at their max do) and the rest share what is left again. +/// Share `free` among the fill items `open` by their content areas: each one's own insets (an +/// auto layout frame's padding and included inside stroke) come off the top and go back on its +/// share, so a child with more padding or a thicker inside stroke takes a little more and the +/// content areas come out the same, as in the CSS border-box model ("Figma distributes space +/// amongst fill container children by the children's content area instead of by their size"). +/// Min and max sizes still clamp each item's outer size; the clamped ones are frozen and the rest +/// share what is left, as before. fn distribute(items: &mut [Item], mut open: Vec, free: f64) { let mut free = free.max(0.0); while !open.is_empty() { - let share = free / open.len() as f64; - let sized: Vec<(usize, f64)> = - open.iter().filter_map(|i| items.get(*i).map(|it| (*i, clamp_size(share, it.min_main, it.max_main)))).collect(); - let violation: f64 = sized.iter().map(|(_, v)| v - share).sum(); - let frozen = |v: f64| violation.abs() < 1e-9 || (violation > 0.0 && v > share + 1e-9) || (violation < 0.0 && v < share - 1e-9); - for (i, v) in &sized { - if frozen(*v) + let insets: f64 = open.iter().filter_map(|i| items.get(*i)).map(|it| it.inset_main).sum(); + let content_share = ((free - insets) / open.len() as f64).max(0.0); + let sized: Vec<(usize, f64, f64)> = open + .iter() + .filter_map(|i| { + items.get(*i).map(|it| { + let want = content_share + it.inset_main; + (*i, want, clamp_size(want, it.min_main, it.max_main)) + }) + }) + .collect(); + let violation: f64 = sized.iter().map(|(_, want, v)| v - want).sum(); + let frozen = |want: f64, v: f64| violation.abs() < 1e-9 || (violation > 0.0 && v > want + 1e-9) || (violation < 0.0 && v < want - 1e-9); + for (i, want, v) in &sized { + if frozen(*want, *v) && let Some(it) = items.get_mut(*i) { it.main = *v; @@ -616,7 +637,7 @@ fn distribute(items: &mut [Item], mut open: Vec, free: f64) { } } free = free.max(0.0); - open = sized.into_iter().filter(|(_, v)| !frozen(*v)).map(|(i, _)| i).collect(); + open = sized.into_iter().filter(|(_, want, v)| !frozen(*want, *v)).map(|(i, _, _)| i).collect(); } } diff --git a/crates/layout/src/nested_tests.rs b/crates/layout/src/nested_tests.rs index 4b77b3b94..2a51e282e 100644 --- a/crates/layout/src/nested_tests.rs +++ b/crates/layout/src/nested_tests.rs @@ -287,6 +287,48 @@ fn padding_and_included_strokes() { assert_eq!(pos(&d, c), (15.0, 15.0, 70.0, 20.0)); } +/// "Figma distributes space amongst fill container children by the children's content area +/// instead of by their size, matching the CSS border-box model. A layer with a thicker stroke will +/// take up slightly more of the available width or height, so that its inner content area matches +/// its sibling's." (Use auto layout with CSS Flexbox in mind) +#[test] +fn fill_children_share_by_content_area() { + let mut d = Document::new("t"); + let p = page(&d); + let f = al(&mut d, p, LayoutMode::Horizontal, (200.0, 50.0), (Sizing::Fixed, Sizing::Fixed)); + layout_mut(&mut d, f).gap = 0.0; + let a = al(&mut d, f, LayoutMode::Horizontal, (10.0, 50.0), (Sizing::Fill, Sizing::Fixed)); + let b = al(&mut d, f, LayoutMode::Horizontal, (10.0, 50.0), (Sizing::Fill, Sizing::Fixed)); + layout_mut(&mut d, b).padding = [0.0, 20.0, 0.0, 20.0]; + layout_frame(&mut d, f, &NoMeasure); + // 200 less b's 40 of padding leaves 160 of content, 80 each: a is 80 wide, b 120. + assert_eq!((size(&d, a).0, size(&d, b).0), (80.0, 120.0)); + assert_eq!(pos(&d, b).0, 80.0); + // A 10 px inside stroke counted in b's layout instead: 90 and 110. + layout_mut(&mut d, b).padding = [0.0; 4]; + { + let n = d.get_mut(b).unwrap(); + n.strokes = vec![figcraft_doc::color::Paint::solid(figcraft_doc::color::Color::BLACK)]; + n.stroke.weight = 10.0; + n.stroke.align = StrokeAlign::Inside; + } + layout_mut(&mut d, b).strokes_included = true; + layout_frame(&mut d, f, &NoMeasure); + assert_eq!((size(&d, a).0, size(&d, b).0), (90.0, 110.0)); + // A stroke not counted in the layout is no inset: an even split, as before. + layout_mut(&mut d, b).strokes_included = false; + layout_frame(&mut d, f, &NoMeasure); + assert_eq!((size(&d, a).0, size(&d, b).0), (100.0, 100.0)); + // Equal insets: still even. A max on a freezes it there and b takes the rest, insets kept. + layout_mut(&mut d, a).padding = [0.0, 20.0, 0.0, 20.0]; + layout_mut(&mut d, b).padding = [0.0, 20.0, 0.0, 20.0]; + layout_frame(&mut d, f, &NoMeasure); + assert_eq!((size(&d, a).0, size(&d, b).0), (100.0, 100.0)); + d.get_mut(a).unwrap().child_layout.max_w = Some(60.0); + layout_frame(&mut d, f, &NoMeasure); + assert_eq!((size(&d, a).0, size(&d, b).0), (60.0, 140.0)); +} + #[test] fn grid_hug_tracks_and_wrapping_text_rows() { use figcraft_doc::GridTrack; diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index f481fc7ab..61462a2c1 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (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-02 · **Change:** patch (fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); 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%, @@ -38,6 +38,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Hug: the frame sizes to its children plus padding (the 40 px text + 10 px padding = 60 px example) | pass | `sizing_rules` | | Fixed: the frame keeps its size whatever its children need | pass | `sizing_rules` | | Fill: children share the space left after padding, gaps and fixed siblings; across the flow they stretch | pass | `sizing_rules` | +| Fill children share by their content area (border-box): a child with more padding or a thicker included inside stroke takes a little more, so the content areas come out the same | **fixed** | "Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model. A layer with a thicker stroke will take up slightly more of the available width or height, so that its inner content area matches its sibling's" (Use auto layout with CSS Flexbox in mind); the split went by outer size before. Min and max still clamp the outer size; a child's own insets are its padding and its included inside stroke (`nested_tests::fill_children_share_by_content_area`; #1824) | | Fill on a child turns its hugging parent Fixed on that axis | pass | `al_behaviour_tests::fill_on_a_child_turns_the_hugging_parent_fixed` | | Hug only on auto layout frames (and text); Fill only in an auto layout flow, never on a top-level frame | pass | `al_behaviour_tests::hug_and_fill_only_where_they_apply` | | Min/max width and height bound Hug, Fill and Fixed sizes, on frames and children | pass | `sizing_rules`; a fill child at its max leaves the rest to the other fill children (silent on redistribution: CSS flexbox) | @@ -97,6 +98,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-02 | patch | M2, #1824: fill container children share the free space by their content area: each one's own insets (padding and an included inside stroke, from the same `insets` the frame uses) come off the free space before the equal split and go back on its share, so a child with more padding or a thicker inside stroke takes a little more and the content areas match ("Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model", Use auto layout with CSS Flexbox in mind). Min and max still clamp the outer sizes and the frozen-share loop is as it was; children without insets split as before. Test: `nested_tests::fill_children_share_by_content_area` | | 2026-11-01 | patch | M2: a text layer keeps a max height or a number of max lines, not both ("Text layers cannot have both a max height and a set number of max lines", Guide to auto layout): `node.set {maxHeight}` on a text sets its max lines to Auto, and `node.set {maxLines}` or `text.maxLines` with a number removes its max height. Found by a documentation audit of this page. Test: `text_behaviour_tests::a_text_has_a_max_height_or_max_lines_not_both`. Numbers unchanged | | 2026-11-01 | minor | M2: Remove all auto layout ("To remove auto layout from a frame and all of its nested objects at once, right-click on the frame and go to More layout options > Remove all auto layout", Toggle on auto layout in designs): `layout.removeAll {ids?}` strips the frames and every frame nested in them in one undo step, leaving instances and their layers alone; in the canvas context menu beside Add auto layout and in the Actions palette. Found by a documentation audit of this page. Test: `al_nesting_tests::remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it`. Numbers unchanged | | 2026-10-30 | minor | M8, #1083: grid placement finds free cells on a bitmap, a word at a time, with the same placements; crafted grids of wide children no longer stall a layout pass. Numbers unchanged. | From 33589610334929e5d8a7059e8f2332952e76283a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:29:33 -0500 Subject: [PATCH 107/326] M4: Backspace or Delete at a list item's start keeps its indentation level (#1862) * M4: Backspace or Delete at a list item's start keeps its indentation level Co-Authored-By: Claude Fable 5.1 * Lists: the level is kept by Backspace and Delete alone, and the tests read the text's own glyph Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/doc/src/text.rs | 18 +++++++++-- crates/engine/src/canvas/textedit.rs | 45 +++++++++++++++++++--------- crates/engine/src/text_tail_tests.rs | 22 ++++++++++++++ crates/text/src/behaviour_tests.rs | 32 +++++++++++++++++++- crates/text/src/layout.rs | 12 ++++---- docs/ui-parity.md | 5 ++-- 6 files changed, 110 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 0ba0aeeca..8a7253e9e 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -251,7 +251,10 @@ pub const MAX_LIST_INDENT: u8 = 8; #[serde(default)] pub struct ParaList { pub list: ListStyle, - /// Nesting level (0 = outermost; plain paragraphs are always 0). + /// Nesting level (0 = outermost). A plain paragraph is 0, except one that left its list by + /// Backspace or Delete at its start ([`TextData::unlist_keeping_levels`]): it keeps the level + /// it had and starts where that level's item text does ("delete the counter, but keep the + /// same level of indentation"). pub indent: u8, /// A numbered list that starts counting at this paragraph counts from `start_offset + 1` /// (items that go on counting ignore it; other paragraphs are always 0). @@ -798,11 +801,22 @@ impl TextData { /// paragraphs stay at level 0, only numbered ones keep a start, levels stop at /// [`MAX_LIST_INDENT`]); one style for all with no nesting or start folds back into `list`. pub fn set_para_lists(&mut self, start: usize, end: usize, f: impl Fn(&mut ParaList)) { + self.set_para_lists_with(start, end, false, f); + } + + /// Take the list items among the paragraphs chars `start..end` touch out of their list at the + /// level they had, as Backspace or Delete at an item's start does: "delete the counter, but + /// keep the same level of indentation" (Create bulleted and numbered lists). + pub fn unlist_keeping_levels(&mut self, start: usize, end: usize) { + self.set_para_lists_with(start, end, true, |pl| pl.list = ListStyle::None); + } + + fn set_para_lists_with(&mut self, start: usize, end: usize, keep_levels: bool, f: impl Fn(&mut ParaList)) { let (a, b) = self.para_span(start, end); self.fill_paragraphs(); for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) { f(pl); - if pl.list == ListStyle::None { + if pl.list == ListStyle::None && !keep_levels { pl.indent = 0; } if pl.list != ListStyle::Numbered { diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index d7a70e5c7..368a48c90 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -303,9 +303,21 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result Result { let Some(te) = s.ds()?.text_edit.clone() else { return Ok(false) }; let t = text_of(s, te.id)?; @@ -315,19 +327,24 @@ fn list_key(s: &mut Session, key: &str, shift: bool) -> Result { let item = t.para_list(t.para_of(a)).list != ListStyle::None; let (pa, pb) = t.para_span(a, b); let any_item = (pa..=pb).any(|p| t.para_list(p).list != ListStyle::None); - let deeper = match key { - "Tab" if any_item => !shift, - "Backspace" if item && at_start => false, - "Enter" if item && at_start && chars.get(a).is_none_or(|c| *c == '\n') => false, + let mv = match key { + "Tab" if any_item && !shift => ListMove::Deeper, + "Tab" if any_item => ListMove::Out, + "Backspace" | "Delete" if item && at_start => ListMove::Unlist, + "Enter" if item && at_start && chars.get(a).is_none_or(|c| *c == '\n') => ListMove::Out, _ => return Ok(false), }; edit(s, |t, _| { - t.set_para_lists(a, b, |pl| match pl.list { - ListStyle::None => {} - _ if deeper => pl.indent = pl.indent.saturating_add(1), - _ if pl.indent > 0 => pl.indent -= 1, - _ => pl.list = ListStyle::None, - }) + if mv == ListMove::Unlist { + t.unlist_keeping_levels(a, b); + } else { + t.set_para_lists(a, b, |pl| match (pl.list, mv) { + (ListStyle::None, _) | (_, ListMove::Unlist) => {} + (_, ListMove::Deeper) => pl.indent = pl.indent.saturating_add(1), + (_, ListMove::Out) if pl.indent > 0 => pl.indent -= 1, + (_, ListMove::Out) => pl.list = ListStyle::None, + }); + } })?; Ok(true) } @@ -411,7 +428,7 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R let t = text_of(s, te.id)?; let chars: Vec = t.characters.chars().collect(); let n = chars.len(); - if matches!(key, "Tab" | "Backspace" | "Enter") && !word && !line && list_key(s, key, shift)? { + if matches!(key, "Tab" | "Backspace" | "Delete" | "Enter") && !word && !line && list_key(s, key, shift)? { return Ok(()); } match key { diff --git a/crates/engine/src/text_tail_tests.rs b/crates/engine/src/text_tail_tests.rs index a94852093..8e399ba3a 100644 --- a/crates/engine/src/text_tail_tests.rs +++ b/crates/engine/src/text_tail_tests.rs @@ -129,6 +129,28 @@ fn list_keys_at_list_items() { "silent: Backspace at an item's start removes its bullet", ), ("a\nbc", vec![(B, 0), (B, 0)], 4, "Backspace", false, "a\nb", vec![(B, 0), (B, 0)], "Backspace inside an item deletes text"), + ( + "a\nb", + vec![(B, 0), (B, 1)], + 2, + "Backspace", + false, + "a\nb", + vec![(B, 0), (P, 1)], + "Backspace at a nested item's start removes its bullet and keeps its level", + ), + ("a\nb", vec![(N, 0), (N, 2)], 2, "Delete", false, "a\nb", vec![(N, 0), (P, 2)], "Delete at an item's start does the same"), + ("a\nbc", vec![(B, 0), (B, 1)], 3, "Delete", false, "a\nb", vec![(B, 0), (B, 1)], "Delete inside an item deletes text"), + ( + "a\nb", + vec![(B, 0), (P, 1)], + 2, + "Tab", + false, + "a\n\tb", + vec![(B, 0), (P, 1)], + "a plain paragraph at a level isn't an item: Tab types a tab", + ), ("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb\t", vec![(P, 0), (P, 0)], "outside a list Tab types a tab"), ("a", vec![(B, 8)], 1, "Tab", false, "a", vec![(B, 8)], "silent: nesting stops at 8 levels"), ]; diff --git a/crates/text/src/behaviour_tests.rs b/crates/text/src/behaviour_tests.rs index fe63e3866..439a81fcf 100644 --- a/crates/text/src/behaviour_tests.rs +++ b/crates/text/src/behaviour_tests.rs @@ -9,7 +9,7 @@ use super::*; use crate::breaks::{break_between, grapheme_starts}; -use figcraft_doc::{LeadingTrim, LetterSpacing, LineHeight, TextAlignH, TextAutoResize, TextData, TextDecoration}; +use figcraft_doc::{LeadingTrim, LetterSpacing, LineHeight, ListStyle, ParaList, TextAlignH, TextAutoResize, TextData, TextDecoration}; /// The default face once system fonts are indexed (a Latin face where the system has one, so CJK /// and emoji come from fallback faces), or None (skip) on a machine without fonts. @@ -100,6 +100,36 @@ fn letter_spacing_percent_and_pixels() { } } +/// "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 at a list +/// level starts where that level's item text starts, even once no list is left; a plain +/// paragraph at level 0 starts at the box as always. +#[test] +fn a_plain_paragraph_at_a_list_level_starts_where_the_items_text_does() { + if face().is_none() { + return; + } + let level = |list: ListStyle, indent: u8| ParaList { list, indent, start_offset: 0 }; + let mut t = text("a\nb\nc", TextAutoResize::WidthAndHeight); + t.paragraphs = vec![level(ListStyle::Bulleted, 1), level(ListStyle::None, 1), level(ListStyle::None, 0)]; + let l = layout(&t, None, None); + // Where a line's text starts: its first character's glyph (the indent is in the glyphs); a + // list marker shares that character and sits in the gutter to its left, so the text is the + // rightmost of them. + let text_x = |l: &TextLayout, li: usize| { + l.glyphs.iter().filter(|g| g.char_start == l.lines[li].char_start).map(|g| g.x).fold(f64::NAN, |a, b| if a.is_nan() { b } else { a.max(b) }) + }; + let (x0, x1, x2) = (text_x(&l, 0), text_x(&l, 1), text_x(&l, 2)); + assert!((x1 - x0).abs() < EPS, "the plain paragraph keeps the item's text start: {x1} vs {x0}"); + assert!(x0 > 20.0, "a nested item's text starts two gutters in: {x0}"); + assert!(x2.abs() < EPS, "a level-0 plain paragraph starts at the box: {x2}"); + // No list left at all: the level still indents, by the same gutters. + let mut alone = text("b", TextAutoResize::WidthAndHeight); + alone.paragraphs = vec![level(ListStyle::None, 1)]; + let a = layout(&alone, None, None); + assert!((text_x(&a, 0) - x1).abs() < EPS, "{} vs {x1}", text_x(&a, 0)); +} + #[test] fn paragraph_spacing_and_indent() { if face().is_none() { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 7f5872fdf..51dd6d06b 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -951,10 +951,12 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) // The start indent of a line of paragraph `p` (`first`: its first line, starting at char `ci`). let line_indent_of = |p: usize, first: bool, ci: usize| { let pl = list_of(p); + let level = step * (f64::from(pl.indent) + 1.0) - hang_list; match pl.list { - ListStyle::None if first => indent_at(ci), - ListStyle::None => 0.0, - _ => step * (f64::from(pl.indent) + 1.0) - hang_list, + // A plain paragraph that kept its level on leaving a list starts where that level's + // item text does; paragraph indent goes on its first line as on any plain paragraph. + ListStyle::None => (if pl.indent > 0 { level } else { 0.0 }) + if first { indent_at(ci) } else { 0.0 }, + _ => level, } }; // Hanging punctuation: at the start edge of left-aligned and justified lines, at the end edge @@ -1237,9 +1239,9 @@ fn roman(mut n: usize) -> String { } /// The width of one list level's gutter: room for the widest number plus half an em, at least one -/// and a half ems (0 without lists). +/// and a half ems (0 without lists, or plain paragraphs that kept a list level). fn list_step(lists: &[ParaList], markers: &[String], style: Option<&TextStyle>, face: Option<&Arc>) -> f64 { - if lists.iter().all(|l| l.list == ListStyle::None) { + if lists.iter().all(|l| l.list == ListStyle::None && l.indent == 0) { return 0.0; } let size = style.map(|s| sanitize_size(s.font_size)).unwrap_or(12.0); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3963e4624..b4f3d9023 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-01 · **Change:** minor (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-02 · **Change:** patch (Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; 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: @@ -89,7 +89,7 @@ interaction feel not yet compared. | 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`). 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) | -| Text: point, auto height, fixed; caret, words, lines, IME | done | 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`); 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 | | 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`) | | Comment (C), Shift+C to show/hide | done | local only | | 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 | @@ -176,6 +176,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 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-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From e9eb7ce7f43b298b44233b55eb0dccdf303addb2 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:29:59 -0500 Subject: [PATCH 108/326] M4: max lines on auto-width text keep it auto width, hugging that many lines (#1864) * M4: max lines on auto-width text keep it auto width, hugging that many lines Co-Authored-By: Claude Fable 5.1 * M4: an auto-width text with max lines hugs the ellipsis on its last line, and the editing test expects auto width Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/doc/src/text.rs | 8 +++--- crates/engine/src/canvas/textedit/tests.rs | 2 +- crates/engine/src/cmd/text.rs | 4 +-- crates/engine/src/text_behaviour_tests.rs | 30 +++++++++++++++++++++- crates/text/src/layout.rs | 2 ++ docs/ui-parity.md | 5 ++-- 6 files changed, 42 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 8a7253e9e..0c41d3c9a 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -609,12 +609,14 @@ impl TextData { } /// Whether text that runs out of room ends in an ellipsis: a truncating box, or auto height - /// with a line limit (the box hugs up to `max_lines` lines). + /// or auto width with a line limit (the box hugs up to `max_lines` lines: "Max lines is + /// available only if truncate text is enabled, and: Text resizing is set to auto height or + /// auto width"). pub fn truncates(&self) -> bool { match self.auto_resize { TextAutoResize::Truncate => true, - TextAutoResize::Height => self.max_lines > 0, - TextAutoResize::WidthAndHeight | TextAutoResize::None => false, + TextAutoResize::Height | TextAutoResize::WidthAndHeight => self.max_lines > 0, + TextAutoResize::None => false, } } diff --git a/crates/engine/src/canvas/textedit/tests.rs b/crates/engine/src/canvas/textedit/tests.rs index fecca5808..81756901d 100644 --- a/crates/engine/src/canvas/textedit/tests.rs +++ b/crates/engine/src/canvas/textedit/tests.rs @@ -242,7 +242,7 @@ fn paragraph_and_feature_commands_on_nodes() { s.execute("text.listStyle", &json!({"ids": ids, "style": "bulleted"})).unwrap(); let t = data(&s, id); assert_eq!((t.paragraph_indent, t.paragraph_spacing, t.max_lines), (16.0, 8.0, 2)); - assert_eq!(t.auto_resize, TextAutoResize::Truncate); + assert_eq!(t.auto_resize, TextAutoResize::WidthAndHeight, "max lines keep an auto-width text auto width"); assert_eq!(t.style.decoration, TextDecoration::Strikethrough); assert_eq!(t.style.case, TextCase::SmallCaps); assert_eq!(t.list, ListStyle::Bulleted); diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index b507afd6b..446b01d29 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -319,13 +319,13 @@ pub fn specs() -> Vec { spec!( "text.maxLines", "Max lines", - "{lines (0 = no limit; truncates: auto-height text hugs up to that many lines, other text becomes a truncating box), ids?}", + "{lines (0 = no limit; truncates: auto-height and auto-width text hug up to that many lines, fixed-size text becomes a truncating box), ids?}", true, |s, p| { let v = finite(req_num("text.maxLines", p, "lines")?).clamp(0.0, 10_000.0) as u32; let r = para(s, p, |t| { t.max_lines = v; - if v > 0 && t.auto_resize != TextAutoResize::Height { + if v > 0 && !matches!(t.auto_resize, TextAutoResize::Height | TextAutoResize::WidthAndHeight) { t.auto_resize = TextAutoResize::Truncate; } })?; diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index 9ae7dd62c..ab62136c4 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -365,12 +365,40 @@ fn max_lines_on_auto_height_text_hugs_that_many_lines() { s.execute("node.set", &json!({"id": t, "props": {"maxLines": 1}})).unwrap(); s.execute("node.set", &json!({"id": t, "props": {"height": 30}})).unwrap(); assert_eq!((resize_mode(&s, t), size(&s, t).1), (TextAutoResize::Truncate, 30.0)); - // Other text still becomes a truncating box with max lines. + // Fixed-size text still becomes a truncating box with max lines. let fixed = text(&mut s, "Lorem", json!({"textAutoResize": "none", "width": 100, "height": 100})); s.execute("text.maxLines", &json!({"ids": [fixed], "lines": 2})).unwrap(); assert_eq!(resize_mode(&s, fixed), TextAutoResize::Truncate); } +#[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 + // auto height or auto width" (Explore text properties): an auto-width text with max lines + // stays auto width, growing with its longest line and hugging up to that many lines. + use figcraft_doc::TextAutoResize; + // The synthetic font: every character 8 px wide at 16 px, so the widths are the same + // everywhere and never depend on what the system has installed. + let font = test_mono_font(); + let mut s = Session::new(); + let t = text(&mut s, "one\ntwo\nthree", json!({"fontFamily": font, "fontSize": 16, "lineHeight": 24})); + assert_eq!(resize_mode(&s, t), TextAutoResize::WidthAndHeight); + assert_eq!(size(&s, t), (40.0, 72.0), "three lines tall, as wide as 'three'"); + s.execute("text.maxLines", &json!({"ids": [t], "lines": 2})).unwrap(); + assert_eq!(resize_mode(&s, t), TextAutoResize::WidthAndHeight, "max lines keep auto width"); + assert_eq!(size(&s, t), (32.0, 48.0), "two lines tall, as wide as the widest line it shows with its ellipsis (two…), not the hidden third"); + assert_eq!(crate::inspect::node_json(s.doc().unwrap(), t, 0)["maxLines"], json!(2)); + // Still auto width: a longer line widens the box. + s.execute("text.edit.begin", &json!({"id": t, "caret": 3})).unwrap(); + s.execute("text.edit.insert", &json!({"text": " and a longer line"})).unwrap(); + crate::textedit::end(&mut s).unwrap(); + assert_eq!(size(&s, t), (168.0, 48.0), "the box grew with its longest line (21 characters)"); + assert_eq!(resize_mode(&s, t), TextAutoResize::WidthAndHeight); + // No limit: all of its lines again. + s.execute("node.set", &json!({"id": t, "props": {"maxLines": 0}})).unwrap(); + assert_eq!(size(&s, t).1, 72.0); +} + /// A synthetic monospaced TrueType font (outline-less glyphs, every printable ASCII character 500 of /// 1000 units wide), loaded into the font database so text measures the same on every machine. fn test_mono_font() -> &'static str { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 51dd6d06b..5d3d3c27f 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -798,6 +798,8 @@ fn truncate_layout(out: &mut TextLayout, finish: &LayoutFinish<'_>) { } } add_ellipsis(out, wrap); + // The ellipsis can make the last line the widest: an auto-width box hugs it too. + out.width = out.width.max(out.lines.last().map_or(0.0, |l| l.width)); // Carets and selections reach every char the line shows, borrowed ones included. if let Some(l) = out.lines.last() { let shown = diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b4f3d9023..aa1c4510e 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-02 · **Change:** patch (Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; 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-02 · **Change:** patch (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; 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: @@ -89,7 +89,7 @@ interaction feel not yet compared. | 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`). 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) | -| 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`); 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`); 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 | | 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`) | | Comment (C), Shift+C to show/hide | done | local only | | 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 | @@ -177,6 +177,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| | 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-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From c44cfc94af9c1efa47f3359932245480cfdfaed8 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:30:50 -0500 Subject: [PATCH 109/326] M4: superscript and subscript are synthesised where the font has no glyphs for them (#1828) (#1868) * M4: superscript and subscript are synthesised where the font has no glyphs for them (#1828) Co-Authored-By: Claude Fable 5.1 * Text: a zero OS/2 script offset counts as unset, and the native-glyph check sees the case-mapped characters Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/text_behaviour_tests.rs | 40 ++++++++++ crates/text/src/fontdb.rs | 18 +++++ crates/text/src/layout.rs | 92 +++++++++++++++-------- crates/text/src/tests.rs | 43 +++++++++++ docs/ui-parity.md | 4 +- 5 files changed, 163 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index ab62136c4..bed6b3d6b 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -399,6 +399,46 @@ fn max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines() { assert_eq!(size(&s, t).1, 72.0); } +#[test] +fn superscript_and_subscript_are_synthesised_without_glyphs_for_them() { + // "If it isn't provided, Figma draws a synthesized version by using the font's standard + // version of the character, shrinking it, and positioning it accordingly" (Explore text + // properties). The synthetic font has no sups or subs feature and no OS/2 metrics, so the + // usual 0.65 em at 0.35 em up (superscript) or 0.14 em down (subscript) apply. + let font = test_mono_font(); + let mut s = Session::new(); + let t = text(&mut s, "x2", json!({"fontFamily": font, "fontSize": 40})); + let glyphs = |s: &Session| -> Vec<(f64, f64, f64)> { + let (l, _) = figcraft_text::layout_node(s.doc().unwrap().node(t).unwrap()).unwrap(); + l.glyphs.iter().map(|g| (g.size, g.y, g.advance)).collect() + }; + let plain = glyphs(&s); + assert_eq!(plain.len(), 2); + assert_eq!((plain[0].0, plain[0].2), (40.0, 20.0)); + assert_eq!(size(&s, t).0, 40.0); + s.execute("text.setFeatures", &json!({"ids": [t], "features": {"sups": true}})).unwrap(); + let sup = glyphs(&s); + for (g, p) in sup.iter().zip(&plain) { + assert!((g.0 - 26.0).abs() < 1e-6 && (g.2 - 13.0).abs() < 1e-6, "shrunk to 0.65 em, the advance with it: {g:?}"); + assert!((p.1 - g.1 - 14.0).abs() < 1e-6, "raised 0.35 em: {g:?} against {p:?}"); + } + assert!((size(&s, t).0 - 26.0).abs() < 1e-6, "the auto-width box hugs the smaller glyphs: {:?}", size(&s, t)); + s.execute("text.setFeatures", &json!({"ids": [t], "features": {"sups": null, "subs": true}})).unwrap(); + let sub = glyphs(&s); + for (g, p) in sub.iter().zip(&plain) { + assert!((g.0 - 26.0).abs() < 1e-6 && (g.1 - p.1 - 5.6).abs() < 1e-6, "shrunk, and lowered 0.14 em: {g:?} against {p:?}"); + } + // Capitalised, the same: the synthesis follows the characters shaping saw. + s.execute("node.set", &json!({"id": t, "props": {"textCase": "upper"}})).unwrap(); + s.execute("text.setFeatures", &json!({"ids": [t], "features": {"subs": null, "sups": true}})).unwrap(); + for (g, p) in glyphs(&s).iter().zip(&plain) { + assert!((g.0 - 26.0).abs() < 1e-6 && (p.1 - g.1 - 14.0).abs() < 1e-6, "upper case, superscript: {g:?} against {p:?}"); + } + s.execute("node.set", &json!({"id": t, "props": {"textCase": "original"}})).unwrap(); + s.execute("text.setFeatures", &json!({"ids": [t], "features": {"sups": null, "subs": false}})).unwrap(); + assert_eq!(glyphs(&s), plain, "off again"); +} + /// A synthetic monospaced TrueType font (outline-less glyphs, every printable ASCII character 500 of /// 1000 units wide), loaded into the font database so text measures the same on every machine. fn test_mono_font() -> &'static str { diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 2c6aac948..d0004fcd9 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -102,6 +102,11 @@ pub struct Face { pub underline_pos: f64, pub underline_thickness: f64, pub strike_pos: f64, + /// Synthesised superscript and subscript (the OS/2 table's values, or the usual ones without + /// it): the glyph size as a fraction of the em, and the baseline shift up in font units + /// (negative for a subscript, which sits below). + pub superscript: (f64, f64), + pub subscript: (f64, f64), pub shaper: harfrust::ShaperData, /// OpenType GSUB feature tags the face provides (e.g. `smcp`). gsub_features: Vec<[u8; 4]>, @@ -179,6 +184,17 @@ impl Face { let colr = has_table(b"COLR"); let under = m.underline.map(|d| (f64::from(d.offset), f64::from(d.thickness))).unwrap_or((-upem * 0.1, upem * 0.06)); let strike = m.strikeout.map(|d| f64::from(d.offset)).unwrap_or(ascent * 0.3); + // Superscript and subscript sizes and offsets: the OS/2 table's, else the usual 0.65 em, + // 0.35 em up and 0.14 em down (what common fonts carry); a zero counts as unset, as some + // fonts leave these fields. + let os2 = f.os2().ok(); + let script = |size: Option, offset: Option, up: bool, usual_offset: f64| -> (f64, f64) { + let size = size.map(f64::from).filter(|v| *v > 0.0).map_or(0.65, |v| v / upem); + let offset = offset.map(f64::from).filter(|v| *v != 0.0).unwrap_or(usual_offset * upem); + (size, if up { offset } else { -offset }) + }; + let superscript = script(os2.as_ref().map(|t| t.y_superscript_y_size()), os2.as_ref().map(|t| t.y_superscript_y_offset()), true, 0.35); + let subscript = script(os2.as_ref().map(|t| t.y_subscript_y_size()), os2.as_ref().map(|t| t.y_subscript_y_offset()), false, 0.14); let weight = { let w = attrs.weight.value(); if w.is_finite() && w > 0.0 { w.round() as u16 } else { figcraft_doc::style_weight(&style) } @@ -200,6 +216,8 @@ impl Face { underline_pos: under.0, underline_thickness: under.1.max(upem * 0.02), strike_pos: strike, + superscript, + subscript, shaper, gsub_features, track, diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 5d3d3c27f..7305dac15 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -1418,39 +1418,65 @@ fn shape_segment(chars: &[char], seg: &Segment, face: &Arc, features: &[Fe // Variable fonts: the axis values the style asks for (named instance, implied weight, custom). let values = face.axis_values(style); let coords = face.coords(&values); - let mut raw: Vec<(u32, u32, i32, i32, i32)> = Vec::new(); - if let Some(hb) = face.hb() { - let instance = (!coords.is_empty()).then(|| { - let vars = face - .axes - .iter() - .zip(&values) - .filter_map(|(a, v)| <[u8; 4]>::try_from(a.tag.as_bytes()).ok().map(|t| Variation { tag: Tag::new(&t), value: *v as f32 })); - ShaperInstance::from_variations(&hb, vars) - }); - let shaper = face.shaper.shaper(&hb).instance(instance.as_ref()).build(); - let mut buf = UnicodeBuffer::new(); - for (u, src, _) in &mapped { - buf.add(*u, *src as u32); - } - let rtl = seg.level % 2 == 1; - buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight }); - buf.guess_segment_properties(); - let gb = shaper.shape(buf, ShapeOptions::new().features(&feats)); - for (info, pos) in gb.glyph_infos().iter().zip(gb.glyph_positions()) { - raw.push((info.glyph_id, info.cluster, pos.x_advance, pos.x_offset, pos.y_offset)); - } - // Right-to-left glyphs come out in visual order; items are kept in logical order (lines - // put runs back in visual order). - if rtl { - raw.reverse(); - } - } else { - for (u, src, _) in &mapped { - let gid = face.glyph_for(*u); - raw.push((gid, *src as u32, face.advance_at(gid, &coords) as i32, 0, 0)); + let shape = |feats: &[Feature]| -> Vec<(u32, u32, i32, i32, i32)> { + let mut raw = Vec::new(); + if let Some(hb) = face.hb() { + let instance = (!coords.is_empty()).then(|| { + let vars = face + .axes + .iter() + .zip(&values) + .filter_map(|(a, v)| <[u8; 4]>::try_from(a.tag.as_bytes()).ok().map(|t| Variation { tag: Tag::new(&t), value: *v as f32 })); + ShaperInstance::from_variations(&hb, vars) + }); + let shaper = face.shaper.shaper(&hb).instance(instance.as_ref()).build(); + let mut buf = UnicodeBuffer::new(); + for (u, src, _) in &mapped { + buf.add(*u, *src as u32); + } + let rtl = seg.level % 2 == 1; + buf.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight }); + buf.guess_segment_properties(); + let gb = shaper.shape(buf, ShapeOptions::new().features(feats)); + for (info, pos) in gb.glyph_infos().iter().zip(gb.glyph_positions()) { + raw.push((info.glyph_id, info.cluster, pos.x_advance, pos.x_offset, pos.y_offset)); + } + // Right-to-left glyphs come out in visual order; items are kept in logical order + // (lines put runs back in visual order). + if rtl { + raw.reverse(); + } + } else { + for (u, src, _) in &mapped { + let gid = face.glyph_for(*u); + raw.push((gid, *src as u32, face.advance_at(gid, &coords) as i32, 0, 0)); + } } + raw + }; + let mut raw = shape(&feats); + // Superscript or subscript (`sups` / `subs` on the node): the face's own glyphs where it has + // the feature and every letter or digit here got one; otherwise synthesised from the standard + // glyphs, shrunk and shifted ("Figma draws a synthesized version by using the font's standard + // version of the character, shrinking it, and positioning it accordingly"; a run mixing + // available and unavailable glyphs is synthesised whole, "for consistency"). + let script = [(b"sups", true), (b"subs", false)].into_iter().find(|(tag, _)| feats.iter().any(|f| f.tag == Tag::new(tag) && f.value != 0)); + // The glyph a cluster's character has on its own, after the case mapping shaping saw. + let plain_gid = |cl: usize| mapped.iter().find(|(_, src, _)| *src == cl).map(|(u, _, _)| face.glyph_for(*u)); + let unchanged = |raw: &[(u32, u32, i32, i32, i32)]| { + raw.iter().any(|&(gid, cl, ..)| { + let cl = cl as usize; + chars.get(cl).is_some_and(|c| c.is_alphanumeric()) && plain_gid(cl) == Some(gid) + }) + }; + let synth = script.filter(|(tag, _)| !face.has_feature(tag) || unchanged(&raw)); + if let Some((tag, _)) = synth + && face.has_feature(tag) + { + let plain: Vec = feats.iter().filter(|f| f.tag != Tag::new(tag)).cloned().collect(); + raw = shape(&plain); } + let (script_scale, script_shift) = synth.map_or((1.0, 0.0), |(_, up)| if up { face.superscript } else { face.subscript }); let n = raw.len(); for gi in 0..n { let Some(&(gid, cl, xa, xo, yo)) = raw.get(gi) else { continue }; @@ -1459,7 +1485,7 @@ fn shape_segment(chars: &[char], seg: &Segment, face: &Arc, features: &[Fe let cend = raw.iter().skip(gi + 1).map(|r| r.1 as usize).find(|c| *c > cl).unwrap_or(end).max(cl + 1); let last_in_cluster = raw.get(gi + 1).is_none_or(|r| r.1 as usize != cl); let ch = chars.get(cl).copied().unwrap_or(' '); - let scale = if small_at(cl) { SMALL_CAP_SCALE } else { 1.0 }; + let scale = if small_at(cl) { SMALL_CAP_SCALE } else { 1.0 } * script_scale; let spacing = if last_in_cluster { seg.spacing * (cend - cl) as f64 } else { 0.0 }; // The glyph's own advance and what shaping added to it (kerning) each land on the grid. let own = face.advance_at(gid, &coords); @@ -1472,7 +1498,7 @@ fn shape_segment(chars: &[char], seg: &Segment, face: &Arc, features: &[Fe adv, spacing, dx: f64::from(xo) * k * scale, - dy: f64::from(yo) * k * scale, + dy: f64::from(yo) * k * scale + script_shift * k, char_start: cl, char_end: cend, style: seg.st_idx, diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index e643ccaee..6d341419c 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -157,6 +157,49 @@ fn small_caps_native_or_synthesised() { assert_eq!(sc.glyphs.iter().find(|g| g.char_start == 0).unwrap().gid, face.glyph_for('A')); } +#[test] +fn superscript_native_or_synthesised_and_never_mixed() { + // "Figma tries to use any superscript/subscript glyphs provided by the font. If it isn't + // provided, Figma draws a synthesized version by using the font's standard version of the + // character, shrinking it, and positioning it accordingly." and a layer mixing both "will all + // update to the synthesized form for consistency" (Explore text properties). + let Some(face) = inter() else { return }; + let mut t = TextData::new("x2"); + t.style.font_size = 20.0; + let plain = layout(&t, None, None); + t.features.insert("sups".into(), true); + let sup = layout(&t, None, None); + let at = |l: &TextLayout, i: usize| l.glyphs.iter().find(|g| g.char_start == i).cloned().unwrap(); + let native = |i: usize| at(&sup, i).gid != at(&plain, i).gid && (at(&sup, i).size - 20.0).abs() < 1e-9; + let synthesised = |i: usize| at(&sup, i).gid == at(&plain, i).gid && at(&sup, i).size < 20.0 && at(&sup, i).y < at(&plain, i).y; + assert!((native(0) && native(1)) || (synthesised(0) && synthesised(1)), "both glyphs the same way: {:?} {:?}", at(&sup, 0), at(&sup, 1)); + if !face.has_feature(b"sups") { + assert!(synthesised(0) && synthesised(1), "no sups in the face: synthesised"); + } + t.features.insert("sups".into(), false); + t.features.insert("subs".into(), true); + let sub = layout(&t, None, None); + let g = at(&sub, 1); + let p = at(&plain, 1); + assert!((g.gid != p.gid && (g.size - 20.0).abs() < 1e-9) || (g.size < 20.0 && g.y > p.y), "subscript: native, or shrunk and lowered: {g:?}"); + // Capitalised, the same holds: the check against the face's own glyphs sees the characters + // shaping saw (an X, not an x), so a face with a superscript 2 and no superscript X + // synthesises both rather than mixing them. + t.features.clear(); + t.style.case = figcraft_doc::TextCase::Upper; + let plain_up = layout(&t, None, None); + t.features.insert("sups".into(), true); + let up = layout(&t, None, None); + let native_up = |i: usize| at(&up, i).gid != at(&plain_up, i).gid && (at(&up, i).size - 20.0).abs() < 1e-9; + let synth_up = |i: usize| at(&up, i).gid == at(&plain_up, i).gid && at(&up, i).size < 20.0 && at(&up, i).y < at(&plain_up, i).y; + assert!( + (native_up(0) && native_up(1)) || (synth_up(0) && synth_up(1)), + "upper case: both glyphs the same way: {:?} {:?}", + at(&up, 0), + at(&up, 1) + ); +} + #[test] fn title_case_across_runs() { let Some(face) = inter() else { return }; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index aa1c4510e..d936c9408 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-02 · **Change:** patch (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; 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-02 · **Change:** patch (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); 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: @@ -90,6 +90,7 @@ interaction feel not yet compared. | 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) | | 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`); 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: 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`) | | Comment (C), Shift+C to show/hide | done | local only | | 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 | @@ -178,6 +179,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look |---|---|---| | 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`. | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From 9f09b7163cfda16241b6693b01510b8cafd83a0a Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:31:00 -0500 Subject: [PATCH 110/326] M2: a double-click on an auto layout edge sets Hug contents, with Alt Fill container (#1838) (#1867) * M2: a double-click on an auto layout edge sets Hug contents, with Alt Fill container (#1838) Co-Authored-By: Claude Fable 5.1 * Auto layout edges: a text child fills with Alt too, and still enters on a plain double-click Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/canvas/tools/click.rs | 31 +++++++++++ crates/engine/src/double_click_tests.rs | 74 +++++++++++++++++++++++++ crates/engine/src/keymap.rs | 2 + crates/ui-egui/locales/en.toml | 5 ++ docs/auto-layout-parity.md | 4 +- 5 files changed, 115 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/canvas/tools/click.rs b/crates/engine/src/canvas/tools/click.rs index 0e07b331d..a48b215bc 100644 --- a/crates/engine/src/canvas/tools/click.rs +++ b/crates/engine/src/canvas/tools/click.rs @@ -22,6 +22,29 @@ impl Session { } } + /// A double-click on an edge handle of the one selected layer auto layout sizes: Hug contents + /// on that axis for an auto layout frame, Fill container with Alt for a child of one (a + /// vertical edge sizes the width, a horizontal one the height). Whether it applied: on any + /// other layer, or off the edges, the double-click goes on as before. + fn edge_double_click(&mut self, doc: &Document, sel: &[NodeId], ev: &PointerEvent) -> Result { + let [id] = sel[..] else { return Ok(false) }; + let Some(super::Handle::Edge(edge)) = super::handles::handle_at(doc, sel, ev.p(), ev.zoom) else { return Ok(false) }; + let Some(n) = doc.node(id) else { return Ok(false) }; + let applies = if ev.alt { + !n.child_layout.absolute && n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some()) + } else { + n.layout.is_some() + }; + if !applies { + return Ok(false); + } + // Edges run top, right, bottom, left: the odd ones are vertical and size the width. + let mut props = serde_json::Map::new(); + props.insert(if edge % 2 == 1 { "sizingH" } else { "sizingV" }.to_string(), json!(if ev.alt { "fill" } else { "hug" })); + self.execute("node.set", &json!({"id": id, "props": props}))?; + Ok(true) + } + pub(super) fn double_click(&mut self, ev: &PointerEvent) -> Result<()> { let ds = self.ds()?; let (doc, sel, page) = (ds.doc.clone(), ds.selection.clone(), ds.page); @@ -61,6 +84,14 @@ impl Session { self.tool.overlay.marquee = None; self.cancel_interaction()?; } + // An edge of an auto layout object's bounding box: Hug contents on that axis, with Alt + // Fill container ("Tip: Double-click the vertical or horizontal edge of an auto layout + // object's bounding box to set it to Hug contents." and "Hold ⌥ Option or Alt and + // double-click the vertical or horizontal edge of an auto layout object's bounding box to + // set it to Fill container.", Guide to auto layout). + if edits && matches!(self.tool.tool, ToolId::Move | ToolId::Scale) && !(ev.shift || ev.cmd) && self.edge_double_click(&doc, &sel, ev)? { + return Ok(()); + } let hit_here = self.hit(&doc, page, ev.p(), ev.tol() * 2.0); // A double-click anywhere on the one selected shape edits its points, like Enter: also // inside a hollow (unfilled) closed shape, where the hit test finds nothing under the diff --git a/crates/engine/src/double_click_tests.rs b/crates/engine/src/double_click_tests.rs index 83ea82fdd..15fbf905c 100644 --- a/crates/engine/src/double_click_tests.rs +++ b/crates/engine/src/double_click_tests.rs @@ -128,3 +128,77 @@ fn a_press_drags_only_past_the_threshold_in_screen_pixels() { assert_eq!(origin(&s, r).2 != 200.0, resizes, "resize by {by}"); } } + +/// A double-click with Alt held throughout, as the canvas sends it. +fn alt_double_click(s: &mut Session, x: f64, y: f64, zoom: f64) { + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::DoubleClick] { + let mut ev = PointerEvent::at(kind, x, y, zoom); + ev.alt = true; + s.pointer(&ev).unwrap(); + } +} + +/// "Tip: Double-click the vertical or horizontal edge of an auto layout object's bounding box to +/// set it to Hug contents." and "Hold ⌥ Option or Alt and double-click the vertical or horizontal +/// edge of an auto layout object's bounding box to set it to Fill container." (Guide to auto +/// layout): a vertical edge sizes the width, a horizontal one the height; a layer auto layout +/// doesn't size keeps the double-click's old meaning. +#[test] +fn a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills() { + use figcraft_doc::Sizing; + let mut s = Session::new(); + let f = id_of(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 100}))["id"]).unwrap(); + ex(&mut s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 0}})); + let c = + id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 40, "parent": f, "props": {"fill": "#FF0000"}}))["id"]) + .unwrap(); + let sizing = |s: &Session, id: NodeId| { + let cl = &s.doc().unwrap().node(id).unwrap().child_layout; + (cl.sizing_h, cl.sizing_v) + }; + let size = |s: &Session, id: NodeId| { + let n = s.doc().unwrap().node(id).unwrap(); + (n.width, n.height) + }; + ex(&mut s, "select.set", json!({"ids": [f]})); + assert_eq!((sizing(&s, f), size(&s, f)), ((Sizing::Fixed, Sizing::Fixed), (400.0, 100.0))); + // The frame's right edge: Hug contents horizontally, and the frame shrinks onto its child. + double_click(&mut s, 400.0, 50.0, 0.0, 1.0); + assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Fixed)); + assert_eq!(size(&s, f), (100.0, 100.0)); + assert_eq!(s.selection(), [f], "still selected, not entered"); + s.undo().unwrap(); + assert_eq!((sizing(&s, f), size(&s, f)), ((Sizing::Fixed, Sizing::Fixed), (400.0, 100.0)), "one undo step"); + // Its bottom edge: Hug contents vertically. + double_click(&mut s, 200.0, 100.0, 0.0, 1.0); + assert_eq!(sizing(&s, f), (Sizing::Fixed, Sizing::Hug)); + assert_eq!(size(&s, f), (400.0, 40.0)); + // Alt on the child's right edge: Fill container horizontally, and the child takes the width. + ex(&mut s, "select.set", json!({"ids": [c]})); + alt_double_click(&mut s, 100.0, 20.0, 1.0); + assert_eq!(sizing(&s, c), (Sizing::Fill, Sizing::Fixed)); + assert_eq!(size(&s, c), (400.0, 40.0)); + // Without Alt the child, no auto layout frame itself, keeps the old meaning (a frame's + // double-click: nothing to enter here), and a plain rectangle's edge still edits its points. + double_click(&mut s, 400.0, 20.0, 0.0, 1.0); + assert_eq!(sizing(&s, c), (Sizing::Fill, Sizing::Fixed)); + // A text child of the frame: Alt+double-click on its edge sets Fill like any child's, and a + // plain double-click on its edge still enters the text. + let x = id_of(&ex(&mut s, "text.create", json!({"text": "Hi", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 16}}))["id"]).unwrap(); + ex(&mut s, "node.set", json!({"id": x, "props": {"textAutoResize": "none", "width": 60, "height": 20}})); + ex(&mut s, "select.set", json!({"ids": [x]})); + let b = s.doc().unwrap().world_bounds(x).unwrap(); + alt_double_click(&mut s, b.x1, (b.y0 + b.y1) / 2.0, 1.0); + assert_eq!(sizing(&s, x), (Sizing::Fill, Sizing::Fixed), "a text child fills too"); + let b = s.doc().unwrap().world_bounds(x).unwrap(); + // On the edge handle, a pixel in (the hit test's reach): the text, not the frame edge it shares. + double_click(&mut s, b.x1 - 1.0, (b.y0 + b.y1) / 2.0, 0.0, 1.0); + assert!(s.ds().unwrap().text_edit.as_ref().is_some_and(|te| te.id == x), "a text's edge still enters it without Alt"); + assert_eq!(sizing(&s, x), (Sizing::Fill, Sizing::Fixed)); + crate::textedit::end(&mut s).unwrap(); + let r = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 300, "width": 100, "height": 100}))["id"]).unwrap(); + ex(&mut s, "select.set", json!({"ids": [r]})); + double_click(&mut s, 99.0, 350.0, 0.0, 1.0); + assert_eq!(sizing(&s, r), (Sizing::Fixed, Sizing::Fixed)); + assert!(s.ds().unwrap().vector_edit.is_some(), "a shape's double-click still edits its points"); +} diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index a0f0bc4b6..fb7713e66 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -364,6 +364,8 @@ pub static GESTURES: &[(Group, &str, &str, &str)] = &[ (Transform, "Opacity 10%…90%, 0: 100%", "1…9, 0", "1…9, 0"), (Transform, "Exact opacity (4 then 5: 45%)", "Two digits", "Two digits"), (Transform, "Suspend snapping while dragging", "Hold ⌃ or ⌘", "Hold Ctrl"), + (Arrange, "Set hug contents", "Double-click an edge of an auto layout frame", "Double-click an edge of an auto layout frame"), + (Arrange, "Set fill container", "⌥ double-click an edge of an auto layout child", "Alt+double-click an edge of an auto layout child"), (Prototype, "Presenting: next frame", "→, Space or N", "→, Space or N"), (Prototype, "Presenting: previous frame", "←", "←"), (Prototype, "Presenting: restart", "R", "R"), diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index c44635a2a..034e3381a 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -407,6 +407,11 @@ name = "English" "Decoration style" = "Decoration style" "Decoration" = "Decoration" "Deep select" = "Deep select" +"Set hug contents" = "Set hug contents" +"Set fill container" = "Set fill container" +"Double-click an edge of an auto layout frame" = "Double-click an edge of an auto layout frame" +"⌥ double-click an edge of an auto layout child" = "⌥ double-click an edge of an auto layout child" +"Alt+double-click an edge of an auto layout child" = "Alt+double-click an edge of an auto layout child" "Default" = "Default" "Default content" = "Default content" "Default value (the top-left variant)" = "Default value (the top-left variant)" diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 61462a2c1..3ddd0072a 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-02 · **Change:** patch (fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); 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-02 · **Change:** patch (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 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%, @@ -41,6 +41,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Fill children share by their content area (border-box): a child with more padding or a thicker included inside stroke takes a little more, so the content areas come out the same | **fixed** | "Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model. A layer with a thicker stroke will take up slightly more of the available width or height, so that its inner content area matches its sibling's" (Use auto layout with CSS Flexbox in mind); the split went by outer size before. Min and max still clamp the outer size; a child's own insets are its padding and its included inside stroke (`nested_tests::fill_children_share_by_content_area`; #1824) | | Fill on a child turns its hugging parent Fixed on that axis | pass | `al_behaviour_tests::fill_on_a_child_turns_the_hugging_parent_fixed` | | Hug only on auto layout frames (and text); Fill only in an auto layout flow, never on a top-level frame | pass | `al_behaviour_tests::hug_and_fill_only_where_they_apply` | +| Double-click an edge of an auto layout frame's box: Hug contents on that axis; Alt+double-click an edge of a child's box: Fill container | **fixed** | "Tip: Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents."; "Hold ⌥ Option or Alt and double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Fill container." A vertical edge sizes the width, a horizontal one the height; any other layer keeps the double-click's old meaning (#1838). `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills` | | Min/max width and height bound Hug, Fill and Fixed sizes, on frames and children | pass | `sizing_rules`; a fill child at its max leaves the rest to the other fill children (silent on redistribution: CSS flexbox) | | A hugging text wider than its max width wraps at the max | pass | `sizing_rules` | | A text has a max height or a number of max lines, not both: a max height sets max lines to Auto, a number of max lines removes the max height | **fixed** | both coexisted; `node.set {maxHeight}` and `{maxLines}` and `text.maxLines` keep one of the two (a frame's max height is untouched); `text_behaviour_tests::a_text_has_a_max_height_or_max_lines_not_both` | @@ -99,6 +100,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| | 2026-11-02 | patch | M2, #1824: fill container children share the free space by their content area: each one's own insets (padding and an included inside stroke, from the same `insets` the frame uses) come off the free space before the equal split and go back on its share, so a child with more padding or a thicker inside stroke takes a little more and the content areas match ("Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model", Use auto layout with CSS Flexbox in mind). Min and max still clamp the outer sizes and the frozen-share loop is as it was; children without insets split as before. Test: `nested_tests::fill_children_share_by_content_area` | +| 2026-11-02 | patch | M2, #1838: a double-click on an edge of an auto layout frame's bounding box sets Hug contents on that axis, Alt+double-click on an edge of a child's Fill container ("Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents", "Hold ⌥ Option or Alt and double-click ... to set it to Fill container", Guide to auto layout); a vertical edge sizes the width, a horizontal one the height; the Keyboard shortcuts panel lists both gestures. Test: `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills`. Numbers unchanged. | | 2026-11-01 | patch | M2: a text layer keeps a max height or a number of max lines, not both ("Text layers cannot have both a max height and a set number of max lines", Guide to auto layout): `node.set {maxHeight}` on a text sets its max lines to Auto, and `node.set {maxLines}` or `text.maxLines` with a number removes its max height. Found by a documentation audit of this page. Test: `text_behaviour_tests::a_text_has_a_max_height_or_max_lines_not_both`. Numbers unchanged | | 2026-11-01 | minor | M2: Remove all auto layout ("To remove auto layout from a frame and all of its nested objects at once, right-click on the frame and go to More layout options > Remove all auto layout", Toggle on auto layout in designs): `layout.removeAll {ids?}` strips the frames and every frame nested in them in one undo step, leaving instances and their layers alone; in the canvas context menu beside Add auto layout and in the Actions palette. Found by a documentation audit of this page. Test: `al_nesting_tests::remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it`. Numbers unchanged | | 2026-10-30 | minor | M8, #1083: grid placement finds free cells on a bitmap, a word at a time, with the same placements; crafted grids of wide children no longer stall a layout pass. Numbers unchanged. | From f9d507f7b0bccf4a8818be9520c670207d77cc5e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:31:11 -0500 Subject: [PATCH 111/326] M2: a child resized to the full available space of its auto layout frame becomes Fill container (#1859) * M2: a child resized to the full available space of its auto layout frame becomes Fill container Co-Authored-By: Claude Fable 5.1 * Auto layout: a child becomes Fill for the full space only across the flow or alone along it Co-Authored-By: Claude Fable 5.1 * Auto layout: the full available space is what layout leaves (padding and an included inside stroke), judged after a new path's size Co-Authored-By: Claude Fable 5.1 * M2: a rotated child resized to the frame's room stays Fixed (review) CodeRabbit on #1859: a rotated layer's local size isn't the room layout gives it, so Fill would squash its geometry. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/al_behaviour_tests.rs | 60 ++++++++++++++++++++++++ crates/engine/src/cmd/arrange.rs | 13 +++--- crates/engine/src/cmd/props.rs | 61 +++++++++++++++++++++---- crates/layout/src/lib.rs | 5 +- docs/auto-layout-parity.md | 4 +- 5 files changed, 126 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index d36b35b8f..514a39fdc 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -72,6 +72,52 @@ fn fill_on_a_child_turns_the_hugging_parent_fixed() { assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug)); } +#[test] +fn a_child_resized_to_the_full_available_space_becomes_fill() { + // Documented: "Child objects of an auto layout frame will also be set to Fill container if + // they are manually resized to the full available space of the parent frame." + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"padding": 10, "gap": 10})); // 200 × 100, fixed + let a = rect(&mut s, f, 50.0, 20.0, "#FF0000"); + // Along the flow, alone in the frame: its width less the padding (200 - 20). + s.execute("transform.resize", &json!({"ids": [a], "width": 180})).unwrap(); + assert_eq!(sizing(&s, a), (Sizing::Fill, Sizing::Fixed)); + assert_eq!(size(&s, a), (180.0, 20.0)); + s.undo().unwrap(); + assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fixed), "undone as part of the edit"); + // Across the flow, beside a sibling too: the frame's height less its padding. + let b = rect(&mut s, f, 50.0, 20.0, "#0000FF"); + set(&mut s, b, json!({"height": 80})); + assert_eq!(sizing(&s, b), (Sizing::Fixed, Sizing::Fill)); + assert_eq!(size(&s, b), (50.0, 80.0)); + // Short of it: fixed, as before. + set(&mut s, b, json!({"height": 70})); + assert_eq!(sizing(&s, b), (Sizing::Fixed, Sizing::Fixed)); + // Along the flow beside a sibling, what is left is not "the full available space": a width + // that happens to match it (180 - 10 - 50) stays fixed. + s.execute("transform.resize", &json!({"ids": [b], "width": 120})).unwrap(); + assert_eq!(sizing(&s, b), (Sizing::Fixed, Sizing::Fixed)); + // A hugging frame has no full space to offer: the child stays fixed. + let g = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug", "padding": 10})); + let c = rect(&mut s, g, 50.0, 20.0, "#00FF00"); + set(&mut s, c, json!({"width": 180})); + assert_eq!(sizing(&s, c), (Sizing::Fixed, Sizing::Fixed)); + // An inside stroke the layout includes takes room like the padding: the full space is what + // layout leaves the child (200 - 2 × 10 - 2 × 4), not the frame less its padding alone. + let h = al_frame(&mut s, json!({"padding": 10, "strokesIncluded": true, "stroke": "#000000", "strokeWeight": 4, "strokeAlign": "inside"})); + let d = rect(&mut s, h, 50.0, 20.0, "#FF0000"); + set(&mut s, d, json!({"width": 180})); + assert_eq!(sizing(&s, d), (Sizing::Fixed, Sizing::Fixed), "wider than the room the stroke leaves"); + assert_eq!(size(&s, d), (180.0, 20.0), "and kept as typed"); + set(&mut s, d, json!({"width": 172})); + assert_eq!(sizing(&s, d), (Sizing::Fill, Sizing::Fixed)); + assert_eq!(size(&s, d), (172.0, 20.0)); + // Excluded from the layout, the stroke takes no room: the frame less its padding again. + set(&mut s, h, json!({"strokesIncluded": false})); + set(&mut s, d, json!({"width": 172})); + assert_eq!(sizing(&s, d), (Sizing::Fixed, Sizing::Fixed)); +} + #[test] fn hug_and_fill_only_where_they_apply() { // Documented: Hug applies to auto layout frames (and text); Fill to children of auto layout, @@ -232,6 +278,20 @@ fn a_size_given_with_a_new_path_fixes_that_axis() { set(&mut s, v, json!({"path": "M0 0 L20 5", "width": 30})); assert_eq!(sizing(&s, v).0, Sizing::Fixed); assert!((size(&s, v).0 - 30.0).abs() < 1e-6, "{:?}", size(&s, v)); + // The axis is judged by the size the path is given, not the one before it: the frame's full + // height (100) given with a path fills; a smaller height given with the next path is fixed, + // though the layer filled the frame until then. + set(&mut s, v, json!({"path": "M0 0 L20 5", "height": 100})); + assert_eq!(sizing(&s, v).1, Sizing::Fill); + assert!((size(&s, v).1 - 100.0).abs() < 1e-6, "{:?}", size(&s, v)); + set(&mut s, v, json!({"height": 40, "path": "M0 0 L20 5"})); + assert_eq!(sizing(&s, v).1, Sizing::Fixed); + assert!((size(&s, v).1 - 40.0).abs() < 1e-6, "{:?}", size(&s, v)); + // Rotated, the layer's local size isn't the room layout gives it: a height matching the + // frame's stays fixed rather than have Fill squash the path. + set(&mut s, v, json!({"rotation": 90})); + set(&mut s, v, json!({"path": "M0 0 L20 5", "height": 100})); + assert_eq!(sizing(&s, v).1, Sizing::Fixed); } /// What one call's auto layout keys give, whichever way they are spelled: the mode (a string, or diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 19572c959..b90cf1d1f 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -569,12 +569,6 @@ pub(crate) fn resize_cmd(s: &mut Session, p: &Value) -> Result { let n = doc.get_mut(i)?; let after = n.transform * Point::new(w * ax, h * ay); n.transform = Affine::translate(before - after) * n.transform; - if num(p, "width").is_some() { - n.child_layout.sizing_h = Sizing::Fixed; - } - if num(p, "height").is_some() { - n.child_layout.sizing_v = Sizing::Fixed; - } if let NodeKind::Text(t) = &mut n.kind { if num(p, "height").is_some() { t.fix_size(num(p, "width").is_some(), true); @@ -582,6 +576,13 @@ pub(crate) fn resize_cmd(s: &mut Session, p: &Value) -> Result { t.auto_resize = TextAutoResize::Height; } } + // A side given is fixed, or fills its auto layout parent when it is the full space there. + if num(p, "width").is_some() { + super::props::fix_axis(doc, i, true)?; + } + if num(p, "height").is_some() { + super::props::fix_axis(doc, i, false)?; + } super::props::restore_worlds(doc, &kept)?; } super::styles::detach_edited(doc, &before); diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index fbf80fc1b..01f83bc85 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -437,17 +437,55 @@ fn layout_keys_beside_none(cmd: &str, props: &Map) -> Result<()> } /// An explicit width (`is_w`) or height makes hugging or filling on that axis fixed, like typing -/// into W or H. -fn fix_axis(doc: &mut Document, id: NodeId, is_w: bool) -> Result<()> { +/// into W or H; sized to the full space its auto layout parent has for it on that axis, the layer +/// fills instead: "Child objects of an auto layout frame will also be set to Fill container if +/// they are manually resized to the full available space of the parent frame" (Guide to auto +/// layout). +pub(crate) fn fix_axis(doc: &mut Document, id: NodeId, is_w: bool) -> Result<()> { + let sizing = if fills_available_space(doc, id, is_w) { Sizing::Fill } else { Sizing::Fixed }; let n = doc.get_mut(id)?; if is_w { - n.child_layout.sizing_h = Sizing::Fixed; + n.child_layout.sizing_h = sizing; } else { - n.child_layout.sizing_v = Sizing::Fixed; + n.child_layout.sizing_v = sizing; } Ok(()) } +/// Whether `id`'s width (`is_w`) or height is the full space its auto layout parent has for it on +/// that axis: the frame's size less its padding and an inside stroke included in the layout (the +/// insets layout itself takes). Across the flow that is every child's room; +/// along the flow only a lone child has it (beside siblings what is left depends on the gaps, the +/// alignment and overflow, so a size that happens to match it is not "the full available +/// space"). Never in a hugging or wrapping frame or a grid, or for a layer that ignores the layout. +fn fills_available_space(doc: &Document, id: NodeId, is_w: bool) -> bool { + let Some(n) = doc.node(id) else { return false }; + let Some(parent) = n.parent.and_then(|p| doc.node(p)) else { return false }; + let Some(l) = &parent.layout else { return false }; + if n.child_layout.absolute || l.wrap || l.mode == LayoutMode::Grid { + return false; + } + // A rotated layer's local size isn't the size layout gives it room for (its rotated bounds + // are): it stays Fixed rather than have Fill squash its geometry. + let [_, b, c, ..] = n.transform.as_coeffs(); + if b.abs() > 1e-9 || c.abs() > 1e-9 { + return false; + } + let hugs = if is_w { parent.child_layout.sizing_h } else { parent.child_layout.sizing_v } == Sizing::Hug; + if hugs { + return false; + } + if (l.mode == LayoutMode::Horizontal) == is_w + && parent.children.iter().filter(|c| **c != id).filter_map(|c| doc.node(*c)).any(|c| c.visible && !c.child_layout.absolute) + { + return false; + } + let (pt, pr, pb, pl) = figcraft_layout::insets(parent, l); + let available = if is_w { parent.width - pl - pr } else { parent.height - pt - pb }; + let size = if is_w { n.width } else { n.height }; + available > 0.0 && (size - available).abs() < 0.01 +} + /// The `geometry` properties of `apply`; `false` when `k` is not one of them. fn apply_geometry( cmd: &str, @@ -459,10 +497,17 @@ fn apply_geometry( path_offset: &mut (f64, f64), ) -> Result { match k { - "path" => *path_offset = set_path(cmd, doc, id, v, props)?, - // A new path takes the size asked for as its scale (`set_path`); the size still fixes - // its auto layout axis. - "width" | "height" | "w" | "h" if props.contains_key("path") => fix_axis(doc, id, k.starts_with('w'))?, + "path" => { + *path_offset = set_path(cmd, doc, id, v, props)?; + // A size given beside the path is its scale (`set_path`), and still fixes or fills + // its auto layout axis, judged once the path has given the layer that size. + for (long, short, is_w) in [("width", "w", true), ("height", "h", false)] { + if props.contains_key(long) || props.contains_key(short) { + fix_axis(doc, id, is_w)?; + } + } + } + "width" | "height" | "w" | "h" if props.contains_key("path") => {} "x" | "y" => { let val = f64_of(v).ok_or_else(|| bad(cmd, format!("`{k}` must be a number")))?; let val = val + if k == "x" { path_offset.0 } else { path_offset.1 }; diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 56f4bf625..19de84afb 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -216,8 +216,9 @@ fn coherent_own_sizing(doc: &mut Document, id: NodeId) -> bool { /// Padding `(top, right, bottom, left)` of an auto layout frame, sanitised, plus the frame's own /// inside stroke (per side) when strokes are included in the layout; center and outside strokes -/// never take up space. -fn insets(f: &figcraft_doc::Node, al: &AutoLayout) -> (f64, f64, f64, f64) { +/// never take up space. The frame's size less these is its children's room, the "full available +/// space" a child resized to it fills. +pub fn insets(f: &figcraft_doc::Node, al: &AutoLayout) -> (f64, f64, f64, f64) { let included = al.strokes_included && f.has_visible_stroke() && f.stroke.align == StrokeAlign::Inside; let stroke = if included { f.stroke.sides.unwrap_or([f.stroke.weight; 4]) } else { [0.0; 4] }; let [pt, pr, pb, pl] = al.padding.map(|p| finite_or_zero(p).max(0.0)); diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 3ddd0072a..3b5466b2c 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-02 · **Change:** patch (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 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-02 · **Change:** patch (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%, @@ -40,6 +40,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Fill: children share the space left after padding, gaps and fixed siblings; across the flow they stretch | pass | `sizing_rules` | | Fill children share by their content area (border-box): a child with more padding or a thicker included inside stroke takes a little more, so the content areas come out the same | **fixed** | "Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model. A layer with a thicker stroke will take up slightly more of the available width or height, so that its inner content area matches its sibling's" (Use auto layout with CSS Flexbox in mind); the split went by outer size before. Min and max still clamp the outer size; a child's own insets are its padding and its included inside stroke (`nested_tests::fill_children_share_by_content_area`; #1824) | | Fill on a child turns its hugging parent Fixed on that axis | pass | `al_behaviour_tests::fill_on_a_child_turns_the_hugging_parent_fixed` | +| A child resized to the full available space becomes Fill container on that axis | **fixed** | "Child objects of an auto layout frame will also be set to Fill container if they are manually resized to the full available space of the parent frame": a width or height given by a resize, the W/H fields or a canvas handle that equals the frame's size less its padding sets Fill there: across the flow for any child, along the flow for a lone child (beside siblings what is left depends on the gaps, the alignment and overflow, so it is left alone); not in a hugging or wrapping frame or a grid. It stayed Fixed before (`al_behaviour_tests::a_child_resized_to_the_full_available_space_becomes_fill`) | | Hug only on auto layout frames (and text); Fill only in an auto layout flow, never on a top-level frame | pass | `al_behaviour_tests::hug_and_fill_only_where_they_apply` | | Double-click an edge of an auto layout frame's box: Hug contents on that axis; Alt+double-click an edge of a child's box: Fill container | **fixed** | "Tip: Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents."; "Hold ⌥ Option or Alt and double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Fill container." A vertical edge sizes the width, a horizontal one the height; any other layer keeps the double-click's old meaning (#1838). `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills` | | Min/max width and height bound Hug, Fill and Fixed sizes, on frames and children | pass | `sizing_rules`; a fill child at its max leaves the rest to the other fill children (silent on redistribution: CSS flexbox) | @@ -101,6 +102,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver |---|---|---| | 2026-11-02 | patch | M2, #1824: fill container children share the free space by their content area: each one's own insets (padding and an included inside stroke, from the same `insets` the frame uses) come off the free space before the equal split and go back on its share, so a child with more padding or a thicker inside stroke takes a little more and the content areas match ("Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model", Use auto layout with CSS Flexbox in mind). Min and max still clamp the outer sizes and the frozen-share loop is as it was; children without insets split as before. Test: `nested_tests::fill_children_share_by_content_area` | | 2026-11-02 | patch | M2, #1838: a double-click on an edge of an auto layout frame's bounding box sets Hug contents on that axis, Alt+double-click on an edge of a child's Fill container ("Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents", "Hold ⌥ Option or Alt and double-click ... to set it to Fill container", Guide to auto layout); a vertical edge sizes the width, a horizontal one the height; the Keyboard shortcuts panel lists both gestures. Test: `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills`. Numbers unchanged. | +| 2026-11-02 | patch | M2: a child of an auto layout frame resized to the full space available to it on an axis (the frame's size less its padding: across the flow for any child, along the flow for a lone child) becomes Fill container on that axis, whether by `transform.resize`, the W/H fields or a canvas handle ("Child objects of an auto layout frame will also be set to Fill container if they are manually resized to the full available space of the parent frame", Guide to auto layout). Any other size keeps the axis Fixed as before; beside siblings along the flow, in a hugging or wrapping frame, in a grid and for a layer that ignores the layout nothing changes. Test: `al_behaviour_tests::a_child_resized_to_the_full_available_space_becomes_fill` | | 2026-11-01 | patch | M2: a text layer keeps a max height or a number of max lines, not both ("Text layers cannot have both a max height and a set number of max lines", Guide to auto layout): `node.set {maxHeight}` on a text sets its max lines to Auto, and `node.set {maxLines}` or `text.maxLines` with a number removes its max height. Found by a documentation audit of this page. Test: `text_behaviour_tests::a_text_has_a_max_height_or_max_lines_not_both`. Numbers unchanged | | 2026-11-01 | minor | M2: Remove all auto layout ("To remove auto layout from a frame and all of its nested objects at once, right-click on the frame and go to More layout options > Remove all auto layout", Toggle on auto layout in designs): `layout.removeAll {ids?}` strips the frames and every frame nested in them in one undo step, leaving instances and their layers alone; in the canvas context menu beside Add auto layout and in the Actions palette. Found by a documentation audit of this page. Test: `al_nesting_tests::remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it`. Numbers unchanged | | 2026-10-30 | minor | M8, #1083: grid placement finds free cells on a bitmap, a word at a time, with the same placements; crafted grids of wide children no longer stall a layout pass. Numbers unchanged. | From 1f0acd2bbd31148898ee514dbdc63598c183d2a4 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:31:21 -0500 Subject: [PATCH 112/326] M4: Alt+Enter while editing text opens the link at the caret (text.openLink) (#1860) Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/text.rs | 26 ++++++++++ crates/engine/src/keymap.rs | 1 + crates/engine/src/lib.rs | 2 + crates/engine/src/shortcut_parity_tests.rs | 3 +- crates/engine/src/text_link_tests.rs | 42 +++++++++++++++ crates/ui-egui/src/app/commands.rs | 7 +++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/text_link_tests.rs | 60 ++++++++++++++++++++++ docs/ui-parity.md | 9 ++-- 9 files changed, 147 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/text_link_tests.rs create mode 100644 crates/ui-egui/src/text_link_tests.rs diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 446b01d29..f72f215ee 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -521,6 +521,32 @@ pub fn specs() -> Vec { textedit::end(s)?; ok() }), + spec!( + "text.openLink", + "Open link", + "{} while editing: the link at the caret (the selection's start) goes to the UI to open, as Alt+Enter does (\"press Option Return / Alt Enter to activate a focused link\"); only a web or mail link opens → {url} ({url: null}: no link there)", + false, + |s, _| { + let Some(te) = s.ds()?.text_edit.clone() else { return Err(bad("text.openLink", "no text is being edited")) }; + let doc = s.doc()?; + let t = doc.node(te.id).and_then(|n| n.kind.text()).ok_or_else(|| bad("text.openLink", format!("{} is not text", te.id)))?; + let n = t.char_count(); + let at = te.caret.min(te.anchor); + // The caret sits between two chars: the link of the one after it, else before it. + let link = (at < n) + .then(|| t.style_at(at).link.clone()) + .flatten() + .or_else(|| (at > 0 && at <= n).then(|| t.style_at(at - 1).link.clone()).flatten()); + match link { + Some(url) if crate::doc_urls::openable(&url) => { + s.request_ui("open.url", json!({"url": url})); + Ok(json!({"url": url})) + } + Some(url) => Err(bad("text.openLink", format!("`{url}` is not a web or mail link"))), + None => Ok(json!({"url": Value::Null})), + } + } + ), spec!( "text.fonts", "List fonts", diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index fb7713e66..4f55fa4ad 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -247,6 +247,7 @@ pub static KEYS: &[Binding] = &[ // Text (on selected text layers, and on the selected characters while editing) k(Text, "text.bold", &["Cmd+B"]).both(), k(Text, "text.italic", &["Cmd+I"]).both(), + k(Text, "text.openLink", &["Alt+Enter"]).both(), k(Text, "text.underline", &["Cmd+U"]).both(), k(Text, "text.strikethrough", &["Shift+Cmd+X"]).both(), k(Text, "text.link", &["Shift+Cmd+U", "Cmd+K"]).text(), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0da532b25..e919444e2 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -565,6 +565,8 @@ mod text_behaviour_tests; #[cfg(test)] mod text_fill_tests; #[cfg(test)] +mod text_link_tests; +#[cfg(test)] mod text_metrics_local_tests; #[cfg(test)] mod text_motion_tests; diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index 0b9b573af..31ce9d18e 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -181,6 +181,7 @@ static ROWS: &[Row] = &[ pin(Zoom, "view.nextFrame", &["N", "End"], &[]), // Text doc(Text, "Bold", &["Cmd+B"], &[], Bound("text.bold"), ""), + doc(Text, "Activate a focused link", &["Alt+Enter"], &[], Bound("text.openLink"), "while editing: the link at the caret; web and mail links only"), doc(Text, "Italic", &["Cmd+I"], &[], Bound("text.italic"), ""), doc(Text, "Underline", &["Cmd+U"], &[], Bound("text.underline"), ""), doc(Text, "Strikethrough", &["Shift+Cmd+X"], &[], Bound("text.strikethrough"), ""), @@ -412,7 +413,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), (133, 132, 1, 0, 2, 57)); + assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (134, 133, 1, 0, 2, 57)); } #[test] diff --git a/crates/engine/src/text_link_tests.rs b/crates/engine/src/text_link_tests.rs new file mode 100644 index 000000000..df0748996 --- /dev/null +++ b/crates/engine/src/text_link_tests.rs @@ -0,0 +1,42 @@ +//! Alt+Enter while editing text activates the link at the caret ("When editing text, press +//! ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma): `text.openLink` +//! hands a web or mail link at the caret to the UI, refuses other schemes, and does nothing where +//! there is no link. + +use serde_json::json; + +use crate::Session; +use crate::params::id_of; + +#[test] +fn the_link_at_the_caret_goes_to_the_ui_and_only_a_web_or_mail_link() { + let mut s = Session::new(); + let t = id_of(&s.execute("text.create", &json!({"text": "See the docs now", "x": 0, "y": 0})).unwrap()["id"]).unwrap(); + s.execute("text.style", &json!({"id": t, "start": 4, "end": 12, "hyperlink": "https://example.com/docs"})).unwrap(); + assert!(s.execute("text.openLink", &json!({})).is_err(), "nothing to activate while no text is edited"); + s.execute("text.edit.begin", &json!({"id": t, "caret": 6})).unwrap(); + let r = s.execute("text.openLink", &json!({})).unwrap(); + assert_eq!(r["url"], "https://example.com/docs"); + let req = s.ui_requests.iter().find(|r| r.kind == "open.url").expect("a UI request to open it"); + assert_eq!(req.data["url"], "https://example.com/docs"); + assert!(s.ds().unwrap().text_edit.is_some(), "still editing"); + // Right after the link's last char the caret still counts as on it; before its start it doesn't. + s.execute("text.edit.caret", &json!({"index": 12})).unwrap(); + assert_eq!(s.execute("text.openLink", &json!({})).unwrap()["url"], "https://example.com/docs"); + s.execute("text.edit.caret", &json!({"index": 2})).unwrap(); + assert!(s.execute("text.openLink", &json!({})).unwrap()["url"].is_null(), "no link there"); + // A selection: its start decides. + s.execute("text.edit.caret", &json!({"index": 14})).unwrap(); + s.execute("text.edit.caret", &json!({"index": 8, "extend": true})).unwrap(); + assert_eq!(s.execute("text.openLink", &json!({})).unwrap()["url"], "https://example.com/docs"); + // Mail links open; anything that isn't a web or mail link is refused and nothing is requested. + s.execute("text.style", &json!({"id": t, "start": 4, "end": 12, "hyperlink": "mailto:hello@example.com"})).unwrap(); + s.execute("text.edit.caret", &json!({"index": 6})).unwrap(); + assert_eq!(s.execute("text.openLink", &json!({})).unwrap()["url"], "mailto:hello@example.com"); + let before = s.ui_requests.len(); + for bad in ["javascript:alert(1)", "file:///etc/passwd", "example.com/docs"] { + s.execute("text.style", &json!({"id": t, "start": 4, "end": 12, "hyperlink": bad})).unwrap(); + assert!(s.execute("text.openLink", &json!({})).is_err(), "{bad} is refused"); + } + assert_eq!(s.ui_requests.len(), before, "nothing requested for a refused link"); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 0e34f437a..93762e579 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -228,6 +228,13 @@ impl FigApp { } "preview.close" => self.ui.preview = None, "open.help" => self.services.open_url("https://getartcraft.com/apps/figcraft"), + // A link in text activated while editing (`text.openLink`): the engine checked it + // is a web or mail link. + "open.url" => { + if let Some(url) = r.data["url"].as_str() { + self.services.open_url(url); + } + } "layers.collapseAll" => layers::collapse_all(self), "contextMenu" => self.ui.key_menu = true, "selectArea" => self.start_key_box(), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7ecb64d22..e9969c106 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -243,6 +243,8 @@ mod table_paste_tests; #[cfg(test)] mod text_enter_tests; #[cfg(test)] +mod text_link_tests; +#[cfg(test)] mod titlebar_tests; #[cfg(test)] mod ui_params_tests; diff --git a/crates/ui-egui/src/text_link_tests.rs b/crates/ui-egui/src/text_link_tests.rs new file mode 100644 index 000000000..5f902e7a9 --- /dev/null +++ b/crates/ui-egui/src/text_link_tests.rs @@ -0,0 +1,60 @@ +//! Alt+Enter while editing text opens the link at the caret through the platform ("When editing +//! text, press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma), +//! driven through egui headless with a recording opener; editing goes on. + +use std::sync::{Arc, Mutex}; + +use egui::{Event, Key, Modifiers}; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::Services; +use crate::layers_drag_tests::Ui; + +/// Records every URL the app asks the platform to open. +#[derive(Default, Clone)] +struct Opened(Arc>>); + +impl Services for Opened { + fn open_url(&mut self, url: &str) { + if let Ok(mut v) = self.0.lock() { + v.push(url.to_string()); + } + } +} + +fn alt_enter(u: &mut Ui) { + let modifiers = Modifiers::ALT; + u.frame_with( + vec![ + Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers }, + Event::Key { key: Key::Enter, physical_key: None, pressed: false, repeat: false, modifiers }, + ], + modifiers, + ); + u.frame(vec![]); +} + +#[test] +fn alt_enter_opens_the_link_at_the_caret_while_editing() { + let mut s = Session::new(); + let t = NodeId(s.execute("text.create", &json!({"text": "See the docs now", "x": 20, "y": 20})).unwrap()["id"].as_u64().unwrap()); + s.execute("text.style", &json!({"id": t, "start": 4, "end": 12, "hyperlink": "https://example.com/docs"})).unwrap(); + s.execute("text.edit.begin", &json!({"id": t, "caret": 2})).unwrap(); + let opened = Opened::default(); + let mut u = Ui::new(s); + u.app.services = Box::new(opened.clone()); + u.frame(vec![]); + alt_enter(&mut u); + assert!(opened.0.lock().unwrap().is_empty(), "no link at the caret: nothing opens"); + assert!(u.app.session.ds().unwrap().text_edit.is_some(), "still editing"); + u.app.session.execute("text.edit.caret", &json!({"index": 6})).unwrap(); + alt_enter(&mut u); + assert_eq!(*opened.0.lock().unwrap(), vec!["https://example.com/docs".to_string()]); + assert!(u.app.session.ds().unwrap().text_edit.is_some(), "still editing"); + // Not a web or mail link: nothing opens. + u.app.session.execute("text.style", &json!({"id": t, "start": 4, "end": 12, "hyperlink": "file:///etc/passwd"})).unwrap(); + alt_enter(&mut u); + assert_eq!(opened.0.lock().unwrap().len(), 1); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d936c9408..7a416f2d6 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-02 · **Change:** patch (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); 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-02 · **Change:** patch (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; 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: @@ -89,7 +89,7 @@ interaction feel not yet compared. | 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`). 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) | -| 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`); 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; no spell check | | 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`) | | Comment (C), Shift+C to show/hide | done | local only | @@ -129,8 +129,8 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | | Count | Notes | |---|---|---| -| Documented shortcuts (rows) | 133 | each with macOS and Windows/Linux keys | -| Bound as documented | 132 (110 before this suite) | 111 keymap bindings, 15 held keys, gestures and presentation keys, 6 vector edit tool keys | +| Documented shortcuts (rows) | 134 | each with macOS and Windows/Linux keys | +| Bound as documented | 133 (110 before this suite) | 112 keymap bindings, 15 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 | @@ -180,6 +180,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | 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`. | +| 2026-11-02 | patch | Shortcuts: Alt+Enter while editing text opens the link at the caret ("When editing text, press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma) through the new `text.openLink` command, which hands a web or mail link to the platform's opener and refuses any other scheme as the prototype player does; editing goes on. The key went to the editor as a plain Enter before. A documented row: 134 documented, 133 bound. Tests: engine `text_link_tests`, `text_link_tests` (UI) | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From e65ce42000ea2bd3c31d14f6c7e47d14bc6ab164 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 05:31:32 -0500 Subject: [PATCH 113/326] M7: Minimize collapses the navigation bar and both sidebars, the right one back while something is selected (#1835) (#1865) * M7: Minimize collapses the navigation bar and both sidebars, the right one back while something is selected (#1835) Co-Authored-By: Claude Fable 5.1 * M7: a narrow window ignores Minimize, and a rename started while minimized waits without repaints Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/view.rs | 7 ++ crates/engine/src/keymap.rs | 2 +- crates/engine/src/shortcut_parity_tests.rs | 2 +- crates/engine/src/view_state.rs | 4 + crates/ui-egui/locales/ar.toml | 1 - crates/ui-egui/locales/bn.toml | 1 - crates/ui-egui/locales/bs.toml | 1 - crates/ui-egui/locales/cs.toml | 1 - crates/ui-egui/locales/de.toml | 1 - crates/ui-egui/locales/en.toml | 2 +- crates/ui-egui/locales/es.toml | 1 - crates/ui-egui/locales/fi.toml | 1 - crates/ui-egui/locales/fr.toml | 1 - crates/ui-egui/locales/id.toml | 1 - crates/ui-egui/locales/it.toml | 1 - crates/ui-egui/locales/ja.toml | 1 - crates/ui-egui/locales/ka.toml | 1 - crates/ui-egui/locales/ko.toml | 1 - crates/ui-egui/locales/nl.toml | 1 - crates/ui-egui/locales/pl.toml | 1 - crates/ui-egui/locales/pt-BR.toml | 1 - crates/ui-egui/locales/ru.toml | 1 - crates/ui-egui/locales/sv.toml | 1 - crates/ui-egui/locales/th.toml | 1 - crates/ui-egui/locales/tr.toml | 1 - crates/ui-egui/locales/vi.toml | 1 - crates/ui-egui/locales/zh-Hans.toml | 1 - crates/ui-egui/src/app.rs | 22 ++++-- crates/ui-egui/src/app/control.rs | 1 + crates/ui-egui/src/app/frame.rs | 16 ++++ crates/ui-egui/src/idle_tests.rs | 17 +++++ crates/ui-egui/src/panel_width_tests.rs | 85 +++++++++++++++++++++- crates/ui-egui/src/panels/layers.rs | 6 +- crates/ui-egui/src/shortcuts_tests.rs | 6 +- docs/ui-parity.md | 5 +- 35 files changed, 161 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 1fc2ef22a..60a5c26f1 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -321,6 +321,13 @@ pub fn specs() -> Vec { spec!("view.snapObjects", "Snap to objects", "{on?}", false, |s, p| toggle(s, p, "view.snapObjects")), spec!("view.snapPixel", "Snap to pixel grid", "{on?}", false, |s, p| toggle(s, p, "view.snapPixel")), spec!("view.toggleUi", "Show/Hide UI", "{on?}", false, |s, p| flag(s, p, |v| &mut v.ui_hidden)), + spec!( + "view.minimize", + "Minimize the interface", + "{on?} collapses the navigation bar and both sidebars and keeps the toolbar (Shift+Cmd/Ctrl+\\, the Minimize button by the file name); the right sidebar shows while something is selected", + false, + |s, p| flag(s, p, |v| &mut v.ui_minimized) + ), spec!("view.fullscreen", "Full screen", "{on?} the window fills the screen (the desktop app; a no-op headless)", false, |s, p| { s.request_ui("window.fullscreen", json!({"on": boolean(p, "on")})); ok() diff --git a/crates/engine/src/keymap.rs b/crates/engine/src/keymap.rs index 4f55fa4ad..cec22d62f 100644 --- a/crates/engine/src/keymap.rs +++ b/crates/engine/src/keymap.rs @@ -225,7 +225,7 @@ pub static KEYS: &[Binding] = &[ k(View, "view.prototype", &["Alt+9"]).label("Prototype panel"), k(View, "view.designPrototype", &["Shift+E"]), k(View, "view.devMode", &["Shift+D"]).label("Dev Mode on/off"), - k(View, "view.leftSidebar", &["Shift+Cmd+\\"]), + k(View, "view.minimize", &["Shift+Cmd+\\"]), k(View, "view.nextRegion", &["F6"]).win(&["F6", "Ctrl+F6"]).label("Focus the next region (toolbar, layers, canvas, properties)").both(), k(View, "view.previousRegion", &["Shift+F6"]).label("Focus the previous region").both(), k(View, "view.contextMenu", &["Shift+F10", "Menu"]).label("Context menu of the selection (the focused layer row or the canvas)"), diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index 31ce9d18e..46eb14447 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -145,7 +145,7 @@ static ROWS: &[Row] = &[ doc(View, "Outline mode", &["Shift+Cmd+O"], &[], Bound("view.outlines"), ""), doc(View, "Pixel preview", &["Ctrl+P"], &["Ctrl+Alt+P"], Bound("view.pixelPreview"), ""), doc(View, "Others' cursors in a live session", &["Alt+Cmd+\\"], &["Ctrl+Alt+\\"], Bound("view.multiplayerCursors"), "new command"), - doc(View, "Hide the side panels (minimize the interface)", &["Shift+Cmd+\\"], &[], Bound("view.leftSidebar"), ""), + doc(View, "Minimize the interface: the navigation bar and both sidebars", &["Shift+Cmd+\\"], &[], Bound("view.minimize"), "the toolbar stays; the right sidebar shows while something is selected"), doc(View, "Layers panel", &["Alt+1"], &["Alt+1", "Ctrl+1"], Bound("view.layers"), "one article writes Ctrl+1 for Windows, another Alt+1; both bound there"), doc(View, "Interface scale: make larger", &["Alt+Shift+Cmd+="], &[], Bound("pref.uiScaleUp"), "Accessibility at Figma, Adjust the scale of the Figma UI"), doc(View, "Interface scale: make smaller", &["Alt+Shift+Cmd+-"], &[], Bound("pref.uiScaleDown"), "Accessibility at Figma"), diff --git a/crates/engine/src/view_state.rs b/crates/engine/src/view_state.rs index 54102d6b7..fd70b4b11 100644 --- a/crates/engine/src/view_state.rs +++ b/crates/engine/src/view_state.rs @@ -38,6 +38,9 @@ pub struct ViewState { pub snap_objects: bool, pub snap_pixel: bool, pub ui_hidden: bool, + /// Minimized interface (Shift+Cmd/Ctrl+\): the navigation bar and both sidebars are collapsed + /// and the toolbar stays; the right sidebar shows while something is selected. + pub ui_minimized: bool, } impl Default for ViewState { @@ -67,6 +70,7 @@ impl Default for ViewState { snap_objects: true, snap_pixel: true, ui_hidden: false, + ui_minimized: false, } } } diff --git a/crates/ui-egui/locales/ar.toml b/crates/ui-egui/locales/ar.toml index 86a21e234..a3dcf0844 100644 --- a/crates/ui-egui/locales/ar.toml +++ b/crates/ui-egui/locales/ar.toml @@ -288,7 +288,6 @@ status = "draft — needs native review" "Code" = "الكود" "Code syntax" = "صياغة الكود" "Collapse" = "طي" -"Collapse panel" = "طي اللوحة" "Collection" = "مجموعة" "Collections" = "المجموعات" "Color" = "اللون" diff --git a/crates/ui-egui/locales/bn.toml b/crates/ui-egui/locales/bn.toml index 9f2e6421a..32d66721f 100644 --- a/crates/ui-egui/locales/bn.toml +++ b/crates/ui-egui/locales/bn.toml @@ -275,7 +275,6 @@ status = "draft — needs native review" "Code" = "কোড" "Code syntax" = "কোড সিনট্যাক্স" "Collapse" = "সংকুচিত করুন" -"Collapse panel" = "প্যানেল সংকুচিত করুন" "Collection" = "সংগ্রহ" "Collections" = "সংগ্রহসমূহ" "Color" = "রঙ" diff --git a/crates/ui-egui/locales/bs.toml b/crates/ui-egui/locales/bs.toml index 67e0a14cd..72f0268bd 100644 --- a/crates/ui-egui/locales/bs.toml +++ b/crates/ui-egui/locales/bs.toml @@ -288,7 +288,6 @@ status = "draft — needs native review" "Code" = "Kod" "Code syntax" = "Sintaksa koda" "Collapse" = "Skupi" -"Collapse panel" = "Skupi panel" "Collection" = "Kolekcija" "Collections" = "Kolekcije" "Color" = "Boja" diff --git a/crates/ui-egui/locales/cs.toml b/crates/ui-egui/locales/cs.toml index e77610771..16de8065a 100644 --- a/crates/ui-egui/locales/cs.toml +++ b/crates/ui-egui/locales/cs.toml @@ -265,7 +265,6 @@ status = "draft — needs native review" "Code" = "Kód" "Code syntax" = "Syntaxe kódu" "Collapse" = "Sbalit" -"Collapse panel" = "Sbalit panel" "Collection" = "Kolekce" "Collections" = "Kolekce" "Color" = "Barva" diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index b088b2d32..344e70912 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -263,7 +263,6 @@ status = "draft — needs native review" "Code" = "Code" "Code syntax" = "Code-Syntax" "Collapse" = "Einklappen" -"Collapse panel" = "Bereich einklappen" "Collection" = "Sammlung" "Collections" = "Sammlungen" "Color" = "Farbe" diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 034e3381a..a23c281ba 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -293,7 +293,6 @@ name = "English" "Code" = "Code" "Code syntax" = "Code syntax" "Collapse" = "Collapse" -"Collapse panel" = "Collapse panel" "Collection" = "Collection" "Collections" = "Collections" "Color" = "Color" @@ -536,6 +535,7 @@ name = "English" "Exclusion" = "Exclusion" "Exit focus view (Esc)" = "Exit focus view (Esc)" "Expand" = "Expand" +"Expand the interface" = "Expand the interface" "Export" = "Export" "Export all" = "Export all" "Export frames and layers as PNG, JPG, SVG or PDF" = "Export frames and layers as PNG, JPG, SVG or PDF" diff --git a/crates/ui-egui/locales/es.toml b/crates/ui-egui/locales/es.toml index 3b1f7296e..b9e004dd0 100644 --- a/crates/ui-egui/locales/es.toml +++ b/crates/ui-egui/locales/es.toml @@ -293,7 +293,6 @@ status = "draft — needs native review" "Code" = "Código" "Code syntax" = "Sintaxis de código" "Collapse" = "Contraer" -"Collapse panel" = "Contraer panel" "Collection" = "Colección" "Collections" = "Colecciones" "Color" = "Color" diff --git a/crates/ui-egui/locales/fi.toml b/crates/ui-egui/locales/fi.toml index f181ba8a5..0c74f9de7 100644 --- a/crates/ui-egui/locales/fi.toml +++ b/crates/ui-egui/locales/fi.toml @@ -281,7 +281,6 @@ status = "draft — needs native review" "Code or invite link" = "Koodi tai kutsulinkki" "Code syntax" = "Koodin syntaksi" "Collapse" = "Tiivistä muunnokset" -"Collapse panel" = "Supista paneeli" "Collection" = "Kokoelma" "Collections" = "Kokoelmat" "Color" = "Väri" diff --git a/crates/ui-egui/locales/fr.toml b/crates/ui-egui/locales/fr.toml index 42a35007b..b30abe731 100644 --- a/crates/ui-egui/locales/fr.toml +++ b/crates/ui-egui/locales/fr.toml @@ -269,7 +269,6 @@ status = "draft — needs native review" "Code" = "Code" "Code syntax" = "Syntaxe du code" "Collapse" = "Réduire" -"Collapse panel" = "Réduire le panneau" "Collection" = "Collection" "Collections" = "Collections" "Color" = "Couleur" diff --git a/crates/ui-egui/locales/id.toml b/crates/ui-egui/locales/id.toml index a3457d820..da08f159d 100644 --- a/crates/ui-egui/locales/id.toml +++ b/crates/ui-egui/locales/id.toml @@ -281,7 +281,6 @@ status = "draft — needs native review" "Code" = "Kode" "Code syntax" = "Sintaks kode" "Collapse" = "Ciutkan" -"Collapse panel" = "Ciutkan panel" "Collection" = "Koleksi" "Collections" = "Koleksi" "Color" = "Warna" diff --git a/crates/ui-egui/locales/it.toml b/crates/ui-egui/locales/it.toml index ce54d15db..3d2877e7e 100644 --- a/crates/ui-egui/locales/it.toml +++ b/crates/ui-egui/locales/it.toml @@ -259,7 +259,6 @@ status = "draft — needs native review" "Code" = "Codice" "Code syntax" = "Sintassi del codice" "Collapse" = "Comprimi" -"Collapse panel" = "Comprimi pannello" "Collection" = "Collezione" "Collections" = "Collezioni" "Color" = "Colore" diff --git a/crates/ui-egui/locales/ja.toml b/crates/ui-egui/locales/ja.toml index 8e2334f4b..8cf2da2d5 100644 --- a/crates/ui-egui/locales/ja.toml +++ b/crates/ui-egui/locales/ja.toml @@ -270,7 +270,6 @@ status = "draft — needs native review" "Code" = "コード" "Code syntax" = "コード構文" "Collapse" = "折りたたむ" -"Collapse panel" = "パネルを折りたたむ" "Collection" = "コレクション" "Collections" = "コレクション" "Color" = "カラー" diff --git a/crates/ui-egui/locales/ka.toml b/crates/ui-egui/locales/ka.toml index 90dffe678..f634a2e7e 100644 --- a/crates/ui-egui/locales/ka.toml +++ b/crates/ui-egui/locales/ka.toml @@ -279,7 +279,6 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv "Code" = "კოდი" "Code syntax" = "კოდის სინტაქსი" "Collapse" = "ჩაკეცვა" -"Collapse panel" = "პანელის ჩაკეცვა" "Collection" = "კოლექცია" "Collections" = "კოლექციები" "Color" = "ფერი" diff --git a/crates/ui-egui/locales/ko.toml b/crates/ui-egui/locales/ko.toml index 691c1cbc7..d52310997 100644 --- a/crates/ui-egui/locales/ko.toml +++ b/crates/ui-egui/locales/ko.toml @@ -260,7 +260,6 @@ status = "draft — needs native review" "Code" = "코드" "Code syntax" = "코드 구문" "Collapse" = "접기" -"Collapse panel" = "패널 접기" "Collection" = "컬렉션" "Collections" = "컬렉션" "Color" = "색상" diff --git a/crates/ui-egui/locales/nl.toml b/crates/ui-egui/locales/nl.toml index 027b0b3a2..070ca4bb4 100644 --- a/crates/ui-egui/locales/nl.toml +++ b/crates/ui-egui/locales/nl.toml @@ -271,7 +271,6 @@ status = "draft — needs native review" "Code or invite link" = "Code of uitnodigingslink" "Code syntax" = "Code-syntaxis" "Collapse" = "Inklappen" -"Collapse panel" = "Paneel samenvouwen" "Collection" = "Verzameling" "Collections" = "Verzamelingen" "Color" = "Kleur" diff --git a/crates/ui-egui/locales/pl.toml b/crates/ui-egui/locales/pl.toml index 28406332a..05d9b60f8 100644 --- a/crates/ui-egui/locales/pl.toml +++ b/crates/ui-egui/locales/pl.toml @@ -275,7 +275,6 @@ name = "Polski" "Code" = "Kod" "Code syntax" = "Składnia kodu" "Collapse" = "Zwiń" -"Collapse panel" = "Zwiń panel" "Collection" = "Kolekcja" "Collections" = "Kolekcje" "Color" = "Kolor" diff --git a/crates/ui-egui/locales/pt-BR.toml b/crates/ui-egui/locales/pt-BR.toml index 7924ed0f8..1b00ce28c 100644 --- a/crates/ui-egui/locales/pt-BR.toml +++ b/crates/ui-egui/locales/pt-BR.toml @@ -258,7 +258,6 @@ status = "draft — needs native review" "Code" = "Código" "Code syntax" = "Sintaxe de código" "Collapse" = "Recolher" -"Collapse panel" = "Recolher painel" "Collection" = "Coleção" "Collections" = "Coleções" "Color" = "Cor" diff --git a/crates/ui-egui/locales/ru.toml b/crates/ui-egui/locales/ru.toml index 90e6c607b..a9a155818 100644 --- a/crates/ui-egui/locales/ru.toml +++ b/crates/ui-egui/locales/ru.toml @@ -272,7 +272,6 @@ name = "Русский" "Code" = "Код" "Code syntax" = "Синтаксис кода" "Collapse" = "Свернуть" -"Collapse panel" = "Свернуть панель" "Collection" = "Коллекция" "Collections" = "Коллекции" "Color" = "Цвет" diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index 1c9cf0ee2..9384ba152 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -293,7 +293,6 @@ name = "Svenska" "Code" = "Kod" "Code syntax" = "Kodsyntax" "Collapse" = "Komprimera" -"Collapse panel" = "Komprimera panel" "Collection" = "Samling" "Collections" = "Samlingar" "Color" = "Färg" diff --git a/crates/ui-egui/locales/th.toml b/crates/ui-egui/locales/th.toml index d3268bdf9..45de7b858 100644 --- a/crates/ui-egui/locales/th.toml +++ b/crates/ui-egui/locales/th.toml @@ -273,7 +273,6 @@ status = "draft — needs native review" "Code" = "โค้ด" "Code syntax" = "ไวยากรณ์โค้ด" "Collapse" = "ยุบ" -"Collapse panel" = "ยุบแผง" "Collection" = "คอลเลกชัน" "Collections" = "คอลเลกชัน" "Color" = "สี" diff --git a/crates/ui-egui/locales/tr.toml b/crates/ui-egui/locales/tr.toml index 6c80e6864..db05d1c93 100644 --- a/crates/ui-egui/locales/tr.toml +++ b/crates/ui-egui/locales/tr.toml @@ -269,7 +269,6 @@ name = "Türkçe" "Code" = "Kod" "Code syntax" = "Kod söz dizimi" "Collapse" = "Daralt" -"Collapse panel" = "Paneli daralt" "Collection" = "Koleksiyon" "Collections" = "Koleksiyonlar" "Color" = "Renk" diff --git a/crates/ui-egui/locales/vi.toml b/crates/ui-egui/locales/vi.toml index 8149ed30b..8b58fc67e 100644 --- a/crates/ui-egui/locales/vi.toml +++ b/crates/ui-egui/locales/vi.toml @@ -256,7 +256,6 @@ status = "draft — needs native review" "Code or invite link" = "Mã hoặc liên kết mời" "Code syntax" = "Cú pháp mã" "Collapse" = "Thu gọn" -"Collapse panel" = "Thu gọn bảng" "Collection" = "Bộ sưu tập" "Collections" = "Bộ sưu tập" "Color" = "Màu" diff --git a/crates/ui-egui/locales/zh-Hans.toml b/crates/ui-egui/locales/zh-Hans.toml index 2fed25ce2..a6ecb8ab3 100644 --- a/crates/ui-egui/locales/zh-Hans.toml +++ b/crates/ui-egui/locales/zh-Hans.toml @@ -261,7 +261,6 @@ status = "draft — needs native review" "Code" = "代码" "Code syntax" = "代码语法" "Collapse" = "折叠" -"Collapse panel" = "折叠面板" "Collection" = "集合" "Collections" = "集合" "Color" = "颜色" diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index c625f342a..e13acce68 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -274,12 +274,21 @@ impl FigApp { return; } let hidden = self.session.ds().map(|d| d.view.ui_hidden).unwrap_or(false); + // Minimized (Shift+Cmd/Ctrl+\, the Minimize button by the file name): "collapses the + // navigation bar, left sidebar, and right sidebar"; "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). The toolbar stays; Hide UI takes everything. let narrow = !hidden && ui.available_width() < NARROW_WIDTH; + // A narrow window has no sidebars beside the canvas to take: its panels open from their + // buttons as before, and the interface is minimized again once the window is wide. + let minimized = !hidden && !narrow && self.session.ds().is_ok_and(|d| d.view.ui_minimized); + let right_minimized = minimized && self.session.selection().is_empty(); let mobile = self.ui.mobile_panel.filter(|_| narrow); 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) || mobile == Some(MobilePanel::Right); - if !hidden && (!narrow || mobile == Some(MobilePanel::Left)) { + let right_open = (self.right_panel_shown(hidden) && !narrow && !right_minimized) || mobile == Some(MobilePanel::Right); + if !hidden && !minimized && (!narrow || mobile == Some(MobilePanel::Left)) { egui::Panel::left("left_rail") .exact_size(layers::RAIL_WIDTH) .resizable(false) @@ -290,7 +299,7 @@ impl FigApp { }); } // The panels are as wide as asked, less in a window too small for them and the canvas. - let left_open = !hidden && if narrow { mobile == Some(MobilePanel::Left) } else { !self.ui.left_collapsed }; + let left_open = !hidden && !minimized && if narrow { mobile == Some(MobilePanel::Left) } else { !self.ui.left_collapsed }; let (left_w, right_w) = if narrow { let w = (ui.available_width() - MOBILE_STRIP).max(0.0); (if left_open { w } else { 0.0 }, w) @@ -353,6 +362,8 @@ impl FigApp { if narrow { let x = if mobile == Some(MobilePanel::Left) { ctx.content_rect().max.x - MOBILE_STRIP + 4.0 } else { ctx.content_rect().min.x + 4.0 }; self.mobile_buttons(&ctx, egui::pos2(x, rows.min + 8.0)); + } else if minimized { + self.expand_button(&ctx, egui::pos2(ctx.content_rect().min.x + 8.0, rows.min + 8.0)); } // The panels' edges, over the canvas and the panels (drawn after them: they take the press). for (name, x, shown, grows) in edges { @@ -385,8 +396,9 @@ impl FigApp { updates_ui::show(self, &ctx); self.toast_ui(&ctx); // A rename started after the layers panel drew (Cmd/Ctrl+R, a double-click) opens its field - // next frame. - if self.ui.rename.is_some_and(|r| r.start) && !hidden && !self.ui.left_collapsed && self.ui.left_tab == LeftTab::File { + // next frame; while the panel isn't drawn (the interface hidden or minimized, the panel + // closed in a narrow window) the rename waits for it without asking for frames. + if self.ui.rename.is_some_and(|r| r.start) && left_open && self.ui.left_tab == LeftTab::File { ctx.request_repaint(); } a11y::end(self, &ctx); diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 72435673c..f63ab334a 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -102,6 +102,7 @@ impl FigApp { "importReport": self.ui.import_report.as_ref().map(import_report::Report::inspect), }); state["homeSearch"] = json!(self.ui.home_view.file_query); + state["panels"]["minimized"] = json!(self.session.ds().is_ok_and(|d| d.view.ui_minimized)); // Set apart from the literal above, which is at the macro recursion limit. state["uiScale"] = json!({"choice": self.session.prefs.ui_scale, "zoom": self.ui.ui_scale.zoom, "drawn": self.ui.ui_scale.drawn, "limited": self.ui.ui_scale.limited}); state["pendingOpens"] = json!(self.ui.pending_opens.len()); diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 128cd0294..49040b7d9 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -247,6 +247,22 @@ impl FigApp { }); } + /// The way back from a minimized interface by mouse: a small Panels button at the top left of + /// the canvas, where the navigation bar was (the shortcut works too). + pub(super) fn expand_button(&mut self, ctx: &egui::Context, at: egui::Pos2) { + use a11y::Tip as _; + let t = theme::Tokens::get(ctx); + egui::Area::new(egui::Id::unique("expand_interface")).order(egui::Order::Foreground).fixed_pos(at).show(ctx, |ui| { + let (r, resp) = ui.allocate_exact_size(egui::vec2(32.0, 32.0), egui::Sense::click()); + let resp = resp.tip(i18n::tr("Expand the interface")); + ui.painter().rect(r, 8.0, t.panel, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + icons::paint(ui.painter(), r.shrink(8.0), icons::Icon::Panels, t.icon); + if resp.clicked() { + self.run("view.minimize", serde_json::json!({})); + } + }); + } + /// Draw the toast: start its lifetime on the frame **after** the first drawn frame, request /// that frame and the frame that hides it, expire and remove it at the deadline, and place it /// at the bottom centre. diff --git a/crates/ui-egui/src/idle_tests.rs b/crates/ui-egui/src/idle_tests.rs index e2054bc84..ae34ded78 100644 --- a/crates/ui-egui/src/idle_tests.rs +++ b/crates/ui-egui/src/idle_tests.rs @@ -513,3 +513,20 @@ fn a_discarded_sizing_pass_sets_up_and_counts_one_frame_only() { assert_eq!(passes, 2, "egui reran the frame"); assert_eq!(app.frame_stats.frames, frames + 1, "one frame was drawn, not one per pass"); } + +#[test] +fn a_rename_started_while_minimized_waits_for_the_layers_panel_quietly() { + let (mut h, _) = document(); + let r = h.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 40, "height": 40})); + h.run("view.minimize", json!({"on": true})); + h.settle(); + // What Cmd/Ctrl+R leaves: the field opens when the layers panel next draws, which a minimized + // interface doesn't do; no frame is asked for meanwhile. + h.app.ui.rename = Some(crate::panels::layers::Rename { id: id(&r), start: true }); + h.assert_idle("a rename started while the interface is minimized"); + h.run("view.minimize", json!({"on": false})); + for _ in 0..3 { + h.frame(vec![]); + } + assert!(h.app.ui.rename.is_some_and(|r| !r.start), "the field opened once the interface expanded"); +} diff --git a/crates/ui-egui/src/panel_width_tests.rs b/crates/ui-egui/src/panel_width_tests.rs index 6f3eacf7e..357b13669 100644 --- a/crates/ui-egui/src/panel_width_tests.rs +++ b/crates/ui-egui/src/panel_width_tests.rs @@ -160,7 +160,7 @@ fn the_command_sets_and_resets_the_widths() { u.app.run("view.panelWidths", json!({"left": 320, "right": 400})); u.frame(vec![]); assert_eq!(widths(&u), (320.0, 400.0)); - assert_eq!(u.app.inspect()["panels"], json!({"left": 320.0, "right": 400.0, "leftCollapsed": false})); + assert_eq!(u.app.inspect()["panels"], json!({"left": 320.0, "right": 400.0, "leftCollapsed": false, "minimized": false})); u.app.run("view.panelWidths", json!({"left": 5000})); assert_eq!(widths(&u), (*LEFT_PANEL.end(), 400.0), "within its limits; the other panel as it was"); for junk in [json!({"left": "wide"}), json!({"left": null, "right": null}), json!({})] { @@ -210,6 +210,58 @@ fn minimize_ui_hides_the_panels_and_keeps_their_widths() { assert_eq!(edges(&u), (56.0, shown.1)); } +/// The middle of the accessible control with `role` and `label`, if one shows. +fn control(u: &mut Ui, role: egui::accesskit::Role, label: &str) -> Option { + 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; + let n = nodes.iter().map(|(_, n)| n).find(|n| n.role() == role && n.label() == Some(label))?; + let b = n.bounds()?; + Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)) +} + +/// "You can click Minimize next to the file name to collapse the navigation bar, left sidebar, +/// and right sidebar" (Explore the navigation bar and left sidebar; Shift+Cmd/Ctrl+\ too): the +/// rail and both sidebars go, the toolbar and the widths stay. "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." The Expand button at +/// the top left puts everything back (#1835). +#[test] +fn minimize_collapses_the_rail_and_both_sidebars_and_the_right_one_follows_the_selection() { + use egui::accesskit::Role; + let (mut u, _) = ui(); + u.app.run("view.panelWidths", json!({"left": 320, "right": 400})); + u.app.run("select.set", json!({"ids": []})); + u.frame(vec![]); + let shown = edges(&u); + let minimize = control(&mut u, Role::Button, "Minimize").expect("the Minimize button by the file name"); + u.button(minimize, true); + u.button(minimize, false); + u.frame(vec![]); + assert_eq!(edges(&u), (0.0, 1440.0), "no rail and no sidebars: the canvas has the window"); + assert!(control(&mut u, Role::Toolbar, "Tools").is_some(), "the toolbar stays"); + assert_eq!(widths(&u), (320.0, 400.0), "the widths are kept"); + // A selection brings the right sidebar, the left stays away; deselecting takes it again. + u.app.run("select.all", json!({})); + u.frame(vec![]); + assert!(edges(&u).0 == 0.0 && edges(&u).1 < 1440.0, "the right sidebar shows for the selection: {:?}", edges(&u)); + u.app.run("select.set", json!({"ids": []})); + u.frame(vec![]); + assert_eq!(edges(&u), (0.0, 1440.0), "and goes once nothing is selected"); + // Expand puts the interface back as it was. + let expand = control(&mut u, Role::Button, "Expand the interface").expect("the Expand button at the top left"); + u.button(expand, true); + u.button(expand, false); + u.frame(vec![]); + assert_eq!((edges(&u), widths(&u)), (shown, (320.0, 400.0)), "back as it was"); + assert!(control(&mut u, Role::Button, "Expand the interface").is_none()); + // Hide UI hides the toolbar as well, as before. + u.app.run("view.toggleUi", json!({})); + assert!(control(&mut u, Role::Toolbar, "Tools").is_none(), "Hide UI takes the toolbar too"); + u.app.run("view.toggleUi", json!({})); +} + #[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)] { @@ -231,6 +283,37 @@ fn the_smallest_window_keeps_its_canvas_whatever_the_widths() { } } +/// Minimize takes nothing from a phone-sized window, which has no sidebars beside the canvas: its +/// panels open from their buttons as before, and the interface is minimized again once the window +/// is wide. +#[test] +fn a_narrow_window_keeps_its_panel_buttons_while_minimized() { + use crate::MobilePanel; + let ctx = egui::Context::default(); + let mut app = FigApp::new(Session::new(), Box::new(NoServices)); + let mut k = 0.0; + let mut canvas_width = |app: &mut FigApp, size: egui::Vec2| { + for _ in 0..4 { + k += 1.0 / 60.0; + let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)), time: Some(k), ..Default::default() }; + ctx.run_ui(input, |ui| app.ui(ui)).textures_delta.clear(); + } + app.canvas.rect.width() + }; + let phone = vec2(390.0, 844.0); + app.run("view.minimize", json!({"on": true})); + assert!(canvas_width(&mut app, phone) >= 380.0, "closed panels leave the whole width"); + app.ui.mobile_panel = Some(MobilePanel::Left); + let w = canvas_width(&mut app, phone); + assert!((1.0..=60.0).contains(&w), "the Layers button opens the left panel while minimized: {w}"); + app.ui.mobile_panel = None; + let wide = canvas_width(&mut app, vec2(1440.0, 900.0)); + assert!(wide >= 1439.0, "wide again, the interface is minimized: the canvas has the window ({wide})"); + app.run("view.minimize", json!({"on": false})); + let wide = canvas_width(&mut app, vec2(1440.0, 900.0)); + assert!(wide > 600.0 && wide < 1100.0, "expanded, both panels are beside the canvas again ({wide})"); +} + /// A phone-sized window: the canvas has the whole width, and each side panel opens alone over it, /// leaving the strip with the panel buttons. A wide window ignores the choice. #[test] diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index feeed46e6..164ec7e4a 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -159,13 +159,15 @@ pub fn left_panel(app: &mut FigApp, ui: &mut Ui) { ui.painter().text(pos2(head.min.x + 16.0, head.min.y + 46.0), Align2::LEFT_CENTER, tr("Drafts"), regular(11.0), t.text_secondary); } let hr = Rect::from_center_size(pos2(head.max.x - 24.0, head.min.y + 24.0), vec2(24.0, 24.0)); - let hresp = ui.interact(hr, ui.scope_id().with("hideui"), Sense::click()).tip(tr("Collapse panel")); + // Minimize, by the file name: "click Minimize next to the file name to collapse the + // navigation bar, left sidebar, and right sidebar" (Explore the navigation bar and left sidebar). + let hresp = ui.interact(hr, ui.scope_id().with("hideui"), Sense::click()).tip(tr("Minimize")); if hresp.hovered() { ui.painter().rect_filled(hr, CornerRadius::same(5), t.hover); } icons::paint(ui.painter(), hr.shrink(5.0), Icon::Panels, t.icon); if hresp.clicked() { - app.ui.close_left_panel(); + app.run("view.minimize", json!({})); } ui.painter().line_segment([head.left_bottom(), head.right_bottom()], Stroke::new(1.0, t.border)); match app.ui.left_tab { diff --git a/crates/ui-egui/src/shortcuts_tests.rs b/crates/ui-egui/src/shortcuts_tests.rs index 5c1e06fab..4b223b211 100644 --- a/crates/ui-egui/src/shortcuts_tests.rs +++ b/crates/ui-egui/src/shortcuts_tests.rs @@ -124,8 +124,12 @@ fn panel_keys_and_cmd_k() { press(&mut u, Key::D, Modifiers::SHIFT); assert_eq!(u.app.ui.right_tab, RightTab::Design); let collapsed = u.app.ui.left_collapsed; + let minimized = |u: &Ui| u.app.session.ds().unwrap().view.ui_minimized; press(&mut u, Key::Backslash, Modifiers::SHIFT | Modifiers::COMMAND); - assert_eq!(u.app.ui.left_collapsed, !collapsed, "Shift+Cmd+\\ toggles the left sidebar"); + assert!(minimized(&u), "Shift+Cmd+\\ minimizes the interface"); + assert_eq!(u.app.ui.left_collapsed, collapsed, "without collapsing the left sidebar for good"); + press(&mut u, Key::Backslash, Modifiers::SHIFT | Modifiers::COMMAND); + assert!(!minimized(&u), "and back"); press(&mut u, Key::K, Modifiers::COMMAND); assert!(u.app.ui.palette.is_some(), "Cmd+K opens Actions on the canvas"); } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7a416f2d6..1d3c01373 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-02 · **Change:** patch (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; 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-02 · **Change:** patch (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: @@ -17,7 +17,7 @@ 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 | 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 (Cmd+\\) | done | | +| 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 | | 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 | @@ -181,6 +181,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | 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`. | | 2026-11-02 | patch | Shortcuts: Alt+Enter while editing text opens the link at the caret ("When editing text, press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma) through the new `text.openLink` command, which hands a web or mail link to the platform's opener and refuses any other scheme as the prototype player does; editing goes on. The key went to the editor as a plain Enter before. A documented row: 134 documented, 133 bound. Tests: engine `text_link_tests`, `text_link_tests` (UI) | +| 2026-11-02 | patch | M7, #1835: Minimize (`view.minimize`, Shift+Cmd/Ctrl+\\, the Minimize button by the file name) collapses the navigation bar, the left sidebar and the right sidebar and keeps the toolbar and the panel widths ("click Minimize next to the file name to collapse the navigation bar, left sidebar, and right sidebar"; "This collapses the navigation bar, left sidebar, and right sidebar for an expanded view", Explore the navigation bar and left sidebar); the right sidebar shows while something is selected and goes once nothing is; an Expand button at the top left of the canvas puts everything back. The shortcut and the button collapsed the left sidebar alone before (`view.leftSidebar` stays as a command without a key). Tests: `panel_width_tests`, `shortcuts_tests`. Numbers unchanged (the row is bound to the new command) | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Shift+Alt+= and - make the interface larger and smaller through the sizes Preferences offers, and Cmd/Ctrl+Shift+Alt+0 puts it back to the system's size ("Adjust the scale of the Figma UI [...] Reset to Default: Control ⇧Shift Alt 0; Make Larger: Control ⇧Shift Alt =; Make Smaller: Control ⇧Shift Alt -", Accessibility at Figma); the size is kept at once, as one picked in Preferences is. `pref.uiScaleUp`, `pref.uiScaleDown`, `pref.uiScaleReset`; the sizes list now lives in the engine (`UI_SCALE_SIZES`) and Preferences reads it from there. Found by a documentation audit of the shortcuts. Test: `keymap_tests::the_interface_size_keys_step_through_the_preferences_sizes`. Documented rows 130 → 133, bound 129 → 132 | | 2026-11-01 | patch | Shortcuts: Cmd/Ctrl+Alt+↑/↓ (and ←/→) rotate the selection one degree at a time, 15 with Shift ("Press ⌘Command ⌥Option ↑/ ↓ on Mac or Control Alt ↑/↓ on Windows to rotate an object one degree at a time", Accessibility at Figma); they resized by the nudge before, which Cmd/Ctrl+arrows without Alt still do. Down and right turn clockwise, up and left back (the documentation is silent on the direction). In the shortcuts panel's Transform tab, over the control channel's `ui.key` too. Found by a documentation audit of the shortcuts. Test: `shortcut_keys_tests::cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift`. Documented rows 129 → 130, bound 128 → 129 | | 2026-11-01 | patch | Shortcuts: the Layers panel opens with Ctrl+1 as well as Alt+1 on Windows and Linux ("Mac: Option 1 Windows: Ctrl 1" in Select layers and objects; "Windows: Alt 1" in Explore the navigation bar and left sidebar). macOS keeps Option+1. Found by a documentation audit of the shortcuts (every chord driven over the control channel). Tests: `keymap_tests::the_layers_panel_answers_both_of_its_documented_windows_keys`, the parity row. Counts unchanged | From 99d5e3e5881631bd12fb086e8b91bc0aebecd0b5 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 06:05:20 -0500 Subject: [PATCH 114/326] Formatting after the merge Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7247eccdf..20e5847b0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -242,9 +242,9 @@ mod style_props_tests; mod table_paste_tests; #[cfg(test)] mod text_enter_tests; +mod text_link_tests; #[cfg(test)] mod text_mixed_fill_tests; -mod text_link_tests; #[cfg(test)] mod titlebar_tests; #[cfg(test)] From 695ca0752874c94138bd5e362136bf28850a3c42 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 06:43:02 -0500 Subject: [PATCH 115/326] M3: text styles carry paragraph spacing and indent, the list style and the OpenType features (#1829) ParagraphStyle beside TextStyle in StyleKind::Text: style.create takes it from the layer or a value, style.apply sets it (the list on the paragraphs touched for a range), style.update moves it, editing it unlinks, .fig files keep it with the style; tests in styles_behaviour_tests and fig_export_assets_tests. Co-Authored-By: Claude Fable 5.1 --- crates/doc/src/colors.rs | 2 +- crates/doc/src/lib.rs | 2 +- crates/doc/src/styles.rs | 22 ++++- crates/doc/src/text.rs | 68 ++++++++++++++ crates/engine/src/assets/style_vars.rs | 4 +- crates/engine/src/cmd/file/load.rs | 6 +- crates/engine/src/cmd/styles.rs | 94 ++++++++++++++++--- crates/engine/src/content/synthetic_ds.rs | 4 +- crates/engine/src/fig_export_assets_tests.rs | 21 +++++ crates/engine/src/fonts.rs | 2 +- crates/engine/src/fonts/tests.rs | 5 +- crates/engine/src/sketch_import_tests.rs | 2 +- crates/engine/src/styles_behaviour_tests.rs | 65 ++++++++++++- crates/engine/src/text_style_picker_tests.rs | 4 +- crates/format/src/fig/assets_tests.rs | 4 +- crates/format/src/fig/export/assets.rs | 7 +- crates/format/src/fig/text_skip_ink_tests.rs | 6 +- crates/format/src/fig/text_style_tests.rs | 2 +- crates/format/src/penpot.rs | 12 +-- crates/format/src/rest.rs | 10 +- crates/format/src/rest/tests.rs | 2 +- crates/format/src/sketch/shared_tests.rs | 2 +- crates/ui-egui/src/widgets/style_picker.rs | 41 +++++++- .../ui-egui/src/widgets/style_picker/tests.rs | 8 +- docs/components-parity.md | 5 +- docs/mcp.md | 12 ++- 26 files changed, 346 insertions(+), 66 deletions(-) diff --git a/crates/doc/src/colors.rs b/crates/doc/src/colors.rs index f4681601b..bd4dfdbab 100644 --- a/crates/doc/src/colors.rs +++ b/crates/doc/src/colors.rs @@ -79,7 +79,7 @@ impl Style { pub fn for_each_color_mut(&mut self, f: &mut ColorVisitor) { match &mut self.kind { StyleKind::Paint { paints } => paints.iter_mut().for_each(|p| p.for_each_color_mut(f)), - StyleKind::Text { style } => style.for_each_color_mut(f), + StyleKind::Text { style, .. } => style.for_each_color_mut(f), StyleKind::Effect { effects } => effects.iter_mut().for_each(|e| e.for_each_color_mut(f)), StyleKind::Grid { grids } => grids.iter_mut().for_each(|g| f(&mut g.color)), } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 89eb97269..eecb64af2 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1206,7 +1206,7 @@ impl Document { .styles .iter() .filter_map(|s| match &s.kind { - StyleKind::Text { style } => Some((s.id.clone(), style.clone())), + StyleKind::Text { style, .. } => Some((s.id.clone(), style.clone())), _ => None, }) .collect(); diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index f3893077e..b10806e33 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -1,7 +1,7 @@ //! Shared styles and variables. use crate::props::{Effect, LayoutGrid}; -use crate::text::TextStyle; +use crate::text::{ParagraphStyle, TextStyle}; use figcraft_color::{Color, Paint}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; @@ -14,10 +14,22 @@ pub type ModeId = String; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum StyleKind { - Paint { paints: Vec }, - Text { style: TextStyle }, - Effect { effects: Vec }, - Grid { grids: Vec }, + Paint { + paints: Vec, + }, + Text { + style: TextStyle, + /// What the style sets at the paragraph and layer level (#1829); boxed to keep the enum + /// small. + #[serde(default, skip_serializing_if = "crate::node::is_default")] + paragraph: Box, + }, + Effect { + effects: Vec, + }, + Grid { + grids: Vec, + }, } impl StyleKind { diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 0c41d3c9a..76771c80c 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -291,6 +291,23 @@ pub struct TextStyle { pub style_id: Option, } +/// What a text style sets at the paragraph and layer level, beside its character style +/// ([`TextStyle`]): 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). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ParagraphStyle { + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_spacing: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub paragraph_indent: f64, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub list: ListStyle, + #[serde(skip_serializing_if = "crate::node::is_default")] + pub features: std::collections::BTreeMap, +} + /// The font new text starts in. A build can name another (`FIGCRAFT_DEFAULT_FONT="Noto Sans Thai"`, /// for a distribution whose users mostly write a script Inter lacks); empty means Inter. pub const DEFAULT_FONT: &str = match option_env!("FIGCRAFT_DEFAULT_FONT") { @@ -843,6 +860,57 @@ impl TextData { (a..=b).all(|p| self.para_list(p).list == first.list && self.para_list(p).indent == first.indent).then_some(first) } + /// What a text style made from this text sets at the paragraph and layer level: the paragraph + /// spacing and indent, the list style (the one every paragraph shares; the base one when they + /// differ) and the OpenType features. + pub fn paragraph_style(&self) -> ParagraphStyle { + let list = match self.paragraphs.first() { + 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() } + } + + /// Take what text style `ps` sets at the paragraph and layer level: the spacing, indent and + /// features on the layer, the list style on every paragraph. + pub fn take_paragraph_style(&mut self, ps: &ParagraphStyle) { + let len = self.char_count(); + self.take_paragraph_style_in(0, len, ps); + } + + /// As [`take_paragraph_style`](Self::take_paragraph_style), with the list style going to the + /// paragraphs chars `start..end` touch only; the spacing, indent and features are the + /// layer's, as in Figma. + pub fn take_paragraph_style_in(&mut self, start: usize, end: usize, ps: &ParagraphStyle) { + self.paragraph_spacing = ps.paragraph_spacing; + self.paragraph_indent = ps.paragraph_indent; + self.features.clone_from(&ps.features); + self.set_para_lists(start, end, |pl| pl.list = ps.list); + } + + /// Follow text style `id`'s paragraph-level definition wherever chars link to it. + pub fn update_paragraph_style(&mut self, id: &str, ps: &ParagraphStyle) { + let linked: Vec<(usize, usize)> = + self.spans().into_iter().filter(|(_, _, s)| s.style_id.as_deref() == Some(id)).map(|(a, b, _)| (a, b)).collect(); + for (a, b) in linked { + self.take_paragraph_style_in(a, b, ps); + } + } + + /// Whether chars `start..end` show what text style `ps` sets at the paragraph and layer + /// level: the layer's spacing, indent and features, and their paragraphs' list style. + pub fn shows_paragraph_style_in(&self, start: usize, end: usize, ps: &ParagraphStyle) -> bool { + self.paragraph_spacing == ps.paragraph_spacing + && self.paragraph_indent == ps.paragraph_indent + && self.features == ps.features + && self.common_para_list(start, end).is_some_and(|pl| pl.list == ps.list) + } + + /// Whether the whole text shows what text style `ps` sets at the paragraph and layer level. + pub fn shows_paragraph_style(&self, ps: &ParagraphStyle) -> bool { + self.shows_paragraph_style_in(0, self.char_count(), ps) + } + /// Link chars `start..end` (all of them when the range is empty or the whole text) to text /// style `id`, defined as `def`. pub fn link_text_style(&mut self, start: usize, end: usize, def: &TextStyle, id: &str) { diff --git a/crates/engine/src/assets/style_vars.rs b/crates/engine/src/assets/style_vars.rs index 7fb30fd06..12db4eaa8 100644 --- a/crates/engine/src/assets/style_vars.rs +++ b/crates/engine/src/assets/style_vars.rs @@ -113,7 +113,7 @@ fn resolved(vars: &Variables, st: &Style, modes: &Modes) -> StyleKind { (StyleKind::Grid { grids }, Some((BoundList::Grids, i, field)), VariableValue::Number(x)) => { crate::cmd::lists::set_grid_field(grids, i, field, *x); } - (StyleKind::Text { style }, None, _) => set_text_field(style, key, &val), + (StyleKind::Text { style, .. }, None, _) => set_text_field(style, key, &val), _ => {} } } @@ -206,7 +206,7 @@ pub fn refresh(doc: &mut Document, before: Option<&Document>, only: Option<&BTre && was.is_none_or(|w| w.kind == n.kind) { for st in doc.styles.iter().filter(|s| !s.bound.is_empty()) { - if let StyleKind::Text { style } = kind_for(doc, st, id).as_ref() { + if let StyleKind::Text { style, .. } = kind_for(doc, st, id).as_ref() { t.update_text_style(&st.id, style); } } diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index 5033a057e..3e917d5dd 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -250,7 +250,7 @@ fn match_font_families(doc: &mut Document) { } // Shared text styles too, so they stay like the layers linked to them. for st in &mut doc.styles { - if let StyleKind::Text { style } = &mut st.kind { + if let StyleKind::Text { style, .. } = &mut st.kind { fix(style); } } @@ -294,7 +294,7 @@ fn platform_tracking(doc: &mut Document) { } } for st in &mut doc.styles { - if let StyleKind::Text { style } = &mut st.kind { + if let StyleKind::Text { style, .. } = &mut st.kind { track(style); } } @@ -365,7 +365,7 @@ fn sketch_line_heights(doc: &mut Document) { } } for st in &mut doc.styles { - if let StyleKind::Text { style } = &mut st.kind { + if let StyleKind::Text { style, .. } = &mut st.kind { set(style); } } diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 99d4521e4..313062a68 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -3,6 +3,7 @@ use std::collections::BTreeMap; use figcraft_color::{Color, Paint, PaintKind}; +use figcraft_doc::ParagraphStyle; use figcraft_doc::{ Collection, CollectionId, Document, Effect, EffectKind, Mode, ModeId, Node, NodeId, NodeKind, Style, StyleId, StyleKind, TextData, TextStyle, Variable, VariableId, VariableType, VariableValue, Variables, trim_num, @@ -261,6 +262,41 @@ fn text_style_of(n: &Node, at: Option) -> Option { Some(at.map_or(&t.style, |a| t.style_at(a)).as_text_style()) } +/// What a text style definition from JSON sets at the paragraph level, in the `node.set` +/// spellings (`paragraphSpacing`, `paragraphIndent`, `listStyle`: none|bulleted|numbered, +/// `features` or `openTypeFeatures`: `{tag: bool}`); keys left out are the defaults. +fn paragraph_style_json(cmd: &str, v: &Value) -> Result { + let Value::Object(m) = v else { return Ok(ParagraphStyle::default()) }; + let mut ps = ParagraphStyle::default(); + let length = + |k: &str, x: &Value| f64_of(x).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 10_000.0)).ok_or_else(|| bad(cmd, format!("{k}: a number"))); + for (k, x) in m { + match k.as_str() { + "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"))?, + "features" | "openTypeFeatures" | "fontFeatures" | "textFeatures" => { + ps.features = super::props::features_of(cmd, x)?.into_iter().filter_map(|(tag, on)| Some((tag, on?))).collect(); + } + _ => {} + } + } + Ok(ps) +} + +/// What a layer's text sets at the paragraph level, the list style being that of the paragraphs +/// chars `range` touch when given (the layer's when they differ). +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; + } + Some(ps) +} + fn detach(s: &mut Session, p: &Value) -> Result { let cmd = "style.detach"; let which = req_string(cmd, p, "which")?; @@ -295,7 +331,7 @@ fn kind_from_node(t: &str, n: &Node) -> Option { Some(match t { "paint" | "color" | "fill" => StyleKind::Paint { paints: n.fills.clone() }, "stroke" => StyleKind::Paint { paints: n.strokes.clone() }, - "text" => StyleKind::Text { style: text_style_of(n, None)? }, + "text" => StyleKind::Text { style: text_style_of(n, None)?, paragraph: Box::new(paragraph_style_of(n, None)?) }, "effect" => StyleKind::Effect { effects: n.effects.clone() }, "grid" => StyleKind::Grid { grids: n.grids.clone() }, _ => return None, @@ -317,13 +353,17 @@ fn create(s: &mut Session, p: &Value) -> Result { let kind = if let Some(v) = get(p, "value") { match t.as_str() { "paint" | "color" | "fill" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)? }, + "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, "grid" => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => return Err(bad(cmd, "type: paint|text|effect|grid")), } - } else if let Some((tid, a, _)) = range { - StyleKind::Text { style: doc.node(tid).and_then(|n| text_style_of(n, Some(a))).ok_or_else(|| bad(cmd, "not a text layer"))? } + } else if let Some((tid, a, b)) = range { + let n = doc.node(tid).ok_or_else(|| bad(cmd, "not a text layer"))?; + StyleKind::Text { + style: text_style_of(n, Some(a)).ok_or_else(|| bad(cmd, "not a text layer"))?, + paragraph: Box::new(paragraph_style_of(n, Some((a, b))).ok_or_else(|| bad(cmd, "not a text layer"))?), + } } else { let n = from.and_then(|f| doc.node(f)).ok_or_else(|| bad(cmd, "pass `value` or select a layer to take it from"))?; kind_from_node(&t, n).ok_or_else(|| bad(cmd, "that layer has no such property"))? @@ -343,7 +383,7 @@ fn create(s: &mut Session, p: &Value) -> Result { }; doc.styles.push(Style { id: sid.clone(), name, description: string(p, "description").unwrap_or_default(), kind: kind.clone(), bound }); // The source layer (or the selected chars) becomes linked to the new style. - if let (Some((tid, a, b)), StyleKind::Text { style }) = (range, &kind) { + if let (Some((tid, a, b)), StyleKind::Text { style, .. }) = (range, &kind) { if let NodeKind::Text(td) = &mut doc.get_mut(tid)?.kind { td.link_text_style(a, b, style, &sid); } @@ -387,11 +427,13 @@ pub fn apply_style_ref(doc: &mut Document, id: NodeId, field: &str, sid: Option< n.grids = grids.clone(); n.styles.grid = Some(id.clone()); } - ("textStyle", Some(Style { kind: StyleKind::Text { style }, id, .. })) => { - // Every char takes the style's typography (their fills and links stay). + ("textStyle", Some(Style { kind: StyleKind::Text { style, paragraph }, id, .. })) => { + // Every char takes the style's typography (their fills and links stay), and the layer + // what the style sets at the paragraph level (#1829). if let NodeKind::Text(t) = &mut n.kind { let len = t.char_count(); t.link_text_style(0, len, style, id); + t.take_paragraph_style(paragraph); } n.styles.text = Some(id.clone()); } @@ -416,7 +458,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { let st = req_string(cmd, p, "style")?; let style = s.doc()?.style(&st).cloned().ok_or_else(|| bad(cmd, format!("no style `{st}`")))?; // Text styles go on chars: a range, the selected chars of the edited text, or whole layers. - if let StyleKind::Text { style: def } = &style.kind { + if let StyleKind::Text { style: def, paragraph } = &style.kind { // A text style is no property of other layers: they're left alone. let doc = s.doc()?; let targets: Vec = @@ -430,6 +472,8 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { Some((a, b)) => { if let NodeKind::Text(t) = &mut doc.get_mut(i)?.kind { t.link_text_style(a, b, def, &style.id); + // The list goes to the paragraphs touched; the rest is the layer's. + t.take_paragraph_style_in(a, b, paragraph); } } None => apply_style_ref(doc, i, "textStyle", Some(&style.id))?, @@ -506,7 +550,7 @@ fn update(s: &mut Session, p: &Value) -> Result { let cur = doc.styles.get(idx).map(|x| x.kind.type_name()).unwrap_or("paint"); Some(match cur { "paint" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)? }, + "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, }) @@ -651,22 +695,23 @@ fn rename_folder(s: &mut Session, p: &Value) -> Result { /// Re-apply style `sid` to every node (and text chars) linked to it. pub fn propagate_style(doc: &mut Document, sid: &str) { let text_def = match doc.style(sid).map(|s| &s.kind) { - Some(StyleKind::Text { style }) => Some(style.clone()), + Some(StyleKind::Text { style, paragraph }) => Some((style.clone(), paragraph.clone())), _ => None, }; let ids: Vec = doc.ids().collect(); for i in ids { let Some(n) = doc.node(i) else { continue }; - if let Some(def) = &text_def { + if let Some((def, paragraph)) = &text_def { if n.kind.text().is_some_and(|t| t.links_text_style(sid)) { let def = match doc.style(sid).map(|st| crate::style_vars::kind_for(doc, st, i).into_owned()) { - Some(StyleKind::Text { style }) => style, + Some(StyleKind::Text { style, .. }) => style, _ => def.clone(), }; if let Ok(n) = doc.get_mut(i) && let NodeKind::Text(t) = &mut n.kind { t.update_text_style(sid, &def); + t.update_paragraph_style(sid, paragraph); } } continue; @@ -695,7 +740,16 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { .styles .iter() .filter_map(|s| match &s.kind { - StyleKind::Text { style } => Some((s.id.clone(), style.clone())), + StyleKind::Text { style, .. } => Some((s.id.clone(), style.clone())), + _ => None, + }) + .collect(); + // What each text style sets at the paragraph level (#1829); no variable binds those. + let paras: BTreeMap<&str, &ParagraphStyle> = doc + .styles + .iter() + .filter_map(|s| match &s.kind { + StyleKind::Text { paragraph, .. } => Some((s.id.as_str(), paragraph.as_ref())), _ => None, }) .collect(); @@ -707,7 +761,7 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { // Styles with bound fields read as this layer sees them. let mut defs = std::borrow::Cow::Borrowed(&defs); for st in &varying { - if let StyleKind::Text { style } = crate::style_vars::kind_for(doc, st, id).into_owned() { + if let StyleKind::Text { style, .. } = crate::style_vars::kind_for(doc, st, id).into_owned() { defs.to_mut().insert(st.id.clone(), style); } } @@ -717,11 +771,23 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { && t2.text_style_link() == Some(None) && let Some(def) = defs.get(sid) && t2.spans().iter().all(|(_, _, s)| s.shows_text_style(def)) + && paras.get(sid.as_str()).is_some_and(|ps| t2.shows_paragraph_style(ps)) { let len = t2.char_count(); t2.restyle(0, len, |s| s.style_id = Some(sid.clone())); } t2.check_text_styles(|sid| defs.get(sid)); + // Chars whose paragraphs left their style's list, and every char of a layer whose + // paragraph spacing, indent or features were edited, unlink too (#1829). + let gone: Vec<(usize, usize)> = t2 + .spans() + .iter() + .filter(|(a, b, s)| s.style_id.as_deref().is_some_and(|sid| paras.get(sid).is_none_or(|ps| !t2.shows_paragraph_style_in(*a, *b, ps)))) + .map(|(a, b, _)| (*a, *b)) + .collect(); + for (a, b) in gone { + t2.unlink_text_style(a, b); + } let link = t2.text_style_link().flatten().map(str::to_string); if t2 != *t || link != n.styles.text { updates.push((id, link, t2)); diff --git a/crates/engine/src/content/synthetic_ds.rs b/crates/engine/src/content/synthetic_ds.rs index 74558567f..be5268355 100644 --- a/crates/engine/src/content/synthetic_ds.rs +++ b/crates/engine/src/content/synthetic_ds.rs @@ -154,7 +154,7 @@ fn auto_layout(doc: &mut Document, id: NodeId, mode: LayoutMode, gap: f64, pad: fn styled_text(doc: &mut Document, parent: NodeId, chars: &str, name: &str, style: &str) -> DocResult { let id = doc.create(parent, text(chars), name, 0.0, 0.0, 60.0, 16.0)?; let def = doc.styles.iter().find(|s| s.id == style).and_then(|s| match &s.kind { - StyleKind::Text { style } => Some(style.clone()), + StyleKind::Text { style, .. } => Some(style.clone()), _ => None, }); set_node(doc, id, |n| { @@ -242,7 +242,7 @@ fn foundations(doc: &mut Document) -> (CollectionId, ModeId, ModeId) { id: format!("ds:text:{name}"), name: name.into(), description: String::new(), - kind: StyleKind::Text { style }, + kind: StyleKind::Text { style, paragraph: Default::default() }, bound: Default::default(), }); } diff --git a/crates/engine/src/fig_export_assets_tests.rs b/crates/engine/src/fig_export_assets_tests.rs index f5b9f7758..ef88bc680 100644 --- a/crates/engine/src/fig_export_assets_tests.rs +++ b/crates/engine/src/fig_export_assets_tests.rs @@ -122,6 +122,27 @@ fn variables_styles_and_instance_sizes_come_back() { assert!(after.iter().any(|l| l.contains("\"In the dark\"") && l.contains("FFFFFF")), "{after:#?}"); } +/// #1829: a text style's paragraph spacing and indent and its list style go through a `.fig` +/// file with it (the style's sample layer carries them, as a Figma file's does). +#[test] +fn a_text_styles_paragraph_values_come_back_from_a_fig_file() { + let mut s = Session::new(); + let t = id(&run(&mut s, "text.create", json!({"text": "One\nTwo", "x": 0, "y": 0}))); + run(&mut s, "node.set", json!({"ids": [t], "paragraphSpacing": 12, "paragraphIndent": 8, "listStyle": "bulleted"})); + run(&mut s, "style.create", json!({"type": "text", "name": "Audit", "from": t})); + let path = std::env::temp_dir().join(format!("figcraft-fig-text-style-{}.fig", std::process::id())); + run(&mut s, "file.export", json!({"format": "fig", "path": path.to_string_lossy()})); + run(&mut s, "file.open", json!({"path": path.to_string_lossy()})); + let _ = std::fs::remove_file(&path); + let doc = s.doc().unwrap(); + let st = doc.styles.iter().find(|x| x.name == "Audit").unwrap(); + let figcraft_doc::StyleKind::Text { paragraph, .. } = &st.kind else { panic!("{:?}", st.kind) }; + assert_eq!((paragraph.paragraph_spacing, paragraph.paragraph_indent, paragraph.list), (12.0, 8.0, figcraft_doc::ListStyle::Bulleted)); + // The layer the style was made from is linked to it again, showing the same values. + let layer = doc.nodes().find(|n| n.kind.text().is_some()).unwrap(); + assert_eq!(layer.styles.text.as_deref(), Some(st.id.as_str())); +} + #[test] fn every_example_keeps_its_variables_and_styles() { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples"); diff --git a/crates/engine/src/fonts.rs b/crates/engine/src/fonts.rs index 484e7b88e..e0538db67 100644 --- a/crates/engine/src/fonts.rs +++ b/crates/engine/src/fonts.rs @@ -54,7 +54,7 @@ pub fn missing(doc: &Document) -> Vec { } } for st in &doc.styles { - if let StyleKind::Text { style } = &st.kind { + if let StyleKind::Text { style, .. } = &st.kind { add(&style.font_family, false); } if let Some(var) = st.bound.get("fontFamily") { diff --git a/crates/engine/src/fonts/tests.rs b/crates/engine/src/fonts/tests.rs index 5df9a8540..fc9713535 100644 --- a/crates/engine/src/fonts/tests.rs +++ b/crates/engine/src/fonts/tests.rs @@ -37,7 +37,10 @@ fn lists_families_of_layers_ranges_styles_and_variables_once_each() { id: "S:1".into(), name: "Heading".into(), description: String::new(), - kind: StyleKind::Text { style: TextStyle { font_family: "FigCraft Missing C".into(), ..TextStyle::default() } }, + kind: StyleKind::Text { + style: TextStyle { font_family: "FigCraft Missing C".into(), ..TextStyle::default() }, + paragraph: Default::default(), + }, bound: Default::default(), }); s.execute("variable.createCollection", &json!({"name": "Type", "modes": ["Light", "Dark"]})).unwrap(); diff --git a/crates/engine/src/sketch_import_tests.rs b/crates/engine/src/sketch_import_tests.rs index e05dade6c..b5ddab8b0 100644 --- a/crates/engine/src/sketch_import_tests.rs +++ b/crates/engine/src/sketch_import_tests.rs @@ -520,7 +520,7 @@ fn sketch_shared_text_styles_match_their_layers() { .styles .iter() .find_map(|st| match &st.kind { - figcraft_doc::StyleKind::Text { style } if st.name == "Body" => Some(style.clone()), + figcraft_doc::StyleKind::Text { style, .. } if st.name == "Body" => Some(style.clone()), _ => None, }) .unwrap(); diff --git a/crates/engine/src/styles_behaviour_tests.rs b/crates/engine/src/styles_behaviour_tests.rs index de9da5a5d..f1ebd96de 100644 --- a/crates/engine/src/styles_behaviour_tests.rs +++ b/crates/engine/src/styles_behaviour_tests.rs @@ -5,10 +5,11 @@ //! line; "docs silent" marks behaviour the documentation doesn't describe (pinned as it is). use serde_json::{Value, json}; +use std::collections::BTreeMap; use crate::Session; use crate::params::id_of; -use figcraft_doc::{Node, NodeId}; +use figcraft_doc::{ListStyle, Node, NodeId, ParagraphStyle, StyleKind, TextData}; fn id(v: Value) -> NodeId { id_of(&v["id"]).unwrap() @@ -355,6 +356,68 @@ fn text_styles_go_on_text_layers_and_chars() { assert_eq!(tx.styles.text, None, "mixed: the layer isn't linked as a whole"); } +#[test] +fn text_styles_carry_paragraph_spacing_indent_lists_and_features() { + // "Supported in text styles": "Paragraph spacing and indentation", "Lists" and "OpenType + // features", beside the character properties (Create and apply text styles). A style made + // from a text takes them, applying it sets them, editing one on a styled text unlinks it. + 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); + let props = json!({"characters": "One\nTwo", "paragraphSpacing": 12, "paragraphIndent": 8, "listStyle": "bulleted", "features": {"tnum": true, "liga": false}}); + run(&mut s, "node.set", json!({"id": t, "props": props})); + let st = sid(run(&mut s, "style.create", json!({"type": "text", "name": "Audit", "from": t}))); + let listed = run(&mut s, "style.list", json!({"type": "text"})); + let audit = listed.as_array().unwrap().iter().find(|x| x["id"] == json!(st)).unwrap(); + assert_eq!( + audit["paragraph"], + json!({"paragraph_spacing": 12.0, "paragraph_indent": 8.0, "list": "bulleted", "features": {"liga": false, "tnum": true}}) + ); + // Applying it sets them on a plain text, every paragraph in the list; the layer links. + let t2 = text(&mut s, 300.0); + run(&mut s, "node.set", json!({"id": t2, "props": {"characters": "A\nB\nC"}})); + run(&mut s, "style.apply", json!({"ids": [t2], "style": st})); + let d = td(&s, t2); + assert_eq!((d.paragraph_spacing, d.paragraph_indent), (12.0, 8.0)); + assert!((0..3).all(|p| d.para_list(p).list == ListStyle::Bulleted), "{:?}", d.paragraphs); + assert_eq!(d.features, BTreeMap::from([("liga".to_string(), false), ("tnum".to_string(), true)])); + assert_eq!(node(&s, t2).styles.text.as_deref(), Some(st.as_str())); + // Redefining the style moves its layers' paragraph values with the rest. + let value = json!({"fontSize": 22, "paragraphSpacing": 20, "listStyle": "numbered", "openTypeFeatures": {"tnum": true}}); + run(&mut s, "style.update", json!({"style": st, "value": value})); + let d = td(&s, t2); + assert_eq!((d.paragraph_spacing, d.paragraph_indent, d.para_list(1).list), (20.0, 0.0, ListStyle::Numbered)); + assert_eq!(d.features, BTreeMap::from([("tnum".to_string(), true)])); + assert_eq!(font_size(&s, t2), 22.0); + assert_eq!(node(&s, t2).styles.text.as_deref(), Some(st.as_str()), "still linked after the update"); + // Editing a paragraph value the style sets unlinks the text, as editing its font does. + run(&mut s, "node.set", json!({"id": t2, "props": {"paragraphSpacing": 5}})); + assert_eq!(node(&s, t2).styles.text, None, "paragraph spacing edited: unlinked"); + assert!(td(&s, t2).spans().iter().all(|(_, _, x)| x.style_id.is_none())); + // On a range, the list goes to the paragraphs touched; the spacing is the layer's. Taking + // the paragraph out of the style's list unlinks its chars. + let t3 = text(&mut s, 600.0); + run(&mut s, "node.set", json!({"id": t3, "props": {"characters": "A\nB\nC"}})); + run(&mut s, "style.apply", json!({"ids": [t3], "style": st, "start": 0, "end": 1})); + let d = td(&s, t3); + assert_eq!((d.para_list(0).list, d.para_list(1).list, d.paragraph_spacing), (ListStyle::Numbered, ListStyle::None, 20.0)); + assert_eq!(d.style_at(0).style_id.as_deref(), Some(st.as_str())); + run(&mut s, "node.set", json!({"id": t3, "props": {"start": 0, "end": 1, "listStyle": "none"}})); + assert_eq!(td(&s, t3).style_at(0).style_id, None, "its paragraph left the style's list"); + // A definition given as a value takes the node.set spellings; junk is refused. + let value = json!({"fontSize": 11, "paragraphSpacing": 4, "listStyle": "bulleted", "features": {"liga": false}}); + let st2 = sid(run(&mut s, "style.create", json!({"type": "text", "name": "Note", "value": value}))); + let want = ParagraphStyle { + paragraph_spacing: 4.0, + list: ListStyle::Bulleted, + features: BTreeMap::from([("liga".to_string(), false)]), + ..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": {"listStyle": "dotted"}})).is_err()); + assert!(s.execute("style.create", &json!({"type": "text", "name": "Bad", "value": {"paragraphSpacing": "wide"}})).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_style_picker_tests.rs b/crates/engine/src/text_style_picker_tests.rs index 6ee8cc2c3..733845a52 100644 --- a/crates/engine/src/text_style_picker_tests.rs +++ b/crates/engine/src/text_style_picker_tests.rs @@ -86,7 +86,7 @@ fn editing_text_applies_to_the_selected_chars() { s.execute("text.style", &json!({"id": t, "start": 6, "end": 11, "fontSize": 20})).unwrap(); let c = s.execute("style.create", &json!({"type": "text", "name": "Type/Caption"})).unwrap()["id"].as_str().unwrap().to_string(); let style = s.doc().unwrap().style(&c).cloned().unwrap(); - let StyleKind::Text { style: def } = style.kind else { panic!("not a text style") }; + let StyleKind::Text { style: def, .. } = style.kind else { panic!("not a text style") }; assert_eq!(def.font_size, 20.0); assert_eq!(def.style_id, None, "definitions link to nothing"); assert_eq!(links(&s, t)[8].as_deref(), Some(c.as_str())); @@ -117,7 +117,7 @@ fn edits_unlink_and_style_edits_follow() { assert_eq!(layer_link(&s, a).as_deref(), Some(h.as_str())); // Redefining the style moves linked chars only. let mut def = match &s.doc().unwrap().style(&h).unwrap().kind { - StyleKind::Text { style } => style.clone(), + StyleKind::Text { style, .. } => style.clone(), _ => panic!("not a text style"), }; def.font_size = 40.0; diff --git a/crates/format/src/fig/assets_tests.rs b/crates/format/src/fig/assets_tests.rs index ce4192008..36c70a687 100644 --- a/crates/format/src/fig/assets_tests.rs +++ b/crates/format/src/fig/assets_tests.rs @@ -225,7 +225,7 @@ fn same_after_round_trip(doc: &Document, what: &str) -> Vec { normalize(&mut n, &|i| i); *paints = n.fills; } - StyleKind::Text { style } => { + StyleKind::Text { style, .. } => { if let NodeKind::Text(td) = &mut n.kind { td.style = style.clone(); } @@ -444,7 +444,7 @@ fn styled() -> Document { bound: Default::default(), }; doc.styles = vec![ - style("s-text", "Heading", StyleKind::Text { style: heading.clone() }), + style("s-text", "Heading", StyleKind::Text { style: heading.clone(), paragraph: Default::default() }), style("s-brand", "Brand/Primary", StyleKind::Paint { paints: vec![solid(0.25, 0.5, 1.0)] }), style("s-unused", "Brand/Unused", StyleKind::Paint { paints: vec![solid(1.0, 0.0, 0.0), solid(0.0, 1.0, 0.0)] }), style("s-shadow", "Elevation/1", StyleKind::Effect { effects: vec![shadow.clone()] }), diff --git a/crates/format/src/fig/export/assets.rs b/crates/format/src/fig/export/assets.rs index 3874b073c..f1df1874d 100644 --- a/crates/format/src/fig/export/assets.rs +++ b/crates/format/src/fig/export/assets.rs @@ -159,7 +159,7 @@ impl<'d> Exporter<'d> { Bound::default() } else { let mut sample = Node::new(NodeId(0), NodeKind::Rectangle, "", 0.0, 0.0); - if let StyleKind::Text { style } = &st.kind { + if let StyleKind::Text { style, .. } = &st.kind { sample.kind = NodeKind::Text(TextData { style: style.as_text_style(), ..TextData::new("Ag") }); } sample.bound.clone_from(&st.bound); @@ -179,8 +179,9 @@ impl<'d> Exporter<'d> { let list = grids.iter().enumerate().map(|(i, g)| layout_grid(g, i, &none)).collect(); f.extend([("fillPaints", arr(Vec::new())), ("layoutGrids", arr(list))]); } - StyleKind::Text { style } => { - let td = TextData { style: style.as_text_style(), ..TextData::new("Ag") }; + StyleKind::Text { style, paragraph } => { + let mut td = TextData { style: style.as_text_style(), ..TextData::new("Ag") }; + td.take_paragraph_style(paragraph); let fills = [Paint::solid(Color::BLACK)]; f.push(("fillPaints", self.paints(style.fills.as_deref().unwrap_or(&fills), true, &none))); self.text(&td, &fills, &mut f); diff --git a/crates/format/src/fig/text_skip_ink_tests.rs b/crates/format/src/fig/text_skip_ink_tests.rs index 485663847..b5285e1b6 100644 --- a/crates/format/src/fig/text_skip_ink_tests.rs +++ b/crates/format/src/fig/text_skip_ink_tests.rs @@ -113,7 +113,7 @@ fn local_skip_ink_override_preserves_shared_style_and_omitted_value_inherits() { let node = doc.nodes().find(|n| n.name == "Label").unwrap(); assert_eq!(node.kind.text().unwrap().style.look().skip_ink, expected); let linked = doc.style(node.styles.text.as_deref().unwrap()).unwrap(); - let StyleKind::Text { style } = &linked.kind else { panic!("linked definition must remain text") }; + let StyleKind::Text { style, .. } = &linked.kind else { panic!("linked definition must remain text") }; assert!(style.look().skip_ink, "local value must not alter definition"); } } @@ -223,7 +223,7 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only id: "body".into(), name: "Body".into(), description: String::new(), - kind: StyleKind::Text { style: shared }, + kind: StyleKind::Text { style: shared, paragraph: Default::default() }, bound: Default::default(), }); let id = linked_doc @@ -237,7 +237,7 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only let node = back.nodes().find(|n| n.name == "Label").unwrap(); assert!(!node.kind.text().unwrap().style.look().skip_ink); let linked = back.style(node.styles.text.as_deref().unwrap()).unwrap(); - let StyleKind::Text { style } = &linked.kind else { panic!("shared style link must remain text") }; + let StyleKind::Text { style, .. } = &linked.kind else { panic!("shared style link must remain text") }; assert!(style.look().skip_ink, "local false must not alter the shared definition"); } diff --git a/crates/format/src/fig/text_style_tests.rs b/crates/format/src/fig/text_style_tests.rs index 0f08459e6..dadd052c1 100644 --- a/crates/format/src/fig/text_style_tests.rs +++ b/crates/format/src/fig/text_style_tests.rs @@ -85,7 +85,7 @@ fn seen(doc: &Document) -> Seen { assert_eq!((text.style.font_family.as_str(), text.style.font_size), ("Inter", 20.0)); let linked = doc.style(label.styles.text.as_deref().unwrap()).unwrap(); assert_eq!(linked.name, "Shared"); - let StyleKind::Text { style } = &linked.kind else { panic!("the linked definition must stay a text style") }; + let StyleKind::Text { style, .. } = &linked.kind else { panic!("the linked definition must stay a text style") }; Seen { case: text.style.case, decoration: text.style.decoration, diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index 6cd8fe53c..a0e50a067 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -1531,7 +1531,7 @@ fn import_typography_styles( id: format!("penpot:text:{base}:{id}"), name: name.chars().take(256).collect(), description: "Imported from Penpot typography library".into(), - kind: StyleKind::Text { style }, + kind: StyleKind::Text { style, paragraph: Default::default() }, bound: BTreeMap::new(), }); } @@ -1596,7 +1596,7 @@ fn composite_token_style(token: &Value) -> Option { } } let parsed = text_style(&Value::Object(fields), &style); - Some(StyleKind::Text { style: parsed }) + Some(StyleKind::Text { style: parsed, paragraph: Default::default() }) } "boxShadow" | "shadow" => { let parts: Vec<&Value> = if let Some(items) = value.as_array() { items.iter().take(32).collect() } else { vec![value] }; @@ -5927,7 +5927,7 @@ mod tests { let (doc, warnings) = import(&archive_with_design_system(tokens, None, None, None)).unwrap(); assert_eq!(doc.styles.len(), 2); assert!(doc.styles.iter().any(|s| s.name == "Penpot tokens/Core/title" - && matches!(&s.kind, StyleKind::Text { style } + && matches!(&s.kind, StyleKind::Text { style, .. } if style.font_family == "Spicy Rice" && style.font_size == 24.0 && style.line_height == LineHeight::Pixels(32.0)))); assert!(doc.styles.iter().any(|s| s.name == "Penpot tokens/Core/elevation" && matches!(&s.kind, StyleKind::Effect { effects } @@ -5983,10 +5983,8 @@ mod tests { let (doc, warnings) = import(&archive_with_design_system(serde_json::json!({"sets":{}}), Some(typ), Some(color), None)).unwrap(); assert!(warnings.is_empty(), "{warnings:?}"); assert_eq!(doc.styles.len(), 2); - assert!( - doc.styles.iter().any(|s| s.name == "Brand/Heading" - && matches!(&s.kind, StyleKind::Text { style } if style.font_family == "Inter" && style.font_size == 24.0)) - ); + assert!(doc.styles.iter().any(|s| s.name == "Brand/Heading" + && matches!(&s.kind, StyleKind::Text { style, .. } if style.font_family == "Inter" && style.font_size == 24.0))); assert!(doc.styles.iter().any(|s| s.name == "Brand/Primary" && matches!(s.kind, StyleKind::Paint { .. }))); assert_eq!(doc.document_colors.len(), 1); } diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 4604b73a6..eb9a10112 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -913,7 +913,11 @@ impl<'a> Ctx<'a> { Some("FILL") => StyleKind::Paint { paints: props::paints(self, node, "fills").unwrap_or_default() }, Some("EFFECT") => StyleKind::Effect { effects: props::effects(self, node) }, Some("GRID") => StyleKind::Grid { grids: props::layout_grids(node) }, - Some("TEXT") => StyleKind::Text { style: text::text_data(self, node).style.as_text_style() }, + Some("TEXT") => { + // The sample layer carries the paragraph-level values too (#1829). + let td = text::text_data(self, node); + StyleKind::Text { style: td.style.as_text_style(), paragraph: Box::new(td.paragraph_style()) } + } _ => continue, }; let name = text(d, "name").filter(|s| !s.is_empty()).map_or_else(|| format!("Style {id}"), |s| clip_str(s).to_string()); @@ -955,7 +959,9 @@ impl<'a> Ctx<'a> { "effect" | "effects" => (StyleKind::Effect { effects: n.effects.clone() }, &mut n.styles.effect), "grid" | "grids" => (StyleKind::Grid { grids: n.grids.clone() }, &mut n.styles.grid), "text" => match &n.kind { - NodeKind::Text(t) => (StyleKind::Text { style: t.style.as_text_style() }, &mut n.styles.text), + NodeKind::Text(t) => { + (StyleKind::Text { style: t.style.as_text_style(), paragraph: Box::new(t.paragraph_style()) }, &mut n.styles.text) + } _ => continue, }, _ => continue, diff --git a/crates/format/src/rest/tests.rs b/crates/format/src/rest/tests.rs index 050dcbaa6..43c9db6f2 100644 --- a/crates/format/src/rest/tests.rs +++ b/crates/format/src/rest/tests.rs @@ -530,7 +530,7 @@ fn shared_styles_link_with_metadata_names() { let fill = doc.style("S:1").unwrap(); assert_eq!((fill.name.as_str(), fill.description.as_str()), ("Brand/Primary", "Main")); assert!(matches!(&fill.kind, StyleKind::Paint { paints } if paints.len() == 1)); - assert!(matches!(&doc.style("S:2").unwrap().kind, StyleKind::Text { style } if style.font_size == 32.0)); + assert!(matches!(&doc.style("S:2").unwrap().kind, StyleKind::Text { style, .. } if style.font_size == 32.0)); assert!(matches!(&doc.style("Soft").unwrap().kind, StyleKind::Effect { effects } if effects.len() == 1)); let r = named(&doc, "R"); assert_eq!((r.styles.fill.as_deref(), r.styles.effect.as_deref()), (Some("S:1"), Some("S:4"))); diff --git a/crates/format/src/sketch/shared_tests.rs b/crates/format/src/sketch/shared_tests.rs index 240fdb7ea..4636c652e 100644 --- a/crates/format/src/sketch/shared_tests.rs +++ b/crates/format/src/sketch/shared_tests.rs @@ -91,7 +91,7 @@ fn text_style_links() { let sid = n.styles.text.clone().expect("text style linked"); let s = style(&doc, &sid); assert_eq!(s.name, "Heading/H1"); - let StyleKind::Text { style: ts } = &s.kind else { panic!("not a text style") }; + let StyleKind::Text { style: ts, .. } = &s.kind else { panic!("not a text style") }; assert_eq!((ts.font_family.as_str(), ts.font_style.as_str(), ts.font_size), ("Helvetica", "Bold", 32.0)); assert!(n.fills.iter().any(|p| matches!(p.kind, PaintKind::Solid { color } if color.r == 1.0 && color.g == 0.0))); } diff --git a/crates/ui-egui/src/widgets/style_picker.rs b/crates/ui-egui/src/widgets/style_picker.rs index eb2a2b44b..f616ddec7 100644 --- a/crates/ui-egui/src/widgets/style_picker.rs +++ b/crates/ui-egui/src/widgets/style_picker.rs @@ -10,7 +10,9 @@ use egui::{Align2, Color32, CornerRadius, Id, Rect, Response, Sense, Stroke, Ui, pos2, vec2}; use figcraft_color::{Paint, PaintKind}; -use figcraft_doc::{Document, GridKind, Node, NodeId, PublishedLibrary, Style, StyleKind, TextStyle, VariableType, trim_num}; +use figcraft_doc::{ + Document, GridKind, ListStyle, Node, NodeId, ParagraphStyle, PublishedLibrary, Style, StyleKind, TextStyle, VariableType, trim_num, +}; use figcraft_engine::library; use serde_json::{Value, json}; @@ -354,7 +356,7 @@ fn by_folder<'a>(styles: impl Iterator) -> Vec<(&'a str, Vec<& /// A text style's definition, if `s` is one. fn text_def(s: &Style) -> Option<&TextStyle> { match &s.kind { - StyleKind::Text { style } => Some(style), + StyleKind::Text { style, .. } => Some(style), _ => None, } } @@ -974,6 +976,39 @@ fn text_properties(ui: &mut Ui, doc: &Document, style: &Style, def: &TextStyle, if let Some(sr) = style_resp { font_style_menu(id, def, &sr, out); } + if let StyleKind::Text { paragraph, .. } = &style.kind { + paragraph_rows(ui, paragraph); + } +} + +/// What a text style sets at the paragraph level (#1829), when it sets anything: the spacing, +/// indent, list style and OpenType features (as `+tnum -liga`). A layer's Type settings edit +/// them; Update from selection takes them into the style. +fn paragraph_rows(ui: &mut Ui, ps: &ParagraphStyle) { + let mut rows: Vec = Vec::new(); + if ps.paragraph_spacing != 0.0 { + let label = tr("Paragraph spacing"); + rows.push(format!("{label}: {}", trim_num(ps.paragraph_spacing))); + } + if ps.paragraph_indent != 0.0 { + let label = tr("Paragraph indent"); + rows.push(format!("{label}: {}", trim_num(ps.paragraph_indent))); + } + match ps.list { + ListStyle::None => {} + ListStyle::Bulleted => rows.push(tr("Bulleted list").into()), + ListStyle::Numbered => rows.push(tr("Numbered list").into()), + } + if !ps.features.is_empty() { + rows.push(ps.features.iter().map(|(tag, on)| format!("{}{tag}", if *on { '+' } else { '-' })).collect::>().join(" ")); + } + if rows.is_empty() { + return; + } + ui.add_space(4.0); + for row in rows { + caption(ui, &row); + } } /// Editing one style: name, description, its values (paints open the colour picker; text styles @@ -1038,7 +1073,7 @@ fn editor(ui: &mut Ui, doc: &Document, p: &mut Picker, out: &mut Frame) { binding_cell(ui, doc, &style, &format!("layoutGrids/{i}/size"), figcraft_doc::VariableType::Number, out); } } - StyleKind::Text { style: def } => text_properties(ui, doc, &style, def, out), + StyleKind::Text { style: def, .. } => text_properties(ui, doc, &style, def, out), } }); ui.add_space(8.0); diff --git a/crates/ui-egui/src/widgets/style_picker/tests.rs b/crates/ui-egui/src/widgets/style_picker/tests.rs index fa996374c..0f3392e48 100644 --- a/crates/ui-egui/src/widgets/style_picker/tests.rs +++ b/crates/ui-egui/src/widgets/style_picker/tests.rs @@ -29,7 +29,7 @@ fn names_split_into_folders() { for s in [StyleSlot::Fill, StyleSlot::Stroke, StyleSlot::Effect, StyleSlot::Grid, StyleSlot::Text] { assert_eq!(StyleSlot::parse(s.key()), Some(s)); } - assert!(StyleSlot::Text.holds(&StyleKind::Text { style: Default::default() }) && StyleSlot::Text.has_grid()); + assert!(StyleSlot::Text.holds(&StyleKind::Text { style: Default::default(), paragraph: Default::default() }) && StyleSlot::Text.has_grid()); } fn frame(ctx: &egui::Context, app: &mut FigApp, t: &mut f64) { @@ -255,7 +255,7 @@ fn commit_text_field(def: &TextStyle, field: &str, typed: &str) -> Option = texts.iter().filter(|(_, p)| p.x > left && p.x < left + W).cloned().collect(); @@ -434,7 +434,7 @@ fn text_style_editor_binds_variables_from_its_fields() { assert_eq!(bound_to(&u, field).as_deref(), Some(name)); } let doc = u.app.session.doc().unwrap(); - let Some(StyleKind::Text { style: def }) = doc.style("Body").map(|s| &s.kind) else { panic!("a text style") }; + let Some(StyleKind::Text { style: def, .. }) = doc.style("Body").map(|s| &s.kind) else { panic!("a text style") }; assert_eq!((def.font_size, def.font_style.as_str()), (18.0, "Bold"), "the style takes the variables' values"); assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); } diff --git a/docs/components-parity.md b/docs/components-parity.md index 0e3248248..7fce63d14 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-01 · **Change:** minor (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-02 · **Change:** minor (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); 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 @@ -59,7 +59,7 @@ 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` | +| 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) | | 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 | @@ -78,6 +78,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 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-01 | patch | M3: Delete on a layer inside an instance hides it (an override) instead of being refused ("You can't delete a layer or object from an instance. If you try, Figma will only toggle the layer's visibility instead of removing it", Guide to auto layout); `edit.delete` reports those ids under `hidden`, the structure and the main component stay as they were, one undo step; deleting the instance itself still removes it. Found by a documentation audit of the auto layout page. Test: `components_behaviour_tests::deleting_a_layer_inside_an_instance_hides_it_instead` (the refusal row for it is gone from `what_instances_cannot_override_is_refused`). Numbers unchanged | | 2026-10-31 | minor | M3, gap 10: library analytics cover styles and variables. A file reports how many of its layers use each of a library's styles and variables, and Show usage (`library.usage`) lists them beside the components, by a Type choice, with their layers and files. Layers inside instances count for their component. Insertions, detachments and modes aren't counted for them yet. Numbers unchanged. Tests: `library_assets_tests`. | | 2026-10-31 | minor | M6: as the help center describes code syntax, Dev Mode's SwiftUI and Compose code now writes a bound variable's iOS or Android code syntax in place of its value, as CSS already wrote the Web one: fills, strokes and their weight, sizes, corner radius, gaps, padding, opacity, the font family and size and the characters. A variable with no code syntax for the platform keeps the value, since a name made up here wouldn't exist in the code it lands in. ArkUI and Flutter have no code syntax platform and are unchanged. Test: `variables_behaviour_tests::swiftui_and_compose_name_variables_by_their_code_syntax`. Numbers unchanged. Grade unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index b5e49e749..8344f4972 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -312,10 +312,16 @@ 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. Changing what a text style sets (font, size, line height, letter spacing, decoration, case, axis - values) on linked chars unlinks them; `style.update` moves every linked char. `style.create - {type: "text", name}` takes the selected chars while editing; a `value` may use the `node.set` - spellings (`{"fontSize": 32, "lineHeight": "120%", "letterSpacing": "2%"}`). + 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 + selected chars while editing; a `value` may use the `node.set` spellings (`{"fontSize": 32, + "lineHeight": "120%", "letterSpacing": "2%", "paragraphSpacing": 12, "listStyle": "bulleted", + "features": {"liga": false}}`). - **Styles stay true to their layers**: editing a styled fill, stroke, effect or layout grid list (`node.set`, `fill.set`, `fill.add`, a bound variable…) unlinks that style (`styles.fill` etc. go `null`), so a later `style.update` doesn't overwrite the edit; `style.apply` replaces variables From e5a3fcf02820d4e6cdcb4925e73cb3b0f167eb29 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 07:01:04 -0500 Subject: [PATCH 116/326] Merge fix: text_link_tests is a test module The merge's union of two mod lines left upstream's text_link_tests without its cfg(test), so the library build pulled a test module in. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 20e5847b0..b1daf85ec 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -242,6 +242,7 @@ mod style_props_tests; mod table_paste_tests; #[cfg(test)] mod text_enter_tests; +#[cfg(test)] mod text_link_tests; #[cfg(test)] mod text_mixed_fill_tests; From 0a9ecbe596841401607301c614a9e23207a12178 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 07:09:01 -0500 Subject: [PATCH 117/326] Merge fix: 135 documented shortcut rows, 134 bound Both sides of the merge added a documented row: the counts the parity test and the docs table quote move with them. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/shortcut_parity_tests.rs | 2 +- crates/ui-egui/src/padding_individual_tests.rs | 11 +++++++++++ crates/ui-egui/src/widgets.rs | 10 +++++++++- docs/ui-parity.md | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/shortcut_parity_tests.rs b/crates/engine/src/shortcut_parity_tests.rs index 4ab40c302..c2d400589 100644 --- a/crates/engine/src/shortcut_parity_tests.rs +++ b/crates/engine/src/shortcut_parity_tests.rs @@ -414,7 +414,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), (134, 133, 1, 0, 2, 57)); + assert_eq!((documented.len(), bound, moved, missing, reserved, pinned), (135, 134, 1, 0, 2, 57)); } #[test] diff --git a/crates/ui-egui/src/padding_individual_tests.rs b/crates/ui-egui/src/padding_individual_tests.rs index 2b493ca7f..66c283cb9 100644 --- a/crates/ui-egui/src/padding_individual_tests.rs +++ b/crates/ui-egui/src/padding_individual_tests.rs @@ -132,6 +132,17 @@ fn a_command_click_on_a_padding_field_edits_all_sides() { let (mut u, f) = scene(); u.app.run("node.set", json!({"ids": [f], "props": {"paddingLeft": 16.0, "paddingRight": 54.0}})); assert_eq!(padding(&u, f), [10.0, 54.0, 10.0, 16.0]); + // Cmd/Ctrl-click and Tab away without typing: nothing is committed, to any side. + let before = u.app.session.undo_depth().0; + let v = named_field(&mut u, "Vertical padding"); + command_click(&mut u, v); + u.frame(vec![ + Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }, + Event::Key { key: Key::Tab, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }, + ]); + u.frame(vec![]); + assert_eq!(padding(&u, f), [10.0, 54.0, 10.0, 16.0], "an untouched field commits nothing"); + assert_eq!(u.app.session.undo_depth().0, before); // The shut pair: Cmd/Ctrl-click Vertical padding and type 7: every side is 7. let history = u.app.session.undo_depth().0; let v = named_field(&mut u, "Vertical padding"); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 08d919781..c149d8b51 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -368,6 +368,7 @@ fn number_field_impl( d.insert_temp(kept_id, value.map(fmt_num).unwrap_or_default()); d.insert_temp(id.with("selectall"), !typed_now); d.insert_temp(id.with("cmdstart"), with_command); + d.remove::(id.with("edited")); }); ui.memory_mut(|m| m.request_focus(id.with("te"))); } else if editing.is_none() { @@ -386,6 +387,11 @@ fn number_field_impl( // top would move its baseline below the centered value painted while idle. let mut child = ui.new_child(egui::UiBuilder::new().max_rect(edit_rect)); let r = child.add(te); + if r.changed() { + // Typing (the same value again included) is what lets a Cmd/Ctrl-begun edit commit + // to every side; a field left as it was commits nothing. + ui.data_mut(|d| d.insert_temp(id.with("edited"), true)); + } a11y::own_focus(&r); keep_focus(&r, started); crate::shortcuts::release_field_for_save(&r); @@ -412,6 +418,7 @@ fn number_field_impl( ui.data_mut(|d| { d.insert_temp(kept_id, text.clone()); d.insert_temp(id.with("selectall"), true); + d.insert_temp(id.with("edited"), true); }); out = Some(set(nv)); } @@ -430,7 +437,8 @@ fn number_field_impl( // An edit begun with Cmd/Ctrl commits the value even retyped as it was: the other // sides are to take it ([`edit_began_with_command`]). let for_all = ui.data(|d| d.get_temp::(id.with("cmdstart"))).unwrap_or(false); - if (text != kept || for_all) + let edited = ui.data(|d| d.get_temp::(id.with("edited"))).unwrap_or(false); + if (text != kept || (for_all && edited)) && let Some(e) = typed(&text) { out = Some(e); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 15b2ce915..cfb00b3a2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -129,7 +129,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | | Count | Notes | |---|---|---| -| Documented shortcuts (rows) | 134 | each with macOS and Windows/Linux keys | +| Documented shortcuts (rows) | 135 | each with macOS and Windows/Linux keys | | Bound as documented | 134 (110 before this suite) | 112 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 | From 90bec33322d3a33e004a5f632b3dde8d914d684e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 07:23:33 -0500 Subject: [PATCH 118/326] Crosshair: the board Shapes tool places on it, and the view pans to keep it in sight draws_shape includes BoardShape (tool.place lets the tool centre its own shape); a nudge past an edge of the view pans by the overshoot. Tests; docs. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/tools.rs | 1 + crates/engine/src/canvas/tools/keys.rs | 3 +- crates/engine/src/cmd/view.rs | 10 ++++-- crates/engine/src/place_crosshair_tests.rs | 40 ++++++++++++++++++++++ docs/ui-parity.md | 2 +- 5 files changed, 52 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index 9bc4bef2a..788e5eb8e 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -201,6 +201,7 @@ impl ToolId { | ToolId::Star | ToolId::Line | ToolId::Arrow + | ToolId::BoardShape ) } } diff --git a/crates/engine/src/canvas/tools/keys.rs b/crates/engine/src/canvas/tools/keys.rs index 07a91557b..2b56aecd3 100644 --- a/crates/engine/src/canvas/tools/keys.rs +++ b/crates/engine/src/canvas/tools/keys.rs @@ -90,7 +90,8 @@ impl Session { self.tool.place_at = None; let v = &self.ds()?.view; let (c, zoom) = (at.or(crosshair).unwrap_or(Point::new(v.cx, v.cy)), v.zoom); - let (w, h) = tool.click_size(); + // The board Shapes tool centres its own shape on the press; the others get half a click's size. + let (w, h) = if matches!(tool, ToolId::BoardShape) { (0.0, 0.0) } else { tool.click_size() }; let ev = |kind| PointerEvent::at(kind, c.x - w / 2.0, c.y - h / 2.0, zoom); let r = self.pointer(&ev(PointerKind::Down)).and_then(|()| self.pointer(&ev(PointerKind::Up))); if r.is_err() { diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 583d46ba6..305db5399 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -541,9 +541,10 @@ pub fn specs() -> Vec { let step = if boolean(p, "big").unwrap_or(false) { s.prefs.nudge_big } else { s.prefs.nudge_small }; 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 (uid, page, centre) = { + let (uid, page, centre, half) = { let ds = s.ds()?; - (ds.uid, ds.page, figcraft_geom::Point::new(ds.view.cx, ds.view.cy)) + let z = ds.view.zoom.max(1e-6); + (ds.uid, ds.page, figcraft_geom::Point::new(ds.view.cx, ds.view.cy), (ds.view.vw / z / 2.0, ds.view.vh / z / 2.0)) }; // "It will appear in the middle of the viewport": the first arrow shows it there (a // crosshair left on another page or document starts over). @@ -554,6 +555,11 @@ pub fn specs() -> Vec { s.tool.place_at = Some(at); s.tool.place_on = Some((uid, page)); if let Ok(ds) = s.ds_mut() { + // "Move the crosshair around the canvas": nudged past an edge of the view, the + // view pans by the overshoot to keep it in sight. + let v = &mut ds.view; + v.cx += (at.x - (v.cx + half.0)).max(0.0) + (at.x - (v.cx - half.0)).min(0.0); + v.cy += (at.y - (v.cy + half.1)).max(0.0) + (at.y - (v.cy - half.1)).min(0.0); ds.revision += 1; } Ok(json!({"x": at.x, "y": at.y})) diff --git a/crates/engine/src/place_crosshair_tests.rs b/crates/engine/src/place_crosshair_tests.rs index 9bd89dc90..6b5f7b732 100644 --- a/crates/engine/src/place_crosshair_tests.rs +++ b/crates/engine/src/place_crosshair_tests.rs @@ -80,3 +80,43 @@ fn the_crosshair_keeps_its_page_and_goes_with_a_pointer_placement_but_not_the_sa let v = &s.ds().unwrap().view; assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(v.cx), Some(v.cy)), "shown afresh in the middle of this page's view"); } + +#[test] +fn the_view_pans_to_keep_the_crosshair_in_sight() { + // "Use the arrow keys to move the crosshair around the canvas or board": nudged past an edge + // of the view, the view follows it by the overshoot; inside it, the view stays put. + let mut s = Session::new(); + s.execute("view.set", &json!({"zoom": 10.0, "cx": 300, "cy": 200})).unwrap(); + s.execute("tool.rectangle", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({})).unwrap(); + for _ in 0..6 { + s.execute("tool.crosshair", &json!({"dx": 1, "big": true})).unwrap(); + } + let v = s.ds().unwrap().view.clone(); + assert_eq!((s.tool.place_at.map(|p| p.x), v.cx, v.cy), (Some(360.0), 300.0, 200.0), "at the edge of the 120 px wide view: no pan yet"); + s.execute("tool.crosshair", &json!({"dx": 1, "big": true})).unwrap(); + let v = s.ds().unwrap().view.clone(); + assert_eq!((v.cx, v.cy), (310.0, 200.0), "ten past the edge: the view moved ten"); + for _ in 0..5 { + s.execute("tool.crosshair", &json!({"dy": -1, "big": true})).unwrap(); + } + let v = s.ds().unwrap().view.clone(); + assert_eq!((v.cx, v.cy), (310.0, 190.0), "the view is 80 px tall: 40 up is its edge, 50 moves it ten"); +} + +#[test] +fn the_board_shapes_tool_places_on_the_crosshair_too() { + // "...move the crosshair around the canvas or board, then press Return/Enter to place the + // object": the board Shapes tool takes the crosshair like the shape tools, its shape centred + // on it (the tool centres its own 160 px shape on a press). + let mut s = crate::board_tests::board(); + s.execute("view.set", &json!({"zoom": 1.0, "cx": 300, "cy": 200})).unwrap(); + s.execute("tool.set", &json!({"tool": "shape"})).unwrap(); + s.execute("tool.crosshair", &json!({})).unwrap(); + s.execute("tool.crosshair", &json!({"dx": 2})).unwrap(); + let placed = s.execute("tool.place", &json!({})).unwrap(); + let id = crate::params::id_of(&placed["ids"][0]).unwrap(); + let b = s.doc().unwrap().world_bounds(id).unwrap(); + assert_eq!((b.center().x, b.center().y, b.width(), b.height()), (302.0, 200.0, 160.0, 160.0)); + assert_eq!(s.tool.place_at, None); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0fde4bcd2..a7185146b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -177,7 +177,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| -| 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). Tests: `place_crosshair_tests`, `shortcut_keys_tests::arrows_show_and_move_the_placement_crosshair_with_a_shape_tool`. | +| 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`. | | 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`. | From 2e392e99b1d2310cb9f48a7e5a47fab098e07ffa Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 07:55:27 -0500 Subject: [PATCH 119/326] M8: a fill per region: the Fill section and the fill commands edit the regions selected in vector edit mode (#1875) fill.set/add/remove/move/paste on the edited layer go to the selected regions' own fill stacks (or those named by regions), the layer's fills untouched; the Fill section and the colour picker list them. Test regions_tests::the_fill_commands_edit_the_selected_regions; docs. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/canvas/vectoredit.rs | 15 +++ .../src/canvas/vectoredit/regions_tests.rs | 47 ++++++++ crates/engine/src/cmd/edit.rs | 23 +++- crates/engine/src/cmd/edit/props.rs | 112 ++++++++++++++++-- crates/engine/src/cmd/lists.rs | 17 ++- crates/ui-egui/src/panels/right/paints.rs | 8 +- crates/ui-egui/src/widgets/colorpicker.rs | 7 ++ docs/mcp.md | 5 +- docs/ui-parity.md | 5 +- 9 files changed, 219 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs index 078f0804e..5d5408d02 100644 --- a/crates/engine/src/canvas/vectoredit.rs +++ b/crates/engine/src/canvas/vectoredit.rs @@ -1245,6 +1245,21 @@ pub fn paint_all(doc: &mut Document, id: NodeId, pts: &[Point]) -> Result Ok(filled) } +/// The fills the Fill section shows for layer `id` while regions of it are selected in edit +/// mode: the stack those regions share (their own, else the layer's), `Some(None)` when they +/// differ (mixed), `None` when no region of that layer is selected (the layer's fills show). The +/// fill commands edit the same regions then ("you can adjust the fill for each region +/// individually", Edit vector layers, #1875). +pub fn selected_region_fills(s: &Session, id: NodeId) -> Option>> { + let ve = s.ds().ok()?.vector_edit.as_ref().filter(|ve| ve.id == id && !ve.regions.is_empty())?; + let doc = s.doc().ok()?; + let node = doc.node(id)?; + let net = network(doc, id)?; + let mut stacks = ve.regions.iter().filter_map(|r| net.regions.get(*r)).map(|r| r.fills.clone().unwrap_or_else(|| node.fills.clone())); + let first = stacks.next()?; + Some(stacks.all(|st| st == first).then_some(first)) +} + /// Add points `vs` of edited layer `id` to its selection. pub(crate) fn add_points(ve: &mut VectorEdit, id: NodeId, vs: &[usize]) { let list = if id == ve.id { Some(&mut ve.vertices) } else { ve.others.iter_mut().find(|o| o.id == id).map(|o| &mut o.vertices) }; diff --git a/crates/engine/src/canvas/vectoredit/regions_tests.rs b/crates/engine/src/canvas/vectoredit/regions_tests.rs index 6787a59f9..c0b762aff 100644 --- a/crates/engine/src/canvas/vectoredit/regions_tests.rs +++ b/crates/engine/src/canvas/vectoredit/regions_tests.rs @@ -6,6 +6,7 @@ use figcraft_geom::{Affine, Point, Rect, Vec2}; use serde_json::json; use super::regions::*; +use super::selected_region_fills; use super::tests::{ex, net, ve}; use crate::Session; use crate::tools::{PointerEvent, PointerKind}; @@ -540,3 +541,49 @@ fn hovered_and_selected_is_hatched_once_and_regions_share_one_pattern() { assert!(!part.is_empty() && part.len() < all.len()); assert!(part.iter().all(|x| all.iter().any(|y| (x - y).abs() < 1e-6))); } + +/// "If there are multiple closed regions within a vector network, you can adjust the fill for each +/// region individually" (Edit vector layers, #1875): with regions selected in edit mode, the fill +/// commands edit those regions' own fills and leave the layer's; `regions` names them outright. +#[test] +fn the_fill_commands_edit_the_selected_regions() { + let mut s = Session::new(); + let id = editing_vector(&mut s, overlapping()); + let fills_of = |s: &Session, r: usize| net(s, id).regions[r].fills.clone(); + let layer = |s: &Session| s.doc().unwrap().node(id).unwrap().fills.clone(); + let colour = |s: &Session, r: usize, i: usize| fills_of(s, r).unwrap()[i].solid_color().unwrap().to_css_hex().to_ascii_uppercase(); + let before = layer(&s); + ex(&mut s, "vector.edit.select", json!({"regions": [1]})); + ex(&mut s, "fill.set", json!({"ids": [id], "color": "#FF0000"})); + assert_eq!(fills_of(&s, 1).map(|f| f.len()), Some(1)); + assert_eq!(colour(&s, 1, 0), "#FF0000"); + assert_eq!(fills_of(&s, 0), None, "the other region still inherits"); + assert_eq!(layer(&s), before, "the layer's fills are untouched"); + // The section's list for the layer is the region's own stack. + assert_eq!(selected_region_fills(&s, id).and_then(|l| l).map(|l| l.len()), Some(1)); + ex(&mut s, "fill.add", json!({"ids": [id], "color": "#00FF00"})); + assert_eq!(fills_of(&s, 1).unwrap().len(), 2); + ex(&mut s, "fill.move", json!({"ids": [id], "from": 0, "to": 1})); + assert_eq!((colour(&s, 1, 0), colour(&s, 1, 1)), ("#00FF00".to_string(), "#FF0000".to_string())); + ex(&mut s, "fill.remove", json!({"ids": [id], "index": 0})); + assert_eq!(fills_of(&s, 1).unwrap().len(), 1); + assert_eq!(colour(&s, 1, 0), "#FF0000"); + assert_eq!(layer(&s), before); + // Both regions selected with different fills: the section shows mixed content. + ex(&mut s, "vector.edit.select", json!({"regions": [0, 1]})); + assert_eq!(selected_region_fills(&s, id), Some(None)); + // Named outright, with no selection; junk is refused. + ex(&mut s, "vector.edit.select", json!({})); + ex(&mut s, "fill.set", json!({"ids": [id], "regions": [0], "color": "#0000FF"})); + assert_eq!(colour(&s, 0, 0), "#0000FF"); + assert!(s.execute("fill.set", &json!({"ids": [id], "regions": [9], "color": "#0000FF"})).is_err()); + assert!(s.execute("fill.set", &json!({"ids": [id], "regions": "all", "color": "#0000FF"})).is_err()); + assert!(s.execute("fill.set", &json!({"ids": [id], "regions": [], "color": "#0000FF"})).is_err()); + // Nothing selected: the layer's fills, as before; the regions keep their own. + ex(&mut s, "fill.set", json!({"ids": [id], "color": "#123456"})); + assert_ne!(layer(&s), before); + assert_eq!(colour(&s, 1, 0), "#FF0000"); + assert_eq!(selected_region_fills(&s, id), None); + s.undo().unwrap(); + assert_eq!(layer(&s), before, "one undo step per command"); +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 700fa7414..1bd9bf45e 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -15,6 +15,7 @@ use crate::{BatchStep, EngineError, Result, Session, bad, spec}; mod clipboard; mod props; +pub(crate) use props::{edit_region_fills, fill_regions}; mod select; pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into}; @@ -330,14 +331,28 @@ pub fn specs() -> Vec { s.doc_mut()?.reorder(i, idx)?; ok() }), - spec!("fill.add", "Add fill", "{ids?, paint? | color? (default #D9D9D9 or white for frames)}", true, |s, p| paint_list(s, p, true, true)), + spec!( + "fill.add", + "Add fill", + "{ids?, paint? | color? (default #D9D9D9 or white for frames), regions? (a vector's regions by index: their own fills, as the regions selected in edit mode)}", + true, + |s, p| paint_list(s, p, true, true) + ), spec!("stroke.add", "Add stroke", "{ids?, paint? | color? (default black)}", true, |s, p| paint_list(s, p, false, true)), - spec!("fill.remove", "Remove fill", "{ids?, index}", true, |s, p| paint_list(s, p, true, false)), + spec!("fill.remove", "Remove fill", "{ids?, index, regions?}", true, |s, p| paint_list(s, p, true, false)), spec!("stroke.remove", "Remove stroke", "{ids?, index}", true, |s, p| paint_list(s, p, false, false)), - spec!("fill.set", "Set fill", "{ids?, index?, paint | color, opacity?, visible?, blend?}", true, |s, p| paint_set(s, p, true)), + spec!( + "fill.set", + "Set fill", + "{ids?, index?, paint | color, opacity?, visible?, blend?, regions? (a vector's regions by index: their own fills, as the regions selected in edit mode)}", + true, + |s, p| paint_set(s, p, true) + ), spec!("stroke.set", "Set stroke", "{ids?, index?, paint | color, opacity?, visible?, blend?}", true, |s, p| paint_set(s, p, false)), spec!("fill.copy", "Copy fill", "{id?, index? (default the top fill)}", false, |s, p| paint_copy(s, p, true)), - spec!("fill.paste", "Paste fill", "{ids?, index? (replace the fill there; without: add one)}", true, |s, p| paint_paste(s, p, true)), + spec!("fill.paste", "Paste fill", "{ids?, index? (replace the fill there; without: add one), regions?}", true, |s, p| paint_paste( + s, p, true + )), spec!( "stroke.copy", "Copy stroke", diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index da19b1eec..f11c228cb 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -260,10 +260,83 @@ pub(super) fn reparent(s: &mut Session, p: &Value) -> Result { ok() } +/// The regions of a vector whose own fill stacks a fill command edits instead of the layer's: the +/// `regions` named (with one target, a vector; indices into its network's regions), else the +/// regions selected in vector edit mode when the one target is the layer being edited ("you can +/// adjust the fill for each region individually", Edit vector layers, #1875). None: the layer's. +pub(crate) fn fill_regions(s: &Session, cmd: &str, p: &Value, ids: &[NodeId]) -> Result)>> { + let doc = s.doc()?; + let region_count = |id: NodeId| match doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Vector { network }) => Some(network.regions.len()), + _ => None, + }; + if let Some(list) = get(p, "regions") { + let [id] = ids else { return Err(bad(cmd, "`regions` goes with one vector layer")) }; + let Some(count) = region_count(*id) else { return Err(bad(cmd, "`regions` goes with a vector layer")) }; + let regions = list + .as_array() + .ok_or_else(|| bad(cmd, "regions: [index, ...]"))? + .iter() + .map(|v| { + v.as_u64() + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < count) + .ok_or_else(|| bad(cmd, format!("regions: indices below {count}"))) + }) + .collect::>>()?; + if regions.is_empty() { + return Err(bad(cmd, "regions: at least one")); + } + return Ok(Some((*id, regions))); + } + let [id] = ids else { return Ok(None) }; + let Some(ve) = s.ds()?.vector_edit.as_ref().filter(|ve| ve.id == *id && !ve.regions.is_empty()) else { return Ok(None) }; + let count = region_count(*id).unwrap_or(0); + let regions: Vec = ve.regions.iter().copied().filter(|r| *r < count).collect(); + Ok((!regions.is_empty()).then_some((*id, regions))) +} + +/// Runs `f` on the own fill stack of each of `regions` of vector `id` (a region without one +/// starts from the layer's fills, which stay as they are). +pub(crate) fn edit_region_fills( + doc: &mut figcraft_doc::Document, + id: NodeId, + regions: &[usize], + mut f: impl FnMut(&mut Vec) -> Result<()>, +) -> Result<()> { + let inherited = doc.get(id)?.fills.clone(); + let NodeKind::Vector { network } = &mut doc.get_mut(id)?.kind else { return Err(bad("fill", "not a vector layer")) }; + for &r in regions { + let Some(region) = network.regions.get_mut(r) else { continue }; + let mut list = region.fills.take().unwrap_or_else(|| inherited.clone()); + f(&mut list)?; + region.fills = Some(list); + } + Ok(()) +} + pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> Result { let cmd = if fills { "fill" } else { "stroke" }; let ids = req_targets(cmd, s, p)?; let index = if add || get(p, "index").is_none() { None } else { Some(req_index(cmd, p, "index")?) }; + if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills) { + let paint = match get(p, "paint").or_else(|| get(p, "color")) { + Some(v) => Some(paint_of(v).ok_or_else(|| bad(cmd, "invalid paint"))?), + None => None, + }; + edit_region_fills(s.doc_mut()?, id, ®ions, |list| { + if add { + list.push(paint.clone().unwrap_or_else(|| figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE))); + } else { + let idx = index.unwrap_or(list.len().saturating_sub(1)); + if idx < list.len() { + let _ = list.remove(idx); + } + } + Ok(()) + })?; + return ok(); + } let doc = s.doc_mut()?; for i in ids { let n = doc.get_mut(i)?; @@ -295,16 +368,8 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result None, }; let col = color(p, "color"); - let doc = s.doc_mut()?; - for i in ids { - let n = doc.get_mut(i)?; - let list = if fills { &mut n.fills } else { &mut n.strokes }; - let at = idx.unwrap_or(list.len().saturating_sub(1)); - if list.is_empty() { - list.push(figcraft_color::Paint::solid(if fills { figcraft_color::Color::DEFAULT_SHAPE } else { figcraft_color::Color::BLACK })); - } - let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) }; - let old = slot.clone(); + // The edit of one paint slot, the same for a layer's list and a region's. + let edit_slot = |slot: &mut figcraft_color::Paint| { if let Some(np) = &new_paint { *slot = np.clone(); } @@ -325,6 +390,30 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result Result { q["index"] = json!(at); diff --git a/crates/engine/src/cmd/lists.rs b/crates/engine/src/cmd/lists.rs index e53291b6d..19be64606 100644 --- a/crates/engine/src/cmd/lists.rs +++ b/crates/engine/src/cmd/lists.rs @@ -15,7 +15,7 @@ use crate::{Result, Session, spec}; pub fn specs() -> Vec { vec![ - spec!("fill.move", "Move fill", "{ids?, from, to} (indices in the fill list, bottom first)", true, |s, p| { + spec!("fill.move", "Move fill", "{ids?, from, to, regions?} (indices in the fill list, bottom first)", true, |s, p| { move_item(s, p, "fill.move", BoundList::Fills) }), spec!("stroke.move", "Move stroke", "{ids?, from, to} (indices in the stroke list, bottom first)", true, |s, p| { @@ -249,7 +249,20 @@ fn reorder(v: &mut Vec, from: usize, to: usize) -> bool { fn move_item(s: &mut Session, p: &Value, cmd: &str, list: BoundList) -> Result { let from = req_index(cmd, p, "from")?; let to = req_index(cmd, p, "to")?; - for id in req_targets(cmd, s, p)? { + let ids = req_targets(cmd, s, p)?; + // Fills of the regions selected (or named) in a vector: their own stacks move (#1875). + if matches!(list, BoundList::Fills) + && let Some((id, regions)) = crate::cmd::edit::fill_regions(s, cmd, p, &ids)? + { + crate::cmd::edit::edit_region_fills(s.doc_mut()?, id, ®ions, |fills| { + if from < fills.len() && to < fills.len() { + reorder(fills, from, to); + } + Ok(()) + })?; + return ok(); + } + for id in ids { let len = s.doc()?.node(id).map(|n| list.len(n)).unwrap_or(0); if from >= len || to >= len || from == to { continue; diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 58423d252..377597841 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -293,7 +293,13 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI } let t = Tokens::get(ui.ctx()); let ids = sel.to_vec(); - let list = common(doc, sel, |n| if fills { n.fills.clone() } else { n.strokes.clone() }); + // Regions selected in vector edit mode: their own fills ("you can adjust the fill for each + // region individually", Edit vector layers, #1875); the fill commands edit those too. + let region_list = match sel { + [id] if fills => figcraft_engine::vectoredit::selected_region_fills(&app.session, *id), + _ => None, + }; + let list = region_list.unwrap_or_else(|| common(doc, sel, |n| if fills { n.fills.clone() } else { n.strokes.clone() })); let title = if fills { tr("Fill") } else { tr("Stroke") }; let empty = list.as_ref().is_none_or(|l| l.is_empty()); let slot = if fills { StyleSlot::Fill } else { StyleSlot::Stroke }; diff --git a/crates/ui-egui/src/widgets/colorpicker.rs b/crates/ui-egui/src/widgets/colorpicker.rs index 5fbcc7b40..d8a5357f6 100644 --- a/crates/ui-egui/src/widgets/colorpicker.rs +++ b/crates/ui-egui/src/widgets/colorpicker.rs @@ -92,6 +92,13 @@ fn current_paint(app: &FigApp, target: &PickerTarget) -> Option { }, PickerTarget::Paint { fills, index, ids } => { let n = doc.node(*ids.first()?)?; + // Regions selected in vector edit mode: the picker edits their own fills (#1875). + if *fills + && ids.len() == 1 + && let Some(Some(list)) = figcraft_engine::vectoredit::selected_region_fills(&app.session, n.id) + { + return list.get(*index).cloned(); + } let list = if *fills { &n.fills } else { &n.strokes }; list.get(*index).cloned() } diff --git a/docs/mcp.md b/docs/mcp.md index b5e49e749..72815b351 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -723,7 +723,10 @@ made active), add?}`, `vector.edit.selectAll` (every edited layer's points), `ve `vector.edit.addVertex`, `vector.edit.connect {a, b}`, `vector.edit.pen {x, y, dx?, dy?}` (continues from the pen's open end; clicking a point connects or branches), `vector.edit.penEnd`, `vector.edit.paint {x, y} | {points}` (paint bucket: fills or unfills the closed area under a page -point; with `points`, the areas under the rest go the way the first went, like a drag), +point; with `points`, the areas under the rest go the way the first went, like a drag), `fill.set`, +`fill.add`, `fill.remove`, `fill.move` and `fill.paste` on the edited layer while regions are +selected (`vector.edit.select {regions}`), which edit those regions' own fills and leave the +layer's (`regions: [index, ...]` names them on any vector layer), `vector.edit.cut {segment, t} | {vertex} | {from: [x, y], to: [x, y]}` (the last cuts every path the page line crosses; parts that come apart move to layers of their own above, listed in `layers`), `vector.edit.erase {points, radius?}` (the eraser), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1d3c01373..fa242b184 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-02 · **Change:** patch (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-02 · **Change:** minor (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); 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: @@ -86,7 +86,7 @@ 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`). 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`); 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, ...]` (#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) | | 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 | @@ -177,6 +177,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| +| 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 ("If there are multiple closed regions within a vector network, you can adjust the fill for each region individually", Edit vector layers). Tests: `regions_tests::the_fill_commands_edit_the_selected_regions`. Numbers unchanged. | | 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`. | From d2e7c49e57271daab2d8e7b002ce45ad352531cf Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 09:14:55 -0500 Subject: [PATCH 120/326] Region fills: each region once, no override for a no-op, Copy fill reads the region, layer-only controls off region rows Named regions are deduplicated; an inheriting region stays inheriting when an edit leaves its stack as it was, and its own stack is only replaced once the edit succeeds; fill.copy reads the selected regions' paint; the Fill section leaves the fill style, a variable bound to the layer's fill and the image crop off region rows. Tests in regions_tests and region_fill_rows_tests. Co-Authored-By: Claude Opus 5.5 --- .../src/canvas/vectoredit/regions_tests.rs | 24 +++++ crates/engine/src/cmd/edit/props.rs | 29 ++++-- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/right/paints.rs | 28 +++--- crates/ui-egui/src/region_fill_rows_tests.rs | 99 +++++++++++++++++++ docs/mcp.md | 3 +- docs/ui-parity.md | 2 +- 7 files changed, 167 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/src/region_fill_rows_tests.rs diff --git a/crates/engine/src/canvas/vectoredit/regions_tests.rs b/crates/engine/src/canvas/vectoredit/regions_tests.rs index c0b762aff..cc40ef6f0 100644 --- a/crates/engine/src/canvas/vectoredit/regions_tests.rs +++ b/crates/engine/src/canvas/vectoredit/regions_tests.rs @@ -587,3 +587,27 @@ fn the_fill_commands_edit_the_selected_regions() { s.undo().unwrap(); assert_eq!(layer(&s), before, "one undo step per command"); } + +/// Region fill edits from review: a region named twice is edited once; an edit that changes +/// nothing leaves an inheriting region inheriting; Copy fill reads the selected region's fill. +#[test] +fn region_fill_edits_apply_once_skip_no_ops_and_copy_the_region() { + let mut s = Session::new(); + let id = editing_vector(&mut s, overlapping()); + let fills_of = |s: &Session, r: usize| net(s, id).regions[r].fills.clone(); + ex(&mut s, "vector.edit.select", json!({"regions": [1]})); + ex(&mut s, "fill.move", json!({"ids": [id], "from": 0, "to": 0})); + assert_eq!(fills_of(&s, 1), None, "moving a paint onto itself leaves the region inheriting"); + ex(&mut s, "fill.remove", json!({"ids": [id], "index": 5})); + assert_eq!(fills_of(&s, 1), None, "removing a paint that isn't there leaves it inheriting"); + ex(&mut s, "fill.add", json!({"ids": [id], "regions": [0, 0], "color": "#00FF00"})); + assert_eq!(fills_of(&s, 0).map(|f| f.len()), Some(2), "the layer's fill and one added, once"); + // Copy fill takes the selected region's own paint, not the layer's. + ex(&mut s, "fill.set", json!({"ids": [id], "color": "#FF0000"})); + ex(&mut s, "fill.copy", json!({"ids": [id], "index": 0})); + let copied = s.clipboard.paint.clone().map(|(_, p)| p.solid_color().unwrap().to_css_hex().to_ascii_uppercase()); + assert_eq!(copied.as_deref(), Some("#FF0000")); + // Regions whose fills differ have no one paint to copy. + ex(&mut s, "vector.edit.select", json!({"regions": [0, 1]})); + assert!(s.execute("fill.copy", &json!({"ids": [id], "index": 0})).is_err()); +} diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index f11c228cb..04315bbed 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -273,7 +273,7 @@ pub(crate) fn fill_regions(s: &Session, cmd: &str, p: &Value, ids: &[NodeId]) -> if let Some(list) = get(p, "regions") { let [id] = ids else { return Err(bad(cmd, "`regions` goes with one vector layer")) }; let Some(count) = region_count(*id) else { return Err(bad(cmd, "`regions` goes with a vector layer")) }; - let regions = list + let mut regions = list .as_array() .ok_or_else(|| bad(cmd, "regions: [index, ...]"))? .iter() @@ -284,6 +284,9 @@ pub(crate) fn fill_regions(s: &Session, cmd: &str, p: &Value, ids: &[NodeId]) -> .ok_or_else(|| bad(cmd, format!("regions: indices below {count}"))) }) .collect::>>()?; + // A region named twice is edited once. + regions.sort_unstable(); + regions.dedup(); if regions.is_empty() { return Err(bad(cmd, "regions: at least one")); } @@ -292,12 +295,16 @@ pub(crate) fn fill_regions(s: &Session, cmd: &str, p: &Value, ids: &[NodeId]) -> let [id] = ids else { return Ok(None) }; let Some(ve) = s.ds()?.vector_edit.as_ref().filter(|ve| ve.id == *id && !ve.regions.is_empty()) else { return Ok(None) }; let count = region_count(*id).unwrap_or(0); - let regions: Vec = ve.regions.iter().copied().filter(|r| *r < count).collect(); + let mut regions: Vec = ve.regions.iter().copied().filter(|r| *r < count).collect(); + regions.sort_unstable(); + regions.dedup(); Ok((!regions.is_empty()).then_some((*id, regions))) } /// Runs `f` on the own fill stack of each of `regions` of vector `id` (a region without one -/// starts from the layer's fills, which stay as they are). +/// starts from the layer's fills, which stay as they are). A region that inherits the layer's +/// fills keeps inheriting when `f` leaves the stack as it was, so later edits of the layer's +/// fills still reach it; a region's own stack is only replaced once `f` succeeds. pub(crate) fn edit_region_fills( doc: &mut figcraft_doc::Document, id: NodeId, @@ -308,9 +315,11 @@ pub(crate) fn edit_region_fills( let NodeKind::Vector { network } = &mut doc.get_mut(id)?.kind else { return Err(bad("fill", "not a vector layer")) }; for &r in regions { let Some(region) = network.regions.get_mut(r) else { continue }; - let mut list = region.fills.take().unwrap_or_else(|| inherited.clone()); + let mut list = region.fills.clone().unwrap_or_else(|| inherited.clone()); f(&mut list)?; - region.fills = Some(list); + if region.fills.is_some() || list != inherited { + region.fills = Some(list); + } } Ok(()) } @@ -433,7 +442,15 @@ pub(super) fn paint_copy(s: &mut Session, p: &Value, fills: bool) -> Result list, + Some(None) => return Err(bad(cmd, "the selected regions' fills differ")), + None if fills => &n.fills, + None => &n.strokes, + }; let at = at.unwrap_or(list.len().saturating_sub(1)); let paint = list.get(at).cloned().ok_or_else(|| bad(cmd, format!("no {} at index {at}", if fills { "fill" } else { "stroke" })))?; (paint, (!fills).then(|| n.stroke.clone())) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e9969c106..d787fb1ca 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -221,6 +221,8 @@ mod proto_reorder_tests; #[cfg(test)] mod proto_responsive_tests; #[cfg(test)] +mod region_fill_rows_tests; +#[cfg(test)] mod resources_tests; #[cfg(test)] mod sampled_color_tests; diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 377597841..675becc6d 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -299,20 +299,20 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI [id] if fills => figcraft_engine::vectoredit::selected_region_fills(&app.session, *id), _ => None, }; + // The fill style, a variable bound to the layer's fill and the image crop are the layer's: + // they stay off a region's rows. + let region = region_list.is_some(); let list = region_list.unwrap_or_else(|| common(doc, sel, |n| if fills { n.fills.clone() } else { n.strokes.clone() })); let title = if fills { tr("Fill") } else { tr("Stroke") }; let empty = list.as_ref().is_none_or(|l| l.is_empty()); let slot = if fills { StyleSlot::Fill } else { StyleSlot::Stroke }; // The section's right-click menu adds the copied paint (`fill.paste` / `stroke.paste`). let paste = if fills { tr("Paste fill") } else { tr("Paste stroke") }; - let (clicked, header) = widgets::section_header_resp( - ui, - title, - &[(Icon::Styles, tr("Styles")), (Icon::Plus, if fills { tr("Add fill") } else { tr("Add stroke") })], - empty, - ); + let add = (Icon::Plus, if fills { tr("Add fill") } else { tr("Add stroke") }); + let buttons = if region { vec![add] } else { vec![(Icon::Styles, tr("Styles")), add] }; + let (clicked, header) = widgets::section_header_resp(ui, title, &buttons, empty); if let Some(i) = clicked { - if i == 1 { + if buttons.get(i).is_some_and(|(icon, _)| *icon == Icon::Plus) { // The new paint goes on top; open its picker. A mixed selection has no one index to edit. if app.run(if fills { "fill.add" } else { "stroke.add" }, json!({"ids": ids})).is_some() && let Some(l) = &list @@ -329,14 +329,16 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI ui.close(); } }); - style_picker::chip(app, ui, doc, &ids, slot); + if !region { + style_picker::chip(app, ui, doc, &ids, slot); + } match &list { None => widgets::note(ui, tr("Click + to replace mixed content"), t.text_secondary), Some(l) => { // The last paint is on top: shown first. Rows drag to reorder. 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); + let r = paint_row(app, ui, &ids, i, p, fills, region); drag.row(ui, i, r, r, || paint_label(p)); } if let Some((from, to)) = drag.finish(ui) { @@ -446,7 +448,9 @@ 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. -fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint, fills: bool) -> Rect { +/// 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). +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" }; @@ -461,7 +465,7 @@ fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint, let text_r = Rect::from_min_max(pos2(sw.max.x + 8.0, r.min.y), pos2(r.max.x - 52.0, r.max.y)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(text_r)); // The variable bound to this paint's colour (its key on the layers: `fill` or `fills//color`). - let bound = app.session.doc().ok().and_then(|d| { + let bound = app.session.doc().ok().filter(|_| !region).and_then(|d| { let key = ids.first().and_then(|id| d.node(*id)).and_then(|n| figcraft_engine::cmd::lists::paint_binding_key(n, fills, i))?; Some((key.to_string(), crate::variable_ui::bound_name(d, &ids, key)?)) }); @@ -502,7 +506,7 @@ fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint, _ => { child.painter().text(pos2(text_r.min.x, r.center().y), Align2::LEFT_CENTER, paint_label(p), regular(11.0), t.text); // One layer's image fill: crop it on the canvas. - if fills && ids.len() == 1 && matches!(p.kind, PaintKind::Image(_)) { + if fills && ids.len() == 1 && !region && matches!(p.kind, PaintKind::Image(_)) { let cr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0)); let cresp = ui.interact(cr, Id::unique(("crop_image", i)), Sense::click()).tip(tr("Crop image")); icons::paint(ui.painter(), cr.shrink(3.0), Icon::Crop, if cresp.hovered() { t.icon } else { t.icon_secondary }); diff --git a/crates/ui-egui/src/region_fill_rows_tests.rs b/crates/ui-egui/src/region_fill_rows_tests.rs new file mode 100644 index 000000000..7dc1c9a5b --- /dev/null +++ b/crates/ui-egui/src/region_fill_rows_tests.rs @@ -0,0 +1,99 @@ +//! The Fill section with a region of a vector selected in edit mode (#1875), driven through egui +//! headless: the region's own fill shows, and what belongs to the layer (its fill style, a +//! variable bound to its fill) stays off the region's rows. + +use egui::accesskit::Role; +use egui::{Pos2, pos2}; +use figcraft_doc::{NodeId, NodeKind, Region, Segment, VectorNetwork, Vertex}; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; + +/// Four points and four straight segments of a square, appended to `n`. +fn square(n: &mut VectorNetwork, x0: f64, y0: f64, size: f64) { + let v0 = n.vertices.len(); + for (x, y) in [(x0, y0), (x0 + size, y0), (x0 + size, y0 + size), (x0, y0 + size)] { + n.vertices.push(Vertex::new(x, y)); + } + for k in 0..4 { + n.segments.push(Segment::line(v0 + k, v0 + (k + 1) % 4)); + } +} + +/// A vector of two squares, the outer one's region then the inner one's, its fill bound to a +/// blue colour variable; in edit mode with the inner region selected and given a red fill of its +/// own. +fn ui() -> Ui { + let mut s = Session::new(); + let r = s.execute("vector.create", &json!({"points": [[0, 0], [10, 0], [10, 10]], "closed": true})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + { + let doc = s.doc_mut().unwrap(); + let node = doc.get_mut(id).unwrap(); + let mut n = VectorNetwork::default(); + square(&mut n, 0.0, 0.0, 200.0); + square(&mut n, 60.0, 60.0, 80.0); + n.regions = + vec![Region { loops: vec![vec![0, 1, 2, 3]], ..Default::default() }, Region { loops: vec![vec![4, 5, 6, 7]], ..Default::default() }]; + node.kind = NodeKind::Vector { network: n }; + node.transform = figcraft_geom::Affine::IDENTITY; + node.fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)]; + figcraft_engine::vectoredit::refit(doc, id).unwrap(); + } + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + s.execute("variable.create", &json!({"collection": "Theme", "name": "brand", "type": "color", "value": "#0000FF"})).unwrap(); + s.execute("variable.bind", &json!({"ids": [id.0], "field": "fill", "variable": "brand"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("vector.edit.begin", &json!({"id": id.0})).unwrap(); + s.execute("vector.edit.select", &json!({"regions": [1]})).unwrap(); + s.execute("fill.set", &json!({"ids": [id.0], "color": "#FF0000"})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + u +} + +/// The accessible controls after a frame: role, label, value and centre. +fn controls(u: &mut Ui) -> Vec<(Role, String, String, Pos2)> { + u.frame(vec![]); + let out = u.frame_output(vec![]); + let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; + nodes + .iter() + .map(|(_, n)| { + let at = n.bounds().map_or(pos2(0.0, 0.0), |b| pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)); + (n.role(), n.label().unwrap_or_default().to_string(), n.value().unwrap_or_default().to_string(), at) + }) + .collect() +} + +fn button(c: &[(Role, String, String, Pos2)], name: &str) -> Pos2 { + c.iter().find(|(r, l, _, _)| *r == Role::Button && l == name).map(|(_, _, _, p)| *p).unwrap_or_else(|| panic!("no {name} button: {c:?}")) +} + +/// What the Fill section shows, between its + and the Stroke section's: its hex rows, whether a +/// Detach variable button is there, and whether its header has a Styles button. +fn fill_section(c: &[(Role, String, String, Pos2)]) -> (Vec, bool, bool) { + let (top, bottom) = (button(c, "Add fill"), button(c, "Add stroke")); + let inside = |p: &Pos2| p.y > top.y + 2.0 && p.y < bottom.y - 2.0; + let rows = c.iter().filter(|(r, _, _, p)| *r == Role::TextInput && inside(p)).map(|(_, _, v, _)| v.clone()).collect(); + let detach = c.iter().any(|(_, l, _, p)| l == "Detach variable" && inside(p)); + let styles = c.iter().any(|(r, l, _, p)| *r == Role::Button && l == "Styles" && (p.y - top.y).abs() < 2.0); + (rows, detach, styles) +} + +#[test] +fn a_selected_regions_rows_leave_out_the_layers_style_and_variable() { + let mut u = ui(); + let red = figcraft_color::Color::from_hex("#FF0000").unwrap().to_hex(); + let (rows, detach, styles) = fill_section(&controls(&mut u)); + assert_eq!(rows, [red], "the region's own red, as a hex field"); + assert!(!detach, "the layer's variable binding is not the region's"); + assert!(!styles, "no fill style for a region's fills"); + // No region selected: the layer's row again, with its bound variable and the Styles button. + u.app.run("vector.edit.select", json!({})); + let (rows, detach, styles) = fill_section(&controls(&mut u)); + assert!(rows.is_empty(), "the layer's paint shows as its variable, not a hex field: {rows:?}"); + assert!(detach && styles); +} diff --git a/docs/mcp.md b/docs/mcp.md index 72815b351..c014dc877 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -726,7 +726,8 @@ from the pen's open end; clicking a point connects or branches), `vector.edit.pe point; with `points`, the areas under the rest go the way the first went, like a drag), `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` on the edited layer while regions are selected (`vector.edit.select {regions}`), which edit those regions' own fills and leave the -layer's (`regions: [index, ...]` names them on any vector layer), +layer's (`regions: [index, ...]` names them on any vector layer; `fill.copy` copies the selected +regions' paint), `vector.edit.cut {segment, t} | {vertex} | {from: [x, y], to: [x, y]}` (the last cuts every path the page line crosses; parts that come apart move to layers of their own above, listed in `layers`), `vector.edit.erase {points, radius?}` (the eraser), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index fa242b184..4a9168cb8 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -86,7 +86,7 @@ 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`); 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, ...]` (#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`); 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, and what belongs to the layer (its fill style, a variable bound to its fill, the image crop) stays off a region's rows (#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) | | 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 | From aa2fed07e270cb02153f052b240f06b6a46fdd74 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 09:49:10 -0500 Subject: [PATCH 121/326] Region fills: fill.pattern stays on the layer; the canvas handles and the picker's image paths edit the region's paint fill.pattern sets the layer's fill as its spec says. The gradient and crop handles read the paint from the stack fill.set writes (the selected regions' while there are any); for a region's paint, Upload from computer and image presets write the paint like any edit, and a drop on the picker goes to the canvas (image.replace and image.adjust edit layer paints). Tests in regions_tests, canvas/handles/region_tests and colorpicker image tests. Co-Authored-By: Claude Opus 5.5 --- .../src/canvas/vectoredit/regions_tests.rs | 13 +++++++ crates/engine/src/cmd/edit/props.rs | 10 ++++-- crates/ui-egui/src/canvas/handles.rs | 24 ++++++++++--- .../src/canvas/handles/region_tests.rs | 35 +++++++++++++++++++ crates/ui-egui/src/region_fill_rows_tests.rs | 16 ++++++--- crates/ui-egui/src/widgets/colorpicker.rs | 27 +++++++++++--- .../src/widgets/colorpicker_image_tests.rs | 28 +++++++++++++++ docs/ui-parity.md | 2 +- 8 files changed, 138 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/src/canvas/handles/region_tests.rs diff --git a/crates/engine/src/canvas/vectoredit/regions_tests.rs b/crates/engine/src/canvas/vectoredit/regions_tests.rs index cc40ef6f0..272c556fd 100644 --- a/crates/engine/src/canvas/vectoredit/regions_tests.rs +++ b/crates/engine/src/canvas/vectoredit/regions_tests.rs @@ -611,3 +611,16 @@ fn region_fill_edits_apply_once_skip_no_ops_and_copy_the_region() { ex(&mut s, "vector.edit.select", json!({"regions": [0, 1]})); assert!(s.execute("fill.copy", &json!({"ids": [id], "index": 0})).is_err()); } + +/// `fill.pattern` sets the layer's fill, as its spec says, also while regions are selected. +#[test] +fn fill_pattern_sets_the_layers_fill_with_regions_selected() { + let mut s = Session::new(); + let src = crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": 400, "y": 0, "width": 20, "height": 20}))["id"]).unwrap(); + let id = editing_vector(&mut s, overlapping()); + ex(&mut s, "vector.edit.select", json!({"regions": [1]})); + ex(&mut s, "fill.pattern", json!({"ids": [id], "source": src})); + assert_eq!(net(&s, id).regions[1].fills, None, "the region still inherits"); + let top = s.doc().unwrap().node(id).unwrap().fills.last().cloned().unwrap(); + assert!(matches!(top.kind, figcraft_color::PaintKind::Pattern(_)), "{top:?}"); +} diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index 04315bbed..2a719af0d 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -369,6 +369,12 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> } pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result { + paint_set_in(s, p, fills, true) +} + +/// [`paint_set`]; `to_regions`: whether the regions selected (or named) on a vector take the +/// edit in their own fills (#1875), as for `fill.set`; `fill.pattern` always sets the layer's. +fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Result { let cmd = if fills { "fill.set" } else { "stroke.set" }; let ids = req_targets(cmd, s, p)?; let idx = opt_index(cmd, p, "index")?; @@ -400,7 +406,7 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result Result { q["paint"] = serde_json::to_value(figcraft_color::Paint { kind: figcraft_color::PaintKind::Pattern(pt), ..figcraft_color::Paint::pattern(src.0) }) .map_err(|e| bad(CMD, e.to_string()))?; - paint_set(s, &q, true) + paint_set_in(s, &q, true, false) } pub(super) fn effect_add(s: &mut Session, p: &Value) -> Result { diff --git a/crates/ui-egui/src/canvas/handles.rs b/crates/ui-egui/src/canvas/handles.rs index 137e2c92b..aa3033b0d 100644 --- a/crates/ui-egui/src/canvas/handles.rs +++ b/crates/ui-egui/src/canvas/handles.rs @@ -40,6 +40,17 @@ enum Drag { /// The Crop-mode image being edited: (node, fills, index, paint, image rect in the unit box). type UnitRect = (f64, f64, f64, f64); +/// The paint list a picker paint at an index belongs to on layer `n`: the selected regions' own +/// fills while regions of it are selected in vector edit mode, as the Fill section lists them and +/// `fill.set` edits them (#1875), else the layer's fills or strokes. None when those regions' +/// fills differ. +fn edited_list(app: &FigApp, n: &figcraft_doc::Node, fills: bool) -> Option> { + if fills && let Some(regions) = figcraft_engine::vectoredit::selected_region_fills(&app.session, n.id) { + return regions; + } + Some(if fills { n.fills.clone() } else { n.strokes.clone() }) +} + /// The paint open in the colour picker, else the image fill in crop mode (while its layer is the /// selection). fn crop_target(app: &FigApp) -> Option<(NodeId, bool, usize, ImagePaint, UnitRect)> { @@ -53,7 +64,7 @@ fn crop_target(app: &FigApp) -> Option<(NodeId, bool, usize, ImagePaint, UnitRec }; let doc = app.session.doc().ok()?; let n = doc.node(id)?; - let list = if fills { &n.fills } else { &n.strokes }; + let list = edited_list(app, n, fills)?; let PaintKind::Image(img) = &list.get(index)?.kind else { return None }; if img.scale_mode != ImageScaleMode::Crop { return None; @@ -193,7 +204,7 @@ fn gradient_target(app: &FigApp) -> Option<(NodeId, bool, usize, figcraft_color: return None; } let n = app.session.doc().ok()?.node(id)?; - let list = if *fills { &n.fills } else { &n.strokes }; + let list = edited_list(app, n, *fills)?; match &list.get(*index)?.kind { PaintKind::Gradient(g) => Some((id, *fills, *index, g.clone())), _ => None, @@ -233,7 +244,7 @@ fn line_param(a: Pos2, b: Pos2, p: Pos2) -> Option<(f64, f32)> { fn set_gradient(app: &mut FigApp, id: NodeId, fills: bool, index: usize, g: figcraft_color::Gradient) { let Some(n) = app.session.doc().ok().and_then(|d| d.node(id)).cloned() else { return }; - let list = if fills { &n.fills } else { &n.strokes }; + let Some(list) = edited_list(app, &n, fills) else { return }; let Some(mut paint) = list.get(index).cloned() else { return }; paint.kind = PaintKind::Gradient(g); let cmd = if fills { "fill.set" } else { "stroke.set" }; @@ -652,7 +663,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { Drag::Gradient { id, fills, index, which } => { let Some(u) = screen_to_unit(app, *id, pos) else { return }; let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return }; - let list = if *fills { &n.fills } else { &n.strokes }; + let Some(list) = edited_list(app, &n, *fills) else { return }; let Some(mut paint) = list.get(*index).cloned() else { return }; if let PaintKind::Gradient(g) = &mut paint.kind { match which { @@ -727,7 +738,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { (ax.min(ax + nw), ay.min(ay + nh), ax.max(ax + nw), ay.max(ay + nh)) }; let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return }; - let list = if *fills { &n.fills } else { &n.strokes }; + let Some(list) = edited_list(app, &n, *fills) else { return }; let Some(mut paint) = list.get(*index).cloned() else { return }; if let PaintKind::Image(img) = &mut paint.kind { img.crop = Some(ImagePaint::crop_from_rect(r.0, r.1, r.2, r.3)); @@ -749,3 +760,6 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) { } } } + +#[cfg(test)] +mod region_tests; diff --git a/crates/ui-egui/src/canvas/handles/region_tests.rs b/crates/ui-egui/src/canvas/handles/region_tests.rs new file mode 100644 index 000000000..d5033d7f7 --- /dev/null +++ b/crates/ui-egui/src/canvas/handles/region_tests.rs @@ -0,0 +1,35 @@ +//! The canvas paint handles with a region of a vector selected in edit mode (#1875): they read +//! and write the paint the colour picker shows, the region's own, not the layer's. + +use figcraft_color::{Color, Gradient, GradientKind, Paint, PaintKind}; +use serde_json::json; + +use super::{gradient_target, set_gradient}; +use crate::colorpicker::PickerTarget; +use crate::layers_drag_tests::Ui; + +#[test] +fn the_gradient_handles_edit_a_selected_regions_own_paint() { + let mut s = figcraft_engine::Session::new(); + let id = crate::region_fill_rows_tests::two_region_vector(&mut s); + s.execute("vector.edit.begin", &json!({"id": id.0})).unwrap(); + s.execute("vector.edit.select", &json!({"regions": [1]})).unwrap(); + // The region's own paint: a gradient at half opacity; the layer keeps its solid grey. + let mut paint = Paint::gradient(Gradient::default_for(GradientKind::Linear, Color::BLACK)); + paint.opacity = 0.5; + s.execute("fill.set", &json!({"ids": [id.0], "paint": paint})).unwrap(); + let mut u = Ui::new(s); + u.app.ui.picker = Some(PickerTarget::Paint { fills: true, index: 0, ids: vec![id] }); + let (at, fills, index, g) = gradient_target(&u.app).expect("the handles show the region's gradient"); + assert_eq!((at, fills, index), (id, true, 0)); + let mut moved = g.clone(); + moved.from = (0.1, 0.2); + set_gradient(&mut u.app, id, true, 0, moved); + let doc = u.app.session.doc().unwrap(); + let n = doc.node(id).unwrap(); + let figcraft_doc::NodeKind::Vector { network } = &n.kind else { panic!("not a vector") }; + let region = network.regions[1].fills.clone().unwrap(); + assert!(matches!(®ion[0].kind, PaintKind::Gradient(x) if x.from == (0.1, 0.2)), "{region:?}"); + assert_eq!(region[0].opacity, 0.5, "the region's paint keeps its own opacity"); + assert!(matches!(n.fills[0].kind, PaintKind::Solid { .. }), "the layer's fill is untouched: {:?}", n.fills); +} diff --git a/crates/ui-egui/src/region_fill_rows_tests.rs b/crates/ui-egui/src/region_fill_rows_tests.rs index 7dc1c9a5b..5d071bca3 100644 --- a/crates/ui-egui/src/region_fill_rows_tests.rs +++ b/crates/ui-egui/src/region_fill_rows_tests.rs @@ -21,11 +21,9 @@ fn square(n: &mut VectorNetwork, x0: f64, y0: f64, size: f64) { } } -/// A vector of two squares, the outer one's region then the inner one's, its fill bound to a -/// blue colour variable; in edit mode with the inner region selected and given a red fill of its -/// own. -fn ui() -> Ui { - let mut s = Session::new(); +/// A vector of two squares on the page, the outer one's region then the inner one's, both +/// inheriting the layer's default grey fill (also used by the canvas handle and picker tests). +pub(crate) fn two_region_vector(s: &mut Session) -> NodeId { let r = s.execute("vector.create", &json!({"points": [[0, 0], [10, 0], [10, 10]], "closed": true})).unwrap(); let id = NodeId(r["id"].as_u64().unwrap()); { @@ -41,6 +39,14 @@ fn ui() -> Ui { node.fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)]; figcraft_engine::vectoredit::refit(doc, id).unwrap(); } + id +} + +/// [`two_region_vector`] with its fill bound to a blue colour variable; in edit mode with the +/// inner region selected and given a red fill of its own. +fn ui() -> Ui { + let mut s = Session::new(); + let id = two_region_vector(&mut s); s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); s.execute("variable.create", &json!({"collection": "Theme", "name": "brand", "type": "color", "value": "#0000FF"})).unwrap(); s.execute("variable.bind", &json!({"ids": [id.0], "field": "fill", "variable": "brand"})).unwrap(); diff --git a/crates/ui-egui/src/widgets/colorpicker.rs b/crates/ui-egui/src/widgets/colorpicker.rs index d8a5357f6..60c1e0b32 100644 --- a/crates/ui-egui/src/widgets/colorpicker.rs +++ b/crates/ui-egui/src/widgets/colorpicker.rs @@ -581,6 +581,18 @@ fn set_image_pending(ctx: &egui::Context, target: Option<&PickerTarget>) { } /// `image.replace`'s parameters for layers' paint `index`. +/// Whether `target` is a paint of the regions selected in vector edit mode (#1875): the picker +/// shows the regions' own fills, which the image commands (layer paints only) don't reach, so +/// their image edits are written as paints like any other. +fn region_backed(app: &FigApp, target: &PickerTarget) -> bool { + match target { + PickerTarget::Paint { fills: true, ids, .. } => { + matches!(ids.as_slice(), [id] if figcraft_engine::vectoredit::selected_region_fills(&app.session, *id).is_some()) + } + _ => false, + } +} + fn image_params(fills: bool, index: usize, ids: &[NodeId]) -> serde_json::Value { json!({"ids": ids, "target": if fills { "fill" } else { "stroke" }, "index": index}) } @@ -591,6 +603,11 @@ fn image_params(fills: bool, index: usize, ids: &[NodeId]) -> serde_json::Value pub(crate) fn image_drop_target(app: &FigApp, ctx: &egui::Context) -> Option<(Rect, serde_json::Value)> { let target = app.ui.picker.as_ref()?; let PickerTarget::Paint { fills, index, ids } = target else { return None }; + // A region's own paint takes no drop (`image.replace` edits layer paints); the file goes to + // the canvas as it would without the picker. + if region_backed(app, target) { + return None; + } if !image_pending(ctx, target) && !matches!(current_paint(app, target)?.kind, PaintKind::Image(_)) { return None; } @@ -611,7 +628,9 @@ fn picked_bytes(file: &serde_json::Value) -> Option> { fn upload_image(app: &mut FigApp, target: &PickerTarget) { let target = target.clone(); app.pick_file(tr("Choose image"), &IMAGE_FILES, true, move |app, file| { - if let PickerTarget::Paint { fills, index, ids } = &target { + if let PickerTarget::Paint { fills, index, ids } = &target + && !region_backed(app, &target) + { let mut params = image_params(*fills, *index, ids); for key in ["path", "data"] { if let Some(v) = file.get(key) { @@ -1404,9 +1423,9 @@ fn image_presets(app: &mut FigApp, ui: &mut Ui, target: &PickerTarget, paint: &m app.run("image.deletePreset", json!({"name": name})); } Some(PresetAction::Apply(name)) => match target { - // Layer paints go through the command; other targets (a text range, a style) get the - // preset's values written like any edit. - PickerTarget::Paint { fills, index, ids } => { + // Layer paints go through the command; other targets (a text range, a style, a + // region's own paint) get the preset's values written like any edit. + PickerTarget::Paint { fills, index, ids } if !region_backed(app, target) => { app.run("image.adjust", json!({"ids": ids, "target": if *fills { "fill" } else { "stroke" }, "index": index, "preset": name})); } _ => { diff --git a/crates/ui-egui/src/widgets/colorpicker_image_tests.rs b/crates/ui-egui/src/widgets/colorpicker_image_tests.rs index 539a69fc9..5d4b229a5 100644 --- a/crates/ui-egui/src/widgets/colorpicker_image_tests.rs +++ b/crates/ui-egui/src/widgets/colorpicker_image_tests.rs @@ -284,3 +284,31 @@ fn cancelling_the_upload_changes_nothing() { } let _ = std::fs::remove_dir_all(&dir); } + +/// A region of a vector selected in edit mode (#1875): Upload from computer puts the image in the +/// region's own fill the picker shows, the layer's fills untouched; a file dropped on the picker +/// isn't taken for a region's paint (it goes to the canvas, as without the picker). +#[test] +fn upload_from_computer_on_a_regions_fill_puts_the_image_in_the_region() { + let dir = temp_dir("region"); + let mut s = Session::new(); + let id = crate::region_fill_rows_tests::two_region_vector(&mut s); + s.execute("vector.edit.begin", &json!({"id": id.0})).unwrap(); + s.execute("vector.edit.select", &json!({"regions": [1]})).unwrap(); + s.execute("fill.set", &json!({"ids": [id.0], "color": "#FF0000"})).unwrap(); + let layer_fills = s.doc().unwrap().node(id).unwrap().fills.clone(); + let mut u = Ui::new(s); + open_picker(&mut u, id, 0); + let asked = fake_picker(&mut u, Some(png(5)), false, &dir); + click_image_tab(&mut u); + assert!(super::image_drop_target(&u.app, &u.ctx).is_none(), "a drop isn't taken for a region's paint"); + click_upload(&mut u); + assert_eq!(asked.load(Ordering::SeqCst), 1); + let doc = u.app.session.doc().unwrap(); + let n = doc.node(id).unwrap(); + assert_eq!(n.fills, layer_fills, "the layer's fills are untouched"); + let figcraft_doc::NodeKind::Vector { network } = &n.kind else { panic!("not a vector") }; + let region = network.regions[1].fills.clone().unwrap(); + assert!(matches!(region.last().map(|p| &p.kind), Some(PaintKind::Image(_))), "{region:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4a9168cb8..b9972b7aa 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -86,7 +86,7 @@ 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`); 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, and what belongs to the layer (its fill style, a variable bound to its fill, the image crop) stays off a region's rows (#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`); 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 | | 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) | | 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 | From 6365e4339b4d4cf5754111715e2ea4e4eee74b9d Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:32:37 +0100 Subject: [PATCH 122/326] M4: Increase and decrease font weight step through the styles the family has (#1831) text.weightUp/weightDown stepped the CSS weight by 100 and stored a canonical name ("Medium", "Semi Bold", ...) whether the family had that face or not, so the first press on Arial Regular changed nothing visible and the stored style named a face no font provides. They now move to the nearest heavier or lighter style of the family with the same slant and width (Narrow stays Narrow), and stay put at either end. A family that isn't installed keeps the old 100 steps. --- crates/engine/src/cmd/text.rs | 65 ++++++++++++++++- crates/engine/src/lib.rs | 2 + crates/engine/src/text_weight_step_tests.rs | 81 +++++++++++++++++++++ 3 files changed, 145 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/text_weight_step_tests.rs diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index f72f215ee..c2b9043c3 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -122,11 +122,70 @@ fn toggle_italic(s: &mut Session, p: &Value) -> Result { }) } +/// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow"). +fn style_rest(style: &str) -> String { + const WORDS: [&str; 25] = [ + "thin", + "hairline", + "extralight", + "ultralight", + "light", + "regular", + "normal", + "roman", + "book", + "medium", + "semibold", + "demibold", + "bold", + "extrabold", + "ultrabold", + "black", + "heavy", + "semi", + "demi", + "extra", + "ultra", + "italic", + "oblique", + "plain", + "standard", + ]; + let s = style.to_ascii_lowercase().replace('-', " "); + let words = s.split_whitespace().filter(|w| !WORDS.contains(w) && !w.chars().all(|c| c.is_ascii_digit())); + words.collect::>().join(" ") +} + +fn slanted(style: &str) -> bool { + let s = style.to_ascii_lowercase(); + s.contains("italic") || s.contains("oblique") +} + +/// The next heavier (`up`) or lighter style of `styles` (a family's) after the chars' style: the +/// nearest weight with the same slant and width, as the style menu lists them. None when the family +/// has nothing further that way. +pub(crate) fn next_style(styles: &[String], st: &TextStyle, up: bool) -> Option { + let (w, italic, rest) = (i32::from(st.weight()), st.italic(), style_rest(&st.font_style)); + styles + .iter() + .filter(|x| slanted(x) == italic && style_rest(x) == rest) + .map(|x| (i32::from(figcraft_doc::style_weight(x)) - w, x)) + .filter(|(d, _)| if up { *d > 0 } else { *d < 0 }) + .min_by_key(|(d, _)| d.abs()) + .map(|(_, x)| x.clone()) +} + fn step_weight(s: &mut Session, p: &Value, up: bool) -> Result { style(s, p, |st| { - let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16; - let italic = st.italic(); - st.set_font_style(styled_name(weight_name(w), italic)); + let styles = figcraft_text::family_styles(&st.font_family); + if styles.is_empty() { + // A family that isn't installed: step the weight by 100 under its canonical name. + let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16; + let italic = st.italic(); + st.set_font_style(styled_name(weight_name(w), italic)); + } else if let Some(next) = next_style(&styles, st, up) { + st.set_font_style(next); + } }) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e919444e2..621fdd8cb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -575,6 +575,8 @@ mod text_style_picker_tests; #[cfg(test)] mod text_tail_tests; #[cfg(test)] +mod text_weight_step_tests; +#[cfg(test)] mod textfit_tests; #[cfg(test)] mod theme_pages_tests; diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs new file mode 100644 index 000000000..f3f7fa587 --- /dev/null +++ b/crates/engine/src/text_weight_step_tests.rs @@ -0,0 +1,81 @@ +//! Increase and decrease font weight step through the styles the family has, by weight with the +//! same slant and width (#1831), not by 100 to a canonical name no face provides. + +use figcraft_doc::{NodeId, TextStyle}; +use serde_json::json; + +use crate::Session; +use crate::cmd::text::next_style; + +fn styles(names: &[&str]) -> Vec { + names.iter().map(|s| (*s).to_string()).collect() +} + +fn at(style: &str) -> TextStyle { + let mut st = TextStyle::default(); + st.set_font_style(style); + st +} + +/// Walk `from` heavier (`up`) or lighter until the family has nothing further. +fn walk(family: &[String], from: &str, up: bool) -> Vec { + let mut st = at(from); + let mut out = Vec::new(); + while let Some(next) = next_style(family, &st, up) { + st.set_font_style(next.clone()); + out.push(next); + } + out +} + +#[test] +fn the_steps_follow_the_family_with_the_same_slant_and_width() { + let arial = styles(&["Narrow", "Regular", "Italic", "Narrow Italic", "Bold", "Narrow Bold", "Bold Italic", "Narrow Bold Italic", "Black"]); + assert_eq!(walk(&arial, "Regular", true), ["Bold", "Black"]); + assert_eq!(walk(&arial, "Black", false), ["Bold", "Regular"]); + assert_eq!(walk(&arial, "Italic", true), ["Bold Italic"]); + assert_eq!(walk(&arial, "Narrow", true), ["Narrow Bold"]); + assert_eq!(walk(&arial, "Narrow Bold Italic", false), ["Narrow Italic"]); + let segoe = styles(&["Light", "Semilight", "Regular", "Italic", "Semibold", "Bold", "Black", "Bold Italic"]); + assert_eq!(walk(&segoe, "Regular", true), ["Semibold", "Bold", "Black"]); + assert_eq!(walk(&segoe, "Regular", false), ["Light"]); + // A style the family doesn't have (as the old steps stored) moves to the next real one. + assert_eq!(next_style(&segoe, &at("Medium"), true).as_deref(), Some("Semibold")); +} + +#[test] +fn a_custom_weight_axis_value_steps_from_where_it_is() { + let family = styles(&["Light", "Regular", "Medium", "Bold"]); + let mut st = at("Regular"); + st.variations.insert("wght".into(), 550.0); + assert_eq!(next_style(&family, &st, true).as_deref(), Some("Bold")); + assert_eq!(next_style(&family, &st, false).as_deref(), Some("Medium")); +} + +fn font_style(s: &Session, t: NodeId) -> String { + s.doc().unwrap().node(t).unwrap().kind.text().unwrap().spans()[0].2.font_style.clone() +} + +#[test] +fn the_commands_land_on_styles_the_family_has() { + figcraft_text::scan_system_fonts(); + // Any installed family with a regular face and a heavier upright one (CI machines differ). + let upright = |x: &String| !x.to_lowercase().contains("italic") && !x.to_lowercase().contains("oblique"); + let pick = figcraft_text::family_names().into_iter().find_map(|f| { + let st = figcraft_text::family_styles(&f); + (st.iter().any(|x| x == "Regular") && st.iter().any(|x| upright(x) && figcraft_doc::style_weight(x) > 400)).then_some((f, st)) + }); + let Some((family, styles)) = pick else { return }; + let mut s = Session::new(); + let r = s.execute("node.create", &json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": "Regular"}})).unwrap(); + let t = crate::params::id_of(&r["id"]).unwrap(); + s.execute("text.weightUp", &json!({"ids": [t]})).unwrap(); + let up = font_style(&s, t); + assert!(styles.contains(&up) && figcraft_doc::style_weight(&up) > 400, "{family}: {up} of {styles:?}"); + s.execute("text.weightDown", &json!({"ids": [t]})).unwrap(); + assert_eq!(font_style(&s, t), "Regular", "{family}: {styles:?}"); + // A family that isn't installed still steps by 100 under the canonical names. + s.execute("node.set", &json!({"ids": [t], "props": {"fontFamily": "No Such Family 7f3a", "fontStyle": "Regular"}})).unwrap(); + s.execute("text.weightUp", &json!({"ids": [t]})).unwrap(); + assert_eq!(font_style(&s, t), "Medium"); +} From dc82e6cac9b3ab2055dd294fa015fb9072d8f26e Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:49:00 +0100 Subject: [PATCH 123/326] M4: weight steps follow the family's order and keep widths and oblique slants (#1831) Review follow-up. The step now finds the chars' style in the family's list (the style menu's order, lightest first) and takes its neighbour, so a style whose name gives no distinct weight (Semilight) is reachable; a style the family lacks or a custom wght value still goes by weight, ties going to the nearer one in that order. "Extra", "Ultra", "Semi" and "Demi" are weight words only before a weight ("Extra Bold"), so "Extra Condensed" keeps its width; Oblique names count as slanted for the current style too; W3-style names are weights; and style_weight reads Hairline as 100, not 400. The installed-font test picks a family the step actually moves. --- crates/doc/src/tests.rs | 1 + crates/doc/src/text.rs | 3 +- crates/engine/src/cmd/text.rs | 65 ++++++++++++++++----- crates/engine/src/text_weight_step_tests.rs | 40 +++++++++++-- 4 files changed, 86 insertions(+), 23 deletions(-) diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a0e3e17b0..0964f2e46 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -223,6 +223,7 @@ fn text_case() { assert_eq!(style_weight("Semi Bold Italic"), 600); assert_eq!(style_weight("Black"), 900); assert_eq!(style_weight("Regular"), 400); + assert_eq!(style_weight("Hairline"), 100); } #[test] diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 0c41d3c9a..a0850ec83 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -389,8 +389,9 @@ pub fn style_weight(style: &str) -> u16 { { return n; } - let table: [(&str, u16); 10] = [ + let table: [(&str, u16); 11] = [ ("thin", 100), + ("hairline", 100), ("extralight", 200), ("ultralight", 200), ("light", 300), diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index c2b9043c3..31008533a 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -122,14 +122,23 @@ fn toggle_italic(s: &mut Session, p: &Value) -> Result { }) } -/// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow"). +/// Hiragino's weight names: "W3" is 300. +fn w_number(word: &str) -> Option { + let n = word.strip_prefix('w')?.parse::().ok()?; + (1..=9).contains(&n).then_some(n * 100) +} + +/// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow", +/// "Extra Condensed Bold" → "extra condensed"). fn style_rest(style: &str) -> String { - const WORDS: [&str; 25] = [ + const WEIGHTS: [&str; 25] = [ "thin", "hairline", "extralight", "ultralight", "light", + "semilight", + "demilight", "regular", "normal", "roman", @@ -141,40 +150,64 @@ fn style_rest(style: &str) -> String { "extrabold", "ultrabold", "black", + "extrablack", + "ultrablack", "heavy", - "semi", - "demi", - "extra", - "ultra", "italic", "oblique", "plain", "standard", ]; + // Words that grade the weight word after them ("Extra Bold") but a width otherwise ("Extra Condensed"). + const GRADES: [&str; 4] = ["extra", "ultra", "semi", "demi"]; let s = style.to_ascii_lowercase().replace('-', " "); - let words = s.split_whitespace().filter(|w| !WORDS.contains(w) && !w.chars().all(|c| c.is_ascii_digit())); - words.collect::>().join(" ") + let words: Vec<&str> = s.split_whitespace().collect(); + let weight = |w: &str| WEIGHTS.contains(&w) || w_number(w).is_some() || w.chars().all(|c| c.is_ascii_digit()); + let rest = words.iter().enumerate().filter(|(i, w)| { + let graded = GRADES.contains(w) && words.get(i + 1).is_some_and(|next| weight(next) && !matches!(*next, "italic" | "oblique")); + !weight(w) && !graded + }); + rest.map(|(_, w)| *w).collect::>().join(" ") } +/// A style name that slants: italic, or oblique as some families name it. fn slanted(style: &str) -> bool { let s = style.to_ascii_lowercase(); s.contains("italic") || s.contains("oblique") } -/// The next heavier (`up`) or lighter style of `styles` (a family's) after the chars' style: the -/// nearest weight with the same slant and width, as the style menu lists them. None when the family -/// has nothing further that way. +/// The weight a style name says ("W3" too). +fn name_weight(style: &str) -> u16 { + w_number(&style.to_ascii_lowercase()).unwrap_or_else(|| figcraft_doc::style_weight(style)) +} + +/// The next heavier (`up`) or lighter style of `styles` (a family's, lightest first, as the style +/// menu lists them) after the chars' style, with the same slant and width. The chars' style is +/// found in the list by name and its neighbour taken; a style the family doesn't have, or a custom +/// weight axis value, goes to the nearest weight that way. None when the family has nothing further. pub(crate) fn next_style(styles: &[String], st: &TextStyle, up: bool) -> Option { - let (w, italic, rest) = (i32::from(st.weight()), st.italic(), style_rest(&st.font_style)); - styles - .iter() - .filter(|x| slanted(x) == italic && style_rest(x) == rest) - .map(|x| (i32::from(figcraft_doc::style_weight(x)) - w, x)) + let italic = st.italic() || slanted(&st.font_style); + let rest = style_rest(&st.font_style); + let mut same: Vec<&String> = styles.iter().filter(|x| slanted(x) == italic && style_rest(x) == rest).collect(); + let norm = |s: &str| s.to_lowercase().replace([' ', '-', '_'], ""); + let here = same.iter().position(|x| norm(x) == norm(&st.font_style)); + if let Some(i) = here.filter(|_| !st.variations.contains_key("wght")) { + let next = if up { i.checked_add(1) } else { i.checked_sub(1) }; + return next.and_then(|n| same.get(n)).map(|x| (*x).clone()); + } + let w = i32::from(st.weight()); + // Of equal weights, the one nearest in the family's order: the first going up, the last going down. + if !up { + same.reverse(); + } + same.into_iter() + .map(|x| (i32::from(name_weight(x)) - w, x)) .filter(|(d, _)| if up { *d > 0 } else { *d < 0 }) .min_by_key(|(d, _)| d.abs()) .map(|(_, x)| x.clone()) } +/// `text.weightUp` / `text.weightDown`: each targeted run moves to the next style of its family. fn step_weight(s: &mut Session, p: &Value, up: bool) -> Result { style(s, p, |st| { let styles = figcraft_text::family_styles(&st.font_family); diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index f3f7fa587..f3647d77d 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -38,11 +38,39 @@ fn the_steps_follow_the_family_with_the_same_slant_and_width() { assert_eq!(walk(&arial, "Narrow Bold Italic", false), ["Narrow Italic"]); let segoe = styles(&["Light", "Semilight", "Regular", "Italic", "Semibold", "Bold", "Black", "Bold Italic"]); assert_eq!(walk(&segoe, "Regular", true), ["Semibold", "Bold", "Black"]); - assert_eq!(walk(&segoe, "Regular", false), ["Light"]); + assert_eq!(walk(&segoe, "Regular", false), ["Semilight", "Light"]); // A style the family doesn't have (as the old steps stored) moves to the next real one. assert_eq!(next_style(&segoe, &at("Medium"), true).as_deref(), Some("Semibold")); } +#[test] +fn extra_and_semi_before_a_width_keep_the_width() { + let family = styles(&["Extra Condensed Regular", "Condensed Regular", "Condensed Bold", "Extra Condensed Bold", "Semi Condensed Extra Bold"]); + assert_eq!(walk(&family, "Extra Condensed Regular", true), ["Extra Condensed Bold"]); + assert_eq!(walk(&family, "Condensed Bold", false), ["Condensed Regular"]); + assert_eq!(walk(&family, "Semi Condensed Extra Bold", false), Vec::::new()); +} + +#[test] +fn oblique_names_step_to_oblique_faces() { + let dejavu = styles(&["Book", "Oblique", "Bold", "Bold Oblique"]); + assert_eq!(walk(&dejavu, "Oblique", true), ["Bold Oblique"]); + assert_eq!(walk(&dejavu, "Bold Oblique", false), ["Oblique"]); + assert_eq!(walk(&dejavu, "Book", true), ["Bold"]); +} + +#[test] +fn hairline_and_w_numbers_are_weights() { + let family = styles(&["Hairline", "Thin", "Regular", "Bold"]); + assert_eq!(walk(&family, "Regular", false), ["Thin", "Hairline"]); + // Off the list (a stored style the family lacks): by weight, the nearer of two equal ones. + assert_eq!(next_style(&family, &at("Extra Light"), false).as_deref(), Some("Thin")); + assert_eq!(next_style(&family, &at("Extra Light"), true).as_deref(), Some("Regular")); + let hiragino = styles(&["W3", "W6"]); + assert_eq!(walk(&hiragino, "W3", true), ["W6"]); + assert_eq!(next_style(&hiragino, &at("Bold"), false).as_deref(), Some("W6")); +} + #[test] fn a_custom_weight_axis_value_steps_from_where_it_is() { let family = styles(&["Light", "Regular", "Medium", "Bold"]); @@ -59,19 +87,19 @@ fn font_style(s: &Session, t: NodeId) -> String { #[test] fn the_commands_land_on_styles_the_family_has() { figcraft_text::scan_system_fonts(); - // Any installed family with a regular face and a heavier upright one (CI machines differ). - let upright = |x: &String| !x.to_lowercase().contains("italic") && !x.to_lowercase().contains("oblique"); + // Any installed family with a Regular face and a style the step takes it to (CI machines differ). let pick = figcraft_text::family_names().into_iter().find_map(|f| { let st = figcraft_text::family_styles(&f); - (st.iter().any(|x| x == "Regular") && st.iter().any(|x| upright(x) && figcraft_doc::style_weight(x) > 400)).then_some((f, st)) + let up = next_style(&st, &at("Regular"), true).filter(|_| st.iter().any(|x| x == "Regular"))?; + Some((f, st, up)) }); - let Some((family, styles)) = pick else { return }; + let Some((family, styles, heavier)) = pick else { return }; let mut s = Session::new(); let r = s.execute("node.create", &json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": "Regular"}})).unwrap(); let t = crate::params::id_of(&r["id"]).unwrap(); s.execute("text.weightUp", &json!({"ids": [t]})).unwrap(); let up = font_style(&s, t); - assert!(styles.contains(&up) && figcraft_doc::style_weight(&up) > 400, "{family}: {up} of {styles:?}"); + assert_eq!(up, heavier, "{family}: {styles:?}"); s.execute("text.weightDown", &json!({"ids": [t]})).unwrap(); assert_eq!(font_style(&s, t), "Regular", "{family}: {styles:?}"); // A family that isn't installed still steps by 100 under the canonical names. From 02c38a6d959f0afd82e44d9d67d396266e6ab4a3 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 2 Nov 2026 19:26:05 -0500 Subject: [PATCH 124/326] Release 0.15.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 44 ++++++++++++++++++++++---------------------- Cargo.toml | 2 +- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 888365316..b9fb98654 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1763,7 +1763,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" [[package]] name = "figcraft" -version = "0.14.0" +version = "0.15.0" dependencies = [ "arboard", "craft-menu", @@ -1795,7 +1795,7 @@ dependencies = [ [[package]] name = "figcraft-cli" -version = "0.14.0" +version = "0.15.0" dependencies = [ "clap", "clap_complete", @@ -1813,7 +1813,7 @@ dependencies = [ [[package]] name = "figcraft-collab" -version = "0.14.0" +version = "0.15.0" dependencies = [ "base64 0.22.1", "chrono", @@ -1831,7 +1831,7 @@ dependencies = [ [[package]] name = "figcraft-collab-net" -version = "0.14.0" +version = "0.15.0" dependencies = [ "base64 0.22.1", "figcraft-collab", @@ -1854,7 +1854,7 @@ dependencies = [ [[package]] name = "figcraft-color" -version = "0.14.0" +version = "0.15.0" dependencies = [ "kurbo", "serde", @@ -1863,7 +1863,7 @@ dependencies = [ [[package]] name = "figcraft-doc" -version = "0.14.0" +version = "0.15.0" dependencies = [ "figcraft-color", "figcraft-geom", @@ -1876,7 +1876,7 @@ dependencies = [ [[package]] name = "figcraft-engine" -version = "0.14.0" +version = "0.15.0" dependencies = [ "base64 0.22.1", "craft-docpath", @@ -1910,7 +1910,7 @@ dependencies = [ [[package]] name = "figcraft-format" -version = "0.14.0" +version = "0.15.0" dependencies = [ "figcraft-doc", "figcraft-layout", @@ -1927,7 +1927,7 @@ dependencies = [ [[package]] name = "figcraft-geom" -version = "0.14.0" +version = "0.15.0" dependencies = [ "kurbo", "serde", @@ -1935,7 +1935,7 @@ dependencies = [ [[package]] name = "figcraft-layout" -version = "0.14.0" +version = "0.15.0" dependencies = [ "figcraft-doc", "figcraft-geom", @@ -1943,7 +1943,7 @@ dependencies = [ [[package]] name = "figcraft-mcp" -version = "0.14.0" +version = "0.15.0" dependencies = [ "base64 0.22.1", "figcraft-collab-net", @@ -1959,7 +1959,7 @@ dependencies = [ [[package]] name = "figcraft-pathops" -version = "0.14.0" +version = "0.15.0" dependencies = [ "figcraft-doc", "figcraft-geom", @@ -1968,7 +1968,7 @@ dependencies = [ [[package]] name = "figcraft-pdf" -version = "0.14.0" +version = "0.15.0" dependencies = [ "figcraft-color", "figcraft-doc", @@ -1985,7 +1985,7 @@ dependencies = [ [[package]] name = "figcraft-plugin" -version = "0.14.0" +version = "0.15.0" dependencies = [ "figcraft-color", "serde", @@ -1998,7 +1998,7 @@ dependencies = [ [[package]] name = "figcraft-render" -version = "0.14.0" +version = "0.15.0" dependencies = [ "crc32fast", "figcraft-color", @@ -2017,7 +2017,7 @@ dependencies = [ [[package]] name = "figcraft-server" -version = "0.14.0" +version = "0.15.0" dependencies = [ "chrono", "crc32fast", @@ -2042,7 +2042,7 @@ dependencies = [ [[package]] name = "figcraft-svg" -version = "0.14.0" +version = "0.15.0" dependencies = [ "base64 0.22.1", "figcraft-color", @@ -2058,7 +2058,7 @@ dependencies = [ [[package]] name = "figcraft-text" -version = "0.14.0" +version = "0.15.0" dependencies = [ "core-text", "craft-font-catalog", @@ -2076,7 +2076,7 @@ dependencies = [ [[package]] name = "figcraft-ui-egui" -version = "0.14.0" +version = "0.15.0" dependencies = [ "base64 0.22.1", "chrono", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "figcraft-vectordrawable" -version = "0.14.0" +version = "0.15.0" dependencies = [ "figcraft-color", "figcraft-doc", @@ -2118,7 +2118,7 @@ dependencies = [ [[package]] name = "figcraft-web" -version = "0.14.0" +version = "0.15.0" dependencies = [ "base64 0.22.1", "eframe", @@ -6739,7 +6739,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.14.0" +version = "0.15.0" dependencies = [ "figcraft-engine", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index c7a86dd21..c9b915a69 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ exclude = ["plugins"] # default-members = ["crates/*", "apps/figcraft", "apps/figcraft-cli", "xtask"] [workspace.package] -version = "0.14.0" +version = "0.15.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 41ec33eeec0b1f102453adc62d7729ea2064144d Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:15:23 +0100 Subject: [PATCH 125/326] Reject negative and fractional indexes in node.reorder Found while testing crates/engine/src/cmd/edit.rs:329 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/al_nesting_tests.rs | 13 +++++++++++++ crates/engine/src/cmd/edit.rs | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/al_nesting_tests.rs b/crates/engine/src/al_nesting_tests.rs index f5d607ecf..f3ab62a06 100644 --- a/crates/engine/src/al_nesting_tests.rs +++ b/crates/engine/src/al_nesting_tests.rs @@ -345,3 +345,16 @@ fn remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(laid_out(&s), [true, true, true]); } + +#[test] +fn reorder_rejects_negative_and_fractional_indexes() { + let mut s = Session::new(); + let f = frame(&mut s, None, 0.0, 0.0, 200.0, 200.0); + let a = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0); + let c = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0); + for bad in [json!(-1), json!(0.5), json!("x")] { + assert!(s.execute("node.reorder", &json!({"id": c, "index": bad})).is_err(), "{bad} accepted"); + assert_eq!(kids(&s, f), vec![a, b, c]); + } +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 700fa7414..2aaa696b3 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -326,7 +326,7 @@ pub fn specs() -> Vec { ), spec!("node.reorder", "Reorder layer", "{id, index}", true, |s, p| { let i = req_id("node.reorder", p, "id")?; - let idx = req_num("node.reorder", p, "index")?.max(0.0) as usize; + let idx = req_index("node.reorder", p, "index")?; s.doc_mut()?.reorder(i, idx)?; ok() }), From 19afdd21f9f63e2a66a5c9cd8ea9f7f712b9b66d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:44:37 -0500 Subject: [PATCH 126/326] fix(format): import a .fig blob once however many hashes name it Distinct image hashes pointing at one embedded blob shared its copy, but the import resolved each hash separately: the blob was copied out and hashed again for every alias. Aliases without an images/ member of their own are now renamed to the first hash naming the blob before layers are built, so the blob is copied and hashed once. Image paints also spelled out their whole hash as hex for every layer, whatever its length; hashes longer than any image can be named by (64 bytes) now resolve to nothing, as a missing hash does. --- crates/format/src/fig.rs | 62 ++++++++++++++++++- .../format/src/fig/map/image_filter_tests.rs | 12 +++- crates/format/src/fig/map/paint.rs | 13 +++- crates/format/src/fig/tests.rs | 38 ++++++++++++ 4 files changed, 119 insertions(+), 6 deletions(-) diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index 55a5d7c34..2a8b542e9 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -72,6 +72,9 @@ use kiwi::{Kv, Schema}; /// Largest `canvas.fig` member read, and largest decompressed chunk. const MAX_CANVAS: u64 = 256 * 1024 * 1024; const MAX_CHUNK: u64 = 512 * 1024 * 1024; +/// Longest image hash (bytes) an image is found by: `images/` names and embedded images both +/// stop at 64 bytes (128 hex digits). +pub(crate) const MAX_IMAGE_HASH: usize = 64; /// Largest image member read. const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES; /// Total decompressed ZIP image bytes read per import: the native image budget (`IMAGE_BUDGET`) on @@ -138,10 +141,14 @@ 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 (json, mut warnings, networks) = map::to_rest(&msg, file_name, max_nodes); + let (mut json, mut warnings, networks) = map::to_rest(&msg, file_name, max_nodes); // The message goes before the layers are built, so the images it carries are copied out first. let embedded = embedded_copies(&msg); drop(msg); + let aliases = embedded_aliases(&embedded, |hash| archive.has_image(hash)); + if !aliases.is_empty() { + canonical_image_refs(&mut json, &aliases); + } let images = |r: &str| archive.image(r).or_else(|| embedded.get(r).map(|b| b.to_vec())); let (mut doc, more) = crate::rest::import_with_networks(&json, &images, networks, max_nodes)?; let skipped = archive.image_budget.skipped.get(); @@ -224,9 +231,53 @@ fn embedded_copies(msg: &Kv) -> BTreeMap> { out } +/// Embedded images ([`embedded_copies`]) whose blob an earlier hash already names, each with that +/// hash. Hashes that also have an `images/` member keep their own name: the member is read first. +/// Pointing every alias at one name has the import copy and hash each blob once, however many +/// hashes a file points at it. +fn embedded_aliases(embedded: &BTreeMap>, in_zip: impl Fn(&str) -> bool) -> BTreeMap { + let mut first: BTreeMap = BTreeMap::new(); + let mut out = BTreeMap::new(); + for (hash, bytes) in embedded { + if in_zip(hash) { + continue; + } + // Hashes naming one blob share its copy, so the copy's address tells the blob. + let canonical = *first.entry(bytes.as_ptr() as usize).or_insert(hash); + if canonical != hash { + out.insert(hash.clone(), canonical.clone()); + } + } + out +} + +/// Rename every `imageRef` in REST `json` found in `aliases` to the name it maps to. +fn canonical_image_refs(json: &mut serde_json::Value, aliases: &BTreeMap) { + use serde_json::Value; + let mut pending = vec![json]; + while let Some(value) = pending.pop() { + match value { + Value::Object(fields) => { + for (key, field) in fields.iter_mut() { + match field { + Value::String(r) if key == "imageRef" => { + if let Some(canonical) = aliases.get(r.as_str()) { + r.clone_from(canonical); + } + } + _ => pending.push(field), + } + } + } + Value::Array(items) => pending.extend(items.iter_mut()), + _ => {} + } + } +} + /// The hash and blob index of an `Image` value whose `dataBlob` points at a usable blob. fn embedded_image(image: &Kv, blobs: &[Kv]) -> Option<(String, usize)> { - let hash = image.get("hash").and_then(Kv::bytes).filter(|h| !h.is_empty() && h.len() <= 64)?; + let hash = image.get("hash").and_then(Kv::bytes).filter(|h| !h.is_empty() && h.len() <= MAX_IMAGE_HASH)?; let Some(Kv::Uint(index)) = image.get("dataBlob") else { return None }; let index = usize::try_from(*index).ok()?; let bytes = blob(blobs, index)?; @@ -272,10 +323,15 @@ impl<'b> Archive<'b> { Ok(Archive { canvas, file_name, zip: Some(z), image_budget }) } + /// Whether `images/` has a member for image `hash`. + fn has_image(&self, hash: &str) -> bool { + self.zip.as_ref().is_some_and(|z| z.index_for_name(&format!("images/{hash}")).is_some()) + } + /// Bytes of image `hash` (lowercase hex) from `images/`. fn image(&self, hash: &str) -> Option> { let budget = &self.image_budget; - if hash.is_empty() || hash.len() > 128 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) { + if hash.is_empty() || hash.len() > 2 * MAX_IMAGE_HASH || !hash.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } // A clone shares the parsed directory and the bytes; the resolver only has shared access. diff --git a/crates/format/src/fig/map/image_filter_tests.rs b/crates/format/src/fig/map/image_filter_tests.rs index a8db39a77..e13a56e32 100644 --- a/crates/format/src/fig/map/image_filter_tests.rs +++ b/crates/format/src/fig/map/image_filter_tests.rs @@ -1,4 +1,5 @@ -//! Malformed image paint filters are skipped with a warning. +//! Malformed image paint filters are skipped with a warning, and image hashes too long to name +//! an image aren't spelled out. use super::*; @@ -25,3 +26,12 @@ fn boolean_filter_values_are_malformed_even_when_false() { assert!(warnings.iter().any(|warning| warning.contains(expected_warning)), "{warnings:?}"); } } + +#[test] +fn an_oversized_image_hash_is_not_spelled_out() { + let paint = |len: usize| Kv::Object(vec![("type", Kv::Enum("IMAGE")), ("image", Kv::Object(vec![("hash", Kv::Bytes(vec![0xab; len]))]))]); + let image_ref = |len: usize| super::paint(&paint(len), &mut |_| {}).and_then(|p| p.get("imageRef").cloned()); + assert_eq!(image_ref(20), Some(Value::String("ab".repeat(20)))); + assert_eq!(image_ref(crate::fig::MAX_IMAGE_HASH), Some(Value::String("ab".repeat(crate::fig::MAX_IMAGE_HASH)))); + assert_eq!(image_ref(crate::fig::MAX_IMAGE_HASH + 1), Some(Value::String(String::new()))); +} diff --git a/crates/format/src/fig/map/paint.rs b/crates/format/src/fig/map/paint.rs index 5b7121757..cf96c2bf0 100644 --- a/crates/format/src/fig/map/paint.rs +++ b/crates/format/src/fig/map/paint.rs @@ -162,8 +162,17 @@ pub(crate) fn paint(p: &Kv, warn: &mut dyn FnMut(String)) -> Option { o.insert("gradientStops".into(), Value::Array(stops)); } "IMAGE" => { - let hash: String = - p.get("image").and_then(|i| i.get("hash")).and_then(Kv::bytes).unwrap_or_default().iter().map(|b| format!("{b:02x}")).collect(); + // A hash longer than any the file's images can be named by resolves to nothing: it + // isn't spelled out, which a shared style would repeat for every layer using it. + let hash: String = p + .get("image") + .and_then(|i| i.get("hash")) + .and_then(Kv::bytes) + .filter(|h| h.len() <= crate::fig::MAX_IMAGE_HASH) + .unwrap_or_default() + .iter() + .map(|b| format!("{b:02x}")) + .collect(); o.insert("imageRef".into(), json!(hash)); let mode = p.get("imageScaleMode").and_then(Kv::str).unwrap_or("FILL"); o.insert("scaleMode".into(), json!(mode)); diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index 657f2f81d..2afae4361 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -795,6 +795,44 @@ fn hashes_naming_one_blob_share_one_copy_of_it() { assert_eq!(*copies[&"63".repeat(20)], [7; 16]); } +/// Hashes naming one blob are imported as one image: every alias is renamed to the first hash +/// before layers are built, so the blob is copied and hashed once, not once per hash. +#[test] +fn hashes_naming_one_blob_are_imported_once() { + let rect = |i: u64, hash: u8, blob: u64| { + let paint = o(vec![("type", e("IMAGE")), ("image", o(vec![("hash", Kv::Bytes(vec![hash; 20])), ("dataBlob", u(blob))]))]); + node(i, Some((1, &format!("{i:04}"))), "RECTANGLE", &format!("R{i}"), vec![("size", xy(10.0, 10.0)), ("fillPaints", arr(vec![paint]))]) + }; + let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])]; + nodes.extend((2..42).map(|i| rect(i, i as u8, 0))); + let msg = o(vec![("nodeChanges", arr(nodes)), ("blobs", arr(vec![o(vec![("bytes", Kv::Bytes(png()))])]))]); + let copies = embedded_copies(&msg); + let aliases = embedded_aliases(&copies, |_| false); + assert_eq!(aliases.len(), 39); + assert!(aliases.values().all(|c| *c == "02".repeat(20))); + // A hash `images/` also holds keeps its own name. + assert!(!embedded_aliases(&copies, |h| h == "05".repeat(20)).contains_key(&"05".repeat(20))); + let (doc, warnings) = import(&canvas(&schema(), &msg), "x").unwrap(); + assert!(!warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}"); + assert_eq!(doc.images.len(), 1); + let key = doc.images.keys().next().unwrap(); + for i in 2..42 { + let figcraft_doc::color::PaintKind::Image(img) = &named(&doc, &format!("R{i}")).fills[0].kind else { panic!("not an image fill") }; + assert_eq!(&img.image, key); + } +} + +#[test] +fn image_refs_are_renamed_wherever_they_sit() { + let aliases: BTreeMap = [("b".to_string(), "a".to_string())].into(); + let mut json = serde_json::json!({"fills": [{"imageRef": "b"}, {"imageRef": "c"}], "styles": {"s": {"fills": [{"imageRef": "b"}]}}, "name": "b"}); + canonical_image_refs(&mut json, &aliases); + assert_eq!( + json, + serde_json::json!({"fills": [{"imageRef": "a"}, {"imageRef": "c"}], "styles": {"s": {"fills": [{"imageRef": "a"}]}}, "name": "b"}) + ); +} + mod image_budget { use super::*; From 2c9226c0215acf23772cd6c062790019fe9629d7 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 03:44:58 +0100 Subject: [PATCH 127/326] M4: weight steps from an off-list weight compare the faces' own weights (#1831) next_style compared a custom wght value or a style the family lacks with the weights the style names say, so Segoe UI Variable's Semilight (350) counted as 300 and a wght of 325 stepped up to Regular. The family's styles now come with the weights the style menu sorts them by (figcraft_text::family_style_weights), and "W7 Italic" reads as 700. --- crates/engine/src/cmd/text.rs | 33 +++++++++------- crates/engine/src/text_weight_step_tests.rs | 43 ++++++++++++++++++--- crates/text/src/fontdb.rs | 13 ++++++- crates/text/src/lib.rs | 4 +- 4 files changed, 69 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 31008533a..a25d19733 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -176,32 +176,35 @@ fn slanted(style: &str) -> bool { s.contains("italic") || s.contains("oblique") } -/// The weight a style name says ("W3" too). -fn name_weight(style: &str) -> u16 { - w_number(&style.to_ascii_lowercase()).unwrap_or_else(|| figcraft_doc::style_weight(style)) +/// The weight a style name says ("W3" and "W6 Italic" too). +pub(crate) fn name_weight(style: &str) -> u16 { + let first = style.to_ascii_lowercase().replace('-', " "); + first.split_whitespace().next().and_then(w_number).unwrap_or_else(|| figcraft_doc::style_weight(style)) } -/// The next heavier (`up`) or lighter style of `styles` (a family's, lightest first, as the style -/// menu lists them) after the chars' style, with the same slant and width. The chars' style is -/// found in the list by name and its neighbour taken; a style the family doesn't have, or a custom -/// weight axis value, goes to the nearest weight that way. None when the family has nothing further. -pub(crate) fn next_style(styles: &[String], st: &TextStyle, up: bool) -> Option { +/// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed +/// by, lightest first, as the style menu lists them) after the chars' style, with the same slant +/// and width. The chars' style is found in the list by name and its neighbour taken; a style the +/// family doesn't have, or a custom weight axis value, goes to the listed style of nearest weight +/// that way. None when the family has nothing further. +pub(crate) fn next_style(styles: &[(String, u16)], st: &TextStyle, up: bool) -> Option { let italic = st.italic() || slanted(&st.font_style); let rest = style_rest(&st.font_style); - let mut same: Vec<&String> = styles.iter().filter(|x| slanted(x) == italic && style_rest(x) == rest).collect(); + let mut same: Vec<&(String, u16)> = styles.iter().filter(|(x, _)| slanted(x) == italic && style_rest(x) == rest).collect(); let norm = |s: &str| s.to_lowercase().replace([' ', '-', '_'], ""); - let here = same.iter().position(|x| norm(x) == norm(&st.font_style)); - if let Some(i) = here.filter(|_| !st.variations.contains_key("wght")) { + let here = same.iter().position(|(x, _)| norm(x) == norm(&st.font_style)); + let axis = st.variations.contains_key("wght"); + if let Some(i) = here.filter(|_| !axis) { let next = if up { i.checked_add(1) } else { i.checked_sub(1) }; - return next.and_then(|n| same.get(n)).map(|x| (*x).clone()); + return next.and_then(|n| same.get(n)).map(|(x, _)| x.clone()); } - let w = i32::from(st.weight()); + let w = i32::from(if axis { st.weight() } else { name_weight(&st.font_style) }); // Of equal weights, the one nearest in the family's order: the first going up, the last going down. if !up { same.reverse(); } same.into_iter() - .map(|x| (i32::from(name_weight(x)) - w, x)) + .map(|(x, xw)| (i32::from(*xw) - w, x)) .filter(|(d, _)| if up { *d > 0 } else { *d < 0 }) .min_by_key(|(d, _)| d.abs()) .map(|(_, x)| x.clone()) @@ -210,7 +213,7 @@ pub(crate) fn next_style(styles: &[String], st: &TextStyle, up: bool) -> Option< /// `text.weightUp` / `text.weightDown`: each targeted run moves to the next style of its family. fn step_weight(s: &mut Session, p: &Value, up: bool) -> Result { style(s, p, |st| { - let styles = figcraft_text::family_styles(&st.font_family); + let styles = figcraft_text::family_style_weights(&st.font_family); if styles.is_empty() { // A family that isn't installed: step the weight by 100 under its canonical name. let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16; diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index f3647d77d..96562bf7e 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -5,10 +5,16 @@ use figcraft_doc::{NodeId, TextStyle}; use serde_json::json; use crate::Session; -use crate::cmd::text::next_style; +use crate::cmd::text::{name_weight, next_style}; -fn styles(names: &[&str]) -> Vec { - names.iter().map(|s| (*s).to_string()).collect() +/// A family's styles listed by the weights their names say, as for faces not read yet. +fn styles(names: &[&str]) -> Vec<(String, u16)> { + names.iter().map(|s| ((*s).to_string(), name_weight(s))).collect() +} + +/// A family's styles with the faces' own weights. +fn weighed(faces: &[(&str, u16)]) -> Vec<(String, u16)> { + faces.iter().map(|(s, w)| ((*s).to_string(), *w)).collect() } fn at(style: &str) -> TextStyle { @@ -18,7 +24,7 @@ fn at(style: &str) -> TextStyle { } /// Walk `from` heavier (`up`) or lighter until the family has nothing further. -fn walk(family: &[String], from: &str, up: bool) -> Vec { +fn walk(family: &[(String, u16)], from: &str, up: bool) -> Vec { let mut st = at(from); let mut out = Vec::new(); while let Some(next) = next_style(family, &st, up) { @@ -80,6 +86,31 @@ fn a_custom_weight_axis_value_steps_from_where_it_is() { assert_eq!(next_style(&family, &st, false).as_deref(), Some("Medium")); } +#[test] +fn off_the_list_the_faces_own_weights_decide() { + // From 500 between 400 and 700 faces: the neighbours, under their own names (the axis value goes). + let family = weighed(&[("Light", 300), ("Regular", 400), ("Bold", 700)]); + let mut st = at("Regular"); + st.variations.insert("wght".into(), 500.0); + assert_eq!(next_style(&family, &st, true).as_deref(), Some("Bold")); + assert_eq!(next_style(&family, &st, false).as_deref(), Some("Regular")); + st.set_font_style("Bold"); + assert_eq!((st.weight(), st.variations.get("wght")), (700, None)); + // Segoe UI Variable's Semilight is 350, not the 300 its name says: from a `wght` of 325 it is + // the next heavier style, and from 375 the next lighter. + let segoe = weighed(&[("Light", 300), ("Semilight", 350), ("Regular", 400), ("Semibold", 600), ("Bold", 700)]); + st.variations.insert("wght".into(), 325.0); + assert_eq!(next_style(&segoe, &st, true).as_deref(), Some("Semilight")); + assert_eq!(next_style(&segoe, &st, false).as_deref(), Some("Light")); + st.variations.insert("wght".into(), 375.0); + assert_eq!(next_style(&segoe, &st, false).as_deref(), Some("Semilight")); + assert_eq!(next_style(&segoe, &st, true).as_deref(), Some("Regular")); + // A W-numbered name with a slant after it is still that weight ("W7 Italic" is 700). + let hiragino = weighed(&[("W3 Italic", 300), ("W6 Italic", 600), ("W8 Italic", 800)]); + assert_eq!(next_style(&hiragino, &at("W7 Italic"), false).as_deref(), Some("W6 Italic")); + assert_eq!(next_style(&hiragino, &at("W7 Italic"), true).as_deref(), Some("W8 Italic")); +} + fn font_style(s: &Session, t: NodeId) -> String { s.doc().unwrap().node(t).unwrap().kind.text().unwrap().spans()[0].2.font_style.clone() } @@ -89,8 +120,8 @@ fn the_commands_land_on_styles_the_family_has() { figcraft_text::scan_system_fonts(); // Any installed family with a Regular face and a style the step takes it to (CI machines differ). let pick = figcraft_text::family_names().into_iter().find_map(|f| { - let st = figcraft_text::family_styles(&f); - let up = next_style(&st, &at("Regular"), true).filter(|_| st.iter().any(|x| x == "Regular"))?; + let st = figcraft_text::family_style_weights(&f); + let up = next_style(&st, &at("Regular"), true).filter(|_| st.iter().any(|(x, _)| x == "Regular"))?; Some((f, st, up)) }); let Some((family, styles, heavier)) = pick else { return }; diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index d0004fcd9..c3c2f43a6 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -743,6 +743,12 @@ impl FontDb { /// Style names of a family, by weight then italic. pub fn styles(&mut self, family: &str) -> Vec { + self.style_weights(family).into_iter().map(|(name, _)| name).collect() + } + + /// [`styles`](Self::styles) with the weight each is listed by: the face's own (Segoe UI + /// Semilight is 350), a named instance's `wght`, or for a face not read yet its name's. + pub fn style_weights(&mut self, family: &str) -> Vec<(String, u16)> { self.load_family(family, None); let key = self.key(family); // (weight, italic, order in the font, name): named instances keep the font's order. @@ -768,7 +774,7 @@ impl FontDb { v.sort(); let mut seen = std::collections::HashSet::new(); v.retain(|x| seen.insert(norm_style(&x.3))); - v.into_iter().map(|x| x.3).collect() + v.into_iter().map(|x| (x.3, x.0)).collect() } /// The key `family` is known under: itself in any case; for a name designs use for Apple's @@ -1502,6 +1508,11 @@ pub fn family_styles(family: &str) -> Vec { db().write().unwrap_or_else(std::sync::PoisonError::into_inner).styles(family) } +/// [`family_styles`] with the weight each is listed by (see [`FontDb::style_weights`]). +pub fn family_style_weights(family: &str) -> Vec<(String, u16)> { + db().write().unwrap_or_else(std::sync::PoisonError::into_inner).style_weights(family) +} + /// Scan system fonts into the global db (desktop; a no-op on the web, or with /// `FIGCRAFT_NO_SYSTEM_FONTS` set). Runs once per process: a concurrent caller waits for that scan. /// The directory walk runs without holding the database lock; results are merged in one short write. diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index cad3e1326..b6d87d669 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -17,8 +17,8 @@ pub use breaks::{backspace_step, grapheme_step}; pub use color::{ColorBitmap, ColorInk, ColorLayer}; pub use fontdb::{ Axis, CRAFT_FONTS, Coords, Face, FontDb, LocalFont, NamedInstance, Rescan, add_local_fonts, axis_label, db, face_with_char, family_names, - family_styles, find_face, has_family, installed_fonts_known, load_font_bytes, load_local_font, local_only, no_coords, opt_out_of_system_fonts, - rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, take_wanted_local_fonts, + family_style_weights, family_styles, find_face, has_family, installed_fonts_known, load_font_bytes, load_local_font, local_only, no_coords, + opt_out_of_system_fonts, rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, take_wanted_local_fonts, }; pub use layout::{Decoration, Glyph, Line, TextLayout, layout}; pub use onpath::OnPath; From 45c89c5a737e493c9e2e3de12d0e40d02ee2edbc Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 04:38:16 +0100 Subject: [PATCH 128/326] M4: weight steps reach a weight family's italics and read W weights after a width (#1831) A family installed as one family per weight ("Foo Bold" with Regular and Italic faces) now lists Bold and Bold Italic, the names resolve draws them by, with the faces' own weights when they are read. A W-numbered weight counts after other words too ("Condensed W7 Italic" is 700). --- crates/engine/src/cmd/text.rs | 6 +-- crates/engine/src/text_weight_step_tests.rs | 4 ++ crates/text/src/fontdb.rs | 21 ++++++++-- crates/text/src/fontdb_names_tests.rs | 43 ++++++++++++++++++++- 4 files changed, 67 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index a25d19733..9024e1229 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -176,10 +176,10 @@ fn slanted(style: &str) -> bool { s.contains("italic") || s.contains("oblique") } -/// The weight a style name says ("W3" and "W6 Italic" too). +/// The weight a style name says ("W3", "W6 Italic" and "Condensed W7" too). pub(crate) fn name_weight(style: &str) -> u16 { - let first = style.to_ascii_lowercase().replace('-', " "); - first.split_whitespace().next().and_then(w_number).unwrap_or_else(|| figcraft_doc::style_weight(style)) + let words = style.to_ascii_lowercase().replace('-', " "); + words.split_whitespace().find_map(w_number).unwrap_or_else(|| figcraft_doc::style_weight(style)) } /// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index 96562bf7e..e8bf65a7b 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -109,6 +109,10 @@ fn off_the_list_the_faces_own_weights_decide() { let hiragino = weighed(&[("W3 Italic", 300), ("W6 Italic", 600), ("W8 Italic", 800)]); assert_eq!(next_style(&hiragino, &at("W7 Italic"), false).as_deref(), Some("W6 Italic")); assert_eq!(next_style(&hiragino, &at("W7 Italic"), true).as_deref(), Some("W8 Italic")); + // And after a width ("Condensed W7 Italic" is 700 too). + let condensed = weighed(&[("Condensed W3 Italic", 300), ("Condensed W6 Italic", 600), ("Condensed W8 Italic", 800)]); + assert_eq!(next_style(&condensed, &at("Condensed W7 Italic"), true).as_deref(), Some("Condensed W8 Italic")); + assert_eq!(next_style(&condensed, &at("Condensed W7 Italic"), false).as_deref(), Some("Condensed W6 Italic")); } fn font_style(s: &Session, t: NodeId) -> String { diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index c3c2f43a6..a856aa1fe 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -767,9 +767,24 @@ impl FontDb { v.push((w, f.italic || italic_name(&inst.name), k, inst.name.clone())); } } - // A family installed as one family per weight offers those weights too. - for (_, style) in self.split_families(&key) { - v.push((pending_weight(&style).clamp(1, 1000) as u16, italic_name(&style), 0, style)); + // A family installed as one family per weight offers those weights too, upright and italic + // as that family's faces are ("Foo Bold" with Regular and Italic faces: Bold and Bold + // Italic, the names `resolve` finds them by). A face read gives its own weight, one not + // read the name's; the families aren't read for this. + for (k, style) in self.split_families(&key) { + let named = pending_weight(&style).clamp(1, 1000) as u16; + let italic = italic_name(&style); + let read = self.families.get(&k).map(|(_, idx)| idx.as_slice()).unwrap_or_default().iter().filter_map(|i| self.faces.get(*i)); + let unread = self.pending.get(&k).into_iter().flat_map(|(_, entries)| entries).map(|e| (named, italic_name(&e.style))); + let faces: Vec<(u16, bool)> = read.map(|f| (f.weight, f.italic)).chain(unread).collect(); + if faces.is_empty() { + v.push((named, italic, 0, style)); + continue; + } + for (w, slanted) in faces { + let name = if slanted && !italic { format!("{style} Italic") } else { style.clone() }; + v.push((w, slanted || italic, 0, name)); + } } v.sort(); let mut seen = std::collections::HashSet::new(); diff --git a/crates/text/src/fontdb_names_tests.rs b/crates/text/src/fontdb_names_tests.rs index 0d31b7c56..62bd27be3 100644 --- a/crates/text/src/fontdb_names_tests.rs +++ b/crates/text/src/fontdb_names_tests.rs @@ -5,9 +5,10 @@ //! case; the picker lists what is installed. Synthetic family names only, over pending entries //! (no files) and the embedded faces when the build has them. +use std::collections::BTreeMap; use std::sync::Arc; -use super::{CRAFT_FONTS, Face, FontBytes, FontDb, Pending, style_words}; +use super::{CRAFT_FONTS, Face, FontBytes, FontDb, LocalFont, Pending, scan_dir, style_words, system_font_dirs}; fn entry(style: &str) -> Pending { Pending { path: format!("no-such-dir/{style}.ttf").into(), index: 0, style: style.into(), postscript: None, local: None } @@ -104,3 +105,43 @@ fn faces_are_found_and_listed_under_either_name() { assert!(Arc::ptr_eq(&db.find("Synthetic Text SemiBold", "Regular").unwrap(), &semibold)); assert!(Arc::ptr_eq(&db.find("synthetictext", "Semibold").unwrap(), &semibold)); } + +#[test] +fn a_family_per_weight_offers_its_italics_too() { + // Listed by name before anything is read: Synthetic Slab Bold's Italic face is Bold Italic. + let local = |id: usize, family: &str, style: &str| LocalFont { id, family: family.into(), style: style.into(), postscript: String::new() }; + let mut db = FontDb::default(); + db.add_local(vec![ + local(0, "Synthetic Slab", "Regular"), + local(1, "Synthetic Slab", "Italic"), + local(2, "Synthetic Slab Bold", "Regular"), + local(3, "Synthetic Slab Bold", "Italic"), + ]); + let listed = |db: &mut FontDb| db.style_weights("Synthetic Slab"); + let want = |v: &[(&str, u16)]| v.iter().map(|(s, w)| ((*s).to_string(), *w)).collect::>(); + assert_eq!(listed(&mut db), want(&[("Regular", 400), ("Italic", 400), ("Bold", 700), ("Bold Italic", 700)])); + assert_eq!(resolved(&db, "Synthetic Slab", "Bold Italic"), pair("synthetic slab bold", "Italic"), "the style drawn by that face"); + // Faces read give their own weights: Synthetic Slab Semi Light's are 350, not the name's 300. + let stand_in = CRAFT_FONTS.first().map(|f| f.bytes.to_vec()).or_else(|| { + let mut installed = BTreeMap::new(); + for dir in system_font_dirs() { + scan_dir(&dir, 0, &mut installed); + } + installed.values().flat_map(|(_, v)| v).find_map(|p| std::fs::read(&p.path).ok()) + }); + let Some(bytes) = stand_in.map(Arc::new) else { + eprintln!("skipping the read faces: no font to stand in"); + return; + }; + let face = |family: &str, style: &str, weight: u16, italic: bool| { + let mut f = Face::from_bytes(FontBytes::Shared(bytes.clone()), 0, Some(family), Some(style)).unwrap(); + f.instances.clear(); + (f.weight, f.italic) = (weight, italic); + f + }; + let mut db = FontDb::default(); + db.add(face("Synthetic Slab", "Regular", 400, false)); + db.add(face("Synthetic Slab Semi Light", "Regular", 350, false)); + db.add(face("Synthetic Slab Semi Light", "Italic", 350, true)); + assert_eq!(listed(&mut db), want(&[("Semi Light", 350), ("Semi Light Italic", 350), ("Regular", 400)])); +} From 8864068cd592f517d4dd4b0ce6c4270957d9d0c6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:21:45 +0000 Subject: [PATCH 129/326] fix(engine): compare online servers' paths with their case same_server lowercased the whole address, so files on /Team/ and /team/ (which a proxy can route to different servers) counted as one server and the online refresh sent both files' owner tokens to whichever answered. The scheme and host still compare without case; the path keeps its. --- crates/engine/src/online_tests.rs | 3 +++ crates/engine/src/sharing/online.rs | 13 ++++++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/online_tests.rs b/crates/engine/src/online_tests.rs index af13db8e7..c6feca29c 100644 --- a/crates/engine/src/online_tests.rs +++ b/crates/engine/src/online_tests.rs @@ -590,4 +590,7 @@ fn same_server_ignores_the_default_port_before_a_path() { assert!(same_server("wss://share.example:443/figcraft/", "wss://share.example/figcraft/")); assert!(same_server("ws://host:80/x", "ws://host/x")); assert!(!same_server("wss://share.example:8443/figcraft/", "wss://share.example/figcraft/")); + // The path is a route: owner tokens for /Team/ must never be sent to /team/. + assert!(same_server("WSS://Share.Example/team/", "wss://share.example/team")); + assert!(!same_server("wss://share.example/Team/", "wss://share.example/team/")); } diff --git a/crates/engine/src/sharing/online.rs b/crates/engine/src/sharing/online.rs index d68b20f82..89eb8a266 100644 --- a/crates/engine/src/sharing/online.rs +++ b/crates/engine/src/sharing/online.rs @@ -117,14 +117,17 @@ pub(crate) fn plain_server(server: &str) -> String { /// Two addresses name the same server (case, a closing slash and the scheme's own port aside). pub fn same_server(a: &str, b: &str) -> bool { let norm = |s: &str| { - let s = plain_server(s).to_ascii_lowercase(); + let s = plain_server(s); let s = s.trim_end_matches('/'); - let port = if s.starts_with("wss://") { ":443" } else { ":80" }; let start = s.find("://").map_or(0, |i| i + 3); let end = s[start..].find('/').map_or(s.len(), |i| start + i); - match s[start..end].strip_suffix(port) { - Some(host) => format!("{}{}{}", &s[..start], host, &s[end..]), - None => s.to_string(), + // The scheme and host compare without case; the path routes (a proxy may send + // `/Team/` and `/team/` to different servers), so it keeps its case. + let head = s[..end].to_ascii_lowercase(); + let port = if head.starts_with("wss://") { ":443" } else { ":80" }; + match head[start..].strip_suffix(port) { + Some(host) => format!("{}{}{}", &head[..start], host, &s[end..]), + None => format!("{head}{}", &s[end..]), } }; norm(a) == norm(b) From 4e7d8319f1c04428672e7c84e80d63b9eb11f966 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:22:15 +0000 Subject: [PATCH 130/326] fix(collab-net): hold a health check's header read to the handshake deadline The request line was read within the hello timeout, but the header loop after it only timed out per read, so a peer dripping header bytes kept the worker thread and its connection slot for as long as it liked. Each header read now gets what is left of the one deadline. --- crates/collab-net/src/hub/conn.rs | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/collab-net/src/hub/conn.rs b/crates/collab-net/src/hub/conn.rs index 1f365cbab..345f94117 100644 --- a/crates/collab-net/src/hub/conn.rs +++ b/crates/collab-net/src/hub/conn.rs @@ -51,6 +51,12 @@ fn health_check(stream: &mut TcpStream, until: Instant) -> bool { let mut req = Vec::new(); let mut chunk = [0u8; 1024]; while !req.windows(4).any(|w| w == b"\r\n\r\n") && req.len() < 16 << 10 { + // The same deadline as the request line: a peer dripping header bytes would otherwise + // hold this thread and its connection slot for as long as it liked. + let left = until.saturating_duration_since(Instant::now()); + if left.is_zero() || stream.set_read_timeout(Some(left)).is_err() { + break; + } match stream.read(&mut chunk) { Ok(0) | Err(_) => break, Ok(n) => req.extend_from_slice(chunk.get(..n).unwrap_or_default()), @@ -407,3 +413,31 @@ fn linger(ws: &mut WebSocket) { } } } + +#[cfg(test)] +mod health_check_tests { + use super::*; + + #[test] + fn a_health_check_dripping_headers_ends_at_the_deadline() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let client = std::thread::spawn(move || { + let mut c = TcpStream::connect(addr).unwrap(); + c.write_all(b"GET /healthz HTTP/1.1\r\n").unwrap(); + // One header byte every 20 ms, far past the deadline, until the server hangs up. + for _ in 0..200 { + if c.write_all(b"X").is_err() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + }); + let (mut stream, _) = listener.accept().unwrap(); + let start = Instant::now(); + assert!(health_check(&mut stream, start + Duration::from_millis(300))); + assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed()); + drop(stream); + client.join().unwrap(); + } +} From 970a3e6745d27f7a1fab9e27e82553a7545aef66 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:22:36 +0000 Subject: [PATCH 131/326] fix(engine): check the opened file, not the looked-up path, before reading it read_capped checked the path's metadata (type and size) and then opened the path again, so an entry swapped between the two steps was read without those checks. The opened handle's metadata is checked as well; the path check stays, so a pipe is still refused before it is opened. --- crates/engine/src/automation/file_access.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index b40a92f79..26f15700b 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -277,6 +277,14 @@ pub fn read_capped(path: impl AsRef, max: u64) -> Result> { return Err(refuse(format!("is {}, more than the {} allowed here", size(meta.len()), size(max)))); } let f = std::fs::File::open(p).map_err(io(path))?; + // What was opened, not what was looked at: the path could have been swapped in between. + let meta = f.metadata().map_err(io(path))?; + if !meta.is_file() { + return Err(refuse("isn't a regular file (a device or a pipe?), so it isn't read".into())); + } + if meta.len() > max { + return Err(refuse(format!("is {}, more than the {} allowed here", size(meta.len()), size(max)))); + } let mut bytes = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0)); f.take(max.saturating_add(1)).read_to_end(&mut bytes).map_err(io(path))?; // It grew after it was looked at. From 5bbab0fa181329d01973c489bc6fb01b4f863ab4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:23:05 +0000 Subject: [PATCH 132/326] fix(pdf): drop an oversized hyperlink before it is copied once per line Every linked line copied the destination string, and its length was only checked when the annotation was written, so one multi-megabyte link on text wrapping onto many lines was copied that many times first. The length is checked where the link areas are collected. --- crates/pdf/src/export_tests.rs | 17 +++++++++++++++++ crates/pdf/src/text.rs | 4 +++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/pdf/src/export_tests.rs b/crates/pdf/src/export_tests.rs index 259e58327..d41f11379 100644 --- a/crates/pdf/src/export_tests.rs +++ b/crates/pdf/src/export_tests.rs @@ -284,3 +284,20 @@ fn depth_samples() { std::fs::write(format!("{stem}-{name}.png"), figcraft_render::encode_png(&pix).unwrap()).unwrap(); } } + +#[test] +fn an_oversized_link_is_dropped_before_it_is_copied_per_line() { + // One link far past MAX_URL on text that wraps onto many lines: no annotation, and the + // destination is never copied once per line on the way to being refused. + let mut d = Document::new("long link"); + let p = d.first_page().unwrap_or(NodeId(0)); + let f = d.create(p, NodeKind::Frame, "F", 0.0, 0.0, 300.0, 4000.0).unwrap(); + let words = "word ".repeat(2_000); + let mut td = TextData::new(words.trim_end()); + td.style.font_size = 20.0; + td.style.link = Some("https://example.com/".to_string() + &"a".repeat(1 << 20)); + let t = d.create(f, NodeKind::Text(td), "T", 10.0, 10.0, 280.0, 3980.0).unwrap(); + d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::BLACK)]; + let pdf = export_pdf(&d, &[f], &PdfOptions::default()).unwrap(); + assert_eq!(text(&pdf).matches("/Subtype/Link").count(), 0); +} diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs index abbb65b34..3b3917689 100644 --- a/crates/pdf/src/text.rs +++ b/crates/pdf/src/text.rs @@ -111,7 +111,9 @@ fn record_links(ex: &mut Exporter, layout: &TextLayout, gxf: Affine) { let glyphs = layout.glyphs.get(line.glyph_start..line.glyph_end).unwrap_or(&[]); for g in glyphs.iter().map(Some).chain([None]) { let link = g.and_then(|g| { - let url = layout.styles.get(g.style)?.link.as_deref().filter(|u| !u.trim().is_empty())?; + // Checked here, not when the annotation is written: every linked line copies + // the destination, so one oversized link must not be copied at all. + let url = layout.styles.get(g.style)?.link.as_deref().map(str::trim).filter(|u| !u.is_empty() && u.len() <= crate::MAX_URL)?; let (a, b) = (g.x, g.x + g.advance); (a.is_finite() && b.is_finite()).then(|| (url, a.min(b), a.max(b))) }); From a9e66d2de9cc628a09f98898b69ec8a5bb2404fc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:24:32 +0000 Subject: [PATCH 133/326] perf(vectordrawable): keep warning names in a set Each affected layer name was checked against every name already kept for the warning, quadratic in the number of distinct names although only three are ever shown. A set holds the distinct names; the first three stay in order. --- crates/vectordrawable/src/warnings.rs | 38 ++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/vectordrawable/src/warnings.rs b/crates/vectordrawable/src/warnings.rs index 445198d5b..6f7f152ef 100644 --- a/crates/vectordrawable/src/warnings.rs +++ b/crates/vectordrawable/src/warnings.rs @@ -63,27 +63,53 @@ const NAMED: usize = 3; #[derive(Default)] pub(crate) struct Warnings { - seen: std::collections::BTreeMap>, + /// Per warning: the distinct names so far (a set, so a document with many distinct names + /// doesn't make each check a scan of all before it), and the first few in order. + seen: std::collections::BTreeMap, Vec)>, } impl Warnings { pub fn add(&mut self, w: Warn, layer: &str) { - let names = self.seen.entry(w).or_default(); - if !names.iter().any(|n| n == layer) { - names.push(layer.to_string()); + let (distinct, first) = self.seen.entry(w).or_default(); + if distinct.insert(layer.to_string()) && first.len() < NAMED { + first.push(layer.to_string()); } } pub fn finish(self) -> Vec { self.seen .into_iter() - .map(|(w, names)| { + .map(|(w, (distinct, names))| { let shown: Vec = names.iter().take(NAMED).map(|n| if n.is_empty() { "unnamed layer".to_string() } else { n.clone() }).collect(); - let more = names.len().saturating_sub(NAMED); + let more = distinct.len().saturating_sub(NAMED); let more = if more > 0 { format!(", {more} more") } else { String::new() }; format!("{} ({}{more})", w.message(), shown.join(", ")) }) .collect() } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_counted_once_each_and_the_first_three_shown() { + let mut w = Warnings::default(); + for name in ["a", "b", "a", "c", "d", "b", "e"] { + w.add(Warn::NothingDrawn, name); + } + let lines = w.finish(); + assert_eq!(lines.len(), 1); + assert!(lines[0].ends_with("(a, b, c, 2 more)"), "{}", lines[0]); + // Many distinct names: each is one set insertion, not a scan of all before it. + let mut w = Warnings::default(); + let start = std::time::Instant::now(); + for i in 0..200_000 { + w.add(Warn::TooLarge, &format!("layer {i}")); + } + assert!(w.finish()[0].ends_with("199997 more)")); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); + } +} From 1ff0da1841bd4c2b45ef13e3e8ffec26b65cd94f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:26:03 +0000 Subject: [PATCH 134/326] fix(figcraft): write the recovery copy's online note owner-only The .online note beside a recovery copy holds the secret the client resumes its identity with, but it was written with the default mode while the copy itself was created 0600. Both now go through one owner-only writer, which also narrows a note that already existed. --- apps/figcraft/src/recovery.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/apps/figcraft/src/recovery.rs b/apps/figcraft/src/recovery.rs index 750786d1c..92884e528 100644 --- a/apps/figcraft/src/recovery.rs +++ b/apps/figcraft/src/recovery.rs @@ -217,7 +217,8 @@ impl Recovery { return false; } let _ = match online { - Some(text) => std::fs::write(¬e, text), + // The note holds the secret the client resumes with: owner-only, as the copy. + Some(text) => write_private(¬e, text.as_bytes()), None => std::fs::remove_file(¬e), }; true @@ -326,24 +327,29 @@ fn rejoin_online(file: &Path, s: &mut Session) -> Option { fn write_atomic(path: &Path, doc: &figcraft_engine::doc::Document, versions: &[Version], branches: &[Branch]) -> bool { let Ok(bytes) = figcraft_format::save_bytes_with_history(doc, None, versions, branches) else { return false }; let tmp = path.with_extension("tmp"); + if write_private(&tmp, &bytes).is_err() { + let _ = std::fs::remove_file(&tmp); + return false; + } + std::fs::rename(&tmp, path).is_ok() +} + +/// Write `bytes` to `path`, created (or cut back) readable by its owner only on Unix. +fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { #[cfg(unix)] { - use std::os::unix::fs::OpenOptionsExt; + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; let mut opts = std::fs::OpenOptions::new(); opts.write(true).create(true).truncate(true).mode(0o600); - let Ok(mut f) = opts.open(&tmp) else { return false }; - if std::io::Write::write_all(&mut f, &bytes).is_err() { - let _ = std::fs::remove_file(&tmp); - return false; - } + let mut f = opts.open(path)?; + // `mode` applies to a new file only: one that was there keeps its mode unless set. + f.set_permissions(std::fs::Permissions::from_mode(0o600))?; + std::io::Write::write_all(&mut f, bytes) } #[cfg(not(unix))] { - if std::fs::write(&tmp, bytes).is_err() { - return false; - } + std::fs::write(path, bytes) } - std::fs::rename(&tmp, path).is_ok() } /// [`recover_all`], for a start that keeps nothing waiting: how many documents came back as From dd03165d79362b2d25b3c21de7128a0c24d31544 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 05:27:23 +0100 Subject: [PATCH 135/326] M4: weight steps read number weights after a width too (#1831) An off-list "Condensed 600" read as 400, since a number word counted as a weight only at the start of the name: weightUp took Condensed 500 and weightDown found nothing. A number from 100 to 1000 now counts in any position, as W numbers do. Smaller numbers (a width grade, an optical size: "Condensed 2", "Caption 12") are part of the width rather than a weight, so optical sizes no longer step into each other. --- crates/engine/src/cmd/text.rs | 13 ++++++++++--- crates/engine/src/text_weight_step_tests.rs | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 9024e1229..392fd4636 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -128,6 +128,13 @@ fn w_number(word: &str) -> Option { (1..=9).contains(&n).then_some(n * 100) } +/// A weight number as some families name styles ("Condensed 600"). Below 100 it is something else +/// (a width grade, an optical size: "Condensed 2", "Caption 12"). +fn number_weight(word: &str) -> Option { + let n = word.parse::().ok().filter(|_| word.bytes().all(|b| b.is_ascii_digit()))?; + (100..=1000).contains(&n).then_some(n) +} + /// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow", /// "Extra Condensed Bold" → "extra condensed"). fn style_rest(style: &str) -> String { @@ -162,7 +169,7 @@ fn style_rest(style: &str) -> String { const GRADES: [&str; 4] = ["extra", "ultra", "semi", "demi"]; let s = style.to_ascii_lowercase().replace('-', " "); let words: Vec<&str> = s.split_whitespace().collect(); - let weight = |w: &str| WEIGHTS.contains(&w) || w_number(w).is_some() || w.chars().all(|c| c.is_ascii_digit()); + let weight = |w: &str| WEIGHTS.contains(&w) || w_number(w).or_else(|| number_weight(w)).is_some(); let rest = words.iter().enumerate().filter(|(i, w)| { let graded = GRADES.contains(w) && words.get(i + 1).is_some_and(|next| weight(next) && !matches!(*next, "italic" | "oblique")); !weight(w) && !graded @@ -176,10 +183,10 @@ fn slanted(style: &str) -> bool { s.contains("italic") || s.contains("oblique") } -/// The weight a style name says ("W3", "W6 Italic" and "Condensed W7" too). +/// The weight a style name says ("W3", "W6 Italic", "Condensed W7" and "Condensed 600" too). pub(crate) fn name_weight(style: &str) -> u16 { let words = style.to_ascii_lowercase().replace('-', " "); - words.split_whitespace().find_map(w_number).unwrap_or_else(|| figcraft_doc::style_weight(style)) + words.split_whitespace().find_map(|w| w_number(w).or_else(|| number_weight(w))).unwrap_or_else(|| figcraft_doc::style_weight(style)) } /// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed diff --git a/crates/engine/src/text_weight_step_tests.rs b/crates/engine/src/text_weight_step_tests.rs index e8bf65a7b..057a0a4e5 100644 --- a/crates/engine/src/text_weight_step_tests.rs +++ b/crates/engine/src/text_weight_step_tests.rs @@ -77,6 +77,20 @@ fn hairline_and_w_numbers_are_weights() { assert_eq!(next_style(&hiragino, &at("Bold"), false).as_deref(), Some("W6")); } +#[test] +fn number_weights_count_after_a_width_but_other_numbers_dont() { + // An off-list "Condensed 600" is 600, as "600" alone is: between Condensed 500 and 700. + let condensed = weighed(&[("Condensed 300", 300), ("Condensed 500", 500), ("Condensed 700", 700)]); + assert_eq!(next_style(&condensed, &at("Condensed 600"), true).as_deref(), Some("Condensed 700")); + assert_eq!(next_style(&condensed, &at("Condensed 600"), false).as_deref(), Some("Condensed 500")); + assert_eq!((name_weight("Condensed 600"), name_weight("600 Italic"), name_weight("Condensed 1000")), (600, 600, 1000)); + // A number that isn't a weight (a width grade, an optical size) is part of the width. + assert_eq!((name_weight("Condensed 2"), name_weight("Caption 12 Bold"), name_weight("Condensed +600")), (400, 700, 400)); + let optical = styles(&["Caption 12 Regular", "Caption 24 Regular", "Caption 12 Bold", "Caption 24 Bold"]); + assert_eq!(walk(&optical, "Caption 12 Regular", true), ["Caption 12 Bold"]); + assert_eq!(walk(&optical, "Caption 24 Bold", false), ["Caption 24 Regular"]); +} + #[test] fn a_custom_weight_axis_value_steps_from_where_it_is() { let family = styles(&["Light", "Regular", "Medium", "Bold"]); From bd28a9c19e39f24058e4ffb0ae4ca1905b45f71f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:29:07 +0000 Subject: [PATCH 136/326] fix(text): load at most 64 faces from a font collection given as bytes A collection header names its faces in four bytes each, so a small upload could declare any number of faces over the same tables; every one was parsed and kept its own character map under the font database's lock. The largest real collections hold a few dozen faces; 64 are loaded. --- crates/text/src/fontdb.rs | 8 +++++++- crates/text/src/fontdb_tests.rs | 12 ++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index d0004fcd9..0643cb026 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -640,6 +640,9 @@ struct FallbackLists { /// The most styles whose fallback faces are kept (a file naming more starts the list again). const MAX_FALLBACK_STYLES: usize = 64; +/// Most faces loaded from one font collection given as bytes (the largest real collections, +/// the CJK ones, hold a few dozen). +const MAX_COLLECTION_FACES: u32 = 64; /// [`FontDb::key`]'s and [`FontDb::resolve`]'s answers for the families known in one generation. #[derive(Default)] @@ -711,7 +714,10 @@ impl FontDb { pub fn add_bytes(&mut self, bytes: Vec) -> Vec> { let shared = Arc::new(bytes); let count = match FileRef::new(shared.as_slice()) { - Ok(FileRef::Collection(c)) => c.len(), + // A collection's header may name any number of faces, each a few bytes pointing at + // the same tables, and every face keeps its own character map: at most + // [`MAX_COLLECTION_FACES`] of them are loaded. + Ok(FileRef::Collection(c)) => c.len().min(MAX_COLLECTION_FACES), Ok(FileRef::Font(_)) => 1, Err(_) => 0, }; diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index 5f0fa522b..112041050 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -595,3 +595,15 @@ fn system_font_dirs_are_walked_once_each() { let unique: std::collections::HashSet<_> = dirs.iter().collect(); assert_eq!(unique.len(), dirs.len(), "{dirs:?}"); } + +#[test] +fn a_collection_header_naming_billions_of_faces_loads_a_bounded_few() { + // Four bytes per face offset: a header can name far more faces than the data holds, and each + // one would be parsed (and keep a character map) in turn. + let mut bytes = synthetic_font_collection(32); + bytes[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); + let start = std::time::Instant::now(); + let faces = FontDb::default().add_bytes(bytes); + assert!(faces.len() <= 64, "{}", faces.len()); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); +} From 72ec49f92f097393dac8d165093127dfd1a9a7d1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:31:08 +0000 Subject: [PATCH 137/326] fix(engine): bound the keys an effect object is probed for Unknown effect keys are found by reparsing the whole object once per key, so an effect with many unknown keys cost their number squared in cloning and parsing before it was refused. More than 32 keys is refused outright. --- crates/engine/src/cmd/props.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 01f83bc85..3025c5c4a 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -85,10 +85,18 @@ pub fn effect_from(cmd: &str, p: &Value, key: &str) -> Result> { Ok(Some(effect)) } +/// Most keys an effect object may carry (the widest effect takes about a dozen). +const MAX_EFFECT_KEYS: usize = 32; + /// Refuse the keys of effect `given` that `parse` ignores, naming the keys the effect takes. Set to /// null, a key it reads fails to parse or changes the effect; a key it ignores changes nothing. fn refuse_ignored_effect_keys(cmd: &str, at: &str, given: &Value, parse: impl Fn(&Value) -> Option) -> Result<()> { let Some(fields) = given.as_object() else { return Ok(()) }; + // Each key is probed by reparsing the whole object without it: bounded, or a long list of + // unknown keys costs its length squared before it is refused. + if fields.len() > MAX_EFFECT_KEYS { + return Err(bad(cmd, format!("{at}: more than {MAX_EFFECT_KEYS} properties"))); + } let parsed = parse(given); let ignored: Vec<&str> = fields .iter() From 421a8e5126a56ede1cdce45d5b53289c96a848f9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:34:50 +0000 Subject: [PATCH 138/326] fix(doc): stop frame_relative on a looping parent chain A restored dev snapshot can replace an ancestor with a historical descendant while the root keeps that ancestor as its parent; frame_relative walked the parent chain without a guard and never returned. It now stops after more hops than the document has nodes, as is_ancestor does. --- crates/doc/src/lib.rs | 7 +++++++ crates/doc/src/tests.rs | 13 +++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 89eb97269..b637aa8f7 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -585,7 +585,14 @@ impl Document { let Some(n) = self.node(id) else { return Affine::IDENTITY }; let mut t = n.transform; let mut parent = n.parent; + // More hops than nodes means the parent chain loops (a restored snapshot can leave one): + // stop rather than spin. + let mut hops = 0; while let Some(p) = parent.and_then(|p| self.node(p)).filter(|p| p.kind.bounds_follow_children()) { + hops += 1; + if hops > self.nodes.len() { + break; + } t = p.transform * t; parent = p.parent; } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a0e3e17b0..4e55336b6 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -846,3 +846,16 @@ fn the_colour_walker_visits_calculation_literals() { let ColorOperand::Literal { literal } = from else { panic!("literal operand") }; assert_eq!(literal.a, 0.5, "the mix's stored literal was converted like every other colour"); } + +#[test] +fn frame_relative_ends_on_a_looping_parent_chain() { + let mut d = Document::new("x"); + let p = page(&d); + let f = d.create(p, NodeKind::Group, "F", 0.0, 0.0, 100.0, 100.0).unwrap(); + let g = d.create(f, NodeKind::Group, "G", 0.0, 0.0, 10.0, 10.0).unwrap(); + let mut v = serde_json::to_value(&d).unwrap(); + // F's parent is its own child G (as a restored snapshot can leave things). + v["nodes"][f.to_string()]["parent"] = serde_json::json!(g); + let bad: Document = serde_json::from_value(v).unwrap(); + let _ = bad.frame_relative(g); +} From 31a60ed3606c18d8329a04e55faba6e16537419b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:35:27 +0000 Subject: [PATCH 139/326] fix(collab-net): give a management request one deadline for its answer reply read until the server answered, and every ping, pong or control frame renewed the per-read timeout, so a library endpoint could hold a background refresh (and the shared refresh permit) open indefinitely. The whole exchange now ends at one absolute deadline, the idle timeout from when the request went out. --- crates/collab-net/src/manage.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/collab-net/src/manage.rs b/crates/collab-net/src/manage.rs index 04c718c5d..eecbca964 100644 --- a/crates/collab-net/src/manage.rs +++ b/crates/collab-net/src/manage.rs @@ -206,7 +206,15 @@ fn send(ws: &mut Ws, msg: &ClientMsg) -> Result<(), String> { /// The next answer `pick` takes, or why there is none. fn reply(ws: &mut Ws, limits: &NetLimits, pick: impl Fn(ServerMsg) -> Option) -> Result { + // One deadline for the whole answer: pings, pongs and a message trickling in each renew the + // read timeout, so without it a server could keep a request (and the refresh permit the + // caller holds) waiting for as long as it liked. + let until = std::time::Instant::now() + limits.idle_timeout; + ws.get_mut().read_until(Some(until)); loop { + if std::time::Instant::now() >= until { + return Err("no answer from the server (it took too long)".into()); + } return match ws.read() { Ok(Message::Binary(b)) => match message::decode::(&b, limits.max_server_message) { Ok(ServerMsg::Refused { reason }) => Err(format!("{REFUSED}{reason}")), From 3ebf0641cb3b07440460ceb26f20c272fabe8eaf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 23:45:53 -0500 Subject: [PATCH 140/326] fix(collab): place keyed-list puts through an index within a batch (#1893) * fix(collab): place keyed-list puts through an index within a batch Each Put of a comment, style, variable or collection scanned the whole list for its key (cloning String keys on the way) before appending, so a batch of N new entries cost N squared comparisons on the hub every session shares. Removing an image also rebuilt the document's image-use set before checking the image existed. Replica::apply now keeps a per-batch key index for each keyed list; it is rebuilt when the list's length or the entry at a key no longer matches, and dropped on whole-list sets, reorders and real removals. Removing an absent entry or image returns without scanning. * fix(collab): keep the keyed-list index current through removals Build the index without dead code outside tests, drop the wall-clock assertion from the large-batch test, and shift the index down after a single-entry removal instead of discarding it, so a run of removals in one batch does not index the list again each time. Staleness checks for puts and removals share one helper. Tests cover removals, duplicate keys from a whole-list set, and absent keys. --- crates/collab/src/docprops.rs | 152 +++++++++++++++++++++----- crates/collab/src/keyed_list_tests.rs | 132 ++++++++++++++++++++++ crates/collab/src/lib.rs | 2 + crates/collab/src/replica.rs | 7 +- 4 files changed, 261 insertions(+), 32 deletions(-) create mode 100644 crates/collab/src/keyed_list_tests.rs diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index e203d2c3b..b590064df 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -54,18 +54,71 @@ struct List { entry: fn(T::Key) -> Entry, get: fn(&Document) -> &Vec, get_mut: fn(&mut Document) -> &mut Vec, + /// The list's slot in an [`Index`]. + index: fn(&mut Index) -> &mut Option>, } -const STYLES: List\n", out.markup, out.tokens.root_rule(), out.styles) + // Document text can reach the stylesheet through any property: `<\/` reads back as `\n{css}\n", out.markup) } /// Markup being built for a layer tree: HTML (`class`), React JSX (`className`), Vue diff --git a/crates/engine/src/html_codegen_tests.rs b/crates/engine/src/html_codegen_tests.rs index cd1318ee0..ab7115554 100644 --- a/crates/engine/src/html_codegen_tests.rs +++ b/crates/engine/src/html_codegen_tests.rs @@ -163,3 +163,16 @@ fn rem_preserves_text_property_default() { } } } + +#[test] +fn the_stylesheet_never_contains_a_closing_style_tag_from_document_text() { + let mut s = Session::new(); + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()); + let t = id(s.execute("text.create", &json!({"text": "x", "x": 0, "y": 0})).unwrap()); + s.execute("node.set", &json!({"id": t, "props": {"fontFamily": "a"}})).unwrap(); + s.execute("node.reparent", &json!({"ids": [t], "parent": f})).unwrap(); + let code = code_for(s.doc().unwrap(), f, CodeLang::Html); + let (_, css) = code.split_once("").count(), 1, "{code}"); + assert!(!code.contains("