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 01/66] 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 02/66] 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 03/66] 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 04/66] 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 05/66] 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 06/66] 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 07/66] 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 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 08/66] 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 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 09/66] 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 10/66] 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 11/66] 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 16d97cf8e96ab81868e192e1e78930f47d01c67c Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 00:33:58 -0400 Subject: [PATCH 12/66] 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 8bc405edbccc73ed07f9373bf1c173a7e9b22bee Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 1 Nov 2026 12:16:33 -0500 Subject: [PATCH 13/66] 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 14/66] 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 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 15/66] 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 16/66] 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 421a8e5126a56ede1cdce45d5b53289c96a848f9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:34:50 +0000 Subject: [PATCH 17/66] 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 18/66] 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 19/66] 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 20/66] 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 21/66] 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 2dc7bed2a0fd4c516a2edfded323efcc0478ea90 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Tue, 3 Nov 2026 21:08:19 -0500 Subject: [PATCH 22/66] 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 23/66] 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 f05e5684987ce2501dbfada35afff41283505229 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 17:45:24 -0500 Subject: [PATCH 24/66] Pass the Linux signing key to the release workflow (#2001) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 68a705399..975d54114 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -48,3 +48,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} From 5244b0075d85b318b98e484a197087e99eb89fc0 Mon Sep 17 00:00:00 2001 From: JonRC Date: Wed, 4 Nov 2026 23:53:43 -0300 Subject: [PATCH 25/66] fix(engine): an unknown stroke cap lists the caps node.set takes (#2005) strokeCap, startCap and endCap answered only "unknown stroke cap". They now name the key and every cap, as strokeAlign, strokeJoin and dashCap do. --- crates/engine/src/cmd/props.rs | 9 ++++--- crates/engine/src/lib.rs | 2 ++ crates/engine/src/stroke_cap_error_tests.rs | 27 +++++++++++++++++++++ 3 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/stroke_cap_error_tests.rs diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index abd380cfc..ee606f2e1 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -196,6 +196,9 @@ fn set_operand_op(doc: &mut Document, id: NodeId, v: &Value, cmd: &str) -> Resul pub(crate) const WIDTH_PROFILE_HELP: &str = "widthProfile: a preset (uniform|wedge|taper|eye|rounded|pinch), points [[t (0-1 along the path), scale (× stroke weight)] | [t, left, right] (one-sided: each side's scale, looking along the path), ...] or [{t, scale} | {t, left, right}], {preset} | {points}, or null (uniform)"; +/// The stroke caps `strokeCap`, `startCap` and `endCap` take (every [`StrokeCap`]). +pub(crate) const STROKE_CAP_HELP: &str = "none|round|square|lineArrow|triangleArrow|reversedTriangle|circleFilled|diamondFilled"; + pub(crate) const BRUSH_HELP: &str = "brush: a preset (taper|ink|ribbon|bristle: stretched; dots|stars|confetti|leaves: scattered), {preset, spacing? (× weight), sizeJitter? (0-1), rotationJitter? (0-1), scatter? (0-4 × weight), seed?}, or null (a plain stroke)"; /// A brush from a preset id, `{preset, spacing?, sizeJitter?, rotationJitter?, scatter?, seed?}` @@ -611,13 +614,13 @@ fn apply_look(cmd: &str, doc: &mut Document, id: NodeId, k: &str, v: &Value) -> st.sides = Some(sides); } "strokeCap" => { - let c: StrokeCap = enum_of(v).ok_or_else(|| bad(cmd, "unknown stroke cap"))?; + let c: StrokeCap = enum_of(v).ok_or_else(|| bad(cmd, format!("strokeCap: {STROKE_CAP_HELP}")))?; let n = doc.get_mut(id)?; n.stroke.cap_start = c; n.stroke.cap_end = c; } - "startCap" => doc.get_mut(id)?.stroke.cap_start = enum_of(v).ok_or_else(|| bad(cmd, "unknown stroke cap"))?, - "endCap" => doc.get_mut(id)?.stroke.cap_end = enum_of(v).ok_or_else(|| bad(cmd, "unknown stroke cap"))?, + "startCap" => doc.get_mut(id)?.stroke.cap_start = enum_of(v).ok_or_else(|| bad(cmd, format!("startCap: {STROKE_CAP_HELP}")))?, + "endCap" => doc.get_mut(id)?.stroke.cap_end = enum_of(v).ok_or_else(|| bad(cmd, format!("endCap: {STROKE_CAP_HELP}")))?, "strokeJoin" => doc.get_mut(id)?.stroke.join = enum_of(v).ok_or_else(|| bad(cmd, "strokeJoin: miter|bevel|round"))?, "miterLimit" => doc.get_mut(id)?.stroke.miter_limit = f64_of(v).unwrap_or(4.0).clamp(1.0, 100.0), "miterAngle" => { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e919444e2..f7becee87 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -545,6 +545,8 @@ mod slot_tests; #[cfg(test)] mod stored_ids_tests; #[cfg(test)] +mod stroke_cap_error_tests; +#[cfg(test)] mod stroke_style_tests; #[cfg(test)] mod style_tests; diff --git a/crates/engine/src/stroke_cap_error_tests.rs b/crates/engine/src/stroke_cap_error_tests.rs new file mode 100644 index 000000000..11e414d5c --- /dev/null +++ b/crates/engine/src/stroke_cap_error_tests.rs @@ -0,0 +1,27 @@ +//! An unknown stroke cap is refused with the caps there are, as `strokeAlign` and `strokeJoin` +//! list theirs (#2005). + +use serde_json::json; + +use crate::Session; +use crate::cmd::props::STROKE_CAP_HELP; +use crate::params::id_of; +use figcraft_doc::StrokeCap; + +#[test] +fn an_unknown_cap_lists_every_cap() { + let names: Vec = StrokeCap::ALL.iter().map(|c| serde_json::to_value(c).unwrap().as_str().unwrap().to_string()).collect(); + assert_eq!(STROKE_CAP_HELP.split('|').collect::>(), names, "the list is every cap, in order"); + let mut s = Session::new(); + let v = id_of(&s.execute("vector.create", &json!({"path": "M0 0 L200 0", "x": 0, "y": 0})).unwrap()["id"]).unwrap(); + for key in ["strokeCap", "startCap", "endCap"] { + for junk in [json!("butt"), json!(3), json!("")] { + let e = s.execute("node.set", &json!({"id": v, "props": {key: junk}})).unwrap_err().to_string(); + assert!(e.contains(&format!("{key}: {STROKE_CAP_HELP}")), "{key} {junk}: {e}"); + } + // Every name the error lists is taken. + for name in &names { + s.execute("node.set", &json!({"id": v, "props": {key: name}})).unwrap_or_else(|e| panic!("{key} {name}: {e}")); + } + } +} From a55a728c4c5ab39bd2c3c928afc97b9ac5f879b4 Mon Sep 17 00:00:00 2001 From: JonRC Date: Thu, 5 Nov 2026 00:09:19 -0300 Subject: [PATCH 26/66] M6: JPG exports take a quality and embed the sRGB profile (#2004) file.export always encoded JPG at quality 90, and an sRGB document's JPGs carried no colour profile, so viewers could only assume sRGB. PNG exports always get an sRGB chunk, and Display P3 JPGs already embedded their ICC profile. - ExportSetting gets a quality (1 to 100, default 90, saved only when it isn't 90), parsed with the other export options: file.export, export.add, export.update, file.exportLayers and MCP export take it. - encode_export_with takes the quality; encode_export keeps quality 90. Every JPG now embeds the document's profile, sRGB included. --- crates/doc/src/props.rs | 16 ++++ crates/engine/src/cmd/edit.rs | 4 +- crates/engine/src/cmd/file.rs | 5 +- crates/engine/src/cmd/file/export.rs | 17 +++- crates/engine/src/jpg_export_tests.rs | 115 ++++++++++++++++++++++++++ crates/engine/src/lib.rs | 2 + crates/mcp/src/tools.rs | 2 + crates/render/src/lib.rs | 12 ++- crates/render/src/tests.rs | 13 ++- crates/ui-egui/src/ui_params_tests.rs | 1 + docs/file-format-parity.md | 5 +- docs/mcp.md | 2 +- 12 files changed, 180 insertions(+), 14 deletions(-) create mode 100644 crates/engine/src/jpg_export_tests.rs diff --git a/crates/doc/src/props.rs b/crates/doc/src/props.rs index 0c78681f2..b5f1f89cb 100644 --- a/crates/doc/src/props.rs +++ b/crates/doc/src/props.rs @@ -1481,6 +1481,9 @@ pub struct ExportSetting { /// Android Vector Drawable: what to do with what a drawable can't hold exactly. #[serde(skip_serializing_if = "VdCompat::is_default")] pub vd_compat: VdCompat, + /// JPG: the encoder's quality, 1 (smallest file) to 100 (see [`ExportSetting::quality`]). + #[serde(skip_serializing_if = "is_default_quality")] + pub quality: u8, } /// How an Android Vector Drawable export handles what the format can't draw exactly (layer @@ -1531,6 +1534,7 @@ impl Default for ExportSetting { svg_id_attribute: false, svg_simplify_stroke: true, vd_compat: VdCompat::BestEffort, + quality: ExportSetting::DEFAULT_QUALITY, } } } @@ -1543,7 +1547,19 @@ fn is_false(b: &bool) -> bool { !*b } +fn is_default_quality(q: &u8) -> bool { + *q == ExportSetting::DEFAULT_QUALITY +} + impl ExportSetting { + /// The JPG quality a setting has unless it sets one. + pub const DEFAULT_QUALITY: u8 = 90; + + /// The JPG quality made safe: within `1..=100`. + pub fn quality(&self) -> u8 { + self.quality.clamp(1, 100) + } + /// The row adding a setting after `last` creates: 1x first, then one scale step up with a /// matching "@2x"-style suffix. pub fn next_after(last: Option<&ExportSetting>) -> ExportSetting { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 700fa7414..f6665805a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -418,7 +418,7 @@ pub fn specs() -> Vec { spec!( "export.add", "Add export setting", - "{ids?, setting? {size: 2x|512w|512h|{by: scale|width|height, value}, suffix?, format?: png|jpg|svg|pdf|webp|xml (Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore)}} (without a setting: 1x, then one scale step up with an \"@2x\"-style suffix)", + "{ids?, setting? {size: 2x|512w|512h|{by: scale|width|height, value}, suffix?, format?: png|jpg|svg|pdf|webp|xml (Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), quality? (JPG: 1-100, default 90)}} (without a setting: 1x, then one scale step up with an \"@2x\"-style suffix)", true, |s, p| { let cmd = "export.add"; @@ -436,7 +436,7 @@ pub fn specs() -> Vec { spec!( "export.update", "Edit export setting", - "{ids?, index, size? (2x|512w|512h|{by, value}), suffix?, format? (png|jpg|svg|pdf|webp|xml: Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?}", + "{ids?, index, size? (2x|512w|512h|{by, value}), suffix?, format? (png|jpg|svg|pdf|webp|xml: Android Vector Drawable), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), vdCompat? (XML: bestEffort|exact|ignore), quality? (JPG: 1-100), contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?}", true, |s, p| { let cmd = "export.update"; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0cfdd1ffa..c25813381 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -118,7 +118,7 @@ pub fn specs() -> Vec { spec!( "file.export", "Export", - "{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings))}", + "{ids? (default selection, else the page), format? (png|jpg|svg|pdf|webp|xml (an Android Vector Drawable, with `warnings` for what it changed or left out), or fig: the whole file as .fig, experimental, with `warnings` for what was left out; other apps may not open every file; or penpot: the whole file as a Penpot 2.x archive, with warnings for unsupported content), scale? (default 1) | size? (2x|512w|512h or {by: scale|width|height, value}: a scale, or a width or height in pixels), path? (else returns base64 `data`), bleed? (PDF: points, or with a unit: \"3mm\", \"0.125in\", \"9pt\"), cropMarks?, bleedMarks?, cmyk? (PDF print options), contentsOnly? (default true; false also draws the layers that show in their area), includeBoundingBox? (true: only the layers' own boxes, cutting off shadows and outside strokes), svgOutlineText? (default true), svgSimplifyStroke? (default true), svgIdAttribute? (SVG ids, XML android:name), vdCompat? (XML: bestEffort (default: approximate with a warning)|exact (leave out what can't be exact, with a warning)|ignore (no warnings)), quality? (JPG: 1-100, default 90)}", false, export ), @@ -408,7 +408,8 @@ pub fn export_file(doc: &Document, ids: &[NodeId], setting: &ExportSetting, scal _ => { let pix = figcraft_render::render_area(doc, &drawn, area, scale) .ok_or_else(|| EngineError::Other("render failed (empty or too large)".into()))?; - Ok((figcraft_render::encode_export(&pix, setting.format, doc.color_profile).map_err(EngineError::Other)?, Vec::new())) + let bytes = figcraft_render::encode_export_with(&pix, setting.format, doc.color_profile, setting.quality()); + Ok((bytes.map_err(EngineError::Other)?, Vec::new())) } } } diff --git a/crates/engine/src/cmd/file/export.rs b/crates/engine/src/cmd/file/export.rs index 68e003d48..25b5629a1 100644 --- a/crates/engine/src/cmd/file/export.rs +++ b/crates/engine/src/cmd/file/export.rs @@ -1,6 +1,7 @@ use super::load::{ext, write}; use super::save::thumbnail; use super::*; +use crate::params::f64_of; /// Encode `ids` (or the page) in `format` at `scale`. pub fn export_bytes(doc: &Document, ids: &[NodeId], format: ExportFormat, scale: f64) -> Result> { @@ -159,7 +160,8 @@ pub fn export_scale(doc: &Document, ids: &[NodeId], setting: &ExportSetting) -> export_area(doc, ids, setting).map_or(1.0, |b| setting.size.scale_for(b.width(), b.height())) } -/// `e` with the `size` ("2x", "512w", "512h" or `{by, value}`), `suffix` and `format` that `p` sets. +/// `e` with the `size` ("2x", "512w", "512h" or `{by, value}`), `suffix`, `format` and the +/// format options (`quality`, `vdCompat`, PDF print options, the SVG flags) that `p` sets. pub(in crate::cmd) fn export_setting(cmd: &str, mut e: ExportSetting, p: &Value) -> Result { if let Some(size) = size_param(cmd, p)? { e.size = size; @@ -173,6 +175,9 @@ pub(in crate::cmd) fn export_setting(cmd: &str, mut e: ExportSetting, p: &Value) if let Some(c) = vd_compat_param(cmd, p)? { e.vd_compat = c; } + if let Some(q) = quality_param(cmd, p)? { + e.quality = q; + } e.print = print_param(cmd, p, e.print)?; for (key, slot) in [ ("contentsOnly", &mut e.contents_only), @@ -189,6 +194,16 @@ pub(in crate::cmd) fn export_setting(cmd: &str, mut e: ExportSetting, p: &Value) Ok(e) } +/// The JPG `quality` `p` passes: a whole number from 1 to 100 (anything else is an error). +fn quality_param(cmd: &str, p: &Value) -> Result> { + let Some(v) = get(p, "quality") else { return Ok(None) }; + let q = if v.is_boolean() { None } else { f64_of(v) }; + match q.filter(|q| q.fract() == 0.0 && (1.0..=100.0).contains(q)) { + Some(q) => Ok(Some(q as u8)), + None => Err(bad(cmd, "quality: a whole number from 1 to 100 (JPG)")), + } +} + /// Whether `p` sets any PDF print option. fn has_print_param(p: &Value) -> bool { ["bleed", "cropMarks", "bleedMarks", "cmyk"].iter().any(|k| get(p, k).is_some_and(|v| !v.is_null())) diff --git a/crates/engine/src/jpg_export_tests.rs b/crates/engine/src/jpg_export_tests.rs new file mode 100644 index 000000000..37e85af8b --- /dev/null +++ b/crates/engine/src/jpg_export_tests.rs @@ -0,0 +1,115 @@ +//! JPG exports: the quality an export or export setting asks for, and the colour profile every +//! JPG embeds (#2004). + +use image::ImageDecoder; +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; +use figcraft_color::ColorProfile; +use figcraft_doc::{ExportSetting, NodeId}; + +/// A rectangle with a gradient, so the quality shows in the file's size. +fn gradient_rect(s: &mut Session) -> NodeId { + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 120})).unwrap()["id"]).unwrap(); + let fill = json!({"type": "linearGradient", "stops": ["#FF0000", "#00FF88", "#2040FF"]}); + s.execute("node.set", &json!({"ids": [r], "props": {"fills": [fill]}})).unwrap(); + r +} + +fn bytes(v: &Value) -> Vec { + base64::Engine::decode(&base64::engine::general_purpose::STANDARD, v["data"].as_str().unwrap()).unwrap() +} + +fn jpg(s: &mut Session, r: NodeId, extra: Value) -> Vec { + let mut p = json!({"ids": [r], "format": "jpg"}); + if let (Value::Object(m), Value::Object(e)) = (&mut p, extra) { + m.extend(e); + } + bytes(&s.execute("file.export", &p).unwrap()) +} + +fn icc(jpg: &[u8]) -> Option> { + image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(jpg)).unwrap().icc_profile().unwrap() +} + +#[test] +fn jpg_quality_is_taken_and_defaults_to_90() { + let mut s = Session::new(); + let r = gradient_rect(&mut s); + let default = jpg(&mut s, r, json!({})); + assert_eq!(default, jpg(&mut s, r, json!({"quality": 90})), "90 is the default"); + let low = jpg(&mut s, r, json!({"quality": 20})); + let high = jpg(&mut s, r, json!({"quality": 100})); + assert!(low.len() < default.len() && default.len() < high.len(), "{} {} {}", low.len(), default.len(), high.len()); + // Agents send numbers as strings too. + assert_eq!(jpg(&mut s, r, json!({"quality": "20"})), low); + image::load_from_memory(&low).unwrap(); + // The other formats ignore it. + let png = |s: &mut Session, extra: Value| { + let mut p = json!({"ids": [r], "format": "png"}); + if let (Value::Object(m), Value::Object(e)) = (&mut p, extra) { + m.extend(e); + } + bytes(&s.execute("file.export", &p).unwrap()) + }; + assert_eq!(png(&mut s, json!({"quality": 20})), png(&mut s, json!({}))); +} + +#[test] +fn bad_qualities_are_refused() { + let mut s = Session::new(); + let r = gradient_rect(&mut s); + s.execute("export.add", &json!({"ids": [r], "setting": {"format": "jpg"}})).unwrap(); + for q in [json!(0), json!(101), json!(-5), json!(50.5), json!("high"), json!(true), json!([80]), json!(1e300)] { + let e = s.execute("file.export", &json!({"ids": [r], "format": "jpg", "quality": q})).unwrap_err(); + assert!(e.to_string().contains("quality: a whole number from 1 to 100"), "{q}: {e}"); + assert!(s.execute("export.add", &json!({"ids": [r], "setting": {"format": "jpg", "quality": q}})).is_err(), "{q}"); + assert!(s.execute("export.update", &json!({"ids": [r], "index": 0, "quality": q})).is_err(), "{q}"); + } + let n = s.doc().unwrap().node(r).unwrap(); + assert_eq!(n.exports.len(), 1); + assert_eq!(n.exports[0].quality, ExportSetting::DEFAULT_QUALITY); + // null leaves the setting as it is. + s.execute("export.update", &json!({"ids": [r], "index": 0, "quality": 40})).unwrap(); + s.execute("export.update", &json!({"ids": [r], "index": 0, "quality": null})).unwrap(); + assert_eq!(s.doc().unwrap().node(r).unwrap().exports[0].quality, 40); +} + +#[test] +fn export_settings_keep_their_quality() { + let mut s = Session::new(); + let r = gradient_rect(&mut s); + s.execute("export.add", &json!({"ids": [r], "setting": {"format": "jpg", "quality": 30}})).unwrap(); + s.execute("export.add", &json!({"ids": [r], "setting": {"format": "jpg", "suffix": "-hq"}})).unwrap(); + s.execute("export.update", &json!({"ids": [r], "index": 1, "quality": 95})).unwrap(); + let exports = s.doc().unwrap().node(r).unwrap().exports.clone(); + assert_eq!((exports[0].quality, exports[1].quality), (30, 95)); + // `file.exportLayers` encodes each setting at its own quality. + let files = s.execute("file.exportLayers", &json!({"ids": [r]})).unwrap()["files"].as_array().unwrap().clone(); + assert_eq!(bytes(&files[0]), jpg(&mut s, r, json!({"quality": 30}))); + assert_eq!(bytes(&files[1]), jpg(&mut s, r, json!({"quality": 95}))); + // Saved only when it isn't the default, so older files and settings read as 90. + assert_eq!(serde_json::to_value(&exports[0]).unwrap()["quality"], 30); + assert!(serde_json::to_value(ExportSetting::default()).unwrap().get("quality").is_none()); + let old: ExportSetting = serde_json::from_value(json!({"format": "jpg"})).unwrap(); + assert_eq!(old.quality, ExportSetting::DEFAULT_QUALITY); + // A value out of range in a file is clamped when it encodes. + let odd: ExportSetting = serde_json::from_value(json!({"format": "jpg", "quality": 0})).unwrap(); + assert_eq!(odd.quality(), 1); + // Undo takes the setting's quality back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().node(r).unwrap().exports[1].quality, ExportSetting::DEFAULT_QUALITY); +} + +#[test] +fn every_jpg_embeds_the_file_colour_profile() { + for profile in ColorProfile::ALL { + let mut s = Session::new(); + s.execute("file.colorProfile", &json!({"profile": profile.label(), "convert": false})).unwrap(); + let r = gradient_rect(&mut s); + for quality in [json!({}), json!({"quality": 10})] { + assert_eq!(icc(&jpg(&mut s, r, quality)), Some(profile.icc()), "{profile:?}"); + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e919444e2..a106b743a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -383,6 +383,8 @@ mod invite_links_tests; #[cfg(test)] mod jam_open_tests; #[cfg(test)] +mod jpg_export_tests; +#[cfg(test)] mod keymap_tests; #[cfg(test)] mod library_beacon_tests; diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 1cb141b58..23f871b92 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -280,6 +280,7 @@ fn tools() -> Vec { "svgIdAttribute": boolean("SVG: layer names as unique `id` attributes (default false)"), "svgSimplifyStroke": boolean("SVG: strokes as `stroke` attributes where exact (default true); false writes outlines"), "vdCompat": {"type": "string", "enum": ["bestEffort", "exact", "ignore"], "description": "XML: what a Vector Drawable can't draw exactly is approximated with a warning (bestEffort, default), left out with a warning (exact), or written as far as it maps without warnings (ignore: overlapping layer opacity dropped, even-odd fills kept as fillType=evenOdd, diamond gradients left out)"}, + "quality": {"type": "integer", "minimum": 1, "maximum": 100, "description": "JPG: the encoder's quality, 1 (smallest file) to 100; default 90"}, }), &[], ), @@ -1059,6 +1060,7 @@ fn export(b: &mut dyn Backend, a: &Map) -> Result Result, String> { /// Encode an export in `format` (PNG, JPEG over white, WebP) tagged with the document's colour /// `profile`. An sRGB PNG gets an `sRGB` chunk; a Display P3 PNG gets the profile as `iCCP` plus -/// `cICP` code points; Display P3 JPEG and WebP files embed the ICC profile (untagged files are read -/// as sRGB). SVG, PDF and Vector Drawable are not pixel formats: an error. +/// `cICP` code points; a JPEG embeds the ICC profile, sRGB too (JPEG has no small sRGB marker); +/// a Display P3 WebP embeds it (an untagged WebP is read as sRGB). JPEG at quality 90. SVG, PDF and +/// Vector Drawable are not pixel formats: an error. pub fn encode_export(p: &Pixmap, format: ExportFormat, profile: ColorProfile) -> Result, String> { + encode_export_with(p, format, profile, figcraft_doc::ExportSetting::DEFAULT_QUALITY) +} + +/// [`encode_export`] with the JPEG `quality` (1-100); the other formats ignore it. +pub fn encode_export_with(p: &Pixmap, format: ExportFormat, profile: ColorProfile, quality: u8) -> Result, String> { let icc = (!profile.is_srgb()).then(|| profile.icc()); match format { ExportFormat::Png => { let png = png_with(p, icc)?; Ok(if profile.is_srgb() { png_insert_chunk(png, b"sRGB", &[0]) } else { png_insert_chunk(png, b"cICP", &profile.cicp()) }) } - ExportFormat::Jpg => jpeg_with(p, Color::WHITE, 90, icc), + ExportFormat::Jpg => jpeg_with(p, Color::WHITE, quality, Some(profile.icc())), ExportFormat::Webp => webp_with(p, icc), ExportFormat::Svg | ExportFormat::Pdf | ExportFormat::VectorDrawable => Err(format!("{} is not a pixel format", format.label())), } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index f7cfe5748..8e5943b5a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -496,9 +496,16 @@ fn exports_carry_the_colour_profile() { let icc = dec.icc_profile().unwrap(); assert_eq!(icc.is_some(), !profile.is_srgb(), "{profile:?}"); assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(5, 5).0, [0, 255, 0, 255]); - for f in [ExportFormat::Jpg, ExportFormat::Webp] { - assert!(!encode_export(&pix, f, profile).unwrap().is_empty()); - } + // A JPEG always embeds the profile (it has no small sRGB marker); an sRGB WebP is untagged. + let jpg = encode_export(&pix, ExportFormat::Jpg, profile).unwrap(); + let icc = image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(&jpg)).unwrap().icc_profile().unwrap(); + assert_eq!(icc, Some(profile.icc()), "{profile:?}"); + assert_eq!(jpg, encode_export_with(&pix, ExportFormat::Jpg, profile, 90).unwrap(), "quality 90 by default"); + assert_ne!(jpg, encode_export_with(&pix, ExportFormat::Jpg, profile, 30).unwrap()); + let webp = encode_export(&pix, ExportFormat::Webp, profile).unwrap(); + let icc = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&webp)).unwrap().icc_profile().unwrap(); + assert_eq!(icc.is_some(), !profile.is_srgb(), "{profile:?}"); + assert_eq!(webp, encode_export_with(&pix, ExportFormat::Webp, profile, 30).unwrap(), "WebP takes no quality"); assert!(encode_export(&pix, ExportFormat::Svg, profile).is_err()); } assert_eq!(png_insert_chunk(b"not a png".to_vec(), b"sRGB", &[0]), b"not a png"); diff --git a/crates/ui-egui/src/ui_params_tests.rs b/crates/ui-egui/src/ui_params_tests.rs index 6ee71dfc9..fa6464041 100644 --- a/crates/ui-egui/src/ui_params_tests.rs +++ b/crates/ui-egui/src/ui_params_tests.rs @@ -30,6 +30,7 @@ fn export_settings_with_every_option_are_taken() { svg_id_attribute: true, svg_simplify_stroke: false, vd_compat: VdCompat::Exact, + quality: 70, ..ExportSetting::default() }; let mut p = crate::export_panel::setting_params(&setting); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 56cc701a2..a95ccecc2 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -54,7 +54,7 @@ export limit, not a native document nesting limit. | Format | Figma | FigCraft | Notes | Hours | |---|---|---|---|---| | PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels | — | -| JPG | yes | yes | white where transparent; fixed quality (90) | — | +| JPG | yes | yes | white where transparent; quality 1 to 100 (`quality` on `file.export`, export settings and MCP `export`; default 90; the Export panel has no control for it yet); the file's colour profile embedded as ICC (APP2), sRGB too | — | | SVG | yes (outline text option, ids) | yes | alpha/luminance masks kept; noise, texture, progressive and background blur, glass embedded as images; outline text (off: `` with one `` per line, one style per layer), unique id attributes from layer names, explicit depth-limit refusal, nested frames clipped by their parent's clip (#327), simplified strokes (stroke attributes for centred strokes and for inside and outside strokes on boxes and ellipses) | — | | PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal | CMYK output intent 2–4 | | WebP | — | yes (ours) | | — | @@ -187,6 +187,7 @@ source paint coordinates. | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | JPG export: `quality` (1 to 100, default 90) on `file.export`, `export.add` / `export.update` and MCP `export`, kept in the export setting; an sRGB file's JPGs embed the sRGB ICC profile, as Display P3 files' JPGs already embedded theirs, since an untagged JPG is only assumed to be sRGB (#2004). | | 2026-11-01 | patch | `.fig` and `.jam` import: a connector without a saved snapshot (elbowed and curved ones are routed here) took no stroke, so it was invisible (#1807); its line's paint, weight, cap and dashes now come from the file's generated line record, as a saved snapshot's do, and the connector's own values, when it has any, win. Test: `fig::connector_label_tests::a_routed_connector_takes_its_line_style_from_the_generated_record`. Numbers unchanged | | 2026-10-31 | patch | M4: Dash and Custom strokes have a Dash cap (None, Round, Square) in the advanced stroke settings and `node.set {dashCap}`, on both ends of every dash on the canvas and in PNG, PDF and SVG. Unset, dashes keep taking the end point caps, so older files look the same; the saved file writes it only when set. Numbers unchanged | | 2026-10-30 | minor | `.fig` import: a connector's label without a saved snapshot was skipped; now the connector imports as a frame holding its line and the label, as a connector with a saved snapshot does, the label centred on the line's middle by length (in a 200-wide box, laid out again with the fonts at hand), in the connector's fill paints or black. Its background isn't known without the snapshot and is left out. Not checked on real files. Test: `fig::tests::tail::a_labelled_connector_without_a_snapshot_keeps_its_label` | diff --git a/docs/mcp.md b/docs/mcp.md index b5e49e749..9507ff73f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -373,7 +373,7 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match. | `inspect_document {depth, allPages, fields?, outline?}` | The document as JSON (its `id`, layer tree, styles, selection, history); `fields` selects layer properties, `outline: true` gives a compact tree (below). The tools that act on a document also take `document` (see Naming the document below). | | `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. | | `select {ids}` | Replace the selection (`[]` deselects). | -| `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?}` | png, jpg, svg, webp, pdf, xml (an Android Vector Drawable: `svgIdAttribute` writes `android:name`, `vdCompat` is `bestEffort` (default: approximated with a warning), `exact` (left out with a warning) or `ignore` (no warnings: overlapping layer opacity dropped, even-odd fills kept as `fillType="evenOdd"`, diamond gradients left out), and the result lists `warnings` for what was changed or left out), or `fig`: the whole file as `.fig`, experimental (see Exporting `.fig` files below); `size` is `2x`, `512w` or `512h`. The image covers what the layers paint (shadows towards their offset, strokes, unclipped children, a mask group's mask; hidden layers take no room; a slice is its area with everything under it, or only the frame or group it sits in while `contentsOnly` is on); `contentsOnly: false` also draws every other layer showing in that area, `includeBoundingBox` exports the layers' own boxes; SVG: `svgOutlineText: false` keeps ``, `svgIdAttribute` writes unique ids from layer names, `svgSimplifyStroke: false` writes every stroke as an outline. The same options go in export settings (`export.add` / `export.update`). PDF: frames one page each (sized in points), anything else together on one page; print options: `bleed` (points or a length like `"3mm"`, `"0.125in"`), crop and bleed marks, CMYK colour (see Exports below), also taken by `file.export`, `file.exportLayers`, `file.exportFramesPdf` and stored per export setting by `export.add` / `export.update`; `run_command` `file.exportFramesPdf {page?, path?}` writes every top-level frame of a page. Without `path`, images come back as MCP image content, SVG as text, XML as text followed by `{format, bytes, warnings}`. Layers' own export settings: `run_command` with `export.add` / `export.update {index, size?, suffix?, format?}` / `export.remove` and `file.exportLayers {ids?, dir?, assets?}` (every layer once per setting, named `.`, a slash in a layer name making a folder; `assets: true` exports the Inspect tab's assets instead: icons as SVG, images as PNG). | +| `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?, quality?}` | png, jpg, svg, webp, pdf, xml (an Android Vector Drawable: `svgIdAttribute` writes `android:name`, `vdCompat` is `bestEffort` (default: approximated with a warning), `exact` (left out with a warning) or `ignore` (no warnings: overlapping layer opacity dropped, even-odd fills kept as `fillType="evenOdd"`, diamond gradients left out), and the result lists `warnings` for what was changed or left out), or `fig`: the whole file as `.fig`, experimental (see Exporting `.fig` files below); `size` is `2x`, `512w` or `512h`; `quality` is the JPG quality, 1 to 100 (default 90). The image covers what the layers paint (shadows towards their offset, strokes, unclipped children, a mask group's mask; hidden layers take no room; a slice is its area with everything under it, or only the frame or group it sits in while `contentsOnly` is on); `contentsOnly: false` also draws every other layer showing in that area, `includeBoundingBox` exports the layers' own boxes; SVG: `svgOutlineText: false` keeps ``, `svgIdAttribute` writes unique ids from layer names, `svgSimplifyStroke: false` writes every stroke as an outline. The same options go in export settings (`export.add` / `export.update`). PDF: frames one page each (sized in points), anything else together on one page; print options: `bleed` (points or a length like `"3mm"`, `"0.125in"`), crop and bleed marks, CMYK colour (see Exports below), also taken by `file.export`, `file.exportLayers`, `file.exportFramesPdf` and stored per export setting by `export.add` / `export.update`; `run_command` `file.exportFramesPdf {page?, path?}` writes every top-level frame of a page. Without `path`, images come back as MCP image content, SVG as text, XML as text followed by `{format, bytes, warnings}`. Layers' own export settings: `run_command` with `export.add` / `export.update {index, size?, suffix?, format?}` / `export.remove` and `file.exportLayers {ids?, dir?, assets?}` (every layer once per setting, named `.`, a slash in a layer name making a folder; `assets: true` exports the Inspect tab's assets instead: icons as SVG, images as PNG). | | `screenshot {ids?, scale?, maxSize?, window?}` | PNG of the page (with background) or of layers, scaled to fit `maxSize` (default 1600). `window: true` captures the app window in front when attached, a window id (see Windows below) that window. | | `open_file {path, variables?, reload?}` / `save_file {path?}` | Open `.figcraft`, `.json` (FigCraft JSON or REST API file JSON with its variables, see below), `.fig` or FigJam `.jam` (best effort, see below), `.sketch` (Sketch 48 and newer, best effort), `.svg` (see Importing SVG below) or an image; save as `.figcraft`. `open_file` returns `opened` (for a file opened anew, a `summary` of `name`, `pages`, `layers` and `images`, and `warnings` or `repairs`; a file that was already open gives its `index`, with `stale: true` when the file changed on disk since that tab read or saved it; `reload: true` reads it again into the tab, refused while the tab has unsaved changes) and the document's `document` outline. | | `undo` / `redo` | Step through history. | From 19af9c9c3be813fca2715946c34f9aad631dee0c Mon Sep 17 00:00:00 2001 From: JonRC Date: Thu, 5 Nov 2026 00:41:46 -0300 Subject: [PATCH 27/66] M6: test that a bad JPG quality is refused for every format (#2004) As vdCompat, bleed and the SVG flags are: PNG, WebP, SVG and a format taken from the path refuse quality 0 and write nothing, and a quality kept on a PNG setting is used once the setting becomes a JPG. --- crates/engine/src/jpg_export_tests.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/engine/src/jpg_export_tests.rs b/crates/engine/src/jpg_export_tests.rs index 37e85af8b..9d3c823a4 100644 --- a/crates/engine/src/jpg_export_tests.rs +++ b/crates/engine/src/jpg_export_tests.rs @@ -76,6 +76,28 @@ fn bad_qualities_are_refused() { assert_eq!(s.doc().unwrap().node(r).unwrap().exports[0].quality, 40); } +#[test] +fn a_bad_quality_is_refused_whatever_the_format() { + // As `vdCompat`, `bleed` and the SVG flags are: a value is checked for every format, so a + // setting that becomes a JPG later never holds one the encoder can't take. + let mut s = Session::new(); + let r = gradient_rect(&mut s); + assert!(s.execute("file.export", &json!({"ids": [r], "format": "png", "vdCompat": "junk"})).is_err()); + let png = std::env::temp_dir().join(format!("figcraft-bad-quality-{}.png", std::process::id())); + for mut p in [json!({"format": "png"}), json!({"format": "webp"}), json!({"format": "svg"}), json!({"path": png.to_string_lossy()})] { + p["ids"] = json!([r]); + p["quality"] = json!(0); + let e = s.execute("file.export", &p).unwrap_err(); + assert!(e.to_string().contains("quality: a whole number from 1 to 100"), "{p}: {e}"); + } + assert!(!png.exists(), "the refused export wrote nothing"); + // A valid quality on a PNG setting is kept, and used once the setting is a JPG. + s.execute("export.add", &json!({"ids": [r], "setting": {"format": "png", "quality": 40}})).unwrap(); + s.execute("export.update", &json!({"ids": [r], "index": 0, "format": "jpg"})).unwrap(); + let files = s.execute("file.exportLayers", &json!({"ids": [r]})).unwrap()["files"].as_array().unwrap().clone(); + assert_eq!(bytes(&files[0]), jpg(&mut s, r, json!({"quality": 40}))); +} + #[test] fn export_settings_keep_their_quality() { let mut s = Session::new(); From 2b74d22b0f42853da43c009cea30e29b3d34daed Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:35:20 +1030 Subject: [PATCH 28/66] Contributors: credit helenkwok as Helen Kwok --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index c846d8725..f7ee0420e 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -101,3 +101,6 @@ sync_github_name = true [people.aleksei-suholita] real_name = "Oleksii Sukholita" + +[people.helenkwok] +real_name = "Helen Kwok" From fc3679047e0618110c7153339be7bbb103d95acb Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:35:21 +1030 Subject: [PATCH 29/66] feat(web): a host bridge for embedding pages, ?host=parent and data-host="page" (#1356) A page that embeds the web build can hand it a file and get every save back instead of a browser download, and hears about unsaved changes: ?host=parent for a same-origin iframe (postMessage, the protocol the GridCraft, PdfCraft, WordCraft and CADCraft bridges use) and data-host="page" on the canvas for a page that loads the module into its own document (non-bubbling CustomEvents on the canvas). The bridge holds a Transport (Parent or Page) with one send; the pure rules are unit-tested; the hosting guide documents both modes. --- ROADMAP.md | 3 + apps/figcraft-web/Cargo.toml | 1 + apps/figcraft-web/src/host.rs | 273 ++++++++++++++++++++++++++++++ apps/figcraft-web/src/hostmode.rs | 109 ++++++++++++ apps/figcraft-web/src/main.rs | 14 +- apps/figcraft-web/src/web.rs | 62 ++++++- packaging/web/README.md | 88 ++++++++++ 7 files changed, 544 insertions(+), 6 deletions(-) create mode 100644 apps/figcraft-web/src/host.rs create mode 100644 apps/figcraft-web/src/hostmode.rs diff --git a/ROADMAP.md b/ROADMAP.md index 410705919..2a5fa6fff 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -3,6 +3,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **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 tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (web host bridge: `?host=parent` in an iframe or `data-host="page"` on the canvas hands a page the app's files instead of downloads and reports unsaved changes, documented in the hosting guide; colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -143,6 +144,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). - **2026-10-27** · Batch continue-on-error (M0.9, #1386): `command.batch` and MCP `batch` accept `onError: "continue"`, roll back failed steps individually and return one outcome per step. References to failed steps fail with both step numbers; successful edits stay one undo step, and the default abort mode is unchanged. Engine and MCP regression tests. Numbers unchanged. - **2026-10-26** · Non-ASCII layer names transliterate in code export (M6, #1235): `class_name` runs the name through `deunicode` before its ASCII filter, so 로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber` in the HTML/CSS/React/Leptos class names, component roots and `data-*` variant attributes (SwiftUI/Compose type names unchanged); a name left with nothing (symbols only) takes the node's kind (`.text`, `.frame`) instead of `layer-`, and the 40-character cut lands on a word boundary. New dependency: deunicode (pure Rust tables, zero deps, BSD-3-Clause, the `slug` crate's base). `html_codegen_tests`. Numbers unchanged. - **2026-10-25** · M6, #1143: offline Penpot 2.x open/import/export through the editor, CLI and MCP using the existing document model. Unsupported layout settings retain saved positions and bounded source metadata with warnings; font binaries and toggle-overlay are reported, and provider fonts are never downloaded. Shared ZIP/JSON/token budgets guard untrusted input. Figma parity numbers unchanged. +- **2026-10-26** · Web host bridge: `?host=parent` (a same-origin page embedding FigCraft in an iframe) or `data-host="page"` on the canvas (the page's own document, over non-bubbling `CustomEvent`s) opens the host's file like File ▸ Open (over the browser open limit of 512 MB refused) and takes every file the app would otherwise download (`figcraft:save` with the `saveAs` rule), plus `figcraft:dirty`, `figcraft:ready` and `figcraft:failed`; `?author=` names the user for comments and board notes; host mode starts with no document. Unit tests cover the opt-in rule (only the exact `page` value), the `saveAs` rule and the open-name fallback. Numbers unchanged. - **2026-10-25** · egui 0.37 capture lifecycle: screenshots with hidden or unknown visibility queue, request a hidden paint, and expire after 60 seconds if no capture arrives (headless-tested contract). Logic-only edits, saves and inspection continue while hidden. Native visible GUI and forced hidden-window paint, browser and Wayland behavior remain unqualified; parity percentages are unchanged. - **2026-10-24** · Open, Save and the folder dialogs start in the folder of the last file or folder picked in the run (#1290): the Linux portal does not remember it between dialogs as the macOS and Windows panels do. A folder deleted since falls back to the system's choice. No numbers change. - **2026-10-24** · Boards (M12): board pages get a dot grid under their layers (drawn by the canvas render after the page colour, thinned out when zoomed out); a selected connector shows its ends as handles, and dragging one onto another object re-attaches it there, onto empty canvas leaves it free (`board.reattach`, one undo step, also over MCP); connectors can be curved, and elbows go around the objects they join when the short way would cross them. Checked in the app, through MCP and in the web build ([boards-parity](docs/boards-parity.md)). @@ -492,6 +494,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | 2026-10-27 | minor | Placed images keep their own size (M7, #1360): dropping, Place image, paste and `image.place` put an image at its pixel size and fit only a side past 4096 px (they fitted it into 1000 px); a PNG whose `pHYs` records a whole 2x–4x multiple of 72 dpi (macOS screenshots record 144 dpi) is placed at its point size, so an 800 × 600 px capture comes in at 400 × 300; other densities, such as 300 dpi scans, keep their pixel size; the image data stays at full resolution and an explicit width or height still wins. On macOS, paste reads the clipboard's PNG as is (its density and colour profile kept) and falls back to the decoded image. Numbers unchanged | | 2026-10-26 | minor | Non-ASCII layer names transliterate in code export (M6, #1235): `class_name` transliterates through the new `deunicode` dependency (pure Rust tables, zero deps, BSD-3-Clause), so Korean, Cyrillic, Latin-diacritic and CJK names become readable ASCII classes (`rogeuin-hwamyeon`, `knopka`, `uber`, `an-niu`) in HTML/CSS/React/Leptos output, component roots and `data-*` variant attributes; symbols-only names take the node's kind (`.text`) instead of `layer-`, and the 40-character cut lands on a word boundary. `html_codegen_tests` updated and extended. Numbers unchanged | | 2026-10-25 | minor | M6, #1143: offline Penpot 2.x open/import/export through the editor, CLI and MCP using the existing document model. Unsupported layout settings retain saved positions and bounded source metadata with warnings; font binaries and toggle-overlay are reported, and provider fonts are never downloaded. Shared ZIP/JSON/token budgets guard untrusted input. Figma parity numbers unchanged. | +| 2026-10-26 | minor | Web host bridge: `?host=parent` (a same-origin page embedding FigCraft in an iframe) or `data-host="page"` on the canvas (the page's own document, over non-bubbling `CustomEvent`s) opens the host's file like File ▸ Open and takes every file the app would otherwise download, with `figcraft:ready`, `figcraft:open`, `figcraft:save` (a `saveAs` rule), `figcraft:dirty` and `figcraft:failed`; `?author=` names the user for comments and board notes; documented in the hosting guide. Numbers unchanged | | 2026-10-25 | minor | egui 0.37 capture lifecycle: screenshots with hidden or unknown visibility queue, request a hidden paint, and expire after 60 seconds if no capture arrives (headless-tested contract). Logic-only edits, saves and inspection continue while hidden. Native visible GUI and forced hidden-window paint, browser and Wayland behavior remain unqualified; parity percentages are unchanged. | | 2026-10-24 | minor | Server memory (#1134): when the last person leaves a file nobody edited, figcraft-server keeps the client ids it issued in the log instead of rewriting the snapshot (compaction still follows `compact_after`/`compact_mb` and edits), and a snapshot is encoded straight into its file buffer, without a second copy of the body; the file format is unchanged. Numbers unchanged | | 2026-10-24 | minor | Boards (M12): a dot grid on board pages under the layers, connector ends dragged onto other objects or empty canvas (`board.reattach`), curved connectors, elbows that go around what they join. Boards row ~35% → ~37%, ~20% → ~21%, 30–60 h → 28–56 h; headline numbers unchanged (boards are outside the weighted sum) | diff --git a/apps/figcraft-web/Cargo.toml b/apps/figcraft-web/Cargo.toml index 09eca5d0f..75f7e312c 100644 --- a/apps/figcraft-web/Cargo.toml +++ b/apps/figcraft-web/Cargo.toml @@ -31,3 +31,4 @@ wasm-bindgen = "0.2" js-sys = "0.3" wasm-bindgen-futures = "0.4" web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "HtmlElement", "HtmlAnchorElement", "Node", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "HtmlInputElement", "EventTarget", "Url", "Location", "MediaQueryList", "Navigator", "Gamepad", "GamepadButton", "GamepadMappingType", "Storage"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "HtmlCanvasElement", "HtmlElement", "HtmlAnchorElement", "Node", "Blob", "BlobPropertyBag", "File", "FileList", "HtmlInputElement", "EventTarget", "Url", "Location", "MediaQueryList", "Navigator", "Gamepad", "GamepadButton", "GamepadMappingType", "MessageEvent", "UrlSearchParams", "CustomEvent", "CustomEventInit"] } diff --git a/apps/figcraft-web/src/host.rs b/apps/figcraft-web/src/host.rs new file mode 100644 index 000000000..d08bdf45b --- /dev/null +++ b/apps/figcraft-web/src/host.rs @@ -0,0 +1,273 @@ +//! Host modes: a page that runs FigCraft (as an `