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/138] 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/138] 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/138] 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/138] 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/138] 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/138] 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/138] 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/138] 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/138] 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 099cc0375455a63803b49739183583163ef36bf9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:21:43 -0700 Subject: [PATCH 010/138] 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 011/138] 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 01214c6e12aff34a2ac56503b1f7dbe8cb9a60c8 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 31 Oct 2026 11:26:45 -0400 Subject: [PATCH 012/138] 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 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 013/138] 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 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 014/138] 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 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 015/138] 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 467607762616424b9345c8f1cefe09198e6e2d8e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:16:56 -0400 Subject: [PATCH 016/138] 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 16d97cf8e96ab81868e192e1e78930f47d01c67c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:33:58 -0400 Subject: [PATCH 017/138] 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 018/138] 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 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 019/138] 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 d72f0961867826c6bf9983b40734ada6e1dab70e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 11:54:35 -0500 Subject: [PATCH 020/138] 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 8bc405edbccc73ed07f9373bf1c173a7e9b22bee Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 12:16:33 -0500 Subject: [PATCH 021/138] 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 8fb53baa64c73aa3721e636e944a1e9b5db67da9 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 02:02:35 -0500 Subject: [PATCH 022/138] 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 367f188b348f0e575b30b804665d3451c416839b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 04:39:07 -0500 Subject: [PATCH 023/138] 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 024/138] 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 695ca0752874c94138bd5e362136bf28850a3c42 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 06:43:02 -0500 Subject: [PATCH 025/138] 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 90bec33322d3a33e004a5f632b3dde8d914d684e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 2 Nov 2026 07:23:33 -0500 Subject: [PATCH 026/138] 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 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 027/138] 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 028/138] 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 5bbab0fa181329d01973c489bc6fb01b4f863ab4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:23:05 +0000 Subject: [PATCH 029/138] 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 421a8e5126a56ede1cdce45d5b53289c96a848f9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:34:50 +0000 Subject: [PATCH 030/138] 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 6cb724c588d4abcd0a30a8b695431818f2b2ce90 Mon Sep 17 00:00:00 2001 From: Hamza Date: Tue, 3 Nov 2026 12:03:42 +0500 Subject: [PATCH 031/138] docs: credit Hamza Naveed in contributor names --- contributors/people.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index c846d8725..16c4de243 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -101,3 +101,7 @@ sync_github_name = true [people.aleksei-suholita] real_name = "Oleksii Sukholita" + +[people.Hamza0101] +real_name = "Hamza Naveed" +display_name = "Hamza0101" From 58af1a6237228125fe60e05fc4056ccd9a2f1ae3 Mon Sep 17 00:00:00 2001 From: Hamza Date: Tue, 3 Nov 2026 12:23:25 +0500 Subject: [PATCH 032/138] M4, #1747: a text layer's name follows the characters typed into it --- crates/engine/src/canvas/textedit.rs | 7 +++ crates/engine/src/cmd/props.rs | 24 ++++++++ crates/engine/src/text_behaviour_tests.rs | 68 +++++++++++++++++++++++ docs/roadmap.md | 1 + docs/target-app-parity.md | 1 + 5 files changed, 101 insertions(+) diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index 368a48c90..7191f15dd 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -184,14 +184,21 @@ fn edit_if(s: &mut Session, f: impl FnOnce(&mut TextData, &mut TextEdit) -> bool let doc = ds.doc_mut(); let n = doc.get_mut(te.id)?; let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("not a text layer".into())) }; + let derived_before = crate::cmd::props::text_layer_name(&t.characters); if !f(t, &mut te) { return Ok(false); } // Any edit ends a composition (a commit replaces it with the final text). te.preedit = None; let len = t.char_count(); + let derived_after = crate::cmd::props::text_layer_name(&t.characters); te.caret = te.caret.min(len); te.anchor = te.anchor.min(len); + // The layer's name follows the characters while it is the name they derive, so the Layers + // panel keeps up with what the canvas shows; a name the author typed is left alone. + if crate::cmd::props::text_name_is_derived(&n.name, derived_before.as_ref()) { + n.name = derived_after.unwrap_or_default(); + } if n.source.is_some() { n.overrides.insert("characters".into()); } diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 36e33dd79..41cd260da 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -41,6 +41,30 @@ pub(crate) fn normalize_line_endings(s: &str) -> String { s.replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n") } +/// The name a text layer derives from its characters: the first line, at most 64 characters, or +/// None when that line is blank (a layer with no name of its own, which the Layers panel shows by +/// its kind). +/// +/// A layer whose name is this derived name is one nobody has renamed, so the editor keeps its name +/// in step as the characters are typed ([`crate::textedit`]); any other name was chosen by the +/// author and is kept. Commands never rename, so a layer named for its role keeps that name as a +/// field key even when `characters` replace text that reads like it. +pub(crate) fn text_layer_name(characters: &str) -> Option { + let first: String = characters.lines().next().unwrap_or("").chars().take(64).collect(); + (!first.trim().is_empty()).then_some(first) +} + +/// Whether `name` is one a text layer was given for its characters rather than by its author, so +/// the editor may keep it in step with them. Blank text leaves a layer named `""` when the Text +/// tool draws it and `Text` when `node.create` makes it, and both read as unnamed in the panel. +pub(crate) fn text_name_is_derived(name: &str, derived: Option<&String>) -> bool { + match derived { + Some(d) => name == d, + // `NodeKind::Text(_).label()`, which the panel falls back to for an unnamed layer. + None => name.is_empty() || name == "Text", + } +} + /// camelCase object keys → snake_case (accept the inspect/camel forms for serde-backed values). pub fn snake(v: &Value) -> Value { match v { diff --git a/crates/engine/src/text_behaviour_tests.rs b/crates/engine/src/text_behaviour_tests.rs index 1e700c688..12a5dbfbf 100644 --- a/crates/engine/src/text_behaviour_tests.rs +++ b/crates/engine/src/text_behaviour_tests.rs @@ -748,3 +748,71 @@ fn a_link_is_underlined_by_default_and_underline_takes_it_off() { 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"); } + +fn layer_name(s: &Session, t: NodeId) -> String { + s.doc().unwrap().node(t).unwrap().name.clone() +} + +/// Select everything in the layer being edited and delete it. +fn clear_edited_text(s: &mut Session, t: NodeId) { + let len = s.doc().unwrap().node(t).unwrap().kind.text().unwrap().char_count(); + crate::textedit::set_caret(s, 0, false).unwrap(); + crate::textedit::set_caret(s, len, true).unwrap(); + crate::textedit::key(s, "Backspace", false, false, false).unwrap(); +} + +#[test] +fn typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it() { + // The Layers panel shows a layer's name, so a layer still carrying the name its characters + // gave it has to follow them while they are typed or the panel and the canvas disagree + // (#1747). The target app's plugin API calls this `autoRename`: "Whether updating the + // characters in the text node should update the name of the node… This is automatically reset + // to false if `name` is modified in order to allow the node to keep the new name." + let mut s = Session::new(); + + // Nobody renamed this layer, so typing in it keeps its name up to date. + let t = text(&mut s, "hello", json!({})); + assert_eq!(layer_name(&s, t), "hello", "a new layer is named after its first line"); + crate::textedit::begin(&mut s, t, Some(5), false).unwrap(); + crate::textedit::insert(&mut s, " there").unwrap(); + assert_eq!((chars(&s, t).as_str(), layer_name(&s, t).as_str()), ("hello there", "hello there"), "the name follows what is typed"); + + // A name the author typed is theirs: later typing leaves it alone. + s.execute("node.set", &json!({"id": t, "props": {"name": "Greeting"}})).unwrap(); + crate::textedit::begin(&mut s, t, Some(11), false).unwrap(); + crate::textedit::insert(&mut s, "!").unwrap(); + assert_eq!((chars(&s, t).as_str(), layer_name(&s, t).as_str()), ("hello there!", "Greeting"), "a chosen name is kept"); + + // Only the first line names the layer. + let v = text(&mut s, "first", json!({})); + crate::textedit::begin(&mut s, v, Some(5), false).unwrap(); + crate::textedit::insert(&mut s, "\nsecond").unwrap(); + assert_eq!((chars(&s, v).as_str(), layer_name(&s, v).as_str()), ("first\nsecond", "first"), "the first line alone names it"); + + // Emptied text reads as a new empty text layer does, not as the word that was deleted. + clear_edited_text(&mut s, v); + assert_eq!((chars(&s, v).as_str(), layer_name(&s, v).as_str()), ("", ""), "emptied text has no name of its own, so the panel shows its kind"); + + // The usual way a layer is made: the Text tool, a click, then typing into the empty layer. + use crate::tools::{PointerEvent, PointerKind, ToolId}; + s.set_tool(ToolId::Text); + s.pointer(&PointerEvent::at(PointerKind::Down, 300.0, 300.0, 1.0)).unwrap(); + s.pointer(&PointerEvent::at(PointerKind::Up, 300.0, 300.0, 1.0)).unwrap(); + let drawn = s.ds().unwrap().text_edit.as_ref().unwrap().id; + assert_eq!(layer_name(&s, drawn), "", "a layer the tool drew has no name of its own yet"); + crate::textedit::insert(&mut s, "Pricing").unwrap(); + assert_eq!((chars(&s, drawn).as_str(), layer_name(&s, drawn).as_str()), ("Pricing", "Pricing"), "the first word typed names it"); +} + +#[test] +fn setting_characters_as_a_command_never_renames_the_layer() { + // Only the editor follows the characters. Layer names are field keys for `data.fill`, + // component property bindings and templates, which write `characters` into a layer named for + // its role ("Title") and look it up by that name again, so a command must leave the name as it + // is even when it reads like the text it replaces. + let mut s = Session::new(); + let t = text(&mut s, "Title", json!({})); + assert_eq!(layer_name(&s, t), "Title"); + s.execute("node.set", &json!({"id": t, "props": {"characters": "Site em 7 dias"}})).unwrap(); + assert_eq!((chars(&s, t).as_str(), layer_name(&s, t).as_str()), ("Site em 7 dias", "Title"), "the field keeps its name"); +} diff --git a/docs/roadmap.md b/docs/roadmap.md index 6bc72a278..9c9dacf37 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -75,6 +75,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-11-03 | patch | M4, #1747: a text layer still carrying the name its characters gave it is renamed as they are typed, so the Layers panel no longer shows the word a layer started with while the canvas shows another (`hello` typed into `hello there` read as `hello` in the panel). A name the author typed is kept, and only the editor follows the characters: commands leave the name alone, so the layer names `data.fill`, component property bindings and templates use as field keys stay put. Tests: `text_behaviour_tests::typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it`, `setting_characters_as_a_command_never_renames_the_layer`. Grade unchanged | | 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged | | 2026-10-31 | patch | M11: a trackpad or touch tap sends its press and release in one frame, so a plugin panel's field committed in the frame its button was clicked and the value was lost: the Counter's Set count… kept the old count. The plugin now gets both, the field's value first. The `window.figcraft` docs name `screenshot`'s `data`. 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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 75a426231..5a4effee4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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-03 | patch | M4, #1747: a text layer still carrying the name its characters gave it is renamed as they are typed, so the Layers panel no longer shows the word a layer started with while the canvas shows another (`hello` typed into `hello there` read as `hello` in the panel). A name the author typed is kept, and only the editor follows the characters: commands leave the name alone, so the layer names `data.fill`, component property bindings and templates use as field keys stay put. Tests: `text_behaviour_tests::typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it`, `setting_characters_as_a_command_never_renames_the_layer`. Grade unchanged | | 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 | From d68a140755578be37ee048ba6267d532cf1fc4f5 Mon Sep 17 00:00:00 2001 From: Carbocode Date: Tue, 3 Nov 2026 10:42:02 +0100 Subject: [PATCH 033/138] M8: remove parity documentation changes --- docs/ui-parity.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 77b9ecdc2..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-02 · **Change:** minor (Selection colors shares Fill and Stroke’s colour control with fractional opacity and accessible swatches; an outlined selection icon selects matching layers, and Plus and Minus share one pixel-snapped centre; 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-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: @@ -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); 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) | +| 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) | | 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 @@ -176,9 +176,6 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Date | Change | Summary | |---|---|---| -| 2026-11-02 | minor | M8, #1654: merged main while keeping linked variable names resolved by stored id; Plus and Minus share a snapped centre; shared paint controls expose their swatch values to assistive technology and retain fractional opacity through consecutive fine scrubs, with regression tests. Estimates unchanged. | -| 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-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 37803cb1c80902f3e0a6623de8eb9daddce6a48b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:24:14 +0000 Subject: [PATCH 034/138] perf(format): index the lookups that made style-heavy files quadratic REST import searched every style imported so far for each layer's style reference; .fig export compared each text span's style with every distinct style before it; Penpot token-set ordering searched the whole order array for every comparison of the sort. Each now looks up a set, a map or a position table built once. --- crates/format/src/fig/export/shape.rs | 18 +++++++++++++----- crates/format/src/fig/export_tests.rs | 16 ++++++++++++++++ crates/format/src/penpot.rs | 5 ++++- crates/format/src/rest.rs | 8 +++++++- .../format/src/rest/import_regression_tests.rs | 18 ++++++++++++++++++ 5 files changed, 58 insertions(+), 7 deletions(-) diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index e4e2cae6b..58309784f 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -56,16 +56,24 @@ impl<'d> Exporter<'d> { } let spans = td.spans(); let mut table: Vec<&TextStyle> = Vec::new(); + // Each distinct style once, found by its serialized form rather than by comparing it + // with every earlier one (quadratic in the number of distinct styles). + let mut index: std::collections::HashMap = std::collections::HashMap::new(); let mut span_ids = Vec::with_capacity(spans.len()); for (_, _, st) in &spans { span_ids.push(if **st == td.style { 0 } else { - let i = table.iter().position(|t| *t == *st).unwrap_or_else(|| { - table.push(st); - table.len() - 1 - }); - i as u32 + 1 + match serde_json::to_string(st) { + Ok(key) => *index.entry(key).or_insert_with(|| { + table.push(st); + table.len() as u32 + }), + Err(_) => { + table.push(st); + table.len() as u32 + } + } }); } let mut chars = String::new(); diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index b1b31262a..f6951cdcb 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -1611,3 +1611,19 @@ fn a_whole_ellipse_starting_anywhere_comes_back_whole() { } } } + +#[test] +fn text_with_thousands_of_distinct_styles_exports_in_linear_time() { + // The style table used to be searched end to end for every span (quadratic in distinct styles). + let mut doc = Document::new("styles"); + let p = doc.first_page().unwrap(); + let mut td = TextData::new("x".repeat(20_000)); + td.runs = (0..20_000) + .map(|i| StyleRun { start: i, end: i + 1, style: TextStyle { font_size: 8.0 + i as f64 / 100.0, ..TextStyle::default() } }) + .collect(); + doc.create(p, NodeKind::Text(td), "T", 0.0, 0.0, 100.0, 100.0).unwrap(); + let start = std::time::Instant::now(); + let (bytes, _) = export(&doc, None).unwrap(); + assert!(!bytes.is_empty()); + assert!(start.elapsed() < std::time::Duration::from_secs(10), "{:?}", start.elapsed()); +} diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index 6cd8fe53c..7ffd208d8 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -2131,7 +2131,10 @@ fn import_themed_tokens( if set_names.is_empty() { return false; } - set_names.sort_by_key(|name| order.iter().position(|o| o == name).unwrap_or(usize::MAX)); + // Each set's place in the order once: a position search per comparison was quadratic in + // the order's length for every one of the sort's comparisons. + let place: BTreeMap<&str, usize> = order.iter().enumerate().map(|(i, o)| (*o, i)).collect(); + set_names.sort_by_key(|name| place.get(name).copied().unwrap_or(usize::MAX)); let set_names: Vec<&str> = set_names.into_iter().take(512).collect(); let mut tokens: BTreeMap<&str, BTreeMap> = BTreeMap::new(); for name in &set_names { diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 4604b73a6..9c1d27dde 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -427,6 +427,9 @@ pub(crate) struct Ctx<'a> { component_meta: BTreeMap<&'a str, &'a Value>, set_meta: BTreeMap<&'a str, &'a Value>, style_meta: BTreeMap<&'a str, &'a Value>, + /// The ids of the styles imported so far (`doc.styles` is a Vec: a lookup per reference + /// would be quadratic in a document with many distinct references). + style_ids: BTreeSet, /// Instances (imported as frames until their main is resolved) with their JSON. instances: Vec<(NodeId, &'a Value)>, /// `SLOT` layers (imported as frames until their slot property is resolved) with their JSON. @@ -468,6 +471,7 @@ impl<'a> Ctx<'a> { component_meta: BTreeMap::new(), set_meta: BTreeMap::new(), style_meta: BTreeMap::new(), + style_ids: BTreeSet::new(), instances: Vec::new(), slots: Vec::new(), slot_defaults: BTreeMap::new(), @@ -941,6 +945,7 @@ impl<'a> Ctx<'a> { }; self.bindings(&mut sample, node); let bound = sample.bound.iter().filter_map(|(k, v)| Some((style_binding(slot, k)?, v.clone()))).collect(); + self.style_ids.insert(id.to_string()); self.doc.styles.push(Style { id: id.to_string(), name, description, kind, bound }); } } @@ -961,13 +966,14 @@ impl<'a> Ctx<'a> { _ => continue, }; *target = Some(sid.to_string()); - if self.doc.styles.iter().any(|s| s.id == sid) { + if self.style_ids.contains(sid) { continue; } let meta = self.style_meta.get(sid); let name = meta.and_then(|m| text(m, "name")).filter(|s| !s.is_empty()).map_or_else(|| format!("Style {sid}"), |s| clip_str(s).to_string()); let description = meta.and_then(|m| text(m, "description")).map(|s| clip_str(s).to_string()).unwrap_or_default(); + self.style_ids.insert(sid.to_string()); self.doc.styles.push(Style { id: sid.to_string(), name, description, kind, bound: BTreeMap::new() }); } } diff --git a/crates/format/src/rest/import_regression_tests.rs b/crates/format/src/rest/import_regression_tests.rs index 71d9e0afb..5aeb4548b 100644 --- a/crates/format/src/rest/import_regression_tests.rs +++ b/crates/format/src/rest/import_regression_tests.rs @@ -75,3 +75,21 @@ fn stroke_colour_variable_on_outlined_vector_is_kept() { icon.bound ); } + +#[test] +fn thousands_of_distinct_style_references_import_in_linear_time() { + // Each reference used to search every style imported so far (quadratic in their number). + let fill = json!({"type": "SOLID", "color": {"r": 1, "g": 0, "b": 0, "a": 1}}); + let n = 20_000; + let children: Vec = (0..n) + .map(|i| { + json!({"id": format!("1:{i}"), "name": "R", "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 10, "y": 10}, + "fills": [fill], "styles": {"fill": format!("S:{i}")}}) + }) + .collect(); + let v = file(Value::Array(children)); + let start = std::time::Instant::now(); + let (doc, _) = import(&v, &no_images).unwrap(); + assert!(start.elapsed() < std::time::Duration::from_secs(10), "{:?}", start.elapsed()); + assert_eq!(doc.styles.len(), n); +} From 024b7fe45284ce0206b4e732720a7506b7ad53fa Mon Sep 17 00:00:00 2001 From: MortenHusted Date: Tue, 3 Nov 2026 09:53:18 +0100 Subject: [PATCH 035/138] M3: importing a file keeps its own variables and styles when their ids are already taken `file.import` of a FigCraft file kept the document's style, variable or collection for every id both files used, and the pasted layers kept those ids. Ids are numbered per file, so two files made apart share them, and the imported layers were bound to the document's unrelated variables, modes and styles. `append_pages` now gives the incoming file new ids first (`Renames`): - an incoming style, variable or collection is shared, as before, only when the document has the same under its id and everything it names is shared too (the same file imported again); a collection and its variables are shared only together; library copies keep their ids; - every other id the document already uses gets a new one from its allocators, which now take ids to avoid (the incoming file's own); - layers' style links, bindings, explicit modes and prototype actions, styles' bindings, variables' collections, aliases, calculations and extensions, and the renamed collections' mode ids follow. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/ids.rs | 27 +- crates/doc/src/ids_tests.rs | 16 ++ crates/engine/src/cmd/file.rs | 1 + crates/engine/src/cmd/file/import_ids.rs | 254 +++++++++++++++++++ crates/engine/src/cmd/file/open.rs | 13 +- crates/engine/src/import_ids_tests.rs | 172 +++++++++++++ crates/engine/src/lib.rs | 2 + crates/engine/src/library_variables_tests.rs | 28 ++ 8 files changed, 508 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/file/import_ids.rs create mode 100644 crates/engine/src/import_ids_tests.rs diff --git a/crates/doc/src/ids.rs b/crates/doc/src/ids.rs index 7e244fbb0..622ca807e 100644 --- a/crates/doc/src/ids.rs +++ b/crates/doc/src/ids.rs @@ -14,6 +14,8 @@ //! space 0. The session server accepts a new object only with an id in its creator's space or //! space 0, so two people never make the same id. +use std::collections::BTreeSet; + use crate::{CollectionId, Document, ModeId, NodeId, StyleId, VariableId}; /// What style ids start with. @@ -74,25 +76,42 @@ impl Document { /// A new style id. pub fn new_style_id(&mut self) -> StyleId { - let taken: Vec = self.styles.iter().filter_map(|s| id_number(&s.id, STYLE_ID_PREFIX)).collect(); + self.new_style_id_avoiding(&BTreeSet::new()) + } + + /// A new style id that is none of `avoid` either: ids of styles about to come in with a file + /// being imported. + pub fn new_style_id_avoiding(&mut self, avoid: &BTreeSet) -> StyleId { + let taken: Vec = self.styles.iter().map(|s| &s.id).chain(avoid).filter_map(|id| id_number(id, STYLE_ID_PREFIX)).collect(); if let Some(n) = self.session_number(taken) { return format!("{STYLE_ID_PREFIX}{n}"); } (self.styles.len() + 1..) .map(|k| format!("{STYLE_ID_PREFIX}{k}")) - .find(|id| self.style(id).is_none()) + .find(|id| self.style(id).is_none() && !avoid.contains(id)) .unwrap_or_else(|| format!("{STYLE_ID_PREFIX}0")) } /// A new variable id. pub fn new_variable_id(&mut self) -> VariableId { - let taken: Vec = self.variables.variables.iter().filter_map(|v| id_number(&v.id, VARIABLE_ID_PREFIX)).collect(); + self.new_variable_id_avoiding(&BTreeSet::new()) + } + + /// A new variable id that is none of `avoid` either (see [`Self::new_style_id_avoiding`]). + pub fn new_variable_id_avoiding(&mut self, avoid: &BTreeSet) -> VariableId { + let taken = self.variables.variables.iter().map(|v| &v.id).chain(avoid).filter_map(|id| id_number(id, VARIABLE_ID_PREFIX)).collect(); self.new_numbered_id(VARIABLE_ID_PREFIX, taken) } /// A new variable collection id. pub fn new_collection_id(&mut self) -> CollectionId { - let taken: Vec = self.variables.collections.iter().filter_map(|c| id_number(&c.id, COLLECTION_ID_PREFIX)).collect(); + self.new_collection_id_avoiding(&BTreeSet::new()) + } + + /// A new variable collection id that is none of `avoid` either (see + /// [`Self::new_style_id_avoiding`]). + pub fn new_collection_id_avoiding(&mut self, avoid: &BTreeSet) -> CollectionId { + let taken = self.variables.collections.iter().map(|c| &c.id).chain(avoid).filter_map(|id| id_number(id, COLLECTION_ID_PREFIX)).collect(); self.new_numbered_id(COLLECTION_ID_PREFIX, taken) } diff --git a/crates/doc/src/ids_tests.rs b/crates/doc/src/ids_tests.rs index a0091623d..e725c2ce4 100644 --- a/crates/doc/src/ids_tests.rs +++ b/crates/doc/src/ids_tests.rs @@ -1,6 +1,8 @@ //! Ids of styles, variables, collections, modes and comments: unchanged outside a live session, //! from the client's own space during one. +use std::collections::BTreeSet; + use crate::ids::{COLLECTION_ID_PREFIX, id_number, id_space, mode_number, space_of}; use crate::{Collection, Comment, Document, Message, Mode, NodeId, NodeKind, Style, StyleKind}; @@ -93,6 +95,20 @@ fn ids_of_the_space_already_in_the_document_stay_taken() { assert_eq!(e.new_style_id(), format!("S:{}", C3 | 1)); } +#[test] +fn new_ids_can_avoid_ids_about_to_come_in() { + let mut d = Document::new("a"); + d.styles.push(style("S:1")); + let avoid: BTreeSet = ["S:2", "S:3", "VariableID:4", "VariableCollectionId:2", "lib:VariableID:9"].map(String::from).into(); + assert_eq!(d.new_style_id_avoiding(&avoid), "S:4"); + assert_eq!(d.new_variable_id_avoiding(&avoid), "VariableID:5"); + assert_eq!(d.new_collection_id_avoiding(&avoid), "VariableCollectionId:3"); + // In a session the numbers come from the client's space, above those of it to avoid. + let avoid: BTreeSet = [format!("VariableID:{}", C3 | 7)].into(); + d.set_client_id(3); + assert_eq!(d.new_variable_id_avoiding(&avoid), format!("VariableID:{}", C3 | 8)); +} + #[test] fn the_highest_space_counts_every_kind_of_id() { let mut d = Document::new("a"); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0cfdd1ffa..79de7c28c 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -15,6 +15,7 @@ use crate::params::{bool_of, boolean, get, id, num, num_or, req_index, req_strin use crate::{DocState, EngineError, Result, Session, bad, spec}; mod export; +mod import_ids; mod load; mod open; mod save; diff --git a/crates/engine/src/cmd/file/import_ids.rs b/crates/engine/src/cmd/file/import_ids.rs new file mode 100644 index 000000000..2b6a7e697 --- /dev/null +++ b/crates/engine/src/cmd/file/import_ids.rs @@ -0,0 +1,254 @@ +//! Ids a file being imported brings that the document already uses for something else. +//! +//! Style, variable and collection ids are numbered per file (`S:1`, `VariableID:1`, +//! `VariableCollectionId:1`; see [`figcraft_doc::ids`]), so two files made apart use the same ones +//! for unrelated things. Kept as they were, the imported layers would show the document's +//! variables and styles instead of their own. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_doc::ids::MODE_ID_INFIX; +use figcraft_doc::proto::{Action, Expr, MAX_EXPR_DEPTH, walk_mut}; +use figcraft_doc::{Document, ModeId, NodeId, NodeKind, VariableValue, Variables}; + +/// A style, variable or collection of the file being imported. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Asset<'a> { + Style(&'a str), + Variable(&'a str), + Collection(&'a str), +} + +/// New ids for styles, variables and collections of a file being imported (its id → the new one). +#[derive(Debug, Default)] +pub(super) struct Renames { + styles: BTreeMap, + variables: BTreeMap, + collections: BTreeMap, +} + +impl Renames { + /// The new ids `other`'s styles, variables and collections take when appended to `doc`. + /// + /// One whose id `doc` doesn't use keeps it. One `doc` already has is shared and keeps its id: + /// the same content under the same id, naming only things that are shared too (the same file + /// imported again). A collection and its variables are shared only all together, so variables + /// of one file never join a collection of another. Library copies keep their ids and are shared + /// with the document's copies, as before (`merge_store` records them). Every other id `doc` + /// already uses is replaced by a new one from `doc`'s allocators, clear of `other`'s ids too. + pub(super) fn new(doc: &mut Document, other: &Document) -> Renames { + let (theirs, libs) = (&other.variables, &other.libraries); + // Each with whether `doc` has the same under its id (None: nothing there), and whether + // it's a library copy. + let styles = other.styles.iter().map(|s| { + let here = doc.styles.iter().find(|m| m.id == s.id); + (Asset::Style(&s.id), here.map(|m| m == s), libs.style_import(&s.id).is_some()) + }); + let colls = theirs.collections.iter().map(|c| { + let here = doc.variables.collection_by_id(&c.id); + (Asset::Collection(&c.id), here.map(|m| m == c), libs.collection_import(&c.id).is_some()) + }); + let vars = theirs.variables.iter().map(|v| { + let here = doc.variables.get_by_id(&v.id); + (Asset::Variable(&v.id), here.map(|m| m == v), libs.variable_import(&v.id).is_some()) + }); + // `taken`: ids `doc` uses; `differs`: what `doc` doesn't have the same of. + let (mut taken, mut copies, mut differs) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); + for (a, same, copy) in styles.chain(colls).chain(vars) { + match same { + None => { + differs.insert(a); + } + Some(same) => { + taken.insert(a); + if copy { + copies.insert(a); + } else if !same { + differs.insert(a); + } + } + } + } + // What differs makes what names it differ (library copies aside), and a collection and its + // variables differ together. + let mut named_by: BTreeMap> = BTreeMap::new(); + for v in &theirs.variables { + let (var, coll) = (Asset::Variable(&v.id), Asset::Collection(&v.collection)); + named_by.entry(coll).or_default().push(var); + named_by.entry(var).or_default().push(coll); + for r in v.values.values().flat_map(VariableValue::references).chain(&v.extends) { + named_by.entry(Asset::Variable(r)).or_default().push(var); + } + } + for c in &theirs.collections { + if let Some(e) = &c.extends { + named_by.entry(Asset::Collection(e)).or_default().push(Asset::Collection(&c.id)); + } + } + for s in &other.styles { + for v in s.bound.values() { + named_by.entry(Asset::Variable(v)).or_default().push(Asset::Style(&s.id)); + } + } + let mut todo: Vec = differs.iter().copied().collect(); + while let Some(a) = todo.pop() { + for &n in named_by.get(&a).into_iter().flatten() { + if !copies.contains(&n) && differs.insert(n) { + todo.push(n); + } + } + } + let renamed = |a: Asset| taken.contains(&a) && differs.contains(&a); + Renames { + collections: fresh( + theirs.collections.iter().map(|c| &c.id), + |id| renamed(Asset::Collection(id)), + |avoid| doc.new_collection_id_avoiding(avoid), + ), + variables: fresh(theirs.variables.iter().map(|v| &v.id), |id| renamed(Asset::Variable(id)), |avoid| doc.new_variable_id_avoiding(avoid)), + styles: fresh(other.styles.iter().map(|s| &s.id), |id| renamed(Asset::Style(id)), |avoid| doc.new_style_id_avoiding(avoid)), + } + } + + pub(super) fn is_empty(&self) -> bool { + self.styles.is_empty() && self.variables.is_empty() && self.collections.is_empty() + } + + /// `other` with the renamed styles, variables and collections under their new ids, and what + /// names them following: layers' style links (text ranges too), bindings, explicit modes and + /// prototype actions; styles' bindings; variables' collections, aliases and calculations; what + /// extended collections and their variables extend; and the ids of the renamed collections' + /// modes, which name their collection (`/mode`). + pub(super) fn applied(&self, other: &Document) -> Document { + let theirs = &other.variables; + let mut doc = other.clone(); + let (styles, vars, colls) = (&self.styles, &self.variables, &self.collections); + for s in &mut doc.styles { + rename(styles, &mut s.id); + s.bound.values_mut().for_each(|v| rename(vars, v)); + } + for c in &mut doc.variables.collections { + for m in &mut c.modes { + self.mode(theirs, &c.id, &mut m.id); + } + for id in std::iter::once(&mut c.id).chain(&mut c.extends) { + rename(colls, id); + } + } + for v in &mut doc.variables.variables { + let values = std::mem::take(&mut v.values).into_iter().map(|(mut mode, mut val)| { + self.mode(theirs, &v.collection, &mut mode); + val.references_mut().into_iter().for_each(|r| rename(vars, r)); + (mode, val) + }); + v.values = values.collect(); + let overrides = std::mem::take(&mut v.overrides).into_iter().map(|mut mode| { + self.mode(theirs, &v.collection, &mut mode); + mode + }); + v.overrides = overrides.collect(); + rename(colls, &mut v.collection); + for id in std::iter::once(&mut v.id).chain(&mut v.extends) { + rename(vars, id); + } + } + let ids: Vec = doc.ids().collect(); + for id in ids { + let Some(n) = doc.node_mut(id) else { continue }; + let links = [&mut n.styles.fill, &mut n.styles.stroke, &mut n.styles.effect, &mut n.styles.grid, &mut n.styles.text]; + for s in links.into_iter().flatten() { + rename(styles, s); + } + if let NodeKind::Text(t) = &mut n.kind { + t.map_text_styles(|s| Some(styles.get(s).cloned().unwrap_or_else(|| s.to_string()))); + } + n.bound.values_mut().for_each(|v| rename(vars, v)); + n.var_modes = std::mem::take(&mut n.var_modes) + .into_iter() + .map(|(mut c, mut mode)| { + self.mode(theirs, &c, &mut mode); + rename(colls, &mut c); + (c, mode) + }) + .collect(); + for it in &mut n.interactions { + walk_mut(&mut it.actions, &mut |a| self.action(theirs, a)); + } + } + doc + } + + /// Rename mode `mode` of collection `of` (`theirs`: the imported file's variables as they were). + /// A mode id names the collection it was made in: `of`, or one `of` extends (an extended + /// collection has the modes of the one it extends). Library copies keep their library's mode + /// ids, which may name one of the file's own collections. + fn mode(&self, theirs: &Variables, of: &str, mode: &mut ModeId) { + let mut at = Some(of); + for _ in 0..=theirs.collections.len() { + let Some(c) = at else { return }; + if let Some(k) = mode.strip_prefix(c).and_then(|rest| rest.strip_prefix(MODE_ID_INFIX)) { + if let Some(new) = self.collections.get(c) { + *mode = format!("{new}{MODE_ID_INFIX}{k}"); + } + return; + } + at = theirs.collection_by_id(c).and_then(|c| c.extends.as_deref()); + } + } + + /// Rename what one prototype action names (not the actions nested in it). + fn action(&self, theirs: &Variables, a: &mut Action) { + match a { + Action::SetVariable { variable, expr, .. } => { + rename(&self.variables, variable); + if let Some(e) = expr { + self.expr(theirs, e, 0); + } + } + Action::SetVariableMode { collection, mode } => { + self.mode(theirs, collection, mode); + rename(&self.collections, collection); + } + Action::Conditional { blocks } => blocks.iter_mut().filter_map(|b| b.condition.as_mut()).for_each(|c| self.expr(theirs, c, 0)), + _ => {} + } + } + + fn expr(&self, theirs: &Variables, e: &mut Expr, depth: usize) { + match e { + Expr::Value(v) => v.references_mut().into_iter().for_each(|r| rename(&self.variables, r)), + Expr::Op { args, .. } if depth < MAX_EXPR_DEPTH => args.iter_mut().for_each(|a| self.expr(theirs, a, depth + 1)), + Expr::Op { .. } => {} + Expr::Mode { collection } => rename(&self.collections, collection), + Expr::InMode { variable, mode } => { + if let Some(v) = theirs.get_by_id(variable) { + self.mode(theirs, &v.collection, mode); + } + rename(&self.variables, variable); + } + } + } +} + +/// New ids, from `new_id`, for those of `ids` that `pick` picks; each clear of all of `ids`. +fn fresh<'a>( + ids: impl Iterator + Clone, + pick: impl Fn(&str) -> bool, + mut new_id: impl FnMut(&BTreeSet) -> String, +) -> BTreeMap { + let mut avoid: BTreeSet = ids.clone().cloned().collect(); + let mut out = BTreeMap::new(); + for id in ids.filter(|id| pick(id)) { + let new = new_id(&avoid); + avoid.insert(new.clone()); + out.insert(id.clone(), new); + } + out +} + +/// `id` as `map` renames it. +fn rename(map: &BTreeMap, id: &mut String) { + if let Some(new) = map.get(id.as_str()) { + *id = new.clone(); + } +} diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index 59afad98d..795584595 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -1,3 +1,4 @@ +use super::import_ids::Renames; use super::load::{ext, file_stem, import_summary, load_path, load_with, read, rest_images, sibling_variables, variables_param}; use super::*; @@ -218,8 +219,18 @@ pub(super) fn import(s: &mut Session, p: &Value) -> Result { /// Append `other`'s pages (with their settings and flows, its images, styles and variables) to /// `doc`. Ids are remapped across all pages at once, so instances keep their main, instance layers /// their source and interactions and flows their targets wherever those are. Styles, variables and -/// collections whose id the document already has are kept as they are. +/// collections the document already has (the same under the same id, as when a file comes in +/// again) and library copies are shared; others whose id the document uses for something else get +/// new ids, and what comes in names them by those ([`Renames`]). pub(super) fn append_pages(doc: &mut Document, other: &Document) -> Result> { + let renames = Renames::new(doc, other); + let renamed; + let other = if renames.is_empty() { + other + } else { + renamed = renames.applied(other); + &renamed + }; for (k, v) in &other.images { doc.images.entry(k.clone()).or_insert_with(|| v.clone()); } diff --git a/crates/engine/src/import_ids_tests.rs b/crates/engine/src/import_ids_tests.rs new file mode 100644 index 000000000..263aa8169 --- /dev/null +++ b/crates/engine/src/import_ids_tests.rs @@ -0,0 +1,172 @@ +//! `file.import` of a file whose style, variable and collection ids the document already uses for +//! other things: ids are numbered per file, so two files made apart share them. The imported +//! layers keep their own variables, modes and styles, and a file imported again still shares what +//! it brought the first time. + +use base64::Engine as _; +use figcraft_doc::proto::Action; +use figcraft_doc::{Document, Node, NodeId, VariableValue}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::components::tests::ex; +use crate::params::id_of; + +fn idv(v: &Value) -> NodeId { + id_of(&v["id"]).unwrap() +} + +fn var_id(s: &Session, name: &str) -> String { + s.doc().unwrap().variables.get(name).unwrap().id.clone() +} + +fn fill(s: &Session, id: NodeId) -> String { + s.doc().unwrap().node(id).unwrap().fills.first().and_then(|p| p.solid_color()).map(|c| c.to_hex()).unwrap_or_default() +} + +/// The document's file: collection A (Light, Dark) with colours `a1`…`a4`, paint style `Host` +/// and a frame filled with `a1`. +fn host() -> (Session, NodeId) { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "A", "modes": ["Light", "Dark"]})); + for i in 1..=4 { + ex(&mut s, "variable.create", json!({"collection": "A", "name": format!("a{i}"), "type": "color", "value": format!("#A{i}0000")})); + } + ex(&mut s, "style.create", json!({"type": "paint", "name": "Host", "value": "#FF0000"})); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "name": "Host frame"}))); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "fill", "variable": "a1"})); + (s, f) +} + +/// Another file made apart: collection B (Light, Dark) with `b1` (green in each mode), `b2` (an +/// alias of `b1`) and `size`; paint style `Brand` bound to `b1`. Frame `Card` shows B in Dark, its +/// corners bound to `size`; in it `Swatch` is filled with `b2` and on click sets B to Dark and +/// `size` to `size + 1`, and `Styled` uses `Brand`. +fn other() -> Session { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "B", "modes": ["Light", "Dark"]})); + ex(&mut s, "variable.create", json!({"collection": "B", "name": "b1", "type": "color", "values": {"Light": "#00B000", "Dark": "#004000"}})); + ex(&mut s, "variable.create", json!({"collection": "B", "name": "b2", "type": "color", "value": {"alias": "b1"}})); + ex(&mut s, "variable.create", json!({"collection": "B", "name": "size", "type": "number", "value": 8})); + let brand = ex(&mut s, "style.create", json!({"type": "paint", "name": "Brand", "value": "#00B000"}))["id"].clone(); + ex(&mut s, "style.bind", json!({"style": brand, "field": "fill", "variable": "b1"})); + let card = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 100, "name": "Card"}))); + ex(&mut s, "variable.setMode", json!({"ids": [card], "collection": "B", "mode": "Dark"})); + ex(&mut s, "variable.bind", json!({"ids": [card], "field": "cornerRadius", "variable": "size"})); + let swatch = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40, "parent": card, "name": "Swatch"}))); + ex(&mut s, "variable.bind", json!({"ids": [swatch], "field": "fill", "variable": "b2"})); + let actions = json!([ + {"type": "setVariableMode", "collection": "B", "mode": "Dark"}, + {"type": "setVariable", "variable": "size", "expression": "size + 1"} + ]); + ex(&mut s, "proto.interaction.add", json!({"id": swatch, "actions": actions})); + let styled = idv(&ex(&mut s, "shape.rectangle", json!({"x": 60, "y": 10, "width": 40, "height": 40, "parent": card, "name": "Styled"}))); + ex(&mut s, "style.apply", json!({"ids": [styled], "style": "Brand"})); + s +} + +fn import(s: &mut Session, file: &Session) -> Value { + let bytes = figcraft_format::save_bytes(file.doc().unwrap(), None).unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(bytes); + ex(s, "file.import", json!({"data": data, "name": "other.figcraft"})) +} + +/// The layers on the pages after the first `kept` pages. +fn layers_after(doc: &Document, kept: usize) -> Vec<&Node> { + doc.pages[kept..].iter().flat_map(|p| doc.subtree(*p).into_iter().skip(1)).filter_map(|id| doc.node(id)).collect() +} + +fn layer<'a>(doc: &'a Document, kept: usize, name: &str) -> &'a Node { + layers_after(doc, kept).into_iter().find(|n| n.name == name).unwrap() +} + +#[test] +fn imported_layers_keep_their_own_variables_and_styles_when_the_ids_are_taken() { + let (mut s, frame) = host(); + let file = other(); + assert_eq!(var_id(&file, "b1"), var_id(&s, "a1"), "the ids must collide for this test"); + assert_eq!(file.doc().unwrap().styles[0].id, s.doc().unwrap().styles[0].id); + let before = s.doc().unwrap().clone(); + import(&mut s, &file); + let doc = s.doc().unwrap(); + assert_eq!(doc.variables.variables.len(), 4 + 3); + assert_eq!(doc.variables.collections.iter().map(|c| c.name.as_str()).collect::>(), ["A", "B"]); + assert_eq!(doc.styles.iter().map(|st| st.name.as_str()).collect::>(), ["Host", "Brand"]); + // The document's own are as they were. + assert_eq!(doc.variables.variables[..4], before.variables.variables[..]); + assert_eq!(doc.variables.collections[0], before.variables.collections[0]); + assert_eq!(doc.styles[0], before.styles[0]); + // Everything imported names B's variables, B and Brand. + let b = doc.variables.collection("B").unwrap().id.clone(); + let imported = layers_after(doc, before.pages.len()); + assert!(imported.iter().any(|n| !n.bound.is_empty())); + for n in imported { + for v in n.bound.values() { + assert_eq!(doc.variables.get_by_id(v).unwrap().collection, b, "{}: {v}", n.name); + } + assert!(n.var_modes.keys().all(|c| *c == b), "{}: {:?}", n.name, n.var_modes); + if let Some(st) = &n.styles.fill { + assert_eq!(doc.styles.iter().find(|x| x.id == *st).unwrap().name, "Brand"); + } + } + let brand = doc.styles.iter().find(|st| st.name == "Brand").unwrap(); + assert_eq!(brand.bound.values().map(|v| doc.variables.get_by_id(v).unwrap().name.as_str()).collect::>(), ["b1"]); + // Bindings applied again leave the imported layers alone. + let swatch = layer(doc, before.pages.len(), "Swatch").id; + let a2 = var_id(&s, "a2"); + ex(&mut s, "variable.set", json!({"variable": a2, "value": "#123456"})); + assert_eq!(fill(&s, swatch), "004000"); + assert_eq!(fill(&s, frame), "A10000"); + assert!(s.doc().unwrap().validate().is_empty()); +} + +#[test] +fn an_alias_a_frame_mode_and_prototype_actions_follow_the_renamed_collection() { + let (mut s, _) = host(); + let file = other(); + let kept = s.doc().unwrap().pages.len(); + import(&mut s, &file); + let doc = s.doc().unwrap(); + let vars = &doc.variables; + let b = vars.collection("B").unwrap(); + let in_b = |name: &str| vars.variables.iter().find(|v| v.name == name && v.collection == b.id).unwrap(); + let (b1, b2, size) = (in_b("b1"), in_b("b2"), in_b("size")); + assert!(b2.values.values().all(|v| *v == VariableValue::Alias(b1.id.clone())), "{:?}", b2.values); + // B's mode ids name B's new id, and its variables' values are by those. + let modes: Vec<&str> = b.modes.iter().map(|m| m.id.as_str()).collect(); + assert_eq!(modes, [format!("{}/mode1", b.id), format!("{}/mode2", b.id)]); + assert!([b1, b2, size].iter().all(|v| v.values.keys().all(|m| modes.contains(&m.as_str())))); + // The frame shows B in Dark: its mode is one of B's. + let card = layer(doc, kept, "Card"); + let dark = b.find_mode("Dark").unwrap().id.clone(); + assert_eq!(card.var_modes.iter().collect::>(), [(&b.id, &dark)]); + assert_eq!(card.bound.get("cornerRadius"), Some(&size.id)); + let swatch = layer(doc, kept, "Swatch"); + assert_eq!(swatch.bound.get("fill"), Some(&b2.id)); + let shown = vars.resolve(&b2.id, &doc.modes_for(swatch.id)); + assert!(matches!(shown, Some(VariableValue::Color(c)) if c.to_hex() == "004000"), "{shown:?}"); + let actions = &swatch.interactions[0].actions; + assert_eq!(actions[0], Action::SetVariableMode { collection: b.id.clone(), mode: dark }); + let Action::SetVariable { variable, expr: Some(e), .. } = &actions[1] else { panic!("{actions:?}") }; + assert_eq!((variable, e.variables()), (&size.id, vec![size.id.as_str()])); +} + +#[test] +fn importing_the_same_file_again_shares_what_it_brought() { + let file = other(); + let mut s = other(); + let before = s.doc().unwrap().clone(); + import(&mut s, &file); + let doc = s.doc().unwrap(); + assert_eq!(doc.variables, before.variables); + assert_eq!(doc.styles, before.styles); + let swatch = layer(doc, before.pages.len(), "Swatch"); + assert_eq!(swatch.bound.get("fill"), Some(&var_id(&s, "b2"))); + // A file imported into an empty one, then again: one copy of its variables. + let mut t = Session::new(); + import(&mut t, &file); + import(&mut t, &file); + let doc = t.doc().unwrap(); + assert_eq!((doc.variables.variables.len(), doc.variables.collections.len(), doc.styles.len()), (3, 1, 1)); + assert!(layers_after(doc, 1).iter().flat_map(|n| n.bound.values()).all(|v| doc.variables.get_by_id(v).is_some())); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e919444e2..0dee66b47 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -367,6 +367,8 @@ mod images_left_in_file_tests; #[cfg(test)] mod import_export_tests; #[cfg(test)] +mod import_ids_tests; +#[cfg(test)] mod import_journal_tests; #[cfg(test)] mod inspect_behaviour_tests; diff --git a/crates/engine/src/library_variables_tests.rs b/crates/engine/src/library_variables_tests.rs index 5a6b329d3..bc82f7a94 100644 --- a/crates/engine/src/library_variables_tests.rs +++ b/crates/engine/src/library_variables_tests.rs @@ -385,6 +385,34 @@ fn library_components_keep_their_variable_bindings() { let _ = std::fs::remove_dir_all(&d); } +#[test] +fn a_file_bringing_older_copies_of_the_same_library_variables_shares_them() { + let d = dir("older-copies"); + let lib_path = path_str(&d.join("kit.figcraft")); + let mut lib = Session::new(); + theme(&mut lib); + let lid = publish_to(&mut lib, &lib_path); + let mut s = Session::new(); + ex(&mut s, "library.add", json!({"path": lib_path})); + let r = idv(&ex(&mut s, "shape.rectangle", json!({"width": 10, "height": 10, "name": "Swatch"}))); + ex(&mut s, "library.bindVariable", json!({"library": lid, "variable": "primary", "field": "fill", "ids": [r]})); + let old_path = path_str(&d.join("old.figcraft")); + ex(&mut s, "file.saveAs", json!({"path": old_path})); + // The copies take an update; the saved file keeps the older ones under the same ids. + ex(&mut lib, "variable.set", json!({"variable": "primary", "mode": "Light", "value": "#444444"})); + republish(&mut lib); + ex(&mut s, "library.acceptUpdates", json!({})); + let before = s.doc().unwrap().clone(); + ex(&mut s, "file.import", json!({"path": old_path})); + let doc = s.doc().unwrap(); + assert_eq!((&doc.variables, &doc.libraries.variables), (&before.variables, &before.libraries.variables), "shared by id, as before"); + let swatches: Vec<&Node> = doc.nodes().filter(|n| n.name == "Swatch").collect(); + assert_eq!(swatches.len(), 2); + assert!(swatches.iter().all(|n| n.bound.get("fill") == Some(©_of(&s, "primary").id))); + healthy(&s); + let _ = std::fs::remove_dir_all(&d); +} + #[test] fn library_variable_commands_fail_cleanly() { let mut s = Session::new(); From 53ebf1f39c51361282ca55e18c83fbffed2f9a34 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:40:54 -0500 Subject: [PATCH 036/138] fix(pathops): sanitize a brush's width profile once before sampling (#1948) --- crates/pathops/src/brush.rs | 4 +++- crates/pathops/src/brush_tests.rs | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/pathops/src/brush.rs b/crates/pathops/src/brush.rs index bfd7f9212..b5875d4a2 100644 --- a/crates/pathops/src/brush.rs +++ b/crates/pathops/src/brush.rs @@ -131,7 +131,9 @@ pub fn outline(path: &BezPath, width: f64, props: &StrokeProps, brush: &Brush) - let p = preset(&brush.preset)?; let unit = shape(p.id)?; let lines = polylines(path)?; - let scale = |t: f64| width * props.profile().map_or(1.0, |pr| pr.scale_at(t)); + // Sanitized once: at most 64 points, so each sample's symmetry scan stays cheap. + let profile = props.profile().map(|pr| pr.sanitized()); + let scale = |t: f64| width * profile.as_ref().map_or(1.0, |pr| pr.scale_at(t)); let mut out = BezPath::new(); match p.kind { BrushKind::Stretch => { diff --git a/crates/pathops/src/brush_tests.rs b/crates/pathops/src/brush_tests.rs index 403935ddd..81cc55e10 100644 --- a/crates/pathops/src/brush_tests.rs +++ b/crates/pathops/src/brush_tests.rs @@ -72,3 +72,14 @@ fn a_width_profile_scales_the_brush() { let (first, last) = (parts.first().unwrap().bounding_box(), parts.last().unwrap().bounding_box()); assert!(last.width() > first.width() * 3.0, "{first:?} {last:?}"); } + +#[test] +fn an_unsanitized_profile_is_bounded_before_sampling() { + // 100k points, all past the 64-point cap and out of range: the brush reads the clamped profile. + let raw = WidthProfile { points: (0..100_000).map(|i| figcraft_doc::WidthPoint::new(f64::from(i), 1e300)).collect() }; + let b = brush("taper"); + let mut p = props(1.0, &b); + p.width_profile = Some(raw); + let out = outline(&line(50.0), 1.0, &p, &b).unwrap(); + assert!(out.bounding_box().height() <= 2.0 * WidthProfile::MAX_SCALE); +} From cfb29a4a9617b75f9072188c15ad1e24307850f8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 17:58:09 -0500 Subject: [PATCH 037/138] perf(text): compute each glyph's cluster end once per run (#1963) --- crates/text/src/layout.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index f2c587206..dd728916b 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -1698,11 +1698,22 @@ fn shape_segment(chars: &[char], seg: &Segment, face: &Arc, features: &[Fe } let (script_scale, script_shift) = synth.map_or((1.0, 0.0), |(_, up)| if up { face.superscript } else { face.subscript }); let n = raw.len(); + // Cluster end: the next larger cluster value, else the segment end. A glyph in the same + // cluster as the next one shares its end, so many glyphs of one cluster aren't rescanned. + let mut cends = vec![0usize; n]; + for gi in (0..n).rev() { + let Some(&(_, cl, ..)) = raw.get(gi) else { continue }; + let cl = cl as usize; + let shared = raw.get(gi + 1).filter(|r| r.1 as usize == cl).and_then(|_| cends.get(gi + 1).copied()); + let cend = shared.unwrap_or_else(|| raw.iter().skip(gi + 1).map(|r| r.1 as usize).find(|c| *c > cl).unwrap_or(end).max(cl + 1)); + if let Some(slot) = cends.get_mut(gi) { + *slot = cend; + } + } for gi in 0..n { let Some(&(gid, cl, xa, xo, yo)) = raw.get(gi) else { continue }; let cl = cl as usize; - // Cluster end: the next larger cluster value, else the segment end. - let cend = raw.iter().skip(gi + 1).map(|r| r.1 as usize).find(|c| *c > cl).unwrap_or(end).max(cl + 1); + let cend = cends.get(gi).copied().unwrap_or(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 } * script_scale; From fb4d0b50352e97debc98b212ba6e2795a6c3d4b6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 17:58:27 -0500 Subject: [PATCH 038/138] perf(doc,engine): rebuild a widget by removing its children in one pass (#1967) --- crates/doc/src/lib.rs | 13 +++++++++++++ crates/doc/src/tests.rs | 14 ++++++++++++++ crates/engine/src/extensions/widgets.rs | 4 +--- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 89eb97269..0181ffd21 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -574,6 +574,19 @@ impl Document { Ok(()) } + /// Remove every child of `id` with its subtree, in one pass over `id`'s child list (removing + /// them one by one would search that list once per child). + pub fn remove_children(&mut self, id: NodeId) -> DocResult<()> { + let kids = std::mem::take(&mut self.get_mut(id)?.children); + for c in kids { + for d in self.subtree(c) { + self.nodes.remove(&d); + self.dirty.touch(d); + } + } + Ok(()) + } + /// Whether sections may go in `parent`: a page or another section (never a frame or a group). pub fn takes_sections(&self, parent: NodeId) -> bool { self.node(parent).is_some_and(|p| p.is_page() || matches!(p.kind, NodeKind::Section { .. })) diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a0e3e17b0..a5c8e8e7a 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -846,3 +846,17 @@ 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 remove_children_removes_every_subtree_and_keeps_the_parent() { + let mut doc = Document::new("T"); + let page = doc.first_page().unwrap(); + let frame = doc.create(page, NodeKind::Frame, "F", 0.0, 0.0, 100.0, 100.0).unwrap(); + let inner = doc.create(frame, NodeKind::Frame, "Inner", 0.0, 0.0, 10.0, 10.0).unwrap(); + let leaf = doc.create(inner, NodeKind::Rectangle, "Leaf", 0.0, 0.0, 5.0, 5.0).unwrap(); + let other = doc.create(page, NodeKind::Rectangle, "Other", 0.0, 0.0, 5.0, 5.0).unwrap(); + doc.remove_children(frame).unwrap(); + assert!(doc.contains(frame) && doc.contains(other)); + assert!(!doc.contains(inner) && !doc.contains(leaf)); + assert!(doc.get(frame).unwrap().children.is_empty()); +} diff --git a/crates/engine/src/extensions/widgets.rs b/crates/engine/src/extensions/widgets.rs index 6386ceab4..498fbeb8a 100644 --- a/crates/engine/src/extensions/widgets.rs +++ b/crates/engine/src/extensions/widgets.rs @@ -243,9 +243,7 @@ fn build(s: &mut Session, plugin: &str, w: NodeId, r: &WidgetRender) -> Result<( if !is_widget(n) || n.plugin_data.get(PLUGIN).map(String::as_str) != Some(plugin) { return Err(bad(cmd, "the layer is no longer this plugin's widget")); } - for c in n.children.clone() { - doc.remove(c)?; - } + doc.remove_children(w)?; crate::cmd::props::apply(cmd, doc, w, &props(&r.root, true))?; let n = doc.get_mut(w)?; n.locked = false; From 3265cbca404644c70fb08035536882960d9f15c3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 17:58:39 -0500 Subject: [PATCH 039/138] perf(engine): look up a component's asset root once per usage report, and skip mode migration without instances (#1966) --- crates/engine/src/assets/components.rs | 4 ++++ crates/engine/src/assets/library_server.rs | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/assets/components.rs b/crates/engine/src/assets/components.rs index cee9b0bb2..7ddb22427 100644 --- a/crates/engine/src/assets/components.rs +++ b/crates/engine/src/assets/components.rs @@ -147,6 +147,10 @@ pub fn inside_instance(doc: &Document, id: NodeId) -> bool { /// main layer's, for files from before `modes` was an override group. Copies follow their main /// layer's modes, so a layer on other modes chose them itself. pub fn mark_layer_modes(doc: &mut Document) { + // Without an instance nothing can be inside one: skip the per-layer ancestry lookups. + if !doc.nodes().any(|n| matches!(n.kind, NodeKind::Instance { .. })) { + return; + } let chose: Vec = doc .nodes() .filter(|n| !n.overrides.contains("modes") && n.source.and_then(|s| doc.node(s)).is_some_and(|m| m.var_modes != n.var_modes)) diff --git a/crates/engine/src/assets/library_server.rs b/crates/engine/src/assets/library_server.rs index 47d15a954..81889be5d 100644 --- a/crates/engine/src/assets/library_server.rs +++ b/crates/engine/src/assets/library_server.rs @@ -79,10 +79,13 @@ pub fn usage(doc: &Document, library: &str) -> Usage { let records: std::collections::BTreeMap = doc.libraries.components.iter().filter(|r| r.library == library).map(|r| (r.root, r.key)).collect(); if !records.is_empty() { + // One component's asset root is looked up once, however many instances use it. + let mut roots = std::collections::BTreeMap::>::new(); for n in doc.nodes() { if let NodeKind::Instance { component, .. } = &n.kind && store.is_none_or(|st| doc.page_of(n.id) != Some(st)) - && let Some(key) = crate::library::asset_root(doc, *component).and_then(|r| records.get(&r)) + && let Some(key) = + roots.entry(*component).or_insert_with(|| crate::library::asset_root(doc, *component)).and_then(|r| records.get(&r)) { let c = counts.entry(*key).or_default(); *c = c.saturating_add(1); From 4bb35d5266aae4dfb156cd85561c4d81198cddd9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 17:58:51 -0500 Subject: [PATCH 040/138] perf(collab): check a replaced list's entries against sets, not a scan per entry (#1962) --- crates/collab/src/change.rs | 11 +++++++++++ crates/collab/src/server.rs | 14 ++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index bcc09ad86..442376f37 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -333,6 +333,17 @@ impl Change { } impl Entry { + /// The synced list this entry belongs to (`None` for entries kept in maps). + pub(crate) fn family(&self) -> Option { + match self { + Entry::Style(_) => Some(Family::Styles), + Entry::Comment(_) => Some(Family::Comments), + Entry::Collection(_) => Some(Family::Collections), + Entry::Variable(_) => Some(Family::Variables), + Entry::DevSnapshot(_) | Entry::Image(_) | Entry::Ballot(_) => None, + } + } + /// The client id space the entry's id lies in ([`figcraft_doc::ids`]): ids made during a live /// session carry their creator's client id, ids from before and ids of other forms are in /// space 0. `None` for entries keyed by something else (dev snapshots by layer, images by diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index b94cb5726..d5af681b2 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use figcraft_doc::{Document, NodeId}; use serde::{Deserialize, Serialize}; -use crate::change::{Change, Entry, Prop, Target}; +use crate::change::{Change, Entry, Family, Prop, Target}; use crate::message::{ Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_signals, }; @@ -557,6 +557,7 @@ impl Server { fn check_entries(&self, from: u32, changes: &[Change], after: &Document) -> Result, Error> { let before = self.state.document(); let mut touched: BTreeSet = BTreeSet::new(); + let mut listed: BTreeMap, BTreeSet)> = BTreeMap::new(); for c in changes { match c { Change::Put { entry, .. } | Change::Remove { entry } if entry.id_space().is_some() => { @@ -565,8 +566,10 @@ impl Server { // A whole list replaced (the fallback for lists whose ids aren't unique). Change::SetDoc { prop, .. } => { if let Some(Ok(family)) = prop.list() { - touched.extend(docprops::entries(before, family)); - touched.extend(docprops::entries(after, family)); + let (b, a) = (docprops::entries(before, family), docprops::entries(after, family)); + touched.extend(b.iter().chain(&a).cloned()); + // Looked up in sets below: a linear search per entry would be quadratic. + listed.entry(family).or_insert_with(|| (b.into_iter().collect(), a.into_iter().collect())); } } _ => {} @@ -574,7 +577,10 @@ impl Server { } let mut out = Vec::new(); for entry in touched { - let (was, now) = (docprops::has(before, &entry), docprops::has(after, &entry)); + let (was, now) = match entry.family().and_then(|f| listed.get(&f)) { + Some((b, a)) => (b.contains(&entry), a.contains(&entry)), + None => (docprops::has(before, &entry), docprops::has(after, &entry)), + }; if was == now { continue; } From 2dc7bed2a0fd4c516a2edfded323efcc0478ea90 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 21:08:19 -0500 Subject: [PATCH 041/138] M12: connectors attached to a side start 4 pt outside the border (#1916) A connector end attached to a side was routed from the middle of that side, so the stroke's centre line started on the border and half its width plus the round cap lay on the fill, and several connectors leaving one side piled up into a knot sticking into the card. FigJam starts the line a few pixels outside the border and connectors leaving one side run together along the side's normal before they fan out (the issue's screenshots). `board_route::END_GAP` (4 pt): an end attached to a side (`RouteEnd::Box`) starts that far outside it along the side's normal; an end placed by hand on the object (`RouteEnd::On`) keeps its exact point; a free end is unchanged. The pinned route coordinates in the engine, format and UI tests move with it; the overlay's attach points stay on the border. Docs: the Connectors rows, status line and history of boards-parity.md. Co-Authored-By: Claude Fable 5.1 --- crates/doc/src/board_route.rs | 15 ++++-- crates/doc/src/board_route_tests.rs | 49 +++++++++++++++++++ crates/doc/src/lib.rs | 4 +- crates/engine/src/board_connector_tests.rs | 26 +++++----- crates/engine/src/board_reshape_tests.rs | 12 ++--- crates/engine/src/board_tests.rs | 22 +++++---- crates/engine/src/board_tools_tests.rs | 14 +++--- crates/engine/src/boards/board/tools.rs | 12 +++-- crates/engine/src/canvas/snap.rs | 18 +++++-- crates/engine/src/connector_anywhere_tests.rs | 2 +- crates/format/src/fig/tail_tests.rs | 6 +-- crates/ui-egui/src/board_ui_tests.rs | 2 +- docs/boards-parity.md | 7 +-- 13 files changed, 136 insertions(+), 53 deletions(-) create mode 100644 crates/doc/src/board_route_tests.rs diff --git a/crates/doc/src/board_route.rs b/crates/doc/src/board_route.rs index 1aa45c810..7949674d9 100644 --- a/crates/doc/src/board_route.rs +++ b/crates/doc/src/board_route.rs @@ -28,9 +28,15 @@ impl RouteEnd { /// How far an elbow connector going around the objects it joins keeps from them. const ROOM: f64 = 24.0; -/// The points a connector runs through from `from` to `to`: from the middle of the side of each -/// box facing the other end (or the side it names), straight, in right angles, or (curved) its two -/// ends with the curve's two control points between them. `None` when a point isn't finite. +/// How far outside the border a connector attached to a side starts and ends (#1916): the stroke's +/// round cap never lies on the fill, and several connectors leaving one side run together along the +/// side's normal for this much before they part, as FigJam's do. +pub const END_GAP: f64 = 4.0; + +/// The points a connector runs through from `from` to `to`: from [`END_GAP`] outside the middle of +/// the side of each box facing the other end (or the side it names), straight, in right angles, or +/// (curved) its two ends with the curve's two control points between them. `None` when a point isn't +/// finite. pub fn route_points(from: RouteEnd, to: RouteEnd, routing: Routing) -> Option> { let (p0, s0) = attach(from, to.centre()); let (p1, s1) = attach(to, from.centre()); @@ -169,8 +175,9 @@ fn attach(e: RouteEnd, other: Point) -> (Point, Option) { RouteEnd::Point(p) => (p, None), RouteEnd::Box(b, side) => { let side = named_or_facing(b, side, other); - (side.point(b), Some(side)) + (side.point(b) + side.normal() * END_GAP, Some(side)) } + // Placed by hand: the point is the user's, gap or not. RouteEnd::On(b, side, p) => (p, Some(named_or_facing(b, side, other))), } } diff --git a/crates/doc/src/board_route_tests.rs b/crates/doc/src/board_route_tests.rs new file mode 100644 index 000000000..a1e972cba --- /dev/null +++ b/crates/doc/src/board_route_tests.rs @@ -0,0 +1,49 @@ +//! Connector routes (`board_route`): where an end attached to a side starts (#1916). + +use figcraft_geom::{Point, Rect}; + +use crate::board::{Routing, Side}; +use crate::board_route::{END_GAP, RouteEnd, route_points}; + +fn shape(x: f64, y: f64) -> Rect { + Rect::new(x, y, x + 100.0, y + 60.0) +} + +/// An end attached to a side starts `END_GAP` outside the middle of that side, not on the border, +/// so the stroke never lies on the fill (#1916: FigJam starts the line a few pixels outside). +#[test] +fn an_attached_end_starts_outside_the_border() { + let (a, b) = (shape(0.0, 0.0), shape(300.0, 0.0)); + for routing in [Routing::Straight, Routing::Elbow, Routing::Curved] { + let pts = route_points(RouteEnd::Box(a, Side::Auto), RouteEnd::Box(b, Side::Auto), routing).unwrap(); + assert_eq!(pts.first().copied(), Some(Point::new(100.0 + END_GAP, 30.0)), "{routing:?}: leaves the right side"); + assert_eq!(pts.last().copied(), Some(Point::new(300.0 - END_GAP, 30.0)), "{routing:?}: arrives at the left side"); + } + // A named side, and the gap along its own normal. + let pts = route_points(RouteEnd::Box(a, Side::Bottom), RouteEnd::Point(Point::new(50.0, 200.0)), Routing::Straight).unwrap(); + assert_eq!(pts.first().copied(), Some(Point::new(50.0, 60.0 + END_GAP))); +} + +/// Several connectors leaving one side run together along its normal before they part: an elbow's +/// and a curve's first run leave straight out of the side. +#[test] +fn connectors_from_one_side_leave_together() { + let a = shape(0.0, 0.0); + let (up, down) = (RouteEnd::Box(shape(300.0, -200.0), Side::Auto), RouteEnd::Box(shape(300.0, 200.0), Side::Auto)); + for routing in [Routing::Elbow, Routing::Curved] { + let p = route_points(RouteEnd::Box(a, Side::Right), up, routing).unwrap(); + let q = route_points(RouteEnd::Box(a, Side::Right), down, routing).unwrap(); + assert_eq!(p[0], q[0], "{routing:?}: the same start"); + assert_eq!(p[1].y, p[0].y, "{routing:?}: out along the side's normal first"); + assert_eq!(q[1].y, q[0].y, "{routing:?}: out along the side's normal first"); + } +} + +/// A point placed by hand on the object (`RouteEnd::On`) is the user's: no gap is added. +#[test] +fn a_hand_placed_end_keeps_its_point() { + let a = shape(0.0, 0.0); + let on = Point::new(80.0, 60.0); + let pts = route_points(RouteEnd::On(a, Side::Bottom, on), RouteEnd::Point(Point::new(80.0, 200.0)), Routing::Straight).unwrap(); + assert_eq!(pts.first().copied(), Some(on)); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 0181ffd21..ff6fc3b0f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -27,7 +27,7 @@ pub mod vector_faces; pub mod vector_regions; pub use board::*; -pub use board_route::{RouteEnd, attached_sides, path_handles, reshaped, route_along, route_points}; +pub use board_route::{END_GAP, RouteEnd, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; pub use facilitation::*; @@ -1299,6 +1299,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap) { #[cfg(test)] mod blur_tests; #[cfg(test)] +mod board_route_tests; +#[cfg(test)] mod board_shape_tests; #[cfg(test)] mod boolean_hit_tests; diff --git a/crates/engine/src/board_connector_tests.rs b/crates/engine/src/board_connector_tests.rs index da5b3b924..7b6f2dc0a 100644 --- a/crates/engine/src/board_connector_tests.rs +++ b/crates/engine/src/board_connector_tests.rs @@ -2,7 +2,7 @@ //! command and a drag of the selected connector's end), curved connectors, and elbows that go //! around the objects they join. -use figcraft_doc::{BoardItem, End, NodeKind, Routing, Side}; +use figcraft_doc::{BoardItem, END_GAP, End, NodeKind, Routing, Side}; use figcraft_geom::{Point, Rect}; use serde_json::json; @@ -27,7 +27,7 @@ fn reattach_moves_one_end_and_undoes() { s.execute("board.reattach", &json!({"id": k, "end": "to", "target": c, "side": "top"})).unwrap(); assert_eq!(connector(&s, k).to, End::Node { node: c, side: Side::Top, at: None }); assert_eq!(connector(&s, k).from.node(), Some(a)); - assert!(near(*drawn(&s, k).last().unwrap(), Point::new(650.0, 0.0)), "arrives on c's top: {:?}", drawn(&s, k)); + assert!(near(*drawn(&s, k).last().unwrap(), Point::new(650.0, -END_GAP)), "arrives END_GAP above c's top: {:?}", drawn(&s, k)); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(connector(&s, k).to.node(), Some(b), "one undo step"); // Off into the canvas: the end stays there, free. The selection is the default connector. @@ -107,9 +107,9 @@ fn curved_connectors_leave_and_arrive_along_the_sides() { let NodeKind::Vector { network } = &n.kind else { panic!("a vector") }; assert_eq!((network.vertices.len(), network.segments.len()), (2, 1)); assert!(!network.segments[0].is_straight(), "one curve"); - assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(300.0, 50.0)]); + assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(296.0, 50.0)]); // Side to side in a line: the curve's control points lie on that line, so its box is flat. - assert!(n.height.abs() < 1e-9 && (n.width - 200.0).abs() < 1e-9, "{} × {}", n.width, n.height); + assert!(n.height.abs() < 1e-9 && (n.width - 192.0).abs() < 1e-9, "{} × {}", n.width, n.height); // From a's bottom to c's top: out downwards and in from above; the box holds the whole curve. let k2 = id( &s.execute("board.connector", &json!({"from": a, "to": c, "fromSide": "bottom", "toSide": "top", "style": "curved", "label": "x"})).unwrap(), @@ -146,18 +146,18 @@ fn elbows_go_around_the_objects_they_join() { let pts = drawn(&s, k2); let (ra, rb) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(300.0, 0.0, 400.0, 100.0)); assert!(!through(&pts, ra) && !through(&pts, rb), "{pts:?}"); - assert_eq!(pts.first().copied(), Some(Point::new(0.0, 50.0))); - assert_eq!(pts.last().copied(), Some(Point::new(400.0, 50.0))); + assert_eq!(pts.first().copied(), Some(Point::new(-END_GAP, 50.0))); + assert_eq!(pts.last().copied(), Some(Point::new(400.0 + END_GAP, 50.0))); assert_eq!(pts.len(), 6, "out, over, down and in: {pts:?}"); assert!(pts.iter().all(|p| p.y <= 50.0), "over the top, the nearer way round: {pts:?}"); assert!(pts.windows(2).all(|w| w[0].x == w[1].x || w[0].y == w[1].y), "right angles only"); // Facing each other, the short way stays. - assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(300.0, 50.0)]); + assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(296.0, 50.0)]); // An end at the bottom of b leaving towards a above it: around b's side and up. s.execute("board.reattach", &json!({"id": k2, "end": "to", "target": b, "side": "bottom"})).unwrap(); let pts = drawn(&s, k2); assert!(!through(&pts, ra) && !through(&pts, rb), "{pts:?}"); - assert_eq!(pts.last().copied(), Some(Point::new(350.0, 100.0))); + assert_eq!(pts.last().copied(), Some(Point::new(350.0, 100.0 + END_GAP))); } #[test] @@ -202,8 +202,12 @@ fn the_connector_being_drawn_is_the_one_made() { // Over b: its four attach points, the one the end is at lit, and b outlined. assert_eq!(ov.drop_target, Some(b)); let lit: Vec<[f64; 2]> = ov.attach.iter().filter(|a| a.1).map(|a| a.0).collect(); + // The lit attach point is the side's middle, on the border; the route's end sits + // END_GAP outside it along the side's normal (#1916). let end = *drawn(&s, drawing.id).last().unwrap(); - assert_eq!((ov.attach.len(), lit), (4, vec![[end.x, end.y]]), "{style}"); + assert_eq!(ov.attach.len(), 4, "{style}"); + let [lit] = lit.as_slice() else { panic!("{style}: one lit attach point, got {lit:?}") }; + assert!(((lit[0] - end.x).abs() + (lit[1] - end.y).abs() - END_GAP).abs() < 1e-9, "{style}: {lit:?} is END_GAP inside {end:?}"); } else { assert!(ov.attach.is_empty() && ov.drop_target.is_none(), "a free end"); } @@ -259,7 +263,7 @@ fn an_end_dropped_along_a_side_attaches_to_that_side() { s.pointer(&ev(PointerKind::Up, drop)).unwrap(); assert_eq!(connector(&s, k).from, End::Node { node: a, side, at: None }, "{drop:?}"); if side != Side::Auto { - assert_eq!(drawn(&s, k)[0], side.point(bounds), "the route leaves from that side"); + assert_eq!(drawn(&s, k)[0], side.point(bounds) + side.normal() * END_GAP, "the route leaves from that side, END_GAP out"); } } } @@ -307,5 +311,5 @@ fn a_connector_end_snaps_to_the_attach_point_under_the_pointer() { (connector(&s, k).from, connector(&s, k).to), (End::Node { node: a, side: Side::Right, at: None }, End::Node { node: b, side: Side::Top, at: None }) ); - assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(350.0, 200.0)]); + assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(350.0, 196.0)]); } diff --git a/crates/engine/src/board_reshape_tests.rs b/crates/engine/src/board_reshape_tests.rs index 5a73267e3..ea4572cef 100644 --- a/crates/engine/src/board_reshape_tests.rs +++ b/crates/engine/src/board_reshape_tests.rs @@ -11,8 +11,8 @@ use crate::board::{route, selected_connector_handles}; use crate::board_tests::{board, connector, drawn, id, near}; use crate::tools::{PointerEvent, PointerKind}; -const A: Point = Point::new(100.0, 50.0); -const B: Point = Point::new(300.0, 250.0); +const A: Point = Point::new(104.0, 50.0); +const B: Point = Point::new(296.0, 250.0); /// Shapes a (at the origin) and b (down and to the right), 100 × 100, joined side to side. fn joined(style: &str) -> (Session, NodeId, NodeId, NodeId) { @@ -80,11 +80,11 @@ fn a_reshaped_connector_keeps_the_sides_it_left_by() { fn the_first_and_last_runs_gain_a_run_and_stay_on_their_ends() { let (mut s, _, _, k) = joined("elbow"); reshape(&mut s, k, 0.0, 150.0, 120.0).unwrap(); - assert_eq!(drawn(&s, k), [A, pt(124.0, 50.0), pt(124.0, 120.0), pt(200.0, 120.0), pt(200.0, 250.0), B]); + assert_eq!(drawn(&s, k), [A, pt(128.0, 50.0), pt(128.0, 120.0), pt(200.0, 120.0), pt(200.0, 250.0), B]); let last = drawn(&s, k).len() - 2; reshape(&mut s, k, last as f64, 250.0, 200.0).unwrap(); let pts = drawn(&s, k); - assert_eq!(pts, [A, pt(124.0, 50.0), pt(124.0, 120.0), pt(200.0, 120.0), pt(200.0, 200.0), pt(276.0, 200.0), pt(276.0, 250.0), B]); + assert_eq!(pts, [A, pt(128.0, 50.0), pt(128.0, 120.0), pt(200.0, 120.0), pt(200.0, 200.0), pt(272.0, 200.0), pt(272.0, 250.0), B]); assert!(right_angled(&pts)); } @@ -97,8 +97,8 @@ fn a_lone_run_gains_a_run_at_each_end() { let k = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "elbow"})).unwrap(), "id"); assert_eq!(drawn(&s, k).len(), 2); reshape(&mut s, k, 0.0, 200.0, -40.0).unwrap(); - let (l, r) = (pt(100.0, 50.0), pt(300.0, 50.0)); - assert_eq!(drawn(&s, k), [l, pt(124.0, 50.0), pt(124.0, -40.0), pt(276.0, -40.0), pt(276.0, 50.0), r]); + let (l, r) = (pt(104.0, 50.0), pt(296.0, 50.0)); + assert_eq!(drawn(&s, k), [l, pt(128.0, 50.0), pt(128.0, -40.0), pt(272.0, -40.0), pt(272.0, 50.0), r]); } #[test] diff --git a/crates/engine/src/board_tests.rs b/crates/engine/src/board_tests.rs index 6849ac421..9e99bd1c9 100644 --- a/crates/engine/src/board_tests.rs +++ b/crates/engine/src/board_tests.rs @@ -168,7 +168,7 @@ fn connectors_follow_what_they_join_and_undo_with_it() { let b = id(&s.execute("board.sticky", &json!({"x": 400, "y": 0})).unwrap(), "id"); let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight", "label": "then"})).unwrap(), "id"); let pts = drawn(&s, c); - assert!(near(pts[0], Point::new(200.0, 100.0)) && near(pts[1], Point::new(400.0, 100.0)), "{pts:?}"); + assert!(near(pts[0], Point::new(204.0, 100.0)) && near(pts[1], Point::new(396.0, 100.0)), "{pts:?}"); assert_eq!(node(&s, c).stroke.cap_end, StrokeCap::TriangleArrow); // Its label sits at the middle. let label = crate::board::label_of(s.doc().unwrap(), c).unwrap(); @@ -178,19 +178,19 @@ fn connectors_follow_what_they_join_and_undo_with_it() { s.execute("board.setStyle", &json!({"ids": [c], "style": "elbow"})).unwrap(); s.execute("transform.move", &json!({"ids": [b], "dx": 0, "dy": 300})).unwrap(); let pts = drawn(&s, c); - assert!(near(pts[0], Point::new(200.0, 100.0)) && near(*pts.last().unwrap(), Point::new(400.0, 400.0)), "{pts:?}"); + assert!(near(pts[0], Point::new(204.0, 100.0)) && near(*pts.last().unwrap(), Point::new(396.0, 400.0)), "{pts:?}"); assert!(pts.windows(2).all(|w| w[0].x == w[1].x || w[0].y == w[1].y), "right angles: {pts:?}"); // Undo takes the move back and the route with it. s.execute("edit.undo", &json!({})).unwrap(); - assert!(near(*drawn(&s, c).last().unwrap(), Point::new(400.0, 100.0))); + assert!(near(*drawn(&s, c).last().unwrap(), Point::new(396.0, 100.0))); // A deleted end stays where it was, as a point. s.execute("edit.delete", &json!({"ids": [b]})).unwrap(); assert!(matches!(connector(&s, c).to, End::Point { .. })); - assert!(near(*drawn(&s, c).last().unwrap(), Point::new(400.0, 100.0))); + assert!(near(*drawn(&s, c).last().unwrap(), Point::new(396.0, 100.0))); // A connector moved on its own takes its free end along; the attached one stays. s.execute("transform.move", &json!({"ids": [c], "dx": 0, "dy": 50})).unwrap(); - assert!(matches!(connector(&s, c).to, End::Point { x, y } if x == 400.0 && y == 150.0), "{:?}", connector(&s, c)); - assert!(near(drawn(&s, c)[0], Point::new(200.0, 100.0))); + assert!(matches!(connector(&s, c).to, End::Point { x, y } if x == 396.0 && y == 150.0), "{:?}", connector(&s, c)); + assert!(near(drawn(&s, c)[0], Point::new(204.0, 100.0))); // Deleting the connector takes its label. s.execute("edit.delete", &json!({"ids": [c]})).unwrap(); assert!(!s.doc().unwrap().contains(label)); @@ -210,8 +210,8 @@ fn routes_are_the_same_for_the_same_document() { let doc = s.doc().unwrap(); let r = route(doc, &c).unwrap(); assert_eq!(r, route(&doc.clone(), &c).unwrap()); - // Down out of the bottom, across halfway, down into the point. - assert_eq!(r, vec![Point::new(80.0, 160.0), Point::new(80.0, 330.0), Point::new(300.0, 330.0), Point::new(300.0, 500.0)]); + // Down out of the bottom (END_GAP below it), across halfway, down into the point. + assert_eq!(r, vec![Point::new(80.0, 164.0), Point::new(80.0, 332.0), Point::new(300.0, 332.0), Point::new(300.0, 500.0)]); } #[test] @@ -338,7 +338,7 @@ fn boards_sync_in_live_sessions() { let doc = room.server.document(); let NodeKind::Vector { network } = &doc.node(c).unwrap().kind else { panic!("not a vector") }; let end = doc.world_transform(c) * network.vertices.last().unwrap().point(); - assert_eq!(end, Point::new(400.0, 350.0), "to the moved sticky's facing side"); + assert_eq!(end, Point::new(396.0, 350.0), "to END_GAP before the moved sticky's facing side"); assert_eq!(doc.node(a).unwrap().fills[0].solid_color(), board_color("violet")); } @@ -410,7 +410,9 @@ fn a_press_on_a_stickys_background_picks_and_drags_it() { s.pointer(&PointerEvent::at(PointerKind::Up, 100.0, 450.0, 1.0)).unwrap(); assert_eq!(s.selection(), vec![a]); assert_eq!(node(&s, a).transform.translation().y, 300.0); - assert!(near(drawn(&s, c)[0], Point::new(200.0, 400.0)), "the connector followed the drag: {:?}", drawn(&s, c)); + // Its own connector's start, END_GAP outside its edge, is no snap target for it (#1916). + assert_eq!(node(&s, a).transform.translation().x, 0.0, "not nudged sideways by its own connector"); + assert!(near(drawn(&s, c)[0], Point::new(204.0, 400.0)), "the connector followed the drag: {:?}", drawn(&s, c)); } #[test] diff --git a/crates/engine/src/board_tools_tests.rs b/crates/engine/src/board_tools_tests.rs index 6862e4219..24e6df7dd 100644 --- a/crates/engine/src/board_tools_tests.rs +++ b/crates/engine/src/board_tools_tests.rs @@ -100,18 +100,18 @@ fn routes_take_named_sides_and_free_points() { let side = |n, side| End::Node { node: n, side, at: None }; let p = |x, y| End::Point { x, y }; let pt = Point::new; - // Side to side: out, across halfway, in. - assert_eq!(elbow(side(a, Side::Right), side(b, Side::Left)), vec![pt(100.0, 50.0), pt(200.0, 50.0), pt(200.0, 350.0), pt(300.0, 350.0)]); + // Side to side: out (from END_GAP outside each side), across halfway, in. + assert_eq!(elbow(side(a, Side::Right), side(b, Side::Left)), vec![pt(104.0, 50.0), pt(200.0, 50.0), pt(200.0, 350.0), pt(296.0, 350.0)]); // A side and a top or bottom: one turn. - assert_eq!(elbow(side(a, Side::Right), side(b, Side::Top)), vec![pt(100.0, 50.0), pt(350.0, 50.0), pt(350.0, 300.0)]); - assert_eq!(elbow(side(a, Side::Bottom), side(b, Side::Left)), vec![pt(50.0, 100.0), pt(50.0, 350.0), pt(300.0, 350.0)]); + assert_eq!(elbow(side(a, Side::Right), side(b, Side::Top)), vec![pt(104.0, 50.0), pt(350.0, 50.0), pt(350.0, 296.0)]); + assert_eq!(elbow(side(a, Side::Bottom), side(b, Side::Left)), vec![pt(50.0, 104.0), pt(50.0, 350.0), pt(296.0, 350.0)]); // Two free points: the longer way first; in a line, no turns. assert_eq!(elbow(p(0.0, 0.0), p(100.0, 40.0)), vec![pt(0.0, 0.0), pt(50.0, 0.0), pt(50.0, 40.0), pt(100.0, 40.0)]); assert_eq!(elbow(p(0.0, 0.0), p(100.0, 0.0)), vec![pt(0.0, 0.0), pt(100.0, 0.0)]); // An automatic side faces the other end. let straight = route(doc, &figcraft_doc::Connector { from: side(a, Side::Auto), to: p(50.0, 500.0), routing: figcraft_doc::Routing::Straight, path: None }); - assert_eq!(straight.unwrap(), vec![pt(50.0, 100.0), pt(50.0, 500.0)]); + assert_eq!(straight.unwrap(), vec![pt(50.0, 104.0), pt(50.0, 500.0)]); assert_eq!(Side::from_id("TOP"), Some(Side::Top)); assert_eq!(Side::from_id("inside"), None); // The same place twice is refused, as are a side that doesn't exist and a point without numbers. @@ -128,10 +128,10 @@ fn a_connector_follows_a_layer_whose_section_moves_and_ignores_unrelated_edits() let a = id(&s.execute("board.sticky", &json!({"x": 50, "y": 50, "parent": sec})).unwrap(), "id"); let b = id(&s.execute("board.stamp", &json!({"x": 800, "y": 150})).unwrap(), "id"); let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight"})).unwrap(), "id"); - assert!(near(drawn(&s, c)[0], Point::new(250.0, 150.0))); + assert!(near(drawn(&s, c)[0], Point::new(254.0, 150.0))); // Only the section is edited; the sticky inside it moves with it, and so does the connector. s.execute("transform.move", &json!({"ids": [sec], "dx": 0, "dy": 100})).unwrap(); - assert!(near(drawn(&s, c)[0], Point::new(250.0, 250.0)), "{:?}", drawn(&s, c)); + assert!(near(drawn(&s, c)[0], Point::new(254.0, 250.0)), "{:?}", drawn(&s, c)); // An edit that touches neither end leaves the connector as it was. let before = s.doc().unwrap().node_arc(c).cloned().unwrap(); s.execute("board.sticky", &json!({"x": 0, "y": 900})).unwrap(); diff --git a/crates/engine/src/boards/board/tools.rs b/crates/engine/src/boards/board/tools.rs index cf4753357..71f0dcc5b 100644 --- a/crates/engine/src/boards/board/tools.rs +++ b/crates/engine/src/boards/board/tools.rs @@ -133,13 +133,19 @@ impl Session { (to.node().is_none() || to.node() != from.node()).then_some(to) } - /// The object `end` is on (if any) outlined, with its attach points; the one the end is at - /// (`at`, else its named side's) lit. + /// The object `end` is on (if any) outlined, with its attach points (the side middles, on the + /// border); the one the end is at lit: the nearest to `at` (a route's end sits `END_GAP` outside + /// its side's middle, #1916), else its named side's. fn show_attach(&mut self, end: Option, at: Option) { let attach = match end { Some(End::Node { node, side, .. }) => self.doc().ok().and_then(|d| d.world_bounds(node)).map(|b| { let on = at.or_else(|| (side != Side::Auto).then(|| side.point(b))); - SIDES.map(|s| s.point(b)).map(|p| ([p.x, p.y], on.is_some_and(|o| (o - p).hypot() < 1e-6))).to_vec() + let pts = SIDES.map(|s| s.point(b)); + let lit = on.and_then(|o| { + let near = pts.iter().enumerate().map(|(i, p)| (i, (o - *p).hypot())).filter(|(_, d)| *d <= figcraft_doc::END_GAP + 1e-6); + near.min_by(|x, y| x.1.total_cmp(&y.1)).map(|(i, _)| i) + }); + pts.iter().enumerate().map(|(i, p)| ([p.x, p.y], lit == Some(i))).collect() }), _ => None, }; diff --git a/crates/engine/src/canvas/snap.rs b/crates/engine/src/canvas/snap.rs index fab63810c..97c23fa6c 100644 --- a/crates/engine/src/canvas/snap.rs +++ b/crates/engine/src/canvas/snap.rs @@ -4,7 +4,7 @@ //! guide lines (with spacing labels) for the canvas to draw in red. Vector points also snap to //! other points (see `vectoredit::snap`); landing on one shows a marker (a zero-length guide). -use figcraft_doc::{Document, NodeId}; +use figcraft_doc::{BoardItem, Document, NodeId}; use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox}; use serde::Serialize; @@ -94,10 +94,22 @@ impl Targets { t.ys.push((y, b.x0, b.x1)); } } - // Siblings and, at the top level, all top-level layers. + // Siblings and, at the top level, all top-level layers. A board connector joined to a + // moving layer re-routes with it, as does its label: no snapping to where its own route + // starts (#1916). + let follows = |id: NodeId| match doc.node(id).and_then(|n| n.board.as_ref()) { + Some(BoardItem::Connector(k)) => [k.from.node(), k.to.node()].into_iter().flatten().any(|e| moving.contains(&e)), + _ => false, + }; if let Some(p) = doc.node(parent) { for c in &p.children { - if moving.contains(c) || !doc.node(*c).is_some_and(|n| n.visible) { + let Some(n) = doc.node(*c).filter(|n| n.visible) else { continue }; + let joined = match n.board.as_ref() { + Some(BoardItem::Connector(_)) => follows(*c), + Some(BoardItem::Label { connector }) => follows(*connector), + _ => false, + }; + if moving.contains(c) || joined { continue; } if let Some(b) = bbox(*c) { diff --git a/crates/engine/src/connector_anywhere_tests.rs b/crates/engine/src/connector_anywhere_tests.rs index 15776fb23..f979eca57 100644 --- a/crates/engine/src/connector_anywhere_tests.rs +++ b/crates/engine/src/connector_anywhere_tests.rs @@ -46,7 +46,7 @@ fn without_cmd_an_end_keeps_snapping_to_a_side() { let end = *drawn(&s, k).last().unwrap(); drag_end(&mut s, end, Point::new(650.0, 25.0), false); assert_eq!(connector(&s, k).to, End::Node { node: b, side: Side::Right, at: None }); - assert!(near(*drawn(&s, k).last().unwrap(), Point::new(700.0, 50.0))); + assert!(near(*drawn(&s, k).last().unwrap(), Point::new(700.0 + figcraft_doc::END_GAP, 50.0)), "END_GAP outside the side"); } #[test] diff --git a/crates/format/src/fig/tail_tests.rs b/crates/format/src/fig/tail_tests.rs index 2c8cce032..8937ffa5a 100644 --- a/crates/format/src/fig/tail_tests.rs +++ b/crates/format/src/fig/tail_tests.rs @@ -619,7 +619,7 @@ fn other_layer_kinds_import_as_the_closest_layers() { let world = doc.world_transform(link.id); let ends: Vec<(f64, f64)> = network_of(&doc, "Link").vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect(); - assert_eq!(ends, [(0.0, 300.0), (200.0, 300.0), (200.0, 50.0), (400.0, 50.0)]); + assert_eq!(ends, [(0.0, 300.0), (198.0, 300.0), (198.0, 50.0), (396.0, 50.0)]); assert_eq!(link.stroke.cap_end, StrokeCap::TriangleArrow); // A table: a frame. assert!(matches!(named(&doc, "Grid").kind, NodeKind::Frame)); @@ -656,9 +656,9 @@ fn connectors_without_a_saved_path_follow_their_line_style() { // Curved: one curve from A's right side to B's left, leaving and arriving level. let curve = network_of(&doc, "Curve"); let ends: Vec<_> = curve.vertices.iter().map(|v| world("Curve") * figcraft_doc::geom::Point::new(v.x, v.y)).collect(); - assert_eq!(ends.iter().map(|p| (p.x, p.y)).collect::>(), [(100.0, 650.0), (300.0, 650.0)]); + assert_eq!(ends.iter().map(|p| (p.x, p.y)).collect::>(), [(104.0, 650.0), (296.0, 650.0)], "END_GAP outside the sides"); assert_eq!(curve.segments.len(), 1); - assert_eq!((curve.segments[0].ta, curve.segments[0].tb), ((100.0, 0.0), (-100.0, 0.0)), "the curve leaves and arrives along the sides"); + assert_eq!((curve.segments[0].ta, curve.segments[0].tb), ((96.0, 0.0), (-96.0, 0.0)), "the curve leaves and arrives along the sides"); // Straight: unchanged, to the points the file gives on the layers. let line: Vec<_> = network_of(&doc, "Line").vertices.iter().map(|v| world("Line") * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect(); diff --git a/crates/ui-egui/src/board_ui_tests.rs b/crates/ui-egui/src/board_ui_tests.rs index 554d117d9..867ba139a 100644 --- a/crates/ui-egui/src/board_ui_tests.rs +++ b/crates/ui-egui/src/board_ui_tests.rs @@ -290,7 +290,7 @@ fn a_selected_connector_shows_its_ends_as_handles() { let b = u.app.session.execute("board.sticky", &json!({"x": 400, "y": 0})).unwrap()["id"].clone(); u.app.session.execute("board.connector", &json!({"from": a, "to": b, "style": "straight"})).unwrap(); let shapes = flat(&u.frame_output(vec![]).shapes); - let ends = [u.app.to_screen(200.0, 100.0), u.app.to_screen(400.0, 100.0)]; + let ends = [u.app.to_screen(204.0, 100.0), u.app.to_screen(396.0, 100.0)]; for end in ends { let ring = shapes.iter().any(|s| matches!(s, egui::Shape::Circle(c) if (c.center - end).length() < 0.5 && c.radius == 5.0)); assert!(ring, "a handle at {end:?}"); diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 7526d39aa..689dc60a6 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-31 · **Change:** minor (a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill and connectors leaving one side run together before they part (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) **Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that @@ -34,10 +34,10 @@ all end with the same geometry. | Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; no size presets or stacks | | Shapes with text | done | rectangle, rounded rectangle, ellipse, diamond, triangle, speech bubble, chevron; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, more shapes (cylinder, cross, star…), shape libraries | missing | | -| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was | +| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill and connectors leaving one side run together along the side's normal before they part (#1916) | | Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, the advanced shape libraries (engineering and other icon shapes) | missing | | -| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was | +| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill and connectors leaving one side run together along the side's normal before they part (#1916) | | Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before | | Curved connectors, elbows around objects, dragging an end to re-attach | done | `board.setStyle {style: curved}` (and the contextual bar): one curve leaving and arriving along the sides; an elbow whose short way would cross what it joins goes around their boxes, 24 units clear; a selected connector shows its two ends as handles, and dragging one onto an object attaches it there (the object is outlined while dragging), onto empty canvas leaves it free (`board.reattach {id, end, target, side?}`, one undo step) | | A connector end on any part of an object | done | holding Cmd/Ctrl while moving an end places it where the pointer is on the object, as a share of its box, so it follows moves and resizes; the line leaves by the side facing the other end. Without the key an end snaps to a side | @@ -70,6 +70,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap, and connectors leaving one side run together along the side's normal before they fan out), so the stroke never lies on the fill; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. | | 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged | | 2026-10-31 | patch | M12, #1708: a connector end dropped on the outer half of a shape takes the side it is towards, instead of only within 10 px of a side's middle, so a drop anywhere along an edge chooses that edge (dragging a selected connector's end and with the connector tool, ring included); a drop in the middle of a shape still takes the facing side. | | 2026-10-31 | minor | M12, #1710: a selected elbow or curved connector shows path handles. Dragging a run moves it and a first or last run gains an extra run to stay on its end; a curve's middle goes where it is dragged (`board.reshape`, one undo step). The shape travels with what the connector joins, is saved with the file, and goes back to routing itself when the style changes or an end moves to something else. | From 7be7c054ebaa7b4bb5d0ae148607642cb714a75e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 21:46:34 -0500 Subject: [PATCH 042/138] M12: a connector joined to a layer inside a moving section is no snap target; the docs say which connectors share a run (#1916) Review: a section moving carries its stickies and their connectors, so those connectors and their labels are no snap targets for the section either (an end counts as carried when its node or any ancestor is moving). The parity rows, the END_GAP doc and the test's doc no longer say connectors from one side run together: elbows share their first run along the normal, curves leave tangent to it, straight ones fan out from the same point. Co-Authored-By: Claude Fable 5.1 --- crates/doc/src/board_route.rs | 4 ++-- crates/doc/src/board_route_tests.rs | 4 ++-- crates/engine/src/board_tools_tests.rs | 26 ++++++++++++++++++++++++++ crates/engine/src/canvas/snap.rs | 7 ++++--- docs/boards-parity.md | 8 ++++---- 5 files changed, 38 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/board_route.rs b/crates/doc/src/board_route.rs index 7949674d9..74e143cf0 100644 --- a/crates/doc/src/board_route.rs +++ b/crates/doc/src/board_route.rs @@ -29,8 +29,8 @@ impl RouteEnd { const ROOM: f64 = 24.0; /// How far outside the border a connector attached to a side starts and ends (#1916): the stroke's -/// round cap never lies on the fill, and several connectors leaving one side run together along the -/// side's normal for this much before they part, as FigJam's do. +/// round cap never lies on the fill, and elbows leaving one side share their first run along the +/// side's normal (curves leave tangent to it), as FigJam's connectors do. pub const END_GAP: f64 = 4.0; /// The points a connector runs through from `from` to `to`: from [`END_GAP`] outside the middle of diff --git a/crates/doc/src/board_route_tests.rs b/crates/doc/src/board_route_tests.rs index a1e972cba..43530df15 100644 --- a/crates/doc/src/board_route_tests.rs +++ b/crates/doc/src/board_route_tests.rs @@ -24,8 +24,8 @@ fn an_attached_end_starts_outside_the_border() { assert_eq!(pts.first().copied(), Some(Point::new(50.0, 60.0 + END_GAP))); } -/// Several connectors leaving one side run together along its normal before they part: an elbow's -/// and a curve's first run leave straight out of the side. +/// Elbows leaving one side share their first run along its normal, and curves leave tangent to it: +/// the second point of each lies straight out of the side. #[test] fn connectors_from_one_side_leave_together() { let a = shape(0.0, 0.0); diff --git a/crates/engine/src/board_tools_tests.rs b/crates/engine/src/board_tools_tests.rs index 24e6df7dd..6ed291e13 100644 --- a/crates/engine/src/board_tools_tests.rs +++ b/crates/engine/src/board_tools_tests.rs @@ -276,3 +276,29 @@ fn a_board_tool_left_on_presses_as_move_in_a_design_file() { assert_eq!(s.tool.tool, ToolId::Move); assert_eq!(s.selection(), vec![r], "the press selected as Move does"); } + +/// #1916: a connector's start, END_GAP outside the layer it leaves, is a snap line for other layers +/// but not for that layer, nor for a section holding it (both carry the connector along), and nor +/// is the connector's label. +#[test] +fn a_connector_joined_to_a_moving_layer_or_its_section_is_no_snap_target() { + let mut s = board(); + let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 0, "y": 0, "width": 300, "height": 300})).unwrap(), "id"); + let a = id(&s.execute("board.sticky", &json!({"x": 50, "y": 50, "parent": sec})).unwrap(), "id"); + let b = id(&s.execute("board.stamp", &json!({"x": 800, "y": 150})).unwrap(), "id"); + let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight", "label": "to"})).unwrap(), "id"); + // A layer the connector has nothing to do with. + let d = id(&s.execute("board.sticky", &json!({"x": 0, "y": 900})).unwrap(), "id"); + let page = s.page().unwrap(); + let start = drawn(&s, c)[0].x; + let label = crate::board::label_of(s.doc().unwrap(), c).unwrap(); + let lx = s.doc().unwrap().world_bounds(label).unwrap().x0; + // A box whose left edge is 1 past a line snaps back by 1 when the line is a target. + let pull = |s: &Session, moving: &[NodeId], x: f64| { + let t = crate::snap::Targets::gather(s.doc().unwrap(), page, moving); + t.snap_rect(figcraft_geom::Rect::new(x + 1.0, 600.0, x + 9.0, 610.0), 4.0).0 + }; + assert_eq!((pull(&s, &[d], start), pull(&s, &[d], lx)), (-1.0, -1.0), "for an unrelated layer, the connector and its label snap"); + assert_eq!(pull(&s, &[b], start), 0.0, "not for the layer it arrives at"); + assert_eq!((pull(&s, &[sec], start), pull(&s, &[sec], lx)), (0.0, 0.0), "not for the section the connector leaves from"); +} diff --git a/crates/engine/src/canvas/snap.rs b/crates/engine/src/canvas/snap.rs index 97c23fa6c..cd40437d3 100644 --- a/crates/engine/src/canvas/snap.rs +++ b/crates/engine/src/canvas/snap.rs @@ -95,10 +95,11 @@ impl Targets { } } // Siblings and, at the top level, all top-level layers. A board connector joined to a - // moving layer re-routes with it, as does its label: no snapping to where its own route - // starts (#1916). + // moving layer, or to one inside it (a section carries its stickies), re-routes with it, as + // does its label: no snapping to where its own route starts (#1916). + let carried = |e: NodeId| moving.contains(&e) || doc.ancestors(e).iter().any(|a| moving.contains(a)); let follows = |id: NodeId| match doc.node(id).and_then(|n| n.board.as_ref()) { - Some(BoardItem::Connector(k)) => [k.from.node(), k.to.node()].into_iter().flatten().any(|e| moving.contains(&e)), + Some(BoardItem::Connector(k)) => [k.from.node(), k.to.node()].into_iter().flatten().any(carried), _ => false, }; if let Some(p) = doc.node(parent) { diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 689dc60a6..b364c759f 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill and connectors leaving one side run together before they part (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) **Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that @@ -34,10 +34,10 @@ all end with the same geometry. | Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; no size presets or stacks | | Shapes with text | done | rectangle, rounded rectangle, ellipse, diamond, triangle, speech bubble, chevron; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, more shapes (cylinder, cross, star…), shape libraries | missing | | -| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill and connectors leaving one side run together along the side's normal before they part (#1916) | +| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) | | Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, the advanced shape libraries (engineering and other icon shapes) | missing | | -| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill and connectors leaving one side run together along the side's normal before they part (#1916) | +| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) | | Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before | | Curved connectors, elbows around objects, dragging an end to re-attach | done | `board.setStyle {style: curved}` (and the contextual bar): one curve leaving and arriving along the sides; an elbow whose short way would cross what it joins goes around their boxes, 24 units clear; a selected connector shows its two ends as handles, and dragging one onto an object attaches it there (the object is outlined while dragging), onto empty canvas leaves it free (`board.reattach {id, end, target, side?}`, one undo step) | | A connector end on any part of an object | done | holding Cmd/Ctrl while moving an end places it where the pointer is on the object, as a share of its box, so it follows moves and resizes; the line leaves by the side facing the other end. Without the key an end snaps to a side | @@ -70,7 +70,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| -| 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap, and connectors leaving one side run together along the side's normal before they fan out), so the stroke never lies on the fill; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. | +| 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. | | 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged | | 2026-10-31 | patch | M12, #1708: a connector end dropped on the outer half of a shape takes the side it is towards, instead of only within 10 px of a side's middle, so a drop anywhere along an edge chooses that edge (dragging a selected connector's end and with the connector tool, ring included); a drop in the middle of a shape still takes the facing side. | | 2026-10-31 | minor | M12, #1710: a selected elbow or curved connector shows path handles. Dragging a run moves it and a first or last run gains an extra run to stay on its end; a curve's middle goes where it is dragged (`board.reshape`, one undo step). The shape travels with what the connector joins, is saved with the file, and goes back to routing itself when the style changes or an end moves to something else. | From 88851996a0932c2bc436550b2416524289044c40 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 22:22:03 -0500 Subject: [PATCH 043/138] fix(format): a saved file replaces its predecessor with the same permissions (#1957) --- crates/format/src/lib.rs | 5 +++++ crates/format/src/staging_tests.rs | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 3a69ca848..e2880a3ca 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -1028,6 +1028,11 @@ pub fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Resul let tmp = std::path::PathBuf::from(name); match std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) { Ok(mut file) => { + // The replacement keeps the destination's permissions from the start, so a private + // file's content is never readable under default ones (the open handle still writes). + if let Ok(old) = std::fs::metadata(path) { + let _ = file.set_permissions(old.permissions()); + } if let Err(e) = file.write_all(bytes) { let _ = std::fs::remove_file(&tmp); return Err(e); diff --git a/crates/format/src/staging_tests.rs b/crates/format/src/staging_tests.rs index 1bc199e20..abf8eacdc 100644 --- a/crates/format/src/staging_tests.rs +++ b/crates/format/src/staging_tests.rs @@ -123,3 +123,17 @@ fn a_failed_write_leaves_the_destination_alone_and_cleans_up() { } let _ = std::fs::remove_dir_all(&d); } + +#[cfg(unix)] +#[test] +fn a_replaced_file_keeps_its_permissions() { + use std::os::unix::fs::PermissionsExt; + let d = dir("mode"); + let path = d.join("a.figcraft"); + std::fs::write(&path, b"old").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + write_file_atomic(&path, b"new").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(&d); +} From df07ac2d09f0e29d40170a58f70e4bf88a659790 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 22:23:03 -0500 Subject: [PATCH 044/138] fix(engine): never let document text close the generated HTML style element (#1955) --- crates/engine/src/dev/codegen/html.rs | 5 ++++- crates/engine/src/html_codegen_tests.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/dev/codegen/html.rs b/crates/engine/src/dev/codegen/html.rs index d1b144cae..ac23e6a5b 100644 --- a/crates/engine/src/dev/codegen/html.rs +++ b/crates/engine/src/dev/codegen/html.rs @@ -90,7 +90,10 @@ pub(super) fn html(doc: &Document, id: NodeId) -> String { let ctx = Ctx::new(doc, id); let mut out = Markup::new(&ctx, CodeLang::Html); out.node(id, None, 0, ""); - format!("{}\n\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("