Merge remote-tracking branch 'origin/main' into HEAD

# Conflicts:
#	ROADMAP.md
This commit is contained in:
bflatastic
2026-11-27 15:46:21 +07:00
16 changed files with 432 additions and 19 deletions
+5 -1
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (CLI scales reject repeated x suffixes; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (CLI scales reject repeated x suffixes; CLI help and docs name the first non-divider page as the default for export and render; invalid browser-page server endpoints are ignored before they replace the sharing default; the browser crate docs no longer repeat an obsolete same-computer-only live-session restriction; document HTTP(S) links without a host are refused before opening; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
@@ -368,6 +368,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|---|---|---|
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
| 2026-11-24 | minor | M7: New York, Apple's serif that macOS installs as the hidden `.New York`, is found and listed under its public name (it was a missing font). Numbers unchanged. |
| 2026-11-15 | patch | Removed the obsolete duplicate live-session bullet from the browser crate docs; the existing server publishing and remote wss guidance remains authoritative. Runtime behavior unchanged. |
| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged |
| 2026-11-19 | minor | M8: Code Connect for agents. A link can name its source file, what variant values are called in code (Primary becomes `primary` in the snippet) and notes, in the Inspect tab, `codeConnect.set` and `figcraft.connect.json`. `codeConnect.list` and the MCP tool `component_mappings` say which code component each design component is, and whether its source file exists; `sync_mappings` imports and exports a repository's file. `codeConnect.export {path}` keeps the file's other keys and the links of components the design doesn't have, so several designs can share one file. Numbers unchanged |
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
@@ -377,6 +378,9 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| 2026-11-10 | minor | M12, #2226 (step 2 of 4): mind maps in the UI. The Shapes flyout ends in a mind map tool (`tool.mindMap`): a click places a map with the first node's text starting there and types in it. Cmd/Ctrl+Enter adds a child of the selected or edited node (`board.mindMapAdd`), Shift+Cmd/Ctrl+Enter its next sibling (`board.nextSticky` on a node), both typing on; Tab and Shift+Tab walk a node's siblings in the map's order (`select.next`, `select.previous`). The bar over the selection colours a node's text (`board.setColor`) and shows a branch the connector's controls without the line types. Tests: `board_mindmap_tests` (four more), `board_ui_tests` (five more). Breadth ~47% → ~48%, ready ~29% → ~30%. |
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
| 2026-11-10 | minor | Experimental `.fig` export preserves set-variable, set-variable-mode and conditional prototype actions (#2210). |
| 2026-11-15 | patch | Document HTTP(S) links without a host are refused before opening; regressions retain valid query, fragment, IPv6 and mail links. |
| 2026-11-15 | patch | The browser ignores a page server meta tag with an invalid host, port or path, using the same endpoint parser as sharing; valid local, IPv6 and reverse-proxy addresses keep their spelling. |
| 2026-11-15 | patch | CLI export and render help and docs name the existing first non-divider page default, including the all-divider fallback and explicit page selection. Behavior unchanged. |
| 2026-11-15 | patch | CLI export and render reject repeated scale suffixes such as `2xx` as usage errors (exit 2); numeric values and one optional `x` suffix retain the existing limits. |
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
+2 -2
View File
@@ -102,7 +102,7 @@ pub struct ExportArgs {
pub format: Option<String>,
#[command(flatten)]
pub scale: ScaleArg,
/// The page to export (default the first)
/// The page to export (default the first non-divider page)
#[arg(long, value_name = "NAME")]
pub page: Option<String>,
/// The layer to export, by id (12 or 0:12) or name
@@ -171,7 +171,7 @@ pub struct RenderArgs {
pub out: String,
#[command(flatten)]
pub scale: ScaleArg,
/// The page to render (default the first)
/// The page to render (default the first non-divider page)
#[arg(long, value_name = "NAME")]
pub page: Option<String>,
#[command(flatten)]
-2
View File
@@ -22,8 +22,6 @@
//! - host mode: `?host=parent` (a same-origin page embedding FigCraft in an `<iframe>`) or
//! `data-host="page"` on the canvas (the page's own document) hands the page the app's files
//! instead of downloading them and reports unsaved changes (`host`);
//! - live sessions: it joins sessions a desktop app hosts (File ▸ Join live session…) but can't
//! host one. A page served over `https://` can only reach sessions on the same computer
//!
//! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?control` installs
//! `window.figcraft`, the page's control channel (`api.rs`), which is off without it; `?host=parent`
+8 -1
View File
@@ -22,7 +22,14 @@ pub fn join_link(fragment: &str) -> Option<&str> {
pub fn page_server(content: &str) -> Option<String> {
let c = content.trim();
let scheme = c.starts_with("wss://") || c.starts_with("ws://");
(scheme && c.len() <= 512 && !c.contains(|ch: char| ch.is_whitespace() || ch.is_control() || ch == '?' || ch == '#')).then(|| c.to_string())
// Invalid metadata must not replace a usable default with an endpoint sharing cannot reach.
(scheme
&& c.len() <= 512
&& !c.contains(|ch: char| ch.is_whitespace() || ch.is_control() || ch == '?' || ch == '#')
// Endpoint parsing strips pasted-link delimiters; metadata must retain its spelling.
&& !c.ends_with(['<', '>', '"', '\''])
&& figcraft_collab_net::Endpoint::parse(c).is_ok())
.then(|| c.to_string())
}
/// Whether `search` (`location.search`, with or without its `?`) has a `control` entry (`?control`,
+33
View File
@@ -49,3 +49,36 @@ fn a_page_names_its_own_server_without_a_key() {
assert_eq!(page_server(bad), None, "{bad:?} is ignored");
}
}
#[test]
fn a_page_ignores_invalid_server_endpoints() {
for bad in [
"ws://",
"wss://",
"wss:///figcraft/",
"wss://:443/",
"wss://figcraft.example:0/",
"wss://figcraft.example:65536/",
"wss://figcraft.example:port/",
"wss://[::1/",
"wss://figcraft.example/a@b/",
] {
assert_eq!(page_server(bad), None, "{bad:?} must not replace the default server");
}
}
#[test]
fn a_page_preserves_valid_server_endpoint_spelling() {
for server in ["ws://localhost:47900/", "wss://figcraft.example/figcraft/", "wss://[::1]:47900/figcraft/"] {
assert_eq!(page_server(server).as_deref(), Some(server), "{server}");
}
}
#[test]
fn a_page_rejects_server_delimiters_that_endpoint_parsing_would_strip() {
for suffix in ["'", "\"", "<", ">", "\"'>"] {
let server = format!("wss://figcraft.example/{suffix}");
assert!(figcraft_collab_net::Endpoint::parse(&server).is_ok(), "the parser cleans {server:?}");
assert_eq!(page_server(&server), None, "{server:?} must not replace the default server");
}
}
+36 -1
View File
@@ -23,6 +23,11 @@ pub struct Swapped {
pub styles: usize,
pub variables: usize,
pub unmatched: Vec<String>,
/// The old library's copies the swap removed because nothing in the document used them before
/// it (an imported component no instance shows, a variable nothing binds), named as in
/// `unmatched`. Copies that went because what used them moved to the other library aren't
/// listed.
pub dropped: Vec<String>,
/// Nothing of the old library is used any more: it was removed from the document.
pub removed: bool,
}
@@ -70,15 +75,45 @@ fn match_components(doc: &Document, records: &[ImportedComponent], m: &LibraryMa
pairs
}
/// `from`'s copies in `doc`, each by its local id with its name as [`Swapped::dropped`] gives it.
fn copies_of(doc: &Document, from: &str) -> Vec<(String, String)> {
let libs = &doc.libraries;
let coll_name = |id: &str| doc.variables.collection_by_id(id).map(|c| c.name.clone()).unwrap_or_default();
let components = libs
.components
.iter()
.filter(|r| r.library == from)
.map(|r| (format!("node {}", r.root.0), format!("component {}", doc.node(r.root).map(|n| n.name.as_str()).unwrap_or_default())));
let styles = libs
.styles
.iter()
.filter(|r| r.library == from)
.map(|r| (format!("style {}", r.local), format!("style {}", doc.style(&r.local).map(|st| st.name.as_str()).unwrap_or_default())));
let variables = libs.variables.iter().filter(|r| r.library == from).map(|r| {
let name = doc.variables.get_by_id(&r.local).map(|v| format!("{}/{}", coll_name(&v.collection), v.name)).unwrap_or_default();
(format!("variable {}", r.local), format!("variable {name}"))
});
let collections = libs
.collections
.iter()
.filter(|r| r.library == from)
.map(|r| (format!("collection {}", r.local), format!("collection {}", coll_name(&r.local))));
components.chain(styles).chain(variables).chain(collections).collect()
}
/// Swap the copies of library `from` in `doc` to library `to` by names (see the module docs).
pub fn swap_library(doc: &mut Document, from: &str, to: &PublishedLibrary) -> Result<Swapped> {
let m = &to.manifest;
if m.id == from {
return Err(EngineError::Other("that is the same library".into()));
}
// Only what the document uses counts (copies nothing uses any more go first).
// Only what the document uses counts: copies nothing uses any more go first, and are listed
// (#2569). Those the final prune takes were in use, by what moved to B.
let before = copies_of(doc, from);
prune(doc, from)?;
let mut out = Swapped::default();
let kept: BTreeSet<String> = copies_of(doc, from).into_iter().map(|(id, _)| id).collect();
out.dropped = before.into_iter().filter(|(id, _)| !kept.contains(id)).map(|(_, name)| name).collect();
let store = doc.library_store();
let outside = |d: &Document, id: NodeId| store.is_none_or(|s| d.page_of(id) != Some(s));
@@ -180,3 +180,38 @@ fn swap_repoints_colour_calculations() {
let reads: Vec<&VariableId> = ["veil", "wash"].iter().flat_map(|n| vars.get(n).unwrap().values.values()).flat_map(|v| v.references()).collect();
assert!(reads.iter().all(|r| doc.libraries.variable_import(r).is_some_and(|i| i.library == b)), "{reads:?}");
}
/// Copies of A nothing uses (a component imported but not placed, a variable imported but not
/// bound) go with the swap, as they did; the result now names them (#2569). A copy the swap moves
/// to B isn't among them.
#[test]
fn swap_lists_the_unused_copies_it_removes() {
let (_dir, mut s, a, b) = two_libraries("unused", &["Only in A"]);
let placed = idv(&ex(&mut s, "library.place", json!({"library": a, "component": "Button", "x": 0, "y": 0})));
let only = id_of(&ex(&mut s, "library.import", json!({"library": a, "component": "Only in A"}))["component"]).unwrap();
ex(&mut s, "library.importVariable", json!({"library": a, "variable": "accent"}));
let r = ex(&mut s, "library.swap", json!({"from": a, "to": b}));
assert_eq!(r["dropped"], json!(["component Only in A", "variable Theme/accent", "collection Theme"]), "{r}");
assert_eq!((r["components"].as_u64(), r["variables"].as_u64(), &r["unmatched"]), (Some(1), Some(0), &json!([])), "{r}");
assert_eq!(r["removed"], true, "{r}");
let doc = s.doc().unwrap();
assert!(!doc.contains(only), "the dropped copy is gone");
assert_eq!(library_of(doc, main_of(&s, placed)), Some(b.as_str()), "the placed Button moved, so it isn't listed");
assert!(doc.variables.variables.is_empty() && doc.variables.collections.is_empty(), "{:?}", doc.variables);
// One undo step brings them back.
s.undo().unwrap();
let doc = s.doc().unwrap();
assert!(doc.contains(only) && library_of(doc, only) == Some(a.as_str()));
assert_eq!(doc.variables.variables.len(), 1);
// A deleted instance leaves its copy unused, so it is listed too; a placed copy B has no match
// for stays and is listed as unmatched.
ex(&mut s, "edit.delete", json!({"ids": [placed]}));
let kept = idv(&ex(&mut s, "library.place", json!({"library": a, "component": "Only in A", "x": 0, "y": 0})));
let r = ex(&mut s, "library.swap", json!({"from": a, "to": b}));
assert_eq!(r["dropped"], json!(["component Button", "variable Theme/accent", "collection Theme"]), "{r}");
assert_eq!((&r["unmatched"], &r["removed"]), (&json!(["component Only in A"]), &json!(false)), "{r}");
assert_eq!(library_of(s.doc().unwrap(), main_of(&s, kept)), Some(a.as_str()));
}
+5 -1
View File
@@ -55,5 +55,9 @@ pub fn openable(url: &str) -> bool {
// The authority is made of host characters only (an opener that can't parse the address may
// fall back to treating it as a file path).
let authority = after.split(['/', '?', '#']).next().unwrap_or_default();
authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c))
// A query, fragment, userinfo or port alone does not supply a host.
let host = authority.rsplit('@').next().unwrap_or_default();
!host.is_empty()
&& !host.starts_with(':')
&& authority.chars().all(|c| !c.is_ascii() || c.is_ascii_alphanumeric() || "-._~:@[]%!$&'()*+,;=".contains(c))
}
+4 -2
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"library.swap",
"Swap library",
"{from (an enabled library: id, name or path), to (another enabled library)} re-points every component instance, style and variable copied from `from` to the published one of the same name in `to` (instances keep their overrides) → {components, styles, variables, unmatched: [names still from `from`], removed (nothing of `from` is used any more: it was removed)}",
"{from (an enabled library: id, name or path), to (another enabled library)} re-points every component instance, style and variable copied from `from` to the published one of the same name in `to` (instances keep their overrides) → {components, styles, variables, unmatched: [names still from `from`], dropped: [names of `from`'s copies nothing used (a component imported but not placed, a variable imported but not bound): removed, not moved], removed (nothing of `from` is used any more: it was removed)}",
true,
swap_cmd
),
@@ -599,7 +599,9 @@ fn swap_cmd(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "`from` and `to` are the same library"));
}
let r = crate::library_swap::swap_library(s.doc_mut()?, &from, &lib)?;
Ok(json!({"components": r.components, "styles": r.styles, "variables": r.variables, "unmatched": r.unmatched, "removed": r.removed}))
Ok(
json!({"components": r.components, "styles": r.styles, "variables": r.variables, "unmatched": r.unmatched, "dropped": r.dropped, "removed": r.removed}),
)
}
fn assets_json(lib: &PublishedLibrary) -> Value {
+10
View File
@@ -9,17 +9,27 @@ fn web_links_are_opened() {
"http://example.com",
"https://example.com",
"https://example.com/a/b?c=d#e",
"https://example.com?c=d",
"https://example.com#e",
"HTTPS://EXAMPLE.COM",
"HtTp://example.com",
"mailto:a@b.c",
"mailto:a@b.c?subject=hi",
" https://example.com ",
"https://user:pw@example.com:8443/p",
"https://user:pw@[::1]:8443/p",
] {
assert!(openable(url), "{url:?} should open");
}
}
#[test]
fn web_links_without_a_host_are_refused() {
for url in ["https://?c=d", "http://#e", "https://user@", "https://user@:443/p", "https://:443/p", "https://user:pw@?c=d", "https://@#e"] {
assert!(!openable(url), "{url:?} must be refused");
}
}
#[test]
fn script_and_handler_schemes_are_refused() {
for url in [
+138 -2
View File
@@ -373,6 +373,11 @@ fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>)
}
out.push(draw::paint_bounds(doc, parent)?);
}
ancestor_areas(doc, id, out)
}
/// The areas of the ancestors of `id` that a change to it affects, beyond its own.
fn ancestor_areas(doc: &Document, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
// Ancestors that paint from their children's pixels (booleans, effects, masks): all of them.
for a in doc.ancestors(id) {
let Some(an) = doc.node(a) else { break };
@@ -386,6 +391,138 @@ fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>)
Some(())
}
/// Page areas in which `id` looks different in `after` than in `before` (where it was and where
/// it is now, and what of its ancestors follows); `None` when only a full render will do.
fn edited_areas(before: &Document, after: &Document, page: NodeId, id: NodeId, out: &mut Vec<Rect>) -> Option<()> {
// A vector whose points moved looks different only around them.
if let Some(area) = moved_points_area(before, after, page, id) {
out.push(area);
ancestor_areas(before, id, out)?;
return ancestor_areas(after, id, out);
}
changed_areas(before, page, id, out)?;
changed_areas(after, page, id, out)
}
/// Vectors with more points than this are drawn again whole when they change.
const MAX_MOVED_POINTS: usize = 4096;
/// Whether every visible paint of `paints` is one colour: it looks the same wherever the layer's
/// box lies (a gradient or an image is laid out in the box).
fn plain(paints: &[figcraft_color::Paint]) -> bool {
paints.iter().filter(|p| p.visible).all(|p| matches!(p.kind, figcraft_color::PaintKind::Solid { .. }))
}
/// The page area in which vector `id` looks different in `after` than in `before`, when all that
/// changed is where its points and handles are (a point dragged in the vector editor): around the
/// segments that moved and their neighbours (whose joins and rounded corners follow them), as far
/// out as the stroke reaches. The rest of a large shape keeps its pixels, however much of the
/// view it fills. `None` when anything else changed or the look depends on the whole outline
/// (dashes, a width profile, a brush, gradients and images laid out in the box, effects, a mask):
/// the layer is then drawn again whole.
fn moved_points_area(before: &Document, after: &Document, page: NodeId, id: NodeId) -> Option<Rect> {
let (a, b) = (before.node(id)?, after.node(id)?);
let (NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) = (&a.kind, &b.kind) else { return None };
if after.page_of(id) != Some(page) || before.page_of(id) != Some(page) {
return None;
}
let simple = |n: &figcraft_doc::Node, net: &figcraft_doc::VectorNetwork| {
!n.is_mask
&& n.visible
&& !n.effects.iter().any(|e| e.visible)
&& n.stroke.dashes.is_empty()
&& n.stroke.width_profile.is_none()
&& n.stroke.brush.is_none()
&& plain(&n.fills)
&& plain(&n.strokes)
&& net.regions.iter().all(|r| r.fills.as_deref().is_none_or(plain))
};
let same_shape = na.vertices.len() == nb.vertices.len()
&& na.vertices.len() <= MAX_MOVED_POINTS
&& na.segments.len() == nb.segments.len()
&& na.segments.iter().zip(&nb.segments).all(|(x, y)| (x.a, x.b) == (y.a, y.b))
&& na.regions.len() == nb.regions.len()
&& na.regions.iter().zip(&nb.regions).all(|(x, y)| x.loops == y.loops && x.winding == y.winding && x.fills == y.fills);
if !(simple(a, na) && simple(b, nb) && same_shape) {
return None;
}
// A fill closes an open path with a line between its ends that is no segment: it moves
// with either end, across the whole shape.
let mut ends = vec![0u8; na.vertices.len()];
for s in &na.segments {
for i in [s.a, s.b] {
let n = ends.get_mut(i)?;
*n = n.saturating_add(1);
}
}
let filled = a.fills.iter().any(|f| f.visible) || !na.regions.is_empty();
if filled && ends.contains(&1) {
return None;
}
// Nothing but the geometry differs: the box follows the points, and with it the transform.
let mut as_after = a.clone();
as_after.kind = b.kind.clone();
(as_after.transform, as_after.width, as_after.height) = (b.transform, b.width, b.height);
if as_after != *b {
return None;
}
let (wa, wb) = (before.world_transform(id), after.world_transform(id));
// The box following the points moves the layer; anything else a transform does (a scale, a
// turn) changes every stroke's width or direction on the page, whether its path moved or not.
let (ca, cb) = (wa.as_coeffs(), wb.as_coeffs());
if ca.iter().zip(&cb).take(4).any(|(x, y)| (x - y).abs() > 1e-12 * x.abs().max(1.0)) {
return None;
}
// A segment on the page: its ends and handles.
let hull = |w: figcraft_geom::Affine, net: &figcraft_doc::VectorNetwork, s: &figcraft_doc::Segment| {
let (pa, pb) = (net.vertices.get(s.a)?.point(), net.vertices.get(s.b)?.point());
let pts = [pa, pa + figcraft_geom::Vec2::new(s.ta.0, s.ta.1), pb + figcraft_geom::Vec2::new(s.tb.0, s.tb.1), pb].map(|p| w * p);
pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()).then_some(pts)
};
let mut moved = vec![false; na.vertices.len()];
let mut hulls = Vec::with_capacity(na.segments.len());
for (sa, sb) in na.segments.iter().zip(&nb.segments) {
let (ha, hb) = (hull(wa, na, sa)?, hull(wb, nb, sb)?);
// Apart by more than float noise. When the box follows a moved point every local
// coordinate shifts and the transform shifts back: a point that stayed put comes out a
// few ulps from where it was. 64 of them is far above that and far under a pixel at any
// zoom, wherever on the page the vector lies (a tenth of a millionth of a unit at
// coordinates of ten million).
let near = |x: f64, y: f64| (x - y).abs() <= 64.0 * f64::EPSILON * x.abs().max(y.abs()).max(1.0);
let apart = ha.iter().zip(&hb).any(|(p, q)| !(near(p.x, q.x) && near(p.y, q.y)));
let styled =
|i: usize| na.vertices.get(i).zip(nb.vertices.get(i)).is_none_or(|(x, y)| (x.radius, x.cap, x.join) != (y.radius, y.cap, y.join));
if apart || styled(sa.a) || styled(sa.b) {
for i in [sa.a, sa.b] {
*moved.get_mut(i)? = true;
}
}
hulls.push((ha, hb));
}
// Every segment at a point of a segment that moved: its join or rounded corner there follows.
let mut area: Option<Rect> = None;
for (s, (ha, hb)) in na.segments.iter().zip(&hulls) {
if moved.get(s.a).copied().unwrap_or(true) || moved.get(s.b).copied().unwrap_or(true) {
for p in ha.iter().chain(hb) {
let r = Rect::from_points(*p, *p);
area = Some(area.map_or(r, |a| a.union(r)));
}
}
}
let area = area?;
// As far as the stroke reaches from the path, on the page.
// The most the transform stretches a length in any direction (its largest singular value):
// under a skew that is more than either axis is stretched.
let stretch = |w: figcraft_geom::Affine| {
let c = w.as_coeffs();
let sum = c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3];
let det = c[0] * c[3] - c[1] * c[2];
((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
};
let reach = (a.outline_reach() * stretch(wa)).max(b.outline_reach() * stretch(wb));
reach.is_finite().then(|| area.inflate(reach, reach))
}
/// The previous frame brought up to date for `doc` at `px`, rendering only what changed; `None`
/// when a full render is the better (or only correct) choice. Also returns the pixels rendered.
fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64, i64), opts: &Options, s: &Sensitive) -> Option<(Pixmap, u64)> {
@@ -434,8 +571,7 @@ fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64,
if in_pattern_source(doc, s, id) || in_pattern_source(&last.doc, &last.sensitive, id) {
return None;
}
changed_areas(&last.doc, page, id, &mut areas)?;
changed_areas(doc, page, id, &mut areas)?;
edited_areas(&last.doc, doc, page, id, &mut areas)?;
}
for r in areas {
if let Some(p) = to_px(r, view.scale, px) {
+133
View File
@@ -65,3 +65,136 @@ fn a_clip_edge_on_a_pixel_boundary_clips_the_same_in_every_render() {
assert_same(&pix, &render_view(&smaller, page, &shown, &opts).unwrap(), &format!("lod {lod}"));
}
}
/// A closed zigzag of `2 * teeth + 2` points, 240 × 120 units at (20, 20): a ridge.
fn ridge(d: &mut Document, page: NodeId, teeth: usize) -> NodeId {
let mut pts = vec![figcraft_geom::Point::new(0.0, 120.0)];
for i in 0..=teeth * 2 {
pts.push(figcraft_geom::Point::new(240.0 * i as f64 / (teeth * 2) as f64, if i % 2 == 0 { 60.0 } else { 10.0 }));
}
pts.push(figcraft_geom::Point::new(240.0, 120.0));
let network = figcraft_doc::VectorNetwork::from_points(&pts, true);
let id = d.create(page, NodeKind::Vector { network }, "Ridge", 20.0, 20.0, 240.0, 120.0).unwrap();
d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex("7FAE9C").unwrap())];
id
}
fn move_point(d: &mut Document, id: NodeId, point: usize, by: (f64, f64)) {
if let NodeKind::Vector { network } = &mut d.get_mut(id).unwrap().kind {
network.vertices[point].x += by.0;
network.vertices[point].y += by.1;
}
}
/// A point of a vector dragged while the vector fills the view (zoomed to it, as the vector
/// editor does): the shape looks different only around the point's segments, and only that is
/// drawn again. (Its whole box was, and past 60 % of the view that made every frame of the
/// drag a full render.)
#[test]
fn a_moved_point_redraws_the_vector_around_it_only() {
type Style = fn(&mut figcraft_doc::Node);
let styles: [(&str, Style); 4] = [
("filled", |_| {}),
("stroked, mitred", |n| {
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 6.0;
n.stroke.miter_limit = 4.0;
}),
("rounded points", |n| {
if let NodeKind::Vector { network } = &mut n.kind {
network.vertices.iter_mut().for_each(|v| v.radius = 9.0);
}
}),
("stroked only", |n| {
n.fills.clear();
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
}),
];
for (what, style) in styles {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
style(d.get_mut(id).unwrap());
let doc = Arc::new(d);
// The ridge is 720 × 360 of the view's 780 × 420 pixels.
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, what);
let mut d2 = (*doc).clone();
move_point(&mut d2, id, 6, (4.0, -7.0));
let d2 = Arc::new(d2);
let (_, _, work) = r.render(&d2, page, &v, &Options::default()).unwrap();
let Work::Partial { pixels } = work else { panic!("{what}: a full render ({work:?})") };
// A tooth of six each way from the point, and what the stroke adds (36 pixels each way
// for the mitred one); the ridge's box is 259,200 pixels.
assert!(pixels < 780 * 420 * 2 / 5, "{what}: {pixels} pixels drawn again");
check(&mut r, &d2, page, &v, what);
// And back: the same again.
let (_, _, work) = r.render(&doc, page, &v, &Options::default()).unwrap();
assert!(matches!(work, Work::Partial { .. }), "{what}: {work:?}");
check(&mut r, &doc, page, &v, what);
}
}
/// What depends on the whole outline is drawn again whole: a gradient laid out in the vector's
/// box, dashes that run on from the moved point, an open path's closing line.
#[test]
fn a_moved_point_redraws_a_vector_whole_when_its_look_depends_on_all_of_it() {
type Style = fn(&mut figcraft_doc::Node);
let styles: [(&str, Style); 3] = [
("dashed", |n| {
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
n.stroke.dashes = vec![8.0, 5.0];
}),
("a shadow", |n| n.effects.push(Effect::inner_shadow())),
("an open path", |n| {
if let NodeKind::Vector { network } = &mut n.kind {
network.segments.pop();
}
}),
];
for (what, style) in styles {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
style(d.get_mut(id).unwrap());
let doc = Arc::new(d);
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, what);
let mut d2 = (*doc).clone();
move_point(&mut d2, id, 6, (4.0, -7.0));
let d2 = Arc::new(d2);
assert_eq!(r.render(&d2, page, &v, &Options::default()).unwrap().2, Work::Full, "{what}");
check(&mut r, &d2, page, &v, what);
}
}
/// A vector's strokes are as wide on the page as its transform makes them. Scaled up with its
/// points scaled down to match, its paths stay where they were and every stroke doubles: with a
/// point moved too, all of it is drawn again, not the area around that point.
#[test]
fn a_moved_point_with_a_scaled_vector_redraws_all_of_it() {
let mut d = Document::new("ridge");
let page = d.first_page().unwrap();
let id = ridge(&mut d, page, 6);
let n = d.get_mut(id).unwrap();
n.strokes = vec![Paint::solid(Color::from_hex("203040").unwrap())];
n.stroke.weight = 3.0;
let doc = Arc::new(d);
let v = View { origin: (10.0, 10.0), scale: 3.0, width: 780, height: 420 };
let mut r = Retained::default();
check(&mut r, &doc, page, &v, "first");
let mut d2 = (*doc).clone();
let n = d2.get_mut(id).unwrap();
n.transform *= Affine::scale(2.0);
(n.width, n.height) = (n.width / 2.0, n.height / 2.0);
if let NodeKind::Vector { network } = &mut n.kind {
for p in &mut network.vertices {
(p.x, p.y) = (p.x / 2.0, p.y / 2.0);
}
}
move_point(&mut d2, id, 6, (2.0, -3.5));
check(&mut r, &Arc::new(d2), page, &v, "scaled, a point moved");
}
+6 -3
View File
@@ -126,7 +126,7 @@ page 1 "Screens": 380 nodes, 4 top-level
### `export <file> -o <out> [--format png|jpg|svg|webp|pdf|xml|fig|penpot] [--scale N] [--page NAME] [--node ID|NAME] [--bleed LENGTH] [--crop-marks] [--bleed-marks] [--cmyk] [--vd-compat bestEffort|exact|ignore]`
- `<out>` is a directory: one file per top-level frame of the page (default the first page), named
- `<out>` is a directory: one file per top-level frame of the selected page, named
after the frame (`Home.png`, `Settings.png`…); with no frames, one file per top-level layer.
The name is kept as it is, except for the characters file systems refuse (`/ \ : * ? " < > |`
and control characters), which become `_`, and leading or trailing spaces and dots, which are
@@ -135,6 +135,9 @@ page 1 "Screens": 380 nodes, 4 top-level
characters (there a `/` makes a folder). Two layers with the same name get `Name 2`, `Name 3`…
With `--node`, the CLI writes one file named after the selected layer, including a nested layer.
- `<out>` has an image extension: one file with the given `--node`, or the whole page composited.
- `--page` defaults to the first non-divider page: empty pages whose names start with `-` are
skipped. If all pages are dividers, the first is used. `--page NAME` can select one explicitly.
The `.fig` and `.penpot` formats export the whole document and ignore `--page`.
- `--node` takes a layer id (`12` or `0:12`) or a layer name.
- `--format fig` (or an `<out>` ending in `.fig`) writes the whole file as `.fig`, experimental:
written from public format notes, including variables with their modes and bindings and shared
@@ -198,8 +201,8 @@ When converting from a `.penpot` file, import warnings are printed to stderr as
### `render <file> -o <out.png> [--scale N] [--page NAME]`
The whole page (default the first) with its background, as png, jpg or webp. Large pages are scaled
down to fit 16384 px.
The whole page with its background, as png, jpg or webp. `--page` defaults to the first non-divider
page, as for `export`. Large pages are scaled down to fit 16384 px.
### `run <script.json|script.jsonl> [--in <file>] [--out <file>]`
File diff suppressed because one or more lines are too long
+11 -1
View File
File diff suppressed because one or more lines are too long
+3 -1
View File
@@ -1124,7 +1124,9 @@ most when it can't be reached).
by name in their set, styles by name and type, variables by collection, name and type, modes by
name), keeping overrides; one undo step → `{components, styles, variables, unmatched: [names
still from `from`, including this file's collections that extend one of its collections],
removed (nothing of `from` was left, so it was removed)}`.
dropped: [`from`'s copies nothing used before the swap, which it removed rather than moved: a
component imported but not placed, or whose instances were deleted; a variable imported but not
bound], removed (nothing of `from` was left, so it was removed)}`.
### Overrides and variants