diff --git a/.github/workflows/lockfile.yml b/.github/workflows/lockfile.yml index 398740a74..e630c9a8f 100644 --- a/.github/workflows/lockfile.yml +++ b/.github/workflows/lockfile.yml @@ -18,7 +18,7 @@ env: jobs: lockfile: name: Lockfile is in sync - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }} + runs-on: ubuntu-24.04 timeout-minutes: 10 steps: - name: Harden runner diff --git a/ROADMAP.md b/ROADMAP.md index ca5abbbe7..a58494222 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -367,7 +367,9 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| | 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-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`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-18 | minor | M8: asset handoff. `file.exportAssets` and the MCP tool `export_assets` write a design's images and vectors into a folder: images as the file's original bytes, never re-encoded, vectors as SVG, layers with export settings by those settings, each saying which it is. Files are named by their content, so an asset has one file and exporting again writes nothing; what a layer does to an image that isn't in its bytes is listed. Numbers unchanged | diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index 74e14c4b9..7af33a0f9 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -344,6 +344,14 @@ fn main() -> eframe::Result { let mut session = Session::empty(); // Live sessions: the network threads wake the window when something arrives. session.live.install(Box::new(figcraft_collab_net::NetLink::new(Arc::new(wake(&ctx_slot))))); + // The preferences first: a file named on the command line opens where it was left and goes to + // the top of the recent files, and they hold the online files a recovered document may be one of. + let recovery = recovery::Shared::default(); + let svc = services::Desktop::load(recovery.clone()); + svc.follow_system_dark(wake(&ctx_slot)); + if let Some(prefs) = svc.prefs.clone() { + session.prefs = prefs; + } // A file that won't open is said in the window too: it may have been double-clicked. let mut failed_open = None; for f in &args.files { @@ -353,16 +361,9 @@ fn main() -> eframe::Result { failed_open = Some(format!("{name}: {e}")); } } - let opened: Vec = session.docs.iter().map(|d| d.uid).collect(); + let mut opened: Vec = session.docs.iter().map(|d| d.uid).collect(); // Documents a crashed or killed run left unsaved come back; this run keeps its own copies. let recovery_root = services::config_dir().map(|d| d.join("Recovery")); - // The preferences first: they hold the online files a recovered document may be one of. - let recovery = recovery::Shared::default(); - let svc = services::Desktop::load(recovery.clone()); - svc.follow_system_dark(wake(&ctx_slot)); - if let Some(prefs) = svc.prefs.clone() { - session.prefs = prefs; - } let recovered = recovery_root.as_deref().map(|r| recovery::recover_all(r, &mut session)).unwrap_or_default(); let mut copies = recovery_root.as_deref().and_then(recovery::Recovery::start); // Copies of online files stay until their files arrive from their servers. @@ -380,7 +381,20 @@ fn main() -> eframe::Result { session.invite_links_startup(); } let first_run = svc.prefs.is_none() && args.join.is_none(); - if session.docs.is_empty() && opens_new_file(first_run, session.prefs.start_on_home, port.is_some()) { + if reopens_files(first_run, session.prefs.start_on_home) { + let before: Vec = session.docs.iter().map(|d| d.uid).collect(); + for (path, e) in session.reopen_files() { + log::error!("{path}: {e}"); + let name = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned()); + failed_open = Some(format!("{name}: {e}")); + } + // A file named on the command line stays in front. + if let Some(i) = opened.last().and_then(|uid| session.docs.iter().position(|d| d.uid == *uid)) { + session.active = i; + } + opened.extend(session.docs.iter().map(|d| d.uid).filter(|u| !before.contains(u))); + } + if session.docs.is_empty() && opens_new_file(first_run, port.is_some()) { let _ = session.execute("file.new", &json!({})); } // The interface language from the first frame on, and for the message when the window can't @@ -395,7 +409,8 @@ fn main() -> eframe::Result { } fig.automation_roots = roots; fig.ui.home = false; - // Files named on the command line are the user's too: their missing fonts are listed. + // Files named on the command line or reopened are the user's too: their missing fonts are + // listed. fig.ui.font_checks = opened; fig.note_recovered(recovered.copies); if let Some(message) = failed_open { @@ -516,12 +531,17 @@ fn main() -> eframe::Result { graphics.finish(result, frames, port.is_some()) } -/// With nothing to open, whether the window starts in a new file rather than on the home screen. -/// A first run (no settings kept yet) shows the home screen's tips and templates, and later runs -/// start in a new file unless the preference asks for Home, which `--control` overrides: its -/// callers expect a document to act on. -fn opens_new_file(first_run: bool, start_on_home: bool, control: bool) -> bool { - !first_run && (!start_on_home || control) +/// Whether the files open when the app last quit open again: not on a first run (no settings kept +/// yet), nor when the preference asks for the Home screen. +fn reopens_files(first_run: bool, start_on_home: bool) -> bool { + !first_run && !start_on_home +} + +/// With nothing open, whether the window starts in a new file rather than on the home screen: only +/// with a control port open (`--control`), whose callers expect a document to act on. A first run +/// shows the home screen's tips and templates whatever the port. +fn opens_new_file(first_run: bool, control: bool) -> bool { + !first_run && control } /// The title bar FigCraft starts with, decided by the shared craft-window crate so every Craft app @@ -617,14 +637,20 @@ mod title_bar_tests { #[cfg(test)] mod start_tests { - use super::opens_new_file; + use super::{opens_new_file, reopens_files}; #[test] - fn the_home_preference_starts_on_home_except_for_control_callers() { - assert!(opens_new_file(false, false, false), "a new file by default"); - assert!(!opens_new_file(false, true, false), "Home when the preference asks"); - assert!(opens_new_file(false, true, true), "--control still starts with a document"); - assert!(!opens_new_file(true, false, false), "a first run shows the home screen"); + fn the_last_files_reopen_unless_the_home_preference_asks_or_on_a_first_run() { + assert!(reopens_files(false, false), "by default"); + assert!(!reopens_files(false, true), "Home when the preference asks"); + assert!(!reopens_files(true, false), "a first run has nothing to reopen"); + } + + #[test] + fn with_nothing_open_only_control_callers_start_in_a_new_file() { + assert!(!opens_new_file(false, false), "the home screen, not an empty file"); + assert!(opens_new_file(false, true), "--control starts with a document"); + assert!(!opens_new_file(true, true), "a first run shows the home screen"); } } diff --git a/apps/figcraft/src/services.rs b/apps/figcraft/src/services.rs index e4f949c51..e23294567 100644 --- a/apps/figcraft/src/services.rs +++ b/apps/figcraft/src/services.rs @@ -357,9 +357,12 @@ fn open_directory(file: &std::fs::File) -> Result<(), String> { const STATE: &str = "state.json"; /// Everything quitting keeps, all done when it returns (macOS then ends the process): the -/// preferences in `dir`, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit)) +/// preferences in `dir` with the files open now, which the next start reopens, and where each was +/// left, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit)) /// and the live sessions' ends (one this app hosts tells everyone and stops; a joined one leaves). pub fn shutdown(app: &mut FigApp, dir: Option<&Path>, recovery: Option) { + app.session.remember_open_files(); + app.session.remember_views(); if let Some(dir) = dir { write_prefs(dir, &app.session.prefs); } diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 5db5af752..fad9d1a90 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -250,6 +250,15 @@ pub struct CodeLink { pub name: String, /// The snippet with `{property}` and `{property ? "a" : "b"}` placeholders. pub template: String, + /// Where the code component lives, relative to the code repository. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub source: String, + /// What a property's design values are called in code: property → design value → code value. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub values: BTreeMap>, + /// Notes for whoever uses the component. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub notes: String, } /// A dev resource: a link for developers attached to a layer. The URL is data only: it is shown diff --git a/crates/engine/src/assets/components.rs b/crates/engine/src/assets/components.rs index 06c82563a..80108045d 100644 --- a/crates/engine/src/assets/components.rs +++ b/crates/engine/src/assets/components.rs @@ -338,6 +338,8 @@ pub fn prop_default_value(d: &PropDef) -> Value { } } +#[cfg(test)] +mod nested_binding_tests; #[cfg(test)] mod rebase_source_tests; diff --git a/crates/engine/src/assets/components/diff.rs b/crates/engine/src/assets/components/diff.rs index 5c6b7e4c5..9102a38d6 100644 --- a/crates/engine/src/assets/components/diff.rs +++ b/crates/engine/src/assets/components/diff.rs @@ -35,6 +35,38 @@ pub(super) fn bindings_of<'a>(n: &'a Node, g: &'a str) -> impl Iterator bool { + let canonical = |m: &Node| -> std::collections::BTreeSet<(String, String)> { + bindings_of(m, g) + .map(|(k, v)| { + let key = crate::cmd::lists::list_binding(k).map_or_else(|| k.clone(), |(l, i, f)| format!("{}/{i}/{f}", l.prefix())); + (key, v.clone()) + }) + .collect() + }; + canonical(n) != canonical(src) +} + +/// The property groups whose variable bindings differ between layer `n` and its main layer `src`: +/// overrides even where both resolve to the same value. +pub(super) fn rebound_groups(n: &Node, src: &Node) -> Vec<&'static str> { + let mut compared = Vec::new(); + let mut out = Vec::new(); + for k in n.bound.keys().chain(src.bound.keys()) { + let Some(g) = binding_group(k) else { continue }; + if compared.contains(&g) { + continue; + } + compared.push(g); + if bound_differently(n, src, g) { + out.push(g); + } + } + out +} + /// Property groups that differ between two versions of a node. pub fn diff_groups(a: &Node, b: &Node) -> Vec<&'static str> { let mut out = Vec::new(); diff --git a/crates/engine/src/assets/components/nested_binding_tests.rs b/crates/engine/src/assets/components/nested_binding_tests.rs new file mode 100644 index 000000000..035014dcf --- /dev/null +++ b/crates/engine/src/assets/components/nested_binding_tests.rs @@ -0,0 +1,51 @@ +use serde_json::json; + +use super::rebase_instance; +use super::tests::{button, copy_of, ex, fill, idv, node}; +use crate::{NodeId, Session}; + +fn bound_shape_in_button() -> (Session, NodeId, NodeId, NodeId, NodeId) { + let mut s = Session::new(); + let (_, shape, button, nested) = button(&mut s); + ex(&mut s, "variable.createCollection", json!({"name": "T"})); + ex(&mut s, "variable.create", json!({"collection": "T", "name": "ink", "type": "color", "value": "#111111"})); + let inner = copy_of(&s, nested, shape); + ex(&mut s, "variable.bind", json!({"ids": [inner.0], "field": "fill", "variable": "ink"})); + assert!(node(&s, inner).overrides.contains("fills")); + (s, shape, button, nested, inner) +} + +#[test] +fn relinking_an_instance_keeps_a_binding_its_main_lacks_as_an_override() { + let (mut s, shape, button, nested, inner) = bound_shape_in_button(); + let doc = s.ds_mut().unwrap().doc_mut(); + doc.get_mut(inner).unwrap().overrides.clear(); + rebase_instance(doc, nested); + assert!(node(&s, inner).overrides.contains("fills"), "the same colour from a variable the main doesn't bind"); + ex(&mut s, "node.set", json!({"id": shape, "props": {"fill": "#FF0000"}})); + assert_eq!(fill(&s, inner), "111111", "an edit of the icon's main leaves the bound colour"); + let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400}))); + let copy = copy_of(&s, placed, inner); + assert_eq!(node(&s, copy).bound.values().collect::>(), [&node(&s, inner).bound["fill"]]); +} + +#[test] +fn hiding_and_showing_a_bound_fill_keeps_its_override() { + let (mut s, _, _, _, inner) = bound_shape_in_button(); + ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": false})); + ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": true})); + let n = node(&s, inner); + assert!(n.bound.contains_key("fill")); + assert!(n.overrides.contains("fills"), "the binding still differs from the main's"); +} + +#[test] +fn a_top_level_instance_s_own_resizing_binding_is_not_an_override() { + let mut s = Session::new(); + let (_, _, button, _) = button(&mut s); + let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400}))); + let doc = s.ds_mut().unwrap().doc_mut(); + doc.get_mut(placed).unwrap().bound.insert("minWidth".into(), "VariableID:1:1".into()); + rebase_instance(doc, placed); + assert!(!node(&s, placed).overrides.contains("resizing"), "a top-level instance's resizing is its own"); +} diff --git a/crates/engine/src/assets/components/patch.rs b/crates/engine/src/assets/components/patch.rs index 92d2e2f29..1b275721b 100644 --- a/crates/engine/src/assets/components/patch.rs +++ b/crates/engine/src/assets/components/patch.rs @@ -1,4 +1,4 @@ -use super::diff::{binding_group, bindings_of, diff_groups, follow_boolean_defaults, geometry_derived, variable_groups}; +use super::diff::{binding_group, bound_differently, diff_groups, follow_boolean_defaults, geometry_derived, rebound_groups, variable_groups}; use super::guard::{own_slot_content, relink_copy}; use super::instances::{copy_group, field_group, sync_instance}; use super::sync::insert_linked; @@ -179,12 +179,17 @@ fn override_groups(doc: &Document, before: &Document, id: NodeId, n: &Node, b: & // Binding another variable (or none) where the main binds one is an override. for (k, _) in b.bound.iter().chain(n.bound.iter()) { let Some(g) = binding_group(k) else { continue }; - let rebound = b.bound.get(k) != n.bound.get(k) && !bindings_of(n, g).eq(bindings_of(src, g)); + let rebound = b.bound.get(k) != n.bound.get(k) && bound_differently(n, src, g); if rebound && !groups.contains(&g) { groups.push(g); } } - cleared = raw.iter().filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && n.overrides.contains(**g)).copied().collect(); + let rebound = rebound_groups(n, src); + cleared = raw + .iter() + .filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && !rebound.contains(g) && n.overrides.contains(**g)) + .copied() + .collect(); if top_root { cleared.retain(|g| !matches!(*g, "component" | "props")); } diff --git a/crates/engine/src/assets/components/rebase.rs b/crates/engine/src/assets/components/rebase.rs index aa782cb20..b8a6c67c7 100644 --- a/crates/engine/src/assets/components/rebase.rs +++ b/crates/engine/src/assets/components/rebase.rs @@ -1,4 +1,4 @@ -use super::diff::{diff_groups, variable_groups}; +use super::diff::{diff_groups, rebound_groups, variable_groups}; use super::instances::{field_group, path_map}; use super::{BTreeMap, BTreeSet, Document, MAX_DEPTH, Node, NodeId, NodeKind, default_instance_name, holds_content}; @@ -216,6 +216,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa let mut bound: Vec<&str> = m.prop_refs.keys().map(|f| field_group(f)).collect(); bound.extend(variable_groups(n, m)); overrides.extend(value_groups(m, n).into_iter().filter(|g| !bound.contains(&g.as_str()))); + overrides.extend(rebound_groups(n, m).into_iter().map(str::to_string)); if matches!((&m.kind, &n.kind), (NodeKind::Instance { component: a, .. }, NodeKind::Instance { component: b, .. }) if a != b) { overrides.insert("component".into()); } @@ -233,6 +234,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa let mut groups: Vec = value_groups(m, n) .into_iter() .filter(|g| !matches!(g.as_str(), "name" | "exports" | "interactions") && !from_variables.contains(&g.as_str())) + .chain(rebound_groups(n, m).into_iter().map(str::to_string)) .filter(|g| placed_source.is_some() || !matches!(g.as_str(), "resizing" | "modes")) .collect(); let named = if placed_source.is_some() { n.name != m.name } else { n.name != default_instance_name(doc, component) }; diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs index 1cda4aaa3..119f267af 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -115,9 +115,65 @@ fn match_layers( } m.map.insert(*s, nid); } + match_text_by_name(doc, inst, component, src, old, &mut m); m } +/// Main text layers nothing matched take the unmatched old text layer of the same name, when +/// exactly one of each has it: text typed into an instance stays when it switches to a variant that +/// nests the same text layer in other frames (its name path differs). Only layers outside nested +/// instances, which rebuild from their own mains. Names are counted over all those text layers, +/// matched ones too, so a name two layers share on either side never pairs by elimination. +fn match_text_by_name( + doc: &Document, + inst: NodeId, + component: NodeId, + src: &[NodeId], + old: &BTreeMap>, + m: &mut Matched, +) { + fn unique(pairs: impl Iterator) -> BTreeMap { + let mut seen: BTreeMap> = BTreeMap::new(); + for (k, id) in pairs { + seen.entry(k).and_modify(|e| *e = None).or_insert(Some(id)); + } + seen.into_iter().filter_map(|(k, id)| Some((k, id?))).collect() + } + let text = |n: &Node| matches!(n.kind, NodeKind::Text(_)); + let mut mains = + unique(src.iter().filter_map(|s| doc.node(*s)).filter(|s| text(s) && outside_nested(doc, s.id, component)).map(|s| (s.name.clone(), s.id))); + mains.retain(|_, s| m.fresh.contains(s)); + if mains.is_empty() { + return; + } + let olds = unique( + old.iter() + .filter(|(id, o)| text(o) && outside_nested(doc, **id, inst)) + .map(|(id, o)| (o.source.and_then(|s| doc.node(s)).map_or(&o.name, |s| &s.name).clone(), *id)), + ); + for (name, s) in mains { + if let Some(o) = olds.get(&name).filter(|o| !m.used.contains(*o)) { + m.used.insert(*o); + m.map.insert(s, *o); + m.fresh.retain(|f| *f != s); + } + } +} + +/// Whether layer `id` is below `root` with no instance between them. +fn outside_nested(doc: &Document, id: NodeId, root: NodeId) -> bool { + let mut cur = doc.node(id).and_then(|n| n.parent); + for _ in 0..=1_000_000 { + match cur.and_then(|c| doc.node(c)) { + Some(n) if n.id == root => return true, + Some(n) if matches!(n.kind, NodeKind::Instance { .. }) => return false, + Some(n) => cur = n.parent, + None => return false, + } + } + false +} + /// A rebuild's copies of the main's layers, pre-order (parents first). struct Copies { nodes: Vec, diff --git a/crates/engine/src/assets/components/tests.rs b/crates/engine/src/assets/components/tests.rs index fc7d21e86..ea5542c9d 100644 --- a/crates/engine/src/assets/components/tests.rs +++ b/crates/engine/src/assets/components/tests.rs @@ -282,6 +282,50 @@ fn variant_switch_keeps_compatible_overrides() { healthy(&s); } +#[test] +fn typed_text_stays_across_variants_that_nest_it_differently() { + let mut s = Session::new(); + // Each variant's Label layers, by the frames holding them. + let shapes: [(&str, &[&[&str]]); 4] = + [("Kind=Plain", &[&["text"]]), ("Kind=Boxed", &[&["div", "text"]]), ("Kind=Twice", &[&["a"], &["b"]]), ("Kind=Moved", &[&["a"], &["c"]])]; + let mut labels = Vec::new(); + let mut variants = Vec::new(); + for (k, (name, paths)) in shapes.into_iter().enumerate() { + let v = idv(&ex(&mut s, "frame.create", json!({"x": k as f64 * 300.0, "y": 0, "width": 200, "height": 60, "name": name}))); + for frames in paths { + let mut parent = v; + for f in *frames { + parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "parent": parent, "name": f}))); + } + labels.push(idv(&ex(&mut s, "text.create", json!({"text": "I agree", "x": 0, "y": 0, "parent": parent, "props": {"name": "Label"}})))); + } + variants.push(idv(&ex(&mut s, "component.create", json!({"ids": [v]})))); + } + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let i = idv(&ex(&mut s, "instance.create", json!({"component": variants[0], "x": 0, "y": 300}))); + let typed = copy_of(&s, i, labels[0]); + ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"})); + + ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Boxed"}})); + healthy(&s); + assert_eq!(chars(&s, copy_of(&s, i, labels[1])), "Architect", "one frame deeper, same name"); + ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Plain"}})); + assert_eq!(chars(&s, copy_of(&s, i, labels[0])), "Architect", "and back"); + + ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Twice"}})); + healthy(&s); + let texts: Vec = labels[2..4].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect(); + assert_eq!(texts, ["I agree", "I agree"], "two layers of that name: neither is the one typed into"); + + // `a › Label` matches by path; the leftover `b › Label` and `c › Label` still share a name with it. + let typed = copy_of(&s, i, labels[3]); + ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"})); + ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Moved"}})); + healthy(&s); + let texts: Vec = labels[4..].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect(); + assert_eq!(texts, ["I agree", "I agree"], "a name two layers share doesn't pair what path matching left over"); +} + #[test] fn detach_keeps_the_look() { let mut s = Session::new(); diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 3b2eb6186..e58b1e9ba 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -1422,25 +1422,7 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>, remote.extend(merge_components(doc, src, &BTreeMap::new(), Some(&foreign))?); } // Components `src` publishes: from its library. - if let Some(lib) = src.published.as_ref().filter(|l| own.as_deref() != Some(l.manifest.id.as_str())) { - let keys: Vec = - roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect(); - if !keys.is_empty() { - remote.extend(import(doc, lib, &keys, false)?); - let m = &lib.manifest; - if doc.libraries.link(&m.id).is_none() - && let Some(path) = src_path - { - doc.libraries_mut().enabled.push(LibraryLink { - id: m.id.clone(), - name: m.name.clone(), - path: path.to_string(), - version: m.version, - relative: String::new(), - }); - } - } - } + remote.extend(from_published(doc, src, src_path, &roots)?); // Point the pasted layers at those mains; what stays behind gets ids of its own. let mut behind: BTreeMap = BTreeMap::new(); let mut follow = |doc: &mut Document, id: NodeId| -> NodeId { @@ -1479,6 +1461,45 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>, Ok(()) } +/// `doc`'s copies of the components among `roots` (assets of `src`) that `src` publishes as a +/// library (`src`'s ids → `doc`'s), taken from that library, which gets enabled in `doc` when `src` +/// is saved at `src_path`. Empty when `src` publishes no library, or publishes `doc`'s own. +fn from_published(doc: &mut Document, src: &Document, src_path: Option<&str>, roots: &[NodeId]) -> Result> { + let own = doc.published.as_ref().map(|p| p.manifest.id.as_str()); + let Some(lib) = src.published.as_ref().filter(|l| own != Some(l.manifest.id.as_str())) else { return Ok(BTreeMap::new()) }; + let keys: Vec = + roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect(); + if keys.is_empty() { + return Ok(BTreeMap::new()); + } + let remote = import(doc, lib, &keys, false)?; + let m = &lib.manifest; + if doc.libraries.link(&m.id).is_none() + && let Some(path) = src_path + { + doc.libraries_mut().enabled.push(LibraryLink { + id: m.id.clone(), + name: m.name.clone(), + path: path.to_string(), + version: m.version, + relative: String::new(), + }); + } + Ok(remote) +} + +/// The main in `doc` that pasting main component `main`, copied from another document `src`, +/// makes an instance of: `doc`'s copy of it from the library `src` publishes, as +/// [`adopt_pasted`] uses for instances. `None` when `src` doesn't offer it, so the paste copies +/// the main itself: also when the library holds it only because an offered component uses it. +pub fn published_main(doc: &mut Document, src: &Document, src_path: Option<&str>, main: NodeId) -> Result> { + let Some(root) = asset_root(src, main) else { return Ok(None) }; + if !src.published.as_ref().and_then(|l| l.manifest.component(root)).is_some_and(|a| a.published) { + return Ok(None); + } + Ok(from_published(doc, src, src_path, &[root])?.get(&main).copied()) +} + /// Refuse edits of library copies, except by library commands (and imports of other files, /// which bring their copies along). pub fn check_read_only(cmd: &str, before: &Document, after: &Document) -> std::result::Result<(), String> { diff --git a/crates/engine/src/assets/library/tests.rs b/crates/engine/src/assets/library/tests.rs index 4c329cb5f..5edee822f 100644 --- a/crates/engine/src/assets/library/tests.rs +++ b/crates/engine/src/assets/library/tests.rs @@ -695,3 +695,72 @@ fn library_links_follow_a_moved_folder() { link_found(&mut s, &lid); let _ = std::fs::remove_dir_all(&d); } + +/// A main component copied from a library file and pasted into another file is an instance of it +/// from that library, which gets enabled, as pasting an instance of it is; a variant is an instance +/// of that variant. A component the library doesn't offer pastes as a copy of itself, also one the +/// library holds because an offered component uses it. +#[test] +fn a_main_pasted_from_its_library_file_is_an_instance_of_it() { + let d = dir("paste-main"); + let lib_path = path_str(&d.join("kit.figcraft")); + let mut s = Session::new(); + let k = kit(&mut s); + let sizes: Vec = ["Size=S", "Size=L"] + .iter() + .enumerate() + .map(|(n, name)| { + idv(&ex( + &mut s, + "node.create", + json!({"type": "component", "name": name, "x": 600.0 + n as f64 * 100.0, "y": 0, "width": 40, "height": 20}), + )) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": sizes.clone()})); + let spare = idv(&ex(&mut s, "frame.create", json!({"x": 300, "y": 300, "width": 10, "height": 10, "name": "_Spare"}))); + let spare = idv(&ex(&mut s, "component.create", json!({"ids": [spare]}))); + let icon = idv(&ex(&mut s, "frame.create", json!({"x": 400, "y": 300, "width": 10, "height": 10, "name": "_Icon"}))); + let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon]}))); + let badge = idv(&ex(&mut s, "frame.create", json!({"x": 500, "y": 300, "width": 30, "height": 30, "name": "Badge"}))); + ex(&mut s, "instance.create", json!({"component": icon, "x": 5, "y": 5, "parent": badge})); + ex(&mut s, "component.create", json!({"ids": [badge]})); + let lid = publish_to(&mut s, &lib_path); + assert!(s.doc().unwrap().published.as_ref().unwrap().manifest.component(icon).is_some_and(|a| !a.published)); + let at = s.doc().unwrap().world_bounds(k.button).unwrap(); + ex(&mut s, "file.new", json!({"name": "Design"})); + let paste = |s: &mut Session, main: NodeId| -> NodeId { + ex(s, "doc.switch", json!({"index": 0})); + ex(s, "edit.copy", json!({"ids": [main]})); + ex(s, "doc.switch", json!({"index": 1})); + id_of(&ex(s, "edit.paste", json!({}))["ids"][0]).unwrap() + }; + let main_of = |s: &Session, id: NodeId| match node(s, id).kind { + NodeKind::Instance { component, .. } => component, + k => panic!("not an instance: {k:?}"), + }; + let button = paste(&mut s, k.button); + let doc = s.doc().unwrap(); + assert_eq!(library_source(doc, main_of(&s, button)), Some((lid.as_str(), k.button))); + assert_eq!(doc.libraries.enabled.iter().map(|l| l.path.as_str()).collect::>(), [lib_path.as_str()]); + assert_eq!(doc.world_bounds(button), Some(at), "where the main was"); + let label = node(&s, button).children[0]; + assert_eq!(chars(&s, label), "OK"); + healthy(&s); + let copies = s.doc().unwrap().libraries.components.len(); + let again = paste(&mut s, k.button); + assert_eq!(main_of(&s, again), main_of(&s, button), "the same library copy"); + assert_eq!(s.doc().unwrap().libraries.components.len(), copies); + let large = paste(&mut s, sizes[1]); + assert_eq!(library_source(s.doc().unwrap(), main_of(&s, large)), Some((lid.as_str(), sizes[1]))); + let card = paste(&mut s, k.card); + assert_eq!(library_source(s.doc().unwrap(), main_of(&s, card)), Some((lid.as_str(), k.card))); + let copy = paste(&mut s, spare); + assert!(matches!(node(&s, copy).kind, NodeKind::Component { .. }), "not offered by the library: a copy"); + assert!(!s.doc().unwrap().is_remote(copy)); + let icon_copy = paste(&mut s, icon); + assert!(matches!(node(&s, icon_copy).kind, NodeKind::Component { .. }), "only used by an offered component: a copy"); + assert!(!s.doc().unwrap().is_remote(icon_copy)); + healthy(&s); + let _ = std::fs::remove_dir_all(d); +} diff --git a/crates/engine/src/canvas/snap.rs b/crates/engine/src/canvas/snap.rs index ff1a6b64d..329f7503c 100644 --- a/crates/engine/src/canvas/snap.rs +++ b/crates/engine/src/canvas/snap.rs @@ -4,13 +4,32 @@ //! 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::{BoardItem, Document, NodeId}; +use figcraft_doc::{BoardItem, Document, Node, NodeId, NodeKind}; use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox}; use serde::Serialize; use crate::guides; use crate::tools::UNMEASURED_SNAP_PX; +/// Whether `n` lands on whole pixels when dragged whatever Snap to pixel grid says: frames, +/// sections, components, component sets and instances. Figma's help: they "always snap to the +/// pixel grid, even if Snap to pixel grid is disabled". Other layers follow the setting. +pub fn always_on_pixels(n: &Node) -> bool { + n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. }) +} + +/// Put `id`'s position in its parent on whole pixels when its axes are its parent's: returns +/// whether it moved. A layer turned off its parent's axes keeps its position. +pub fn settle_on_pixels(doc: &mut Document, id: NodeId) -> crate::Result { + let n = doc.get_mut(id)?; + let [a, b, c, d, e, f] = n.transform.as_coeffs(); + if !guides::axis_aligned(n.transform) || (e.round() == e && f.round() == f) { + return Ok(false); + } + n.transform = Affine::new([a, b, c, d, e.round(), f.round()]); + Ok(true) +} + /// A guide line to draw: from (x0, y0) to (x1, y1) in page coordinates, with an optional label /// (a distance) at its middle; `dashed` marks a measurement's extension line. #[derive(Clone, Debug, PartialEq, Serialize)] diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index 6c8c15071..9508bfcb8 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -1,8 +1,9 @@ //! On-canvas text editing: caret, selection, typing. A whole editing session is one undo step. +use std::collections::BTreeMap; use std::sync::{LazyLock, Mutex}; -use figcraft_doc::{Document, ListStyle, NodeId, NodeKind, TextData}; +use figcraft_doc::{Document, ImageData, ListStyle, NodeId, NodeKind, TextData}; use crate::{EngineError, Preedit, Result, Session, TextEdit}; @@ -401,6 +402,94 @@ pub fn list_indent(s: &mut Session, out: bool) -> Result { Ok(text_of(s, id)? != before) } +/// Whether Tab in text layer `id` moves between text layers: not in a board object's text (a +/// sticky's note, a table cell, a code block) or a widget's field, where it types as before. +fn tabs_between_texts(doc: &Document, id: NodeId) -> bool { + !in_board_object(doc, id) && crate::widgets::field_of(doc, id).is_none() +} + +fn in_board_object(doc: &Document, id: NodeId) -> bool { + std::iter::once(id).chain(doc.ancestors(id)).any(|a| doc.node(a).is_some_and(|n| n.board.is_some())) +} + +/// Tab (Shift+Tab: `back`) while editing text layer `from`: editing it ends as Escape ends it, and +/// the next (previous) text layer in reading order is edited with all of its text selected. At the +/// last (first) one nothing happens. +fn tab_to_next_text(s: &mut Session, from: NodeId, back: bool) -> Result<()> { + let order = reading_order(s.doc()?, tab_stops(s.doc()?, from)); + let Some(at) = order.iter().position(|t| *t == from) else { return Ok(()) }; + let next = if back { at.checked_sub(1).and_then(|i| order.get(i)) } else { order.get(at + 1) }; + let Some(&next) = next else { return Ok(()) }; + end(s)?; + begin(s, next, None, false) +} + +/// The text layers Tab moves between from text layer `from`: those in the top-level layer holding +/// it (the frame or group on the page or in a section), at any depth and inside instances, that are +/// visible and unlocked with every layer around them and not in a board object; for a text on the +/// page or in a section itself, the text layers beside it there. `from` is always one of them. +fn tab_stops(doc: &Document, from: NodeId) -> Vec { + let is_section = |id: &NodeId| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. })); + let chain: Vec = std::iter::once(from).chain(doc.ancestors(from)).collect(); + let Some(page_at) = chain.iter().position(|c| doc.node(*c).is_some_and(|n| n.is_page())) else { return vec![from] }; + let top = chain.get(..page_at).and_then(|below| below.iter().rev().copied().find(|c| !is_section(c))); + let stop = |n: &figcraft_doc::Node| n.visible && !n.locked && n.board.is_none(); + let mut out = Vec::new(); + match top { + Some(top) if top != from => { + let mut stack = vec![top]; + let mut seen = 0usize; + while let Some(id) = stack.pop() { + seen += 1; + if seen > 1_000_000 { + break; + } + let Some(n) = doc.node(id).filter(|n| stop(n)) else { continue }; + if matches!(n.kind, NodeKind::Text(_)) { + out.push(id); + } + stack.extend(n.children.iter().copied()); + } + } + _ => { + let beside = doc.node(from).and_then(|n| n.parent).and_then(|p| doc.node(p)).map(|p| p.children.clone()).unwrap_or_default(); + out.extend(beside.into_iter().filter(|c| doc.node(*c).is_some_and(|n| stop(n) && matches!(n.kind, NodeKind::Text(_))))); + } + } + if !out.contains(&from) { + out.push(from); + } + out +} + +/// `ids` in reading order by their boxes on the page: rows top to bottom, each row left to right. +/// Rows are made from the top down: a layer joins the row of the topmost layer before it when the +/// two overlap vertically by more than nothing and by at least half the height of the shorter one, +/// else it starts the next row. Layers without bounds are left out. +fn reading_order(doc: &Document, ids: Vec) -> Vec { + let mut boxes: Vec<(NodeId, figcraft_geom::Rect)> = ids.into_iter().filter_map(|i| Some((i, doc.world_bounds(i)?))).collect(); + boxes.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0).then(a.1.x0.total_cmp(&b.1.x0))); + let mut rows: Vec> = Vec::new(); + for (id, b) in boxes { + let joins = |row: &Vec<(NodeId, figcraft_geom::Rect)>| { + row.first().is_some_and(|(_, a)| { + let overlap = a.y1.min(b.y1) - a.y0.max(b.y0); + overlap > 0.0 && overlap >= 0.5 * a.height().min(b.height()) + }) + }; + match rows.last_mut() { + Some(row) if joins(row) => row.push((id, b)), + _ => rows.push(vec![(id, b)]), + } + } + rows.into_iter() + .flat_map(|mut row| { + row.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.1.y0.total_cmp(&b.1.y0))); + row.into_iter().map(|(id, _)| id) + }) + .collect() +} + /// The kind of word char `i` belongs to: 0 for spaces and punctuation, else its script, so a word /// ends where the script changes (Han, hiragana, katakana and Hangul runs are words of their own in /// text without spaces). Combining marks and voicing marks belong to the char before them. @@ -459,7 +548,9 @@ fn word_right(chars: &[char], mut i: usize) -> usize { i } -/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Escape, SelectAll. +/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Tab, Escape, SelectAll. +/// Tab and Shift+Tab outside a list, a code block, a board object and a widget's field edit the +/// next or previous text layer ([`tab_to_next_text`]). /// `word` moves or deletes by word, `line` to the line's ends (Up/Down, Home/End: the text's ends); /// [`crate::keymap::text_motion`] gives them for the platform's keys. `ArrowLeft` etc. also work. pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> Result<()> { @@ -484,6 +575,7 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R match key { "Escape" => return end(s), "Enter" => return insert(s, "\n"), + "Tab" if !word && !line && tabs_between_texts(s.doc()?, te.id) => return tab_to_next_text(s, te.id, shift), "Tab" => return insert(s, "\t"), "Backspace" | "Delete" => { return edit(s, |t, te| { @@ -856,6 +948,106 @@ pub fn selected_text(s: &Session) -> Option { Some(t.characters.chars().skip(a).take(b.saturating_sub(a)).collect()) } +/// Copied characters with their formatting, for a paste into a text edit that keeps it. +#[derive(Clone, Debug, PartialEq)] +pub struct RichText { + pub text: String, + /// Styled runs as `(from, to, style)` char ranges of `text`. Each style carries its fills, + /// the layer's own where the run had none, so the characters keep their colour elsewhere. + pub spans: Vec<(usize, usize, figcraft_doc::TextStyle)>, + /// The data of the images the runs' fills use, so they resolve in another file. + pub images: BTreeMap, +} + +/// The selected characters while editing, with their formatting (for copy). +pub fn selected_rich_text(s: &Session) -> Option { + let (id, a, b) = selected_range(s)?; + rich_text_of(s.doc().ok()?, id, a, b) +} + +/// The characters of the text layers `ids`, one per line, with their formatting; None when one of +/// them isn't a text layer or there are no characters. +pub fn layers_rich_text(doc: &Document, ids: &[NodeId]) -> Option { + let mut joined = RichText { text: String::new(), spans: Vec::new(), images: BTreeMap::new() }; + let mut offset = 0; + for (i, id) in ids.iter().enumerate() { + let layer = rich_text_of(doc, *id, 0, usize::MAX)?; + if i > 0 { + joined.text.push('\n'); + offset += 1; + } + joined.text.push_str(&layer.text); + joined.spans.extend(layer.spans.into_iter().map(|(from, to, style)| (from + offset, to + offset, style))); + joined.images.extend(layer.images); + offset += layer.text.chars().count(); + } + (!joined.text.is_empty()).then_some(joined) +} + +/// Chars `a..b` of the text layer `id` (`b` past the end means to the end), with their formatting. +fn rich_text_of(doc: &Document, id: NodeId, a: usize, b: usize) -> Option { + let n = doc.node(id)?; + let t = n.kind.text()?; + let b = b.min(t.char_count()); + let text: String = t.characters.chars().skip(a).take(b.saturating_sub(a)).collect(); + let spans: Vec<(usize, usize, figcraft_doc::TextStyle)> = t + .spans() + .into_iter() + .filter(|(from, to, _)| *to > a && *from < b) + .map(|(from, to, style)| { + let mut style = style.clone(); + style.fills.get_or_insert_with(|| n.fills.clone()); + (from.max(a) - a, to.min(b) - a, style) + }) + .collect(); + let mut images = BTreeMap::new(); + for paint in spans.iter().flat_map(|(_, _, style)| style.fills.iter().flatten()) { + if let figcraft_color::PaintKind::Image(img) = &paint.kind + && let Some(d) = doc.images.get(&img.image) + { + images.insert(img.image.clone(), d.clone()); + } + } + Some(RichText { text, spans, images }) +} + +/// Replace the selection in the text edit with `rich`, keeping its formatting. A link to a style +/// this file doesn't have is dropped, a fill equal to the layer's is left to the layer, and the +/// copied image data is added where this file lacks the key, as a pasted layer's is. +pub fn insert_rich(s: &mut Session, rich: &RichText) -> Result<()> { + if s.ds()?.text_edit.is_some() { + let doc = s.doc_mut()?; + for (k, v) in &rich.images { + doc.images.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + let doc = s.doc()?; + let layer_fills = s.ds()?.text_edit.as_ref().and_then(|te| doc.node(te.id)).map(|n| n.fills.clone()); + let spans: Vec<(usize, usize, figcraft_doc::TextStyle)> = rich + .spans + .iter() + .map(|(from, to, style)| { + let mut style = style.clone(); + if style.style_id.as_deref().is_some_and(|id| doc.style(id).is_none()) { + style.style_id = None; + } + if style.fills == layer_fills { + style.fills = None; + } + (*from, *to, style) + }) + .collect(); + edit(s, |t, te| { + let (a, b) = range(te); + t.replace_range(a, b, &rich.text); + for (from, to, style) in &spans { + t.restyle(a + from, a + to, |x| *x = style.clone()); + } + te.caret = a + rich.text.chars().count(); + te.anchor = te.caret; + }) +} + /// The selected range while editing (for styling commands), or None. pub fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> { let te = s.ds().ok()?.text_edit.clone()?; diff --git a/crates/engine/src/canvas/textedit/tests.rs b/crates/engine/src/canvas/textedit/tests.rs index 81756901d..e8daa3bf9 100644 --- a/crates/engine/src/canvas/textedit/tests.rs +++ b/crates/engine/src/canvas/textedit/tests.rs @@ -569,3 +569,52 @@ fn an_empty_ime_commit_ends_the_composition_without_inserting_text() { end(&mut s).unwrap(); assert_eq!(insert_ime_commit(&mut s, "").unwrap(), ImeInsertion::Nothing); } + +#[test] +fn rich_text_pastes_its_runs_and_drops_a_link_to_a_style_this_file_lacks() { + let (mut s, id) = setup("ab"); + begin(&mut s, id, Some(2), false).unwrap(); + let mut bold = data(&s, id).style.clone(); + bold.font_style = "Bold".into(); + bold.style_id = Some("from another file".into()); + let plain = data(&s, id).style.clone(); + insert_rich(&mut s, &RichText { text: "XY".into(), spans: vec![(0, 1, bold), (1, 2, plain)], images: Default::default() }).unwrap(); + let t = data(&s, id); + assert_eq!(t.characters, "abXY"); + assert_eq!(t.style_at(2).font_style, "Bold"); + assert_eq!(t.style_at(2).style_id, None, "a link to a style this file doesn't have"); + assert_eq!(t.style_at(3).font_style, "Regular"); + assert_eq!(sel(&s), (4, 4)); + set_caret(&mut s, 2, false).unwrap(); + set_caret(&mut s, 4, true).unwrap(); + let copied = selected_rich_text(&s).unwrap(); + assert_eq!(copied.text, "XY"); + assert_eq!(copied.spans.iter().map(|(a, b, st)| (*a, *b, st.font_style.as_str())).collect::>(), [(0, 1, "Bold"), (1, 2, "Regular")]); +} + +#[test] +fn copied_characters_bring_the_image_their_fill_uses_into_another_file() { + let (mut source, id) = setup("ab"); + let data = figcraft_doc::ImageData { bytes: std::sync::Arc::new(vec![1, 2, 3]), width: 2, height: 2 }; + { + let doc = source.doc_mut().unwrap(); + doc.images.insert("pic".into(), data.clone()); + doc.get_mut(id).unwrap().fills = vec![figcraft_color::Paint::image("pic", figcraft_color::ImageScaleMode::Fill)]; + } + begin(&mut source, id, Some(0), false).unwrap(); + set_caret(&mut source, 2, true).unwrap(); + let copied = selected_rich_text(&source).unwrap(); + let (mut s, target) = setup("cd"); + begin(&mut s, target, Some(2), false).unwrap(); + insert_rich(&mut s, &copied).unwrap(); + assert_eq!(s.doc().unwrap().images.get("pic"), Some(&data), "the run's image fill resolves here"); +} + +#[test] +fn copied_text_layers_join_one_per_line_with_their_runs_in_place() { + let (mut s, first) = setup("ab"); + let second = crate::params::id_of(&s.execute("text.create", &json!({"text": "cdé", "x": 0, "y": 50})).unwrap()["id"]).unwrap(); + let joined = layers_rich_text(s.doc().unwrap(), &[first, second]).unwrap(); + assert_eq!(joined.text, "ab\ncdé"); + assert_eq!(joined.spans.iter().map(|(a, b, _)| (*a, *b)).collect::>(), [(0, 2), (3, 6)]); +} diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index 3149d6557..397c158cd 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -649,6 +649,10 @@ pub struct ToolState { pub place_at: Option, /// The document (uid) and page the crosshair was shown on. pub(crate) place_on: Option<(u64, NodeId)>, + /// The last two Move or Scale presses, oldest first: where each was and the selection just + /// before it. A Shift double-click works from the selection its first click found. A press + /// with another tool clears them, and so does the double-click that uses them. + pub(crate) selections_before_last_two_presses: [Option<(Point, Vec)>; 2], } impl ToolState { diff --git a/crates/engine/src/canvas/tools/click.rs b/crates/engine/src/canvas/tools/click.rs index a7c10d574..265f3075b 100644 --- a/crates/engine/src/canvas/tools/click.rs +++ b/crates/engine/src/canvas/tools/click.rs @@ -139,6 +139,38 @@ impl Session { return crate::vectoredit::begin_many(self, &ids); } // Groups, frames and boolean groups: select one level deeper (the layer under the pointer). + if ev.shift && !ev.cmd { + // Both presses recorded here are this double-click's; without them (the presses came in + // one frame with the double-click, or with another tool) the current selection stands in. + let before_the_clicks = match std::mem::take(&mut self.tool.selections_before_last_two_presses) { + [Some((first, before)), Some((second, _))] if within_slop(ev, first) && within_slop(ev, second) => before, + _ => sel.clone(), + }; + let entered_here = before_the_clicks.iter().any(|s| *s == leaf || doc.is_ancestor(*s, leaf)); + let deeper = if entered_here { + figcraft_doc::geometry::enter_target(&doc, leaf, &before_the_clicks) + } else { + let mut branch = doc.ancestors(leaf); + branch.reverse(); + branch.push(leaf); + let clicked = select_target(&doc, leaf, &before_the_clicks, false); + let beside_the_selection = before_the_clicks + .iter() + .filter_map(|s| branch.iter().rposition(|b| doc.is_ancestor(*b, *s))) + .max() + .and_then(|shared| branch.get(shared + 1)) + .copied(); + let start = beside_the_selection.filter(|b| doc.is_ancestor(clicked, *b)).unwrap_or(clicked); + figcraft_doc::geometry::enter_target(&doc, leaf, &[start]) + }; + let mut alongside: Vec = before_the_clicks + .into_iter() + .filter(|s| doc.contains(*s) && *s != deeper && !doc.is_ancestor(*s, deeper) && !doc.is_ancestor(deeper, *s)) + .collect(); + alongside.push(deeper); + self.set_selection(alongside); + return Ok(()); + } let deeper = figcraft_doc::geometry::enter_target(&doc, leaf, &sel); if deeper != target || !sel.contains(&deeper) { self.set_selection(vec![deeper]); @@ -382,7 +414,15 @@ impl Session { // and what to call it; nothing is applied). self.request_ui("dialog.createFromColor", json!({"color": c.to_css_hex()})); } else if !sel.is_empty() { - self.execute("node.set", &json!({"ids": sel, "props": {"fill": c.to_css_hex()}}))?; + let (stroked, filled): (Vec, Vec) = sel.iter().partition(|id| doc.node(**id).is_some_and(takes_pick_on_stroke)); + self.grouped("Pick color", |s| { + for (ids, key) in [(filled, "fill"), (stroked, "stroke")] { + if !ids.is_empty() { + s.execute("node.set", &json!({"ids": ids, "props": {key: c.to_css_hex()}}))?; + } + } + Ok(()) + })?; } self.recent_colors.retain(|x| *x != c); self.recent_colors.insert(0, c); @@ -392,3 +432,7 @@ impl Session { Ok(()) } } + +fn takes_pick_on_stroke(n: &Node) -> bool { + !n.fills.iter().any(|p| p.visible) && n.strokes.iter().any(|p| p.visible) +} diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index b57c5fc96..b5f8ce82b 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -79,15 +79,22 @@ impl Session { // layers in it is like the canvas (a press starts a marquee inside it) unless the frame is // selected; stepping out from a selected descendant is handled by the marquee below. // An empty frame (or a widget, or a board object such as a sticky) is picked and dragged. + let in_section = |n: &figcraft_doc::Node| n.parent.and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Section { .. })); let board_background = |leaf: NodeId| { - !sel.contains(&leaf) + (ev.cmd || !sel.contains(&leaf)) && doc.node(leaf).is_some_and(|n| { - n.parent == Some(page) && n.kind.is_frame_like() && !n.children.is_empty() && !crate::widgets::is_widget(n) && !n.is_board_atom() + let board = match n.kind { + NodeKind::Section { contents_hidden } => !contents_hidden, + ref k => k.is_frame_like() && (n.parent == Some(page) || in_section(n)), + }; + board && !n.children.is_empty() && !crate::widgets::is_widget(n) && !n.is_board_atom() }) }; let label = label_at(&doc, page, &self.tool.labels, ev.p()); - let hit = label.or_else(|| self.hit(&doc, page, ev.p(), ev.tol() * 2.0)); - let target = label.or_else(|| hit.filter(|leaf| ev.cmd || !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd))); + let leaf = self.hit(&doc, page, ev.p(), ev.tol() * 2.0); + let hit = label.or(leaf); + let background_under_cmd = leaf.filter(|l| ev.cmd && label.is_none() && board_background(*l)); + let target = label.or_else(|| leaf.filter(|leaf| !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd))); // A press inside the selection's box that reaches nothing above it (an unfilled shape's // inside, the frame or canvas behind it, or a layer stacked below the selected layer the // press is in) drags the selection. In a gap between selected layers, what's there is hit. @@ -105,8 +112,15 @@ impl Session { // selects just it. A press that reaches nothing above the selection uses the selection as // its drag target instead; that fallback is not a clicked layer. let clicked = target; + let marks_out_a_selected_board = background_under_cmd.is_some_and(|b| sel.contains(&b)); let target = match sel.iter().copied().find(|s| !locked_in(&doc, *s)) { - Some(first) if label.is_none() && !ev.shift && behind_sel(target) && selection_box(&doc, &sel).is_some_and(|q| in_quad(&q, ev.p())) => { + Some(first) + if label.is_none() + && !ev.shift + && !marks_out_a_selected_board + && behind_sel(target) + && selection_box(&doc, &sel).is_some_and(|q| in_quad(&q, ev.p())) => + { Some(first) } _ => target, @@ -186,7 +200,7 @@ impl Session { if let Some(f) = parent { self.set_selection(vec![f]); } else if !ev.shift { - self.set_selection(vec![]); + self.set_selection(background_under_cmd.into_iter().collect()); } self.tool.gesture = Gesture::Marquee { start: ev.p(), @@ -249,7 +263,11 @@ impl Session { let raw = d; let snap_on = self.ds().map(|ds| ds.view.snap_objects).unwrap_or(true) && !ev.cmd && !ev.ctrl; let mut guides = Vec::new(); - if self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) { + let boards = { + let doc = self.doc()?; + ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels)) + }; + if boards || self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) { // Keep the box's origin on whole pixels (a rotated parent frame's, inside one); // snapping to layers comes after, so it wins on the axes it snaps. d = targets.round_move(d); @@ -259,6 +277,11 @@ impl Session { d += c; guides = g2; } + if boards { + // Frames, sections and components stay on whole pixels even where a layer + // they snap to doesn't. + d = targets.round_move(d); + } let ids = ids.clone(); let dup = *duplicate; let page = self.page()?; @@ -343,6 +366,9 @@ impl Session { doc.reparent(*m, page, None)?; } move_world(doc, *m, d.x, d.y)?; + if doc.node(*m).is_some_and(crate::snap::always_on_pixels) { + shifted &= !crate::snap::settle_on_pixels(doc, *m)?; + } } drop_target = (flow && target != page).then_some(target); Ok(()) @@ -521,7 +547,13 @@ impl Session { // The pixel grid: an upright box's dragged sides land on whole pixels (the Scale tool // scales by the factor as dragged). Snapping to layers comes after, so it wins on the axes // it snaps. - if !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) { + // Frames, sections and components land on whole pixels whatever the setting, also where a + // layer they snap to doesn't. + let boards = { + let doc = self.doc()?; + !scale_tool && crate::guides::axis_aligned(frame) && ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels)) + }; + if boards || !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) { p = Point::new(p.x.round(), p.y.round()); } if let Some(t) = &targets { @@ -530,6 +562,9 @@ impl Session { p.y += dy; guides = g; } + if boards { + p = Point::new(p.x.round(), p.y.round()); + } let q = frame.inverse() * p; let is_line = r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| matches!(n.kind, NodeKind::Line))).unwrap_or(false); if scale_tool { @@ -557,9 +592,16 @@ impl Session { self.tool.overlay.guides = guides; return Ok(()); } - // Constrain proportions (Shift, or the node's lock). - let keep = ev.shift || r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false); - let (x0, y0, x1, y1) = resized_box(r.handle, q, w0, h0, keep, ev.alt); + let image_box = ids.first().filter(|_| ev.cmd && r.single).and_then(|i| self.image_box(*i)); + // Constrain proportions (Shift, or the node's lock; cropping an image ignores the lock). + let locked = + r.single && image_box.is_none() && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false); + let keep = ev.shift || locked; + let resized = resized_box(r.handle, q, w0, h0, keep, ev.alt); + let (x0, y0, x1, y1) = match image_box { + Some(image) => within_the_image(resized, image, (w0, h0), keep), + None => resized, + }; let (flip_x, flip_y) = (x1 < x0, y1 < y0); let (nx0, ny0) = (x0.min(x1), y0.min(y1)); let (nw, nh) = ((x1 - x0).abs(), (y1 - y0).abs()); @@ -571,46 +613,30 @@ impl Session { let keeps = |doc: &Document, id: NodeId| { doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }) || (ev.cmd && single && n.kind.is_frame_like())) }; + let dragged_box = |world: Affine, (ox, oy): (f64, f64)| { + let mut t = world * Affine::translate((ox, oy)); + if flip_x { + t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]); + } + if flip_y { + t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]); + } + t + }; self.preview(|doc, _| { if single { let Some((id, world, _, _)) = nodes.first() else { return Ok(()) }; let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() }; - let mut t = *world * Affine::translate((nx0, ny0)); - if flip_x { - t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]); - } - if flip_y { - t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]); - } + let t = dragged_box(*world, (nx0, ny0)); // Text reflow and auto layout can recompute this box after the preview (a size bound - // to a variable lets go of it: the resize is an explicit edit). + // to a variable lets go of it: the resize is an explicit edit). A text keeps its + // fills; any other layer's image is cropped again for the box layout leaves + // (`crop_to_the_laid_out_box`). let n = doc.get(*id)?; - let crop_images = ev.cmd - && !matches!(n.kind, NodeKind::Text(_)) - && !std::iter::once(*id).chain(doc.ancestors(*id)).any(|a| doc.node(a).is_some_and(|n| n.layout.is_some())); - if crop_images { - // Crop the layer's image fills without moving their pixels on the page. - // Work from the interaction snapshot, just like the geometry on every move. - let (w, h) = (n.width.max(1e-6), n.height.max(1e-6)); - let to_old = - Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * t * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01)); - let mut fills = n.fills.clone(); - for paint in &mut fills { - let PaintKind::Image(img) = &mut paint.kind else { continue }; - // A repeating image cannot be represented by a single Crop placement. - if img.scale_mode == ImageScaleMode::Tile { - continue; - } - let Some(data) = doc.images.get(&img.image) else { continue }; - let (iw, ih) = (f64::from(data.width), f64::from(data.height)); - // A degenerate (zero-scale) layer has no inverse: its image keeps its placement. - let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_old).as_coeffs(); - if !crop.iter().all(|c| c.is_finite()) { - continue; - } - img.crop = Some(crop); - img.scale_mode = ImageScaleMode::Crop; - } + // Crop the layer's image fills without moving their pixels on the page. + // Work from the interaction snapshot, just like the geometry on every move. + if ev.cmd && !matches!(n.kind, NodeKind::Text(_)) { + let fills = cropped_image_fills(doc, n, *world, t, (nw, nh)); doc.get_mut(*id)?.fills = fills; } doc.set_world_transform(*id, t)?; @@ -650,16 +676,81 @@ impl Session { let lin = (mirror * local).with_translation(Vec2::ZERO); let origin = Point::new(x0 + center.x * sx, y0 + center.y * sy) - lin * Point::new(w2 / 2.0, h2 / 2.0); let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() }; - doc.set_world_transform(*id, frame * lin.with_translation(origin))?; + let (t, w2, h2) = if boards { + on_whole_pixels(doc, *id, frame * lin.with_translation(origin), w2, h2) + } else { + (frame * lin.with_translation(origin), w2, h2) + }; + doc.set_world_transform(*id, t)?; crate::cmd::props::resize_node(doc, *id, w2, h2)?; + if boards { + crate::snap::settle_on_pixels(doc, *id)?; + } crate::cmd::props::restore_worlds(doc, &kept)?; } Ok(()) })?; + if single + && ev.cmd + && let Some((id, world, _, _)) = nodes.first() + { + let laid_out_box = |(fw, fh): (f64, f64)| { + let origin = match image_box { + Some((ix0, iy0, ix1, iy1)) => { + (slid_onto_the_image(nx0, fw, flip_x, (ix0, ix1), w0), slid_onto_the_image(ny0, fh, flip_y, (iy0, iy1), h0)) + } + None => (nx0, ny0), + }; + dragged_box(*world, origin) + }; + self.crop_to_the_laid_out_box(*id, *world, laid_out_box, (nw, nh))?; + } self.tool.overlay.guides = guides; Ok(()) } + /// The box `(x0, y0, x1, y1)` of the first visible, untiled image fill of `id` in the layer's + /// own axes, as it was when the gesture began; `None` for a text or a layer without one. + fn image_box(&self, id: NodeId) -> Option<(f64, f64, f64, f64)> { + let snapshot = self.ds().ok()?.interaction.as_ref()?.doc.clone(); + let n = snapshot.node(id)?; + if matches!(n.kind, NodeKind::Text(_)) { + return None; + } + n.fills.iter().filter(|p| p.visible).find_map(|p| match &p.kind { + PaintKind::Image(img) if img.scale_mode != ImageScaleMode::Tile => { + let data = snapshot.images.get(&img.image)?; + let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height); + let (x0, y0, x1, y1) = figcraft_doc::color::ImagePaint::crop_rect(crop); + Some((x0 * n.width, y0 * n.height, x1 * n.width, y1 * n.height)) + } + _ => None, + }) + } + + /// After the preview's layout: when the layer didn't keep the dragged size `(nw, nh)` (a + /// minimum size, a Hug frame), crop its image fills again from the snapshot for the size it + /// has, the box placed by `laid_out_box` (given that size) in the layer's starting axes. + fn crop_to_the_laid_out_box( + &mut self, + id: NodeId, + world: Affine, + laid_out_box: impl Fn((f64, f64)) -> Affine, + (nw, nh): (f64, f64), + ) -> Result<()> { + let ds = self.ds_mut()?; + let Some(snapshot) = ds.interaction.as_ref().map(|it| it.doc.clone()) else { return Ok(()) }; + let Some(before) = snapshot.node(id).filter(|n| !matches!(n.kind, NodeKind::Text(_))) else { return Ok(()) }; + let Some((fw, fh)) = ds.doc.node(id).map(|n| (n.width, n.height)) else { return Ok(()) }; + if (fw - nw.max(0.01)).abs() < 1e-9 && (fh - nh.max(0.01)).abs() < 1e-9 { + return Ok(()); + } + let fills = cropped_image_fills(&snapshot, before, world, laid_out_box((fw, fh)), (fw, fh)); + std::sync::Arc::make_mut(&mut ds.doc).get_mut(id)?.fills = fills; + ds.revision += 1; + Ok(()) + } + /// Scale tool handle drag (`q`: the snapped pointer in the handle box's axes): everything /// scales by one factor about the anchor point (Alt: the centre), strokes, effects, radii and /// text included, children by the same factor whatever their constraints. @@ -697,6 +788,25 @@ impl Session { } } +/// `world` and the size `w` x `h` a layer of a resized selection takes, moved so its box in its +/// parent has its edges on whole pixels, each on the nearest one and the box at least a pixel +/// wide: a frame resized with others lands on whole pixels as one resized alone does. A layer +/// turned or scaled in its parent keeps them. +fn on_whole_pixels(doc: &Document, id: NodeId, world: Affine, w: f64, h: f64) -> (Affine, f64, f64) { + let pw = doc.node(id).and_then(|n| n.parent).map_or(Affine::IDENTITY, |p| doc.world_transform(p)); + let local = pw.inverse() * world; + let [a, b, c, d, e, f] = local.as_coeffs(); + if !crate::guides::axis_aligned(local) || (a.abs() - 1.0).abs() > 1e-9 || (d.abs() - 1.0).abs() > 1e-9 { + return (world, w, h); + } + let edges = |at: f64, flip: bool, len: f64| if flip { (at - len, at) } else { (at, at + len) }; + let ((x0, x1), (y0, y1)) = (edges(e, a < 0.0, w), edges(f, d < 0.0, h)); + let (x0, y0) = (x0.round(), y0.round()); + let (w, h) = ((x1.round() - x0).max(1.0), (y1.round() - y0).max(1.0)); + let (e, f) = (if a < 0.0 { x0 + w } else { x0 }, if d < 0.0 { y0 + h } else { y0 }); + (pw * Affine::new([a, b, c, d, e, f]), w, h) +} + /// Moving `moving` by the same offset moves nothing else and changes nothing about them but where /// they are: none is inside another (it would move twice) or placed by its parent's auto layout /// (the layout would put it back, or close the gap it leaves). @@ -714,3 +824,78 @@ fn only_shifted(doc: &Document, moving: &[NodeId]) -> bool { !in_flow && !nested }) } + +/// `before`'s fills (from the snapshot `doc`) with each image cropped to the box `dragged` (the +/// layer's new transform, `nw` × `nh`), its pixels left where they were on the page (`world`: +/// the layer's transform before the drag). +fn cropped_image_fills( + doc: &Document, + before: &figcraft_doc::Node, + world: Affine, + dragged: Affine, + (nw, nh): (f64, f64), +) -> Vec { + let (w, h) = (before.width.max(1e-6), before.height.max(1e-6)); + let to_before = Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * dragged * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01)); + let mut fills = before.fills.clone(); + for paint in &mut fills { + let PaintKind::Image(img) = &mut paint.kind else { continue }; + // A repeating image cannot be represented by a single Crop placement. + if img.scale_mode == ImageScaleMode::Tile { + continue; + } + let Some(data) = doc.images.get(&img.image) else { continue }; + let (iw, ih) = (f64::from(data.width), f64::from(data.height)); + // A degenerate (zero-scale) layer has no inverse: its image keeps its placement. + let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_before).as_coeffs(); + if !crop.iter().all(|c| c.is_finite()) { + continue; + } + img.crop = Some(crop); + img.scale_mode = ImageScaleMode::Crop; + } + fills +} + +/// The extent `lo..hi` an image of extent `image` lets a crop reach on one axis of a layer that +/// started `len` long: the image's, or the layer's where that reaches further (a Fit image is +/// smaller than its layer). +fn crop_reach(image: (f64, f64), len: f64) -> (f64, f64) { + (image.0.min(image.1).min(0.0), image.0.max(image.1).max(len)) +} + +/// The dragged box `(x0, y0, x1, y1)` drawn back towards the starting box `(0, 0, w0, h0)` until +/// its sides stop at the image's box `image` (see [`crop_reach`]). Both ends of an axis go back by +/// the same fraction, so an Alt resize stays centred, and with `keep` (Shift) both axes do, so the +/// ratio holds. A flipped axis stays as dragged. +fn within_the_image((x0, y0, x1, y1): (f64, f64, f64, f64), image: (f64, f64, f64, f64), (w0, h0): (f64, f64), keep: bool) -> (f64, f64, f64, f64) { + let fraction = |a: f64, b: f64, image: (f64, f64), len: f64| { + if b < a { + return 1.0; + } + let (lo, hi) = crop_reach(image, len); + let mut t: f64 = 1.0; + if a < lo { + t = t.min(lo / a); + } + if b > hi { + t = t.min((hi - len) / (b - len)); + } + if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 } + }; + let (tx, ty) = (fraction(x0, x1, (image.0, image.2), w0), fraction(y0, y1, (image.1, image.3), h0)); + let (tx, ty) = if keep { (tx.min(ty), tx.min(ty)) } else { (tx, ty) }; + (x0 * tx, y0 * ty, w0 + (x1 - w0) * tx, h0 + (y1 - h0) * ty) +} + +/// Where a crop box `len` long, placed at `start` on one axis, starts once it is slid back onto +/// the image (see [`crop_reach`]): layout can make a layer longer than it was dragged (a minimum +/// size), and the crop then moves along the image rather than past its edge. A flipped axis, or +/// a box longer than the reach, stays where it is. +fn slid_onto_the_image(start: f64, len: f64, flipped: bool, image: (f64, f64), len0: f64) -> f64 { + let (lo, hi) = crop_reach(image, len0); + if flipped || len.is_nan() || len > hi - lo { + return start; + } + start.max(lo).min(hi - len) +} diff --git a/crates/engine/src/canvas/tools/draw.rs b/crates/engine/src/canvas/tools/draw.rs index b29768afe..0eaee1cae 100644 --- a/crates/engine/src/canvas/tools/draw.rs +++ b/crates/engine/src/canvas/tools/draw.rs @@ -30,7 +30,10 @@ impl Session { let tool = self.tool.tool; let mut p = ev.p(); let mut guides = Vec::new(); - let pixel = self.ds().map(|d| d.view.snap_pixel).unwrap_or(true); + // Frames and sections land on whole pixels whatever the setting, also where a layer they + // snap to doesn't (see `snap::always_on_pixels`). + let board = matches!(tool, ToolId::Frame | ToolId::Section); + let pixel = board || self.ds().map(|d| d.view.snap_pixel).unwrap_or(true); // The pixel grid first: snapping to layers comes after, so it wins on the axes it snaps. if pixel { p = Point::new(p.x.round(), p.y.round()); @@ -41,6 +44,9 @@ impl Session { p.y += dy; guides = g; } + if board { + p = Point::new(p.x.round(), p.y.round()); + } let mut created = id; let page = self.page()?; // Edit ▸ Set default properties: what new shapes take (not frames, sections, slices, lines @@ -100,6 +106,9 @@ impl Session { n.transform = pw.inverse() * Affine::translate((r.x0, r.y0)); } doc.insert(n, parent, None)?; + if board { + crate::snap::settle_on_pixels(doc, nid)?; + } if let Some(d) = &defaults { // Best effort: a default the shape can't take leaves it as drawn. let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", doc, nid, d); @@ -156,6 +165,11 @@ impl Session { } // A layer can't go into itself; it stays where it is. let _ = d.reparent(*m, target, None); + // Frames, sections and components land on whole pixels of the frame + // they are dropped into too. + if d.node(*m).is_some_and(crate::snap::always_on_pixels) { + crate::snap::settle_on_pixels(d, *m)?; + } } crate::normalize(ds.doc_mut(), &before); } diff --git a/crates/engine/src/canvas/tools/pointer.rs b/crates/engine/src/canvas/tools/pointer.rs index d7a40380e..8de9d59ee 100644 --- a/crates/engine/src/canvas/tools/pointer.rs +++ b/crates/engine/src/canvas/tools/pointer.rs @@ -38,11 +38,34 @@ impl Session { /// (its children), or the focus view's frame. pub(crate) fn marquee_within(&self, p: Point) -> Result> { let (doc, page) = (self.doc()?, self.page()?); - let within = frame_at(doc, page, p, &[]).filter(|f| doc.node(*f).is_some_and(|n| n.parent == Some(page))); - let within = within.filter(|f| doc.world_bounds(*f).is_some_and(|b| b.contains(p))); + let deepest = frame_at(doc, page, p, &[]).filter(|f| doc.world_bounds(*f).is_some_and(|b| b.contains(p))); + let mut chain = deepest.map(|f| doc.ancestors(f)).unwrap_or_default(); + chain.reverse(); + chain.extend(deepest); + let mut within = None; + for c in chain.into_iter().filter(|c| *c != page) { + let Some(n) = doc.node(c) else { break }; + match &n.kind { + NodeKind::Section { contents_hidden: false } => within = Some(c), + k if k.is_frame_like() => { + within = Some(c); + break; + } + _ => break, + } + } Ok(self.ds()?.focused().or(within)) } + fn marquee_root(&self, within: Option) -> Result<(NodeId, Option)> { + let (doc, page) = (self.doc()?, self.page()?); + Ok(match within.and_then(|w| doc.node(w)) { + Some(n) if matches!(n.kind, NodeKind::Section { .. }) => (n.id, None), + Some(n) => (n.parent.unwrap_or(page), Some(n.id)), + None => (page, None), + }) + } + /// The selection a marquee over page rect `r` makes from `base` (what was selected before): /// the layers it touches (`deep`: nested ones too); `additive` (Shift) toggles them. pub(crate) fn marquee_selection(&self, r: Rect, within: Option, deep: bool, base: &[NodeId], additive: bool) -> Result> { @@ -51,7 +74,10 @@ impl Session { let mut hits = match (deep, focused) { (true, _) => figcraft_doc::geometry::marquee_deep(doc, page, r), (false, Some(f)) => figcraft_doc::geometry::marquee(doc, page, r, Some(f)), - (false, None) => figcraft_doc::geometry::marquee_select(doc, page, r, within), + (false, None) => { + let (root, start_inside) = self.marquee_root(within)?; + figcraft_doc::geometry::marquee_select(doc, root, r, start_inside) + } }; if let Some(f) = focused { hits.retain(|h| *h != f && doc.is_ancestor(f, *h)); @@ -136,6 +162,11 @@ impl Session { } let tool = self.acting_tool(); let edits = matches!(tool, ToolId::Move | ToolId::Scale) && !self.tool.dev_mode; + // Presses with another tool don't record the selection: the ones from before them aren't + // this double-click's. + if ev.kind == PointerKind::Down && !matches!(tool, ToolId::Move | ToolId::Scale) { + self.tool.selections_before_last_two_presses = Default::default(); + } if edits && self.origin_pointer(ev)? { return Ok(()); } @@ -155,6 +186,9 @@ impl Session { } // A click on the canvas deselects a ruler guide (the UI selects guides itself). self.ds_mut()?.guide = None; + let now = self.ds()?.selection.clone(); + let [_, last] = std::mem::take(&mut self.tool.selections_before_last_two_presses); + self.tool.selections_before_last_two_presses = [last, Some((ev.p(), now))]; self.move_down(ev) } ToolId::Hand => { diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs index ff8af30a4..cf00a06de 100644 --- a/crates/engine/src/canvas/vectoredit.rs +++ b/crates/engine/src/canvas/vectoredit.rs @@ -642,10 +642,12 @@ fn index(cmd: &str, p: &Value, key: &str) -> Result { } /// Delete the points and segments of `parts` (`heal` keeps paths through deleted points closed). -pub(crate) fn delete_selection(s: &mut Session, parts: Vec, heal: bool) -> Result<()> { +pub(crate) fn delete_selection(s: &mut Session, parts: Vec, heal: bool, then_select_next: bool) -> Result<()> { let doc = s.doc_mut()?; + let mut next = Vec::new(); for EditPart { id, vertices: verts, segments: segs } in parts { - edit(doc, id, |net| { + let following = edit(doc, id, |net| { + let following = if then_select_next { points_following(net, &verts) } else { Vec::new() }; // Segments first (their indices refer to the network before points go). let segs: Vec = segs.into_iter().filter(|si| net.segments.get(*si).is_some_and(|x| !verts.contains(&x.a) && !verts.contains(&x.b))).collect(); @@ -654,15 +656,52 @@ pub(crate) fn delete_selection(s: &mut Session, parts: Vec, heal: bool // Point indices may have shifted: find them again by position. let now: Vec = pts.iter().filter_map(|p| net.vertices.iter().position(|v| v.point() == *p)).collect(); ops::delete_vertices(net, &now, heal); + following.iter().filter_map(|p| net.vertices.iter().position(|v| v.point() == *p)).collect::>() })?; + next.push((id, following)); } set_state(s, |ve| { ve.clear_selection(); ve.anchor = None; ve.pen_out = None; + for (id, following) in next { + if id == ve.id { + ve.vertices = following; + } else if let Some(o) = ve.others.iter_mut().find(|o| o.id == id) { + o.vertices = following; + } + } }) } +fn points_following(net: &VectorNetwork, deleted: &[usize]) -> Vec { + let step = |from: usize, forward: bool| { + net.segments.iter().find_map(|sg| match forward { + true => (sg.a == from).then_some(sg.b), + false => (sg.b == from).then_some(sg.a), + }) + }; + let mut out: Vec = Vec::new(); + for &v in deleted { + let found = [true, false].into_iter().find_map(|forward| { + let mut at = v; + for _ in 0..net.vertices.len() { + at = step(at, forward)?; + if !deleted.contains(&at) { + return Some(at); + } + } + None + }); + if let Some(p) = found.and_then(|i| net.vertices.get(i)).map(|x| x.point()) + && !out.contains(&p) + { + out.push(p); + } + } + out +} + /// The points a command acts on, per layer: `vertices` names points of the active layer; without /// it, every edited layer's selected points (with `ends`, the ends of selected segments too). fn point_sets(s: &Session, p: &Value, ends: bool) -> Result)>> { @@ -1112,7 +1151,7 @@ pub fn specs() -> Vec { }), spec!("vector.deleteHeal", "Delete and heal selection", "{vertices?} (default the selected points of every edited layer)", true, |s, p| { let parts = point_sets(s, p, false)?.into_iter().map(|(id, vertices)| EditPart { id, vertices, segments: vec![] }).collect(); - delete_selection(s, parts, true)?; + delete_selection(s, parts, true, true)?; Ok(json!({"ok": true})) }), spec!("vector.edit.delete", "Delete points", "{vertices?, segments?} (default the selection in every edited layer)", true, |s, p| { @@ -1121,7 +1160,7 @@ pub fn specs() -> Vec { (None, None) => ve.parts(), (v, sg) => vec![EditPart { id: ve.id, vertices: v.unwrap_or_default(), segments: sg.unwrap_or_default() }], }; - delete_selection(s, parts, false)?; + delete_selection(s, parts, false, true)?; Ok(json!({"ok": true})) }), spec!("vector.edit.cornerRadius", "Point corner radius", "{radius, vertices?}", true, |s, p| { diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index f68fac714..c726613b3 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -24,6 +24,7 @@ use instance::{detach, make_slot, push_changes, remove_slot, reset_instance, res pub(crate) use instance::{swap_at, swap_instance}; use props::{add_prop, bind_prop, delete_prop, edit_prop, set_props}; pub(crate) use props::{apply_prop_bindings, check_prop_binding, describe_props}; +pub(crate) use variants::fit_set; use variants::{add_variant, combine, create_set}; pub use variants::{can_add_variant, can_combine_variants, can_create_set}; diff --git a/crates/engine/src/cmd/component/variants.rs b/crates/engine/src/cmd/component/variants.rs index be43bced0..3125daf12 100644 --- a/crates/engine/src/cmd/component/variants.rs +++ b/crates/engine/src/cmd/component/variants.rs @@ -166,7 +166,7 @@ pub(super) fn create_set(s: &mut Session, p: &Value) -> Result { } /// Grow a component set so it wraps its variants with 20 px of padding (right and bottom). -pub(super) fn fit_set(doc: &mut Document, set: NodeId) { +pub(crate) fn fit_set(doc: &mut Document, set: NodeId) { let Some(kids) = doc.node(set).map(|n| n.children.clone()) else { return }; let (mut w, mut h) = (0.0f64, 0.0f64); for c in kids { diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index c5ce462a4..3fd5d11d2 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -127,6 +127,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { // A design-app paste replaces the copied layers, not the copied rows: a `fill.copy` before it // still pastes afterwards. let props = s.clipboard.props.take(); + let props_source_doc = s.clipboard.props_source_doc; let paint = s.clipboard.paint.take(); let stroke = s.clipboard.stroke.take(); let paint_images = std::mem::take(&mut s.clipboard.paint_images); @@ -138,6 +139,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { nodes, images, props, + props_source_doc, paint, stroke, paint_images, @@ -219,8 +221,18 @@ pub(super) fn cut(s: &mut Session, p: &Value) -> Result { delete(s, &json!({"ids": layers})) } -/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords). +/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords). A +/// copied main is pasted as an instance of it; in another file, as an instance of it from the +/// library the source file publishes, and as a copy of it when that library doesn't offer it. pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Result> { + paste_layers(s, parent, at, false) +} + +/// [`paste_into`]. With `as_variants`, copied variants pasted into `parent`, their own set, are +/// deep copies (new variants, as Duplicate makes) and the set grows to hold them. Only a plain +/// paste with that set, or a layer in it, selected asks for this; every other paste of a copied +/// main, into another set too, still makes an instance. +fn paste_layers(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>, as_variants: bool) -> Result> { let clip = s.clipboard.clone(); if clip.nodes.is_empty() { return Err(EngineError::Disabled("edit.paste".into(), "the clipboard is empty".into())); @@ -238,15 +250,20 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re (Some((x, y)), Some(b)) => Affine::translate((x - b.x0, y - b.y0)), _ => Affine::IDENTITY, }; + let into_set = as_variants && copy_local && copied_variants_set(doc, &clip.nodes) == Some(parent); let mut out = Vec::new(); let mut all = BTreeMap::new(); for (root, nodes) in &clip.nodes { - if copy_local - && clip.copied_components.contains(root) - && let Some(n) = nodes.first().filter(|n| matches!(n.kind, NodeKind::Component { .. })) - && doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. })) - { - let instance = crate::components::create_instance(doc, *root, parent, 0.0, 0.0)?; + let copied_main = nodes.first().filter(|n| clip.copied_components.contains(root) && matches!(n.kind, NodeKind::Component { .. })); + let main = match (copied_main, foreign) { + (Some(_), _) if copy_local => { + (!into_set && doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))).then_some(*root) + } + (Some(_), Some(src)) => crate::library::published_main(doc, src, clip.source_path.as_deref(), *root)?, + _ => None, + }; + if let (Some(main), Some(n)) = (main, copied_main) { + let instance = crate::components::create_instance(doc, main, parent, 0.0, 0.0)?; doc.get_mut(instance)?.transform = doc.world_transform(parent).inverse() * shift * n.transform; keep_a_cropped_images_proportions(doc, instance, parent); out.push(instance); @@ -267,6 +284,9 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re out.push(pasted); all.extend(map); } + if into_set { + crate::cmd::component::fit_set(doc, parent); + } // Board connectors pasted with what they join join the pasted copies. let originals: Vec<(NodeId, figcraft_doc::BoardItem)> = clip.nodes.iter().flat_map(|(_, nodes)| nodes).filter_map(|n| Some((*all.get(&n.id)?, n.board.clone()?))).collect(); @@ -307,7 +327,16 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result { let sel = s.selection(); let doc = s.doc()?; let copy_local = s.ds()?.uid == s.clipboard.source_doc; - let target = id(p, "parent").or_else(|| { + let variants_set = copied_variants_set(doc, &s.clipboard.nodes) + .filter(|set| copy_local && id(p, "parent").is_none() && !sel.is_empty() && sel.iter().all(|i| doc.is_ancestor(*set, *i))); + // Where the copied variants are now, not where they were copied: the set may have moved since. + let below_the_variants = variants_set.and_then(|set| { + let copied: Vec = s.clipboard.nodes.iter().map(|(root, _)| *root).collect(); + let left = doc.bounds_of(&copied)?.x0; + let bottom = doc.node(set)?.children.iter().filter_map(|c| doc.world_bounds(*c)).map(|r| r.y1).reduce(f64::max)?; + Some((left, bottom + 20.0)) + }); + let target = id(p, "parent").or(variants_set).or_else(|| { sel.first() .copied() .filter(|i| { @@ -322,6 +351,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result { let parent = target.unwrap_or(page); let at = match (num(p, "x"), num(p, "y")) { (Some(x), Some(y)) => Some((x, y)), + _ if below_the_variants.is_some() => below_the_variants, _ => { let b = s.clipboard.bounds; match (target, b) { @@ -344,7 +374,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result { } } }; - let ids = paste_into(s, parent, at)?; + let ids = paste_layers(s, parent, at, variants_set.is_some())?; if let Some(sel) = sibling_of { let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1); move_above(s, &ids, parent, above)?; @@ -381,14 +411,27 @@ fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option)]) -> Option { + let mut sets = copied.iter().map(|(root, _)| { + let n = doc.node(*root).filter(|n| matches!(n.kind, NodeKind::Component { .. }))?; + n.parent.filter(|set| doc.node(*set).is_some_and(|p| matches!(p.kind, NodeKind::ComponentSet { .. }))) + }); + let first = sets.next()??; + sets.all(|set| set == Some(first)).then_some(first) +} + +/// Paste over selection (Shift+Cmd/Ctrl+V): the copies go into the parent of the selected layer +/// [`last_seen`] picks, just above it, at the place it gives. pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { let sel = s.selection(); let page = s.page()?; let doc = s.doc()?; - let (parent, at, above) = match sel.first() { - Some(i) => { - let parent = doc.node(*i).and_then(|n| n.parent).unwrap_or(page); - (parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)), doc.index_in_parent(*i).map(|ix| ix + 1)) + let (parent, at, above) = match last_seen(doc, &sel) { + Some((i, at)) => { + let parent = doc.node(i).and_then(|n| n.parent).unwrap_or(page); + (parent, at, doc.index_in_parent(i).map(|ix| ix + 1)) } None => (page, None, None), }; @@ -398,6 +441,38 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { Ok(json!({"ids": ids})) } +/// The selected layer Paste over selection pastes after, and where the copies' top-left goes. +/// +/// One layer: that layer, at its position. Several in one auto layout frame's flow (none absolutely +/// positioned): the last of them in the flow, which the layout follows. Several elsewhere: the lowest (then rightmost), with the copies +/// below it, as far below as it is from the selected layers above it. A selection with nothing above +/// its lowest layer is a row: the copies go right of the rightmost, as far as it is from its +/// neighbour on the left. Layers that overlap every way get the copies right under the lowest. +fn last_seen(doc: &Document, sel: &[NodeId]) -> Option<(NodeId, Option<(f64, f64)>)> { + let first = *sel.first()?; + let top_left = |i: NodeId| doc.world_bounds(i).map(|b| (b.x0, b.y0)); + if sel.len() == 1 { + return Some((first, top_left(first))); + } + let parent = doc.node(first).and_then(|n| n.parent); + let one_flow = parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some()) + && sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.parent == parent && !n.child_layout.absolute)); + if one_flow { + let last = sel.iter().copied().max_by_key(|i| doc.index_in_parent(*i))?; + return Some((last, top_left(last))); + } + let boxes: Vec<(NodeId, figcraft_geom::Rect)> = sel.iter().filter_map(|i| Some((*i, doc.world_bounds(*i)?))).collect(); + let (lowest, low) = *boxes.iter().max_by(|(_, a), (_, b)| a.y1.total_cmp(&b.y1).then(a.x1.total_cmp(&b.x1)))?; + if let Some(above) = boxes.iter().filter(|(_, o)| o.y1 <= low.y0).map(|(_, o)| o.y1).max_by(f64::total_cmp) { + return Some((lowest, Some((low.x0, low.y1 + (low.y0 - above))))); + } + let (rightmost, right) = *boxes.iter().max_by(|(_, a), (_, b)| a.x1.total_cmp(&b.x1).then(a.y1.total_cmp(&b.y1)))?; + match boxes.iter().filter(|(_, o)| o.x1 <= right.x0).map(|(_, o)| o.x1).max_by(f64::total_cmp) { + Some(left) => Some((rightmost, Some((right.x1 + (right.x0 - left), right.y0)))), + None => Some((lowest, Some((low.x0, low.y1)))), + } +} + pub(super) fn paste_replace(s: &mut Session, p: &Value) -> Result { let targets = req_targets("edit.pasteReplace", s, p)?; let mut out = Vec::new(); @@ -438,7 +513,19 @@ pub(super) fn copy_props_of(doc: &Document, id: NodeId) -> Value { v["cornerRadius"] = json!(n.corners.radii); v["cornerSmoothing"] = json!(n.corners.smoothing); } + // A frame's layout grids go with its look, as its fills do. + if n.kind.is_frame_like() { + v["grids"] = json!(n.grids); + v["gridStyle"] = json!(n.styles.grid); + } + // The links behind the values: the styles and the variables they come from, so the pasted + // layer follows them as the copied one does. + v["fillStyle"] = json!(n.styles.fill); + v["strokeStyle"] = json!(n.styles.stroke); + v["effectStyle"] = json!(n.styles.effect); + v["boundVariables"] = Value::Object(n.bound.iter().filter(|(f, _)| copied_binding(f)).map(|(f, v)| (f.clone(), json!(v))).collect()); if let NodeKind::Text(t) = &n.kind { + v["textStyle"] = json!(n.styles.text); v["fontFamily"] = json!(t.style.font_family); v["fontStyle"] = json!(t.style.font_style); v["fontSize"] = json!(t.style.font_size); @@ -453,26 +540,110 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result { let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.copyProperties", "select one layer"))?; let v = copy_props_of(s.doc()?, id); s.clipboard.props = Some(v.clone()); + s.clipboard.props_source_doc = s.ds()?.uid; Ok(v) } +/// Copied properties `props` without their style and variable links, for a paste into another +/// file: the copied ids name the source file's styles and variables, and the same ids here can +/// name unrelated ones. The values paste unlinked, and the layer's own links on them go. +fn without_links(mut props: Value) -> Value { + if let Some(m) = props.as_object_mut() { + for (k, v) in m.iter_mut() { + if k.ends_with("Style") && !k.starts_with("font") { + *v = Value::Null; + } else if k == "boundVariables" { + *v = json!({}); + } + } + } + props +} + /// Give layer `id` the properties [`copy_props_of`] copied (`props`), those it can take: the text /// properties only to text, the corners only to a layer with corners. pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, props: &Value) -> Result<()> { let mut m = props.as_object().cloned().unwrap_or_default(); - let is_text = matches!(doc.get(id)?.kind, NodeKind::Text(_)); - if !is_text { - m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing"); + let n = doc.get(id)?; + let (is_text, corners, frame) = (matches!(n.kind, NodeKind::Text(_)), n.kind.has_corner_radius(), n.kind.is_frame_like()); + let takes = |k: &str| { + let text = k.starts_with("font") || k.starts_with("paragraph") || matches!(k, "lineHeight" | "letterSpacing" | "textStyle"); + let corner = k == "cornerSmoothing" || k.ends_with("Radius"); + let grid = k == "gridStyle" || k == "grids" || k.starts_with("layoutGrids/"); + (is_text || !text) && (corners || !corner) && (frame || !grid) + }; + m.retain(|k, _| takes(k)); + // A style or variable the file doesn't have (deleted since the copy) isn't here to link to: the + // values it gave are pasted without a link, so the layer's own link goes too. + let here = |v: &Value| v.as_str().is_none_or(|sid| doc.style(sid).is_some()); + for (k, v) in m.iter_mut() { + if k.ends_with("Style") && !k.starts_with("font") && !here(v) { + *v = Value::Null; + } } - if !doc.get(id)?.kind.has_corner_radius() { - m.remove("cornerRadius"); - m.remove("cornerSmoothing"); + if let Some(Value::Object(copied)) = m.get_mut("boundVariables") { + copied.retain(|_, v| v.as_str().is_some_and(|vid| doc.variables.get_by_id(vid).is_some())); + } + // The layer's own bindings on what is pasted give way to the copied layer's: kept, a binding + // would hold the old value over the pasted one. A binding on what the copy doesn't carry (a + // text layer's font size, pasted from a frame) stays. + if let Some(Value::Object(copied)) = m.get("boundVariables") { + let mut bound: serde_json::Map = + n.bound.keys().filter(|f| copied_binding(f) && m.contains_key(pasted_key(f))).map(|f| (f.clone(), Value::Null)).collect(); + bound.extend(copied.iter().filter(|(f, _)| takes(f)).map(|(f, v)| (f.clone(), v.clone()))); + m.insert("boundVariables".into(), Value::Object(bound)); } crate::cmd::props::apply(cmd, doc, id, &m) } +/// The key of the properties [`copy_props_of`] copies that sets what a variable bound to `field` +/// sets: a corner's radius is `cornerRadius`, a side's stroke weight `strokeWeight`, the font +/// weight `fontStyle`, a layout grid's field `grids` and a paint's or effect's field its list. +fn pasted_key(field: &str) -> &str { + match field { + "topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "cornerRadius", + f if crate::cmd::props::STROKE_SIDES.contains(&f) => "strokeWeight", + "fontWeight" => "fontStyle", + f => match f.split_once('/') { + Some(("layoutGrids", _)) => "grids", + Some((list, _)) => list, + None => f, + }, + } +} + +/// Whether a variable bound to `field` goes with the properties [`copy_props_of`] copies: not a +/// size, auto layout spacing, visibility or text content. +fn copied_binding(field: &str) -> bool { + !matches!( + field, + "width" + | "height" + | "minWidth" + | "maxWidth" + | "minHeight" + | "maxHeight" + | "gap" + | "columnGap" + | "rowGap" + | "crossGap" + | "padding" + | "paddingHorizontal" + | "paddingVertical" + | "paddingTop" + | "paddingRight" + | "paddingBottom" + | "paddingLeft" + | "visible" + | "characters" + ) +} + pub(super) fn paste_props(s: &mut Session, p: &Value) -> Result { - let props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?; + let mut props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?; + if s.ds()?.uid != s.clipboard.props_source_doc { + props = without_links(props); + } let ids = req_targets("edit.pasteProperties", s, p)?; let doc = s.doc_mut()?; for i in ids { diff --git a/crates/engine/src/cmd/edit/vector_clipboard.rs b/crates/engine/src/cmd/edit/vector_clipboard.rs index 72c60bf02..f52916ee8 100644 --- a/crates/engine/src/cmd/edit/vector_clipboard.rs +++ b/crates/engine/src/cmd/edit/vector_clipboard.rs @@ -154,7 +154,7 @@ pub(super) fn cut_selection(s: &mut Session, sel: EditSelection) -> Result Result { } let uid = ds.uid; let active_uid = s.docs.get(s.active).map(|d| d.uid); + s.remember_view(i); s.remove_tabs(|d| d.uid == uid); // Removing a tab before the active one shifts its index; keep the same document selected. s.active = active_uid.and_then(|a| s.docs.iter().position(|d| d.uid == a)).unwrap_or(i.min(s.docs.len().saturating_sub(1))); diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index ea9a0d90a..dbb38f6c6 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -107,6 +107,7 @@ pub(crate) fn open(s: &mut Session, p: &Value) -> Result { ds.on_disk = on_disk.filter(|_| native); s.docs.push(ds); s.active = s.docs.len() - 1; + s.restore_view(); let mut out = json!({"index": s.active, "summary": summary}); out[if warnings { "warnings" } else { "repairs" }] = json!(loaded.issues); Ok(out) diff --git a/crates/engine/src/cmd/file/save.rs b/crates/engine/src/cmd/file/save.rs index 7cd01c2d2..8241ba875 100644 --- a/crates/engine/src/cmd/file/save.rs +++ b/crates/engine/src/cmd/file/save.rs @@ -173,7 +173,8 @@ fn wants_data(p: &Value) -> bool { /// Save the file of the active tab (the main file for a branch tab, with its branches), or export /// the active document as an experimental `.fig` copy without changing its native save state. -/// Without a path the file comes back as base64 `data` for the caller to deliver (#969). +/// Without a path the file comes back as base64 `data` for the caller to deliver (#969). Saved +/// to another file, the document takes that file's name, as its tab does. fn save_to(s: &mut Session, path: Option) -> Result { if let Some(path) = path.as_deref().filter(|p| ext(p) == "fig") { return export_fig(s, &json!({"path": path})); @@ -185,9 +186,7 @@ fn save_to(s: &mut Session, path: Option) -> Result { refuse_dropping_images(ds, path)?; } let mut snapshot = FileSnapshot::of(ds); - let follows_path = ds.path.as_deref().map_or(ds.doc.name == "Untitled", |old| ds.doc.name == file_stem(old)); if let Some(path) = path.as_deref() - && follows_path && ds.path.as_deref() != Some(path) { Arc::make_mut(&mut snapshot.doc).name = file_stem(path); diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index cd2a8fd74..2595bf930 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -234,6 +234,9 @@ fn crop(s: &mut Session, p: &Value) -> Result { // Like any paint edit, the layer leaves its paint style. n.styles.fill = None; } + if s.ds()?.vector_edit.is_some() { + crate::vectoredit::end(s)?; + } s.request_ui(cmd, json!({"id": id, "index": index})); Ok(json!({"id": id, "index": index})) } diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index bf1c92d2f..aa4b9464f 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -238,6 +238,7 @@ fn wrap(s: &mut Session, p: &Value, cmd: &str, w: Wrap) -> Result { } if let Wrap::Frame = w { g.clip = true; + g.fills.clear(); } // Insert the container where the topmost layer is. doc.insert(g, parent, index)?; diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 177155a8a..f80c0c541 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -642,7 +642,7 @@ pub fn specs() -> Vec { spec!( "text.edit.key", "Text key", - "{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent", + "{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent; elsewhere Tab and Shift+Tab edit the next or previous text layer of the frame in reading order (rows top to bottom, each left to right), all of it selected, and do nothing at the last and the first (in a board object or a widget's field Tab types a tab)", true, |s, p| { let k = req_string("text.edit.key", p, "key")?; diff --git a/crates/engine/src/code_connect_tests.rs b/crates/engine/src/code_connect_tests.rs index 4474fe03a..f28aa882c 100644 --- a/crates/engine/src/code_connect_tests.rs +++ b/crates/engine/src/code_connect_tests.rs @@ -298,3 +298,207 @@ fn many_entries_for_one_component_each_link() { let i = idv(&ex(&mut s, "instance.create", json!({"component": hover, "x": 0, "y": 500}))); assert_eq!(code(&mut s, i, "react"), "", 3) { edit = Some(("template", v)); } widgets::note(ui, tr("{property} is its value; {property ? \"a\" : \"b\"} picks a string. Other {…} stays as written."), t.text_secondary); + variant_values(app, ui, doc, owner, lang, &link); if let Some((key, value)) = edit { let mut params = params; params[key] = json!(value); @@ -499,6 +510,44 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId ui.add_space(4.0); } +/// The variant values of a connected component and what code calls them: a value left empty +/// stays as the design names it. +fn variant_values(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, lang: CodeLang, link: &CodeLink) { + let properties = code_connect::variants(doc, owner); + if properties.is_empty() { + return; + } + let mut change: Option<(String, String, String)> = None; + widgets::sublabels(ui, tr("Variant value"), Some(tr("In code"))); + let col = widgets::col_width(ui.available_width()); + for (property, options) in &properties { + for option in options { + let current = link.values.get(property).and_then(|m| m.get(option)).map_or("", String::as_str); + row(ui, 32.0, |ui| { + ui.spacing_mut().item_spacing.x = 8.0; + ui.allocate_ui_with_layout(vec2(col, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(col); + ui.add(egui::Label::new(format!("{property}: {option}")).truncate()); + }); + if let Some(v) = widgets::text_field(ui, Id::unique(("code_connect_value", owner, lang.id(), property, option)), current, col, option) + { + change = Some((property.clone(), option.clone(), v)); + } + }); + } + } + let Some((property, option, value)) = change else { return }; + let mut values = link.values.clone(); + let mapped = values.entry(property).or_default(); + if value.trim().is_empty() { + mapped.remove(&option); + } else { + mapped.insert(option, value.trim().to_string()); + } + values.retain(|_, m| !m.is_empty()); + app.run("codeConnect.set", json!({"id": owner, "language": lang.id(), "values": values})); +} + /// Dev Mode plugins: the installed plugins that only read the document, run from the Inspect tab. pub fn plugins_section(app: &mut FigApp, ui: &mut Ui) { let runnable: Vec<(String, String, String)> = app diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index d24be7ef6..5c39c4375 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -556,8 +556,9 @@ pub(crate) fn list_width(ui: &Ui) -> f32 { } /// A name's room on a row stops growing here: a name of thousands of characters (#1650) elides -/// past it instead of making the list that wide. -pub(crate) const NAME_ROOM: f32 = 1200.0; +/// past it instead of making the list that wide. 400 pt still holds a long variant name +/// (`Size=small, Type=primary, State=default, Icon=leading, Width=full`) in full. +pub(crate) const NAME_ROOM: f32 = 400.0; /// A row's name: the layer's, or its kind's label when it has none. fn row_name(n: &figcraft_doc::Node) -> &str { @@ -1018,20 +1019,34 @@ fn drop_layers(app: &mut FigApp, doc: &Document, rows: &[Row], moving: &[NodeId] app.run("layers.reparent", json!({"ids": ids, "parent": parent.id, "index": index})); } -/// The eye and padlock of a row: painted when hovered (`over`, false in Dev Mode) or set, and, outside -/// Dev Mode, clickable; a drag over them starts a sweep. Returns the layers whose eye / padlock was clicked. -fn eye_lock( - ui: &mut Ui, - t: &Tokens, - rects: [Rect; 2], - row: &Row, - n: &figcraft_doc::Node, - over: bool, - dev: bool, - sweep: &mut Option, -) -> (Option, Option) { - let [r, rr] = rects; - let (mut vis, mut lock) = (None, None); +/// The eye and padlock's span on a row (`rr`, the row inset 8 pt from each side) wider than the view: +/// its end stops 8 pt inside the view's edge, where it is on a row as wide as the view, but never so +/// far in that the buttons cover the row's disclosure triangle, icon or name start (`name_x`, +/// unmirrored). Returns that row span (what [`eye_lock`] places them at the end of) and the +/// buttons' 48 pt: the eye and padlock are 20 pt each, 4 pt from the end and 2 pt apart. +fn row_buttons(rr: Rect, view: Rect, name_x: f32, rtl: bool) -> (Rect, Rect) { + if rtl { + let name_start = rr.min.x + rr.max.x - name_x; + let end = Rect::from_min_max(pos2(rr.min.x.max((view.min.x + 8.0).min(name_start - 48.0)), rr.min.y), rr.max); + return (end, Rect::from_x_y_ranges(end.min.x..=(end.min.x + 48.0), rr.y_range())); + } + let end = Rect::from_min_max(rr.min, pos2(rr.max.x.min((view.max.x - 8.0).max(name_x + 48.0)), rr.max.y)); + (end, Rect::from_x_y_ranges((end.max.x - 48.0)..=end.max.x, rr.y_range())) +} + +/// Where a row's name is drawn: the view, less the eye and padlock's `buttons` while they show, so +/// a long name is clipped before them instead of drawn under them. +fn name_clip(view: Rect, buttons: Rect, buttons_shown: bool, rtl: bool) -> Rect { + match (buttons_shown, rtl) { + (false, _) => view, + (true, false) => Rect::from_x_y_ranges(view.min.x..=view.max.x.min(buttons.min.x), view.y_range()), + (true, true) => Rect::from_x_y_ranges(view.min.x.max(buttons.max.x)..=view.max.x, view.y_range()), + } +} + +/// Whether row `r`'s layer shows as hidden and as locked: what a sweep in progress sets for the rows +/// it took in, else the layer's own state. The row joins the sweep when the pointer is on it. +fn swept_state(ui: &Ui, r: Rect, row: &Row, n: &figcraft_doc::Node, sweep: &mut Option) -> (bool, bool) { // A sweep across the eyes or padlocks takes in the rows the pointer passes. if let Some(sw) = sweep.as_mut() && !sw.ids.contains(&row.id) @@ -1042,9 +1057,26 @@ fn eye_lock( sw.ids.push(row.id); } let swept = |lock: bool| sweep.as_ref().filter(|sw| sw.lock == lock && sw.ids.contains(&row.id)).map(|sw| sw.on); + (swept(false).unwrap_or(!n.visible), swept(true).unwrap_or(n.locked)) +} + +/// The eye and padlock of a row, shown `hidden` and `locked` ([`swept_state`]): painted when hovered +/// (`over`, false in Dev Mode) or set, and, outside Dev Mode, clickable; a drag over them starts a +/// sweep. Returns the layers whose eye / padlock was clicked. +fn eye_lock( + ui: &mut Ui, + t: &Tokens, + rects: [Rect; 2], + row: &Row, + n: &figcraft_doc::Node, + (hidden, locked): (bool, bool), + over: bool, + dev: bool, + sweep: &mut Option, +) -> (Option, Option) { + let [r, rr] = rects; + let (mut vis, mut lock) = (None, None); // Lock / eye on hover (or when set); a layer in a locked one shows a faint padlock. - let hidden = swept(false).unwrap_or(!n.visible); - let locked = swept(true).unwrap_or(n.locked); // In Dev Mode they only show what is set. let show_lock = over || locked || row.locked_above; let show_eye = over || hidden; @@ -1315,6 +1347,8 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { let icon_rect = Rect::from_center_size(pos2(fx(x0 + 22.0), r.center().y), vec2(14.0, 14.0)); icons::paint(ui.painter(), icon_rect, icon, icon_col); let name_x = x0 + 36.0; + let (buttons_end, buttons) = row_buttons(rr, ui.clip_rect(), name_x, rtl); + let toggles = swept_state(ui, r, row, n, &mut sweep); if app.ui.rename.is_some_and(|rn| rn.id == row.id) { if let Some(new) = rename_field(app, ui, row.id, row.depth, &n.name, r) { rename_done = Some((row.id, new)); @@ -1326,9 +1360,11 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { // Room before the lock and eye buttons (the row is wide enough for the whole // name, up to `NAME_ROOM`: a row widened by a deeper name gives no more). let max_w = (rr.max.x - 56.0 - name_x).clamp(20.0, NAME_ROOM); - crate::bidi::paint_name_from(ui.painter(), pos2(fx(name_x), r.center().y), rtl, &name, font, col, max_w); + let buttons_shown = (over && !dev) || toggles.0 || toggles.1 || row.locked_above; + let clip = name_clip(ui.clip_rect(), buttons, buttons_shown, rtl); + crate::bidi::paint_name_from(&ui.painter().with_clip_rect(clip), pos2(fx(name_x), r.center().y), rtl, &name, font, col, max_w); } - let (v, l) = eye_lock(ui, &t, [r, rr], row, n, over && !dev, dev, &mut sweep); + let (v, l) = eye_lock(ui, &t, [r, buttons_end], row, n, toggles, over && !dev, dev, &mut sweep); vis = v.or(vis); lock = l.or(lock); if resp.clicked() { diff --git a/crates/ui-egui/src/panels/right/menu.rs b/crates/ui-egui/src/panels/right/menu.rs index 8f6e7f7fd..9cdea6fa6 100644 --- a/crates/ui-egui/src/panels/right/menu.rs +++ b/crates/ui-egui/src/panels/right/menu.rs @@ -44,22 +44,92 @@ pub(crate) fn preview_blend(app: &mut FigApp, ctx: &egui::Context, ids: &[NodeId /// (else its 600 px default area width) and keeps the size measured; rows ([`menu_row`]) take the /// larger of that width and their content, so the menu fits its content. Chain `.width(w)` for a /// menu at least `w` wide. -pub fn menu_popup(anchor: &egui::Response) -> egui::Popup<'static> { - egui::Popup::menu(anchor).width(anchor.rect.width().max(MENU_MIN_W)).style(menu_style) +pub fn menu_popup(anchor: &egui::Response) -> Menu { + Menu(egui::Popup::menu(anchor).width(anchor.rect.width().max(MENU_MIN_W)).style(menu_style)) } /// A context menu (secondary click on `resp`) sized like [`menu_popup`]. -pub fn context_popup(resp: &egui::Response) -> egui::Popup<'static> { - egui::Popup::context_menu(resp).width(MENU_MIN_W).style(menu_style) +pub fn context_popup(resp: &egui::Response) -> Menu { + Menu(egui::Popup::context_menu(resp).width(MENU_MIN_W).style(menu_style)) } /// A context menu for a property row: a secondary click anywhere over `rect` opens it, even over /// the row's fields (which would otherwise take the click), like the incumbent's row menus. -pub(super) fn row_context_menu(ui: &Ui, rect: Rect, id: Id) -> egui::Popup<'static> { +pub(super) fn row_context_menu(ui: &Ui, rect: Rect, id: Id) -> Menu { let resp = ui.interact(rect, id, Sense::hover()); let open = ui.rect_contains_pointer(rect) && ui.input(|i| i.pointer.secondary_clicked()); let at_pointer = egui::Popup::menu(&resp).width(MENU_MIN_W).style(menu_style).at_pointer_fixed(); - at_pointer.open_memory(open.then_some(egui::SetOpenCommand::Bool(true))) + Menu(at_pointer.open_memory(open.then_some(egui::SetOpenCommand::Bool(true)))) +} + +/// The gap a menu taller than the window keeps from the window's top and bottom edges. +const MENU_WINDOW_GAP: f32 = 8.0; + +/// A popup menu ([`menu_popup`], [`context_popup`]) whose rows scroll when it would be taller +/// than the window. egui keeps a popup inside the window by moving it, but one taller than the +/// window runs off its edge, and rows past it can't be reached. +#[must_use] +pub struct Menu(egui::Popup<'static>); + +impl Menu { + /// At least `width` wide. + pub fn width(self, width: f32) -> Self { + Self(self.0.width(width)) + } + + /// Open and closed under `id` instead of the anchor's. + pub fn id(self, id: Id) -> Self { + Self(self.0.id(id)) + } + + pub fn close_behavior(self, behavior: egui::PopupCloseBehavior) -> Self { + Self(self.0.close_behavior(behavior)) + } + + /// Where the menu may go when its first placement doesn't fit, in order. + pub fn align_alternatives(self, alternatives: &'static [egui::RectAlign]) -> Self { + Self(self.0.align_alternatives(alternatives)) + } + + /// Show the menu while it is open. Its rows `content` scroll with the wheel or the scroll bar + /// once they were taller than the window last frame, as the main menu's do (#2217); a menu + /// that fits is laid out as it is, so it still grows with its rows (a scroll area in a popup + /// would keep the popup's last height). A click on the scroll bar scrolls and leaves the menu + /// open. The rows have the same ids scrolling or not, so the row the keyboard is on keeps it + /// when the window's height changes which of the two the menu does. + pub fn show(self, content: impl FnOnce(&mut Ui) -> R) -> Option> { + let rows = self.0.get_id().with("menu_rows"); + let bar_key = rows.with("scroll_bar"); + let ctx = self.0.ctx().clone(); + let bar_clicked = ctx.data(|d| d.get_temp::(bar_key)).is_some_and(|bar| ctx.interaction_snapshot(|i| i.clicked == Some(bar))); + let popup = if bar_clicked { self.0.close_behavior(egui::PopupCloseBehavior::IgnoreClicks) } else { self.0 }; + let rows_ui = egui::UiBuilder::new().scope_id(rows); + popup.show(|ui| { + let window = ui.ctx().content_rect().height(); + let max_height = (window - ui.style().spacing.menu_margin.sum().y - 2.0 * MENU_WINDOW_GAP).max(0.0); + let rows_height = ui.scope_id().with("menu_rows_height"); + let last = ui.data(|d| d.get_temp::(rows_height)).unwrap_or(0.0); + let (inner, height) = if last > max_height { + let out = egui::ScrollArea::vertical() + .id_salt("menu_rows") + .max_height(max_height) + .scroll_source(egui::scroll_area::ScrollSource::MOUSE_WHEEL | egui::scroll_area::ScrollSource::SCROLL_BAR) + .show(ui, |ui| ui.scope_builder(rows_ui, content).inner); + // egui's id for a scroll area's vertical bar (a test in `menu_scroll_tests` clicks it). + ui.data_mut(|d| d.insert_temp(bar_key, out.id.with(1_usize))); + (out.inner, out.content_size.y) + } else { + let inner = ui.scope_builder(rows_ui, content).inner; + let height = ui.min_rect().height(); + if height > max_height { + ui.ctx().request_repaint(); + } + (inner, height) + }; + ui.data_mut(|d| d.insert_temp(rows_height, height)); + inner + }) + } } pub fn menu_item(ui: &mut Ui, label: &str, shortcut: &str) -> bool { @@ -116,12 +186,23 @@ fn lit_row( // These menus sit on the theme's popup fill (white in the light theme), not on the dark // `t.menu` of the menu bar: the theme's text, white only on the green highlight (#972). let col = if hovered { t.menu_text } else { t.text }; - ui.painter().galley(pos2(r.min.x + MENU_PAD + lead, r.center().y - text.size().y / 2.0), text, col); - if let Some(k) = keys { - let at = pos2(r.max.x - MENU_PAD - k.size().x, r.center().y - k.size().y / 2.0); - ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary }); + let rtl = crate::widgets::rtl(ui); + if rtl { + ui.painter().galley(pos2(r.max.x - MENU_PAD - lead - text.size().x, r.center().y - text.size().y / 2.0), text, col); + if let Some(k) = keys { + let at = pos2(r.min.x + MENU_PAD, r.center().y - k.size().y / 2.0); + ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary }); + } + } else { + ui.painter().galley(pos2(r.min.x + MENU_PAD + lead, r.center().y - text.size().y / 2.0), text, col); + if let Some(k) = keys { + let at = pos2(r.max.x - MENU_PAD - k.size().x, r.center().y - k.size().y / 2.0); + ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary }); + } } - art(ui.painter(), r, col); + // In RTL, anchor right-aligned trailing artwork near the reading end (left) so it stays opposite the label. + let art_r = if rtl && art_w > 0.0 { Rect::from_min_max(r.min, pos2((r.min.x + art_w + MENU_PAD).min(r.max.x), r.max.y)) } else { r }; + art(ui.painter(), art_r, col); resp } @@ -196,16 +277,54 @@ const CHECK_COL: f32 = 14.0; /// `Some(true)`) is drawn in its own column ahead of the icon, so a checked entry's label does /// not move against the unchecked ones. pub fn menu_icon_item(ui: &mut Ui, icon: Option, on: Option, label: &str, shortcut: &str) -> bool { + let rtl = crate::widgets::rtl(ui); let paint = |p: &egui::Painter, r: Rect, col: Color32| { if on == Some(true) { let mark = p.layout_no_wrap("✓".to_owned(), regular(11.5), col); - p.galley(pos2(r.min.x + MENU_PAD, r.center().y - mark.size().y / 2.0), mark, col); + let x = if rtl { r.max.x - MENU_PAD - mark.size().x } else { r.min.x + MENU_PAD }; + p.galley(pos2(x, r.center().y - mark.size().y / 2.0), mark, col); } if let Some(icon) = icon { - crate::icons::paint(p, Rect::from_min_size(pos2(r.min.x + MENU_PAD + CHECK_COL, r.center().y - 8.0), vec2(16.0, 16.0)), icon, col); + let x = if rtl { r.max.x - MENU_PAD - CHECK_COL - 16.0 } else { r.min.x + MENU_PAD + CHECK_COL }; + crate::icons::paint(p, Rect::from_min_size(pos2(x, r.center().y - 8.0), vec2(16.0, 16.0)), icon, col); } }; let resp = lit_row(ui, label, shortcut, 0.0, CHECK_COL + 22.0, paint, false); a11y::menu_item(&resp, label, shortcut, on); resp.clicked() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rtl_lit_row_places_art_opposite_label() { + let ctx = egui::Context::default(); + ctx.all_styles_mut(|s| s.right_to_left = true); + let mut art_rect = None; + ctx.run_ui(Default::default(), |ui| { + egui::Area::new(egui::Id::unique("menu-rtl-test")).fixed_pos(pos2(0.0, 0.0)).show(ui.ctx(), |ui| { + ui.set_width(220.0); + let _ = lit_row( + ui, + "קצוות עגולים", + "", + 64.0, + 0.0, + |_pt, r, _| { + art_rect = Some(r); + }, + false, + ); + }); + }) + .textures_delta + .clear(); + let art_r = art_rect.expect("art invoked"); + // Artwork paints relative to art_r.max.x in [art_r.max.x - 64.0, art_r.max.x], + // so its right edge stays on the left side while the RTL label sits at r.max.x - MENU_PAD. + assert!((art_r.max.x - (art_r.min.x + 64.0 + MENU_PAD)).abs() < 0.01, "art_r={art_r:?}"); + assert!(art_r.max.x < 100.0, "expected trailing left placement, got {art_r:?}"); + } +} diff --git a/crates/ui-egui/src/perf_tests.rs b/crates/ui-egui/src/perf_tests.rs index 7e09d3bf3..ad673ca24 100644 --- a/crates/ui-egui/src/perf_tests.rs +++ b/crates/ui-egui/src/perf_tests.rs @@ -116,10 +116,10 @@ fn report(layers: usize) { let open: Vec = b.app.session.doc().unwrap().nodes().filter(|n| !n.children.is_empty()).map(|n| n.id).collect(); b.app.ui.expanded.extend(open); rows.push(("first frame, every layer expanded", b.frame(vec![]))); - b.app.ui.layers_focus = true; let top = b.app.session.doc().ok().and_then(|d| d.node(page)?.children.last().copied()); b.app.session.set_selection(top.into_iter().collect()); b.frame(vec![]); + b.frame(key(Key::F6, Modifiers::SHIFT)); rows.push(("arrow key down the expanded layers", b.mean(30, |_| key(Key::ArrowDown, Modifiers::NONE)))); b.app.ui.expanded.clear(); b.frame(vec![]); diff --git a/crates/ui-egui/src/pixel_grid_tests.rs b/crates/ui-egui/src/pixel_grid_tests.rs new file mode 100644 index 000000000..9333ffdc1 --- /dev/null +++ b/crates/ui-egui/src/pixel_grid_tests.rs @@ -0,0 +1,66 @@ +//! The pixel grid, drawn headless: from 400% its lines are one screen pixel wide and a grey that +//! shows on a white frame and on the dark canvas alike, as in Figma. + +use egui::{Color32, RawInput, Shape, ViewportId, ViewportInfo}; +use figcraft_engine::Session; +use serde_json::json; + +use crate::canvas::overlays::PIXEL_GRID; +use crate::layers_drag_tests::Ui; +use crate::live_tests::flat; + +/// Each grid line drawn in a frame on a screen of `native` pixels per point (the last of a few, +/// for a new scale to take effect): its width and the coordinate it runs along, its x if +/// vertical and its y if horizontal. +fn grid_lines(u: &mut Ui, native: f32) -> Vec<(f32, f32)> { + let mut out = None; + for _ in 0..4 { + let mut raw = RawInput::default(); + raw.viewports.insert(ViewportId::ROOT, ViewportInfo { native_pixels_per_point: Some(native), ..Default::default() }); + out = Some(u.frame_raw(raw)); + } + let shapes = flat(&out.map(|o| o.shapes).unwrap_or_default()); + shapes + .iter() + .filter_map(|s| match s { + Shape::LineSegment { points: [a, b], stroke } if stroke.color == PIXEL_GRID => Some((stroke.width, if a.x == b.x { a.x } else { a.y })), + _ => None, + }) + .collect() +} + +/// Whether every line in `lines` sits on the middle of a row or column of pixels of a screen of +/// `native` pixels per point, so it covers that one pixel and no half of two. +fn on_pixel_centres(lines: &[(f32, f32)], native: f32) -> bool { + lines.iter().all(|(_, at)| ((at * native - 0.5) - (at * native - 0.5).round()).abs() < 1e-3) +} + +/// `c` drawn over a grey of `bg`, as the canvas blends it. +fn over(c: Color32, bg: u8) -> f32 { + let [r, _, _, a] = c.to_srgba_unmultiplied(); + let a = f32::from(a) / 255.0; + f32::from(bg) * (1.0 - a) + f32::from(r) * a +} + +#[test] +fn the_pixel_grid_shows_on_white_and_on_dark_one_screen_pixel_wide() { + let mut s = Session::new(); + s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + let mut u = Ui::new(s); + let view = &mut u.app.session.ds_mut().unwrap().view; + view.zoom = 8.0; + // A view between whole points, so the page's pixels fall between the screen's. + (view.cx, view.cy) = (50.03, 50.07); + let lines = grid_lines(&mut u, 1.0); + assert!(!lines.is_empty(), "the grid draws at 800%"); + assert!(lines.iter().all(|(w, _)| *w == 1.0), "one screen pixel: {lines:?}"); + assert!(on_pixel_centres(&lines, 1.0), "on the screen's pixels: {lines:?}"); + // Measured in Figma (2026-11-24): a grid line is 242 on white and 78 on a grey of 50. + assert_eq!((over(PIXEL_GRID, 255).round(), over(PIXEL_GRID, 50).round()), (242.0, 78.0)); + // On a 2x screen the lines stay one of its pixels wide. + let lines = grid_lines(&mut u, 2.0); + assert!(!lines.is_empty() && lines.iter().all(|(w, _)| *w == 0.5), "{lines:?}"); + assert!(on_pixel_centres(&lines, 2.0), "on the 2x screen's pixels: {lines:?}"); + u.app.session.ds_mut().unwrap().view.zoom = 3.0; + assert!(grid_lines(&mut u, 2.0).is_empty(), "no grid below 400%"); +} diff --git a/crates/ui-egui/src/save_as_tests.rs b/crates/ui-egui/src/save_as_tests.rs index 8817ab1c8..add2419d9 100644 --- a/crates/ui-egui/src/save_as_tests.rs +++ b/crates/ui-egui/src/save_as_tests.rs @@ -73,7 +73,12 @@ fn toast(app: &FigApp) -> &str { } fn expected_picker() -> Vec<(String, String, Vec)> { - vec![("Save as".into(), "Prototype.figcraft".into(), vec!["figcraft".into(), "fig".into()])] + picker_named("Prototype") +} + +/// The Save as picker suggesting `name` with the native extension. +fn picker_named(name: &str) -> Vec<(String, String, Vec)> { + vec![("Save as".into(), format!("{name}.figcraft"), vec!["figcraft".into(), "fig".into()])] } #[test] @@ -124,7 +129,8 @@ fn native_paths_and_an_extensionless_default_save_native_files_and_show_the_writ let mut reopened = Session::empty(); reopened.execute("file.open", &json!({"path": path})).unwrap(); assert_eq!(reopened.doc().unwrap().nodes().count(), app.session.doc().unwrap().nodes().count()); - assert_eq!(reopened.doc().unwrap().name, "Prototype"); + let stem = std::path::Path::new(written).file_stem().unwrap().to_str().unwrap(); + assert_eq!(reopened.doc().unwrap().name, stem, "named after the file it was saved as"); } } @@ -261,16 +267,19 @@ fn saving_legacy_fig_paths_keeps_the_success_toast_and_original_source_bytes() { let legacy_bytes = std::fs::read(&legacy).unwrap(); app.save(); app.poll_dialog(&egui::Context::default()); - assert_eq!(*picks.lock().unwrap(), expected_picker()); + assert_eq!(*picks.lock().unwrap(), picker_named("original"), "named after the file it was saved as first"); assert_eq!(std::fs::read(&legacy).unwrap(), legacy_bytes); assert!(target.is_file()); assert!(app.ui.last_error.is_none()); - assert_eq!(app.session.doc().unwrap(), &before); if destination == "corrected.figcraft" { + let mut renamed = before.clone(); + renamed.name = "corrected".into(); + assert_eq!(app.session.doc().unwrap(), &renamed, "saved to another file: named after it"); assert_eq!(toast(&app), "Saved corrected.figcraft"); assert_eq!(app.session.ds().unwrap().path.as_deref(), target.to_str()); assert!(!app.session.ds().unwrap().is_dirty()); } else { + assert_eq!(app.session.doc().unwrap(), &before, "an export leaves the document alone"); assert_eq!(toast(&app), "Exported copy.fig"); assert_eq!(app.session.ds().unwrap().path.as_deref(), Some(legacy_path.as_str())); assert!(app.session.ds().unwrap().is_dirty()); diff --git a/crates/ui-egui/src/shortcut_keys_tests.rs b/crates/ui-egui/src/shortcut_keys_tests.rs index e48a3d0bb..f1fbfd715 100644 --- a/crates/ui-egui/src/shortcut_keys_tests.rs +++ b/crates/ui-egui/src/shortcut_keys_tests.rs @@ -2,8 +2,8 @@ //! headless: arrows pan with nothing selected, the keyboard box selection key and Cmd/Ctrl+arrows //! drawing it out, list indentation while editing text, symbols another keyboard layout types with //! Shift, the presentation keys (Space and N forward, C comments, F full screen), Alt+R for the -//! rotation origin, Enter placing a shape with its tool chosen and Cmd/Ctrl+= and - zooming the -//! canvas, not the interface. +//! rotation origin, Enter placing a shape with its tool chosen, Cmd/Ctrl+= and - zooming the +//! canvas, not the interface, and Shift+Cmd/Ctrl+' saying whether it snaps to the pixel grid. use egui::{Event, Key, Modifiers, ViewportCommand, ViewportId}; use figcraft_doc::NodeId; @@ -299,3 +299,16 @@ fn cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift() { assert!((rot(&u) - rot_before).abs() < 1e-6, "no turn while editing points"); u.app.run("vector.edit.end", json!({})); } + +#[test] +fn shift_cmd_quote_says_whether_snapping_to_the_pixel_grid_is_on() { + let mut u = Ui::new(Session::new()); + let toast = |u: &Ui| u.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + let snap = |u: &Ui| u.app.session.ds().unwrap().view.snap_pixel; + press(&mut u, Key::Quote, cmd() | Modifiers::SHIFT); + assert!(!snap(&u)); + assert_eq!(toast(&u), "Snap to pixel grid off"); + press(&mut u, Key::Quote, cmd() | Modifiers::SHIFT); + assert!(snap(&u)); + assert_eq!(toast(&u), "Snap to pixel grid on"); +} diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 7efb651ba..55b2cc56b 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -419,6 +419,9 @@ pub fn run_binding(app: &mut FigApp, id: &str) { "edit.delete" if app.session.tool.pen.is_some() => { let _ = app.session.pen_finish(); } + "edit.pickColor" if app.ui.picker.is_some() => { + app.run("edit.pickColor", json!({"apply": false})); + } // Enter with a shape or frame tool chosen places one in the middle of the view. "select.children" if !dev && app.session.tool.tool.draws_shape() => { app.run("tool.place", json!({})); @@ -483,10 +486,6 @@ fn key_event(app: &mut FigApp, key: Key, physical: Option, m: Modifiers, re } return true; } - // Arrows move through the layers panel while it has the keyboard. - if app.ui.layers_focus && !m.command && !m.alt && crate::layers::key_nav(app, key, m.shift) { - return true; - } // Arrow nudges, Alt held too (measuring stays on while the selection moves); with nothing // selected the arrows pan the view. let (dx, dy) = match key { @@ -783,6 +782,10 @@ fn text_keys(app: &mut FigApp, ctx: &Context, events: &[Event], ime_input: Optio let reject_ime = ime_input.is_some_and(|baseline| baseline.interrupted(app)); // A key that ran a shortcut swallows the text it also produced (Alt+. types "≥" on macOS). let mut skip_text = false; + let paste_in_batch = events.iter().any(|e| matches!(e, Event::Paste(_))); + // The browser sends Shift/Alt+Cmd/Ctrl+V's keys along with its paste event: the chord on the + // key, not the modifiers still held when the paste is handled, says to match the style. + let match_style = events.iter().any(|e| matches!(e, Event::Key { key: Key::V, pressed: true, modifiers: m, .. } if match_style_chord(*m))); for ev in events { if reject_ime && matches!(ev, Event::Ime(_)) { continue; @@ -794,9 +797,19 @@ fn text_keys(app: &mut FigApp, ctx: &Context, events: &[Event], ime_input: Optio } } Event::Ime(ime) => ime_event(app, ctx, ime), - Event::Paste(t) => insert_text(app, ctx, t), + Event::Paste(t) => paste_text(app, ctx, t, match_style), Event::Copy => copy_or_cut(app, ctx, false), Event::Cut => copy_or_cut(app, ctx, true), + // On the desktop the chord comes without a paste event: paste the clipboard's characters. + Event::Key { key: Key::V, pressed: true, modifiers: m, .. } if match_style_chord(*m) => { + if !paste_in_batch + && !app.control_synthetic + && let Some(t) = app.services.clipboard_get_text() + { + insert_text(app, ctx, &t); + } + skip_text = true; + } Event::Key { key, physical_key, pressed: true, modifiers: m, .. } if text_key_event(app, ctx, *key, *physical_key, *m) => { skip_text = true; } @@ -820,6 +833,29 @@ fn insert_text(app: &mut FigApp, ctx: &Context, t: &str) { } } +/// Shift or Alt with Cmd/Ctrl, the Paste and match style chord with V. Shift alone is another +/// paste key (Shift+Insert), which keeps the copied formatting. +fn match_style_chord(m: Modifiers) -> bool { + m.command && (m.alt || m.shift) +} + +/// Paste `t` into the edit: with the formatting it was copied with when it's the characters +/// FigCraft last copied and `match_style` is off, otherwise in the style at the caret. +fn paste_text(app: &mut FigApp, ctx: &Context, t: &str, match_style: bool) { + let pasted = t.replace("\r\n", "\n").replace('\r', "\n"); + let Some(copied) = app.ui.text_copy.clone().filter(|c| !match_style && c.text == pasted) else { + insert_text(app, ctx, t); + return; + }; + let before = ime_stamp(app); + if let Err(e) = figcraft_engine::textedit::insert_rich(&mut app.session, &copied) { + app.toast(e.to_string()); + } + if ime_stamp(app) != before { + note_ime_application_change(app, ctx); + } +} + /// An IME commit, preedit or surrounding-text deletion for the edit. fn ime_event(app: &mut FigApp, ctx: &Context, ev: &egui::ImeEvent) { match ev { @@ -874,6 +910,7 @@ fn copy_or_cut(app: &mut FigApp, ctx: &Context, cut: bool) { && let Some(text) = &selected { app.clipboard_set_text(text); + app.ui.text_copy = figcraft_engine::textedit::selected_rich_text(&app.session); } if cut && selected.is_some() { let _ = figcraft_engine::textedit::key(&mut app.session, "Delete", false, false, false); diff --git a/crates/ui-egui/src/text_enter_tests.rs b/crates/ui-egui/src/text_enter_tests.rs index 89129a7e9..cd0924328 100644 --- a/crates/ui-egui/src/text_enter_tests.rs +++ b/crates/ui-egui/src/text_enter_tests.rs @@ -1,7 +1,8 @@ -//! Enter and Escape on text, and the page a new file gets in each theme, driven through egui +//! Enter, Escape and Tab on text, and the page a new file gets in each theme, driven through egui //! headless: Enter on a selected text layer edits it with all of its text selected (what a //! double-click into it does), typing replaces it, and Escape leaves editing with the layer still -//! selected; File ▸ New in the dark theme makes a dark page. +//! selected; Tab while editing goes on to the next text layer; File ▸ New in the dark theme makes +//! a dark page. use egui::{Event, Key, Modifiers}; use figcraft_color::Color; @@ -12,7 +13,10 @@ use serde_json::json; use crate::layers_drag_tests::Ui; fn press(u: &mut Ui, key: Key) { - let modifiers = Modifiers::NONE; + press_with(u, key, Modifiers::NONE); +} + +fn press_with(u: &mut Ui, key: Key, modifiers: Modifiers) { u.frame(vec![ Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }, Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }, @@ -59,6 +63,48 @@ fn enter_edits_a_selected_text_with_all_of_it_selected_and_escape_keeps_the_laye assert!(u.app.session.selection().is_empty()); } +/// The text layer inside instance `inst`. +fn label_of(s: &Session, inst: NodeId) -> NodeId { + let doc = s.doc().unwrap(); + doc.subtree(inst).into_iter().find(|i| doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))).unwrap() +} + +#[test] +fn tab_edits_the_label_in_the_next_row_of_a_form() { + // A form: a vertical auto layout frame of instances of an option (a box and a label), each + // label set on its instance. + let mut s = Session::new(); + let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap()); + let option = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 160, "height": 24, "name": "Option"})).unwrap()); + s.execute("node.set", &json!({"id": option, "props": {"layout": "horizontal", "gap": 8}})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 16, "height": 16, "parent": option})).unwrap(); + let main_label = id(s.execute("text.create", &json!({"text": "Label", "x": 0, "y": 0, "parent": option})).unwrap()); + let option = id(s.execute("component.create", &json!({"ids": [option]})).unwrap()); + let form = id(s.execute("frame.create", &json!({"x": 0, "y": 200, "width": 240, "height": 200, "name": "Form"})).unwrap()); + s.execute("node.set", &json!({"id": form, "props": {"layout": "vertical", "gap": 12}})).unwrap(); + let mut labels = Vec::new(); + for name in ["Instagram", "Architect", "Designer"] { + let inst = id(s.execute("instance.create", &json!({"component": option, "parent": form})).unwrap()); + let label = label_of(&s, inst); + s.execute("text.set", &json!({"id": label, "characters": name})).unwrap(); + labels.push(label); + } + s.execute("text.edit.begin", &json!({"id": labels[0], "caret": 9})).unwrap(); + let mut u = Ui::new(s); + press(&mut u, Key::Tab); + let te = u.app.session.ds().unwrap().text_edit.clone().expect("still editing"); + assert_eq!((te.id, te.anchor.min(te.caret), te.anchor.max(te.caret)), (labels[1], 0, 9), "Architect, all of it selected"); + u.frame(vec![Event::Text("Writer".into())]); + assert_eq!(text(&u, labels[1]), "Writer", "typing replaces it"); + assert_eq!((text(&u, labels[0]), text(&u, main_label)), ("Instagram".into(), "Label".into()), "the others stay"); + press_with(&mut u, Key::Tab, Modifiers::SHIFT); + assert_eq!(u.app.session.ds().unwrap().text_edit.as_ref().map(|te| te.id), Some(labels[0]), "Shift+Tab: back to Instagram"); + // An override: the main's label changing leaves it as typed. + press(&mut u, Key::Escape); + u.app.session.execute("text.set", &json!({"id": main_label, "characters": "Choice"})).unwrap(); + assert_eq!(text(&u, labels[1]), "Writer", "kept as the instance's own text"); +} + #[test] fn copying_and_cutting_selected_text_use_clipboard_service() { use std::{cell::RefCell, rc::Rc}; diff --git a/crates/ui-egui/src/text_paste_style_tests.rs b/crates/ui-egui/src/text_paste_style_tests.rs new file mode 100644 index 000000000..46d33dc6b --- /dev/null +++ b/crates/ui-egui/src/text_paste_style_tests.rs @@ -0,0 +1,160 @@ +//! Pasting into a text edit: characters FigCraft copied keep their formatting, while +//! Shift/Alt+Cmd/Ctrl+V and text from other apps take the style at the caret. +use std::cell::RefCell; +use std::rc::Rc; + +use egui::{Event, Key, Modifiers}; +use figcraft_doc::{NodeId, TextData}; +use figcraft_engine::{Session, textedit}; +use serde_json::json; + +use crate::layers_drag_tests::Ui; + +struct Clipboard(Rc>); + +impl crate::Services for Clipboard { + fn clipboard_set_text(&mut self, text: &str) { + *self.0.borrow_mut() = text.to_string(); + } + fn clipboard_get_text(&mut self) -> Option { + Some(self.0.borrow().clone()) + } +} + +fn text(u: &Ui, id: NodeId) -> TextData { + u.app.session.doc().unwrap().node(id).unwrap().kind.text().unwrap().clone() +} + +fn layer(s: &mut Session, chars: &str, size: f64, y: f64) -> NodeId { + NodeId(s.execute("text.create", &json!({"text": chars, "x": 0, "y": y, "props": {"fontSize": size}})).unwrap()["id"].as_u64().unwrap()) +} + +fn copy_the_bold_word() -> (Ui, NodeId, Rc>) { + let mut s = Session::new(); + let source = layer(&mut s, "Bold plain", 24.0, 0.0); + let target = layer(&mut s, "Target", 12.0, 100.0); + textedit::begin(&mut s, source, Some(0), false).unwrap(); + textedit::set_caret(&mut s, 4, true).unwrap(); + s.execute("text.bold", &json!({})).unwrap(); + let mut u = Ui::new(s); + let clipboard = Rc::new(RefCell::new(String::new())); + u.app.services = Box::new(Clipboard(clipboard.clone())); + u.frame(vec![Event::Copy]); + textedit::end(&mut u.app.session).unwrap(); + textedit::begin(&mut u.app.session, target, Some(6), false).unwrap(); + (u, target, clipboard) +} + +#[test] +fn pasting_copied_text_brings_its_formatting() { + let (mut u, target, clipboard) = copy_the_bold_word(); + assert_eq!(*clipboard.borrow(), "Bold"); + u.frame(vec![Event::Paste("Bold".into())]); + let t = text(&u, target); + assert_eq!(t.characters, "TargetBold"); + assert_eq!((t.style_at(6).font_style.as_str(), t.style_at(6).font_size), ("Bold", 24.0), "the copied characters keep their look"); + assert_eq!((t.style_at(0).font_style.as_str(), t.style_at(0).font_size), ("Regular", 12.0), "the text around them keeps its own"); +} + +#[test] +fn alt_cmd_v_pastes_the_characters_in_the_style_at_the_caret() { + let (mut u, target, _) = copy_the_bold_word(); + let held = Modifiers { alt: true, command: true, mac_cmd: true, ..Modifiers::NONE }; + let v = Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: true, repeat: false, modifiers: held }; + u.frame_with(vec![v], held); + let t = text(&u, target); + assert_eq!(t.characters, "TargetBold"); + assert_eq!((t.style_at(6).font_style.as_str(), t.style_at(6).font_size), ("Regular", 12.0), "the destination's look"); + assert!(t.runs.is_empty()); +} + +#[test] +fn text_copied_elsewhere_pastes_in_the_style_at_the_caret() { + let (mut u, target, _) = copy_the_bold_word(); + u.frame(vec![Event::Paste("From a browser".into())]); + let t = text(&u, target); + assert_eq!(t.characters, "TargetFrom a browser"); + assert!(t.runs.is_empty(), "nothing FigCraft copied: plain text"); +} + +fn painted(s: &mut Session, id: NodeId, hex: &str) { + let paint = figcraft_color::Paint::solid(figcraft_color::Color::from_hex(hex).unwrap()); + s.ds_mut().unwrap().doc_mut().get_mut(id).unwrap().fills = vec![paint]; +} + +fn color_at(u: &Ui, id: NodeId, i: usize) -> Option { + let n = u.app.session.doc().unwrap().node(id).unwrap(); + let fills = n.kind.text().unwrap().style_at(i).fills.clone().unwrap_or_else(|| n.fills.clone()); + fills.first().and_then(figcraft_color::Paint::solid_color) +} + +fn red_source_and_black_target() -> (Ui, NodeId, NodeId) { + let mut s = Session::new(); + let source = layer(&mut s, "Red", 24.0, 0.0); + let target = layer(&mut s, "Target", 12.0, 100.0); + painted(&mut s, source, "#FF0000"); + painted(&mut s, target, "#000000"); + let mut u = Ui::new(s); + u.app.services = Box::new(Clipboard(Rc::new(RefCell::new(String::new())))); + (u, source, target) +} + +#[test] +fn copied_characters_keep_the_colour_of_their_layer() { + let (mut u, source, target) = red_source_and_black_target(); + textedit::begin(&mut u.app.session, source, Some(0), false).unwrap(); + textedit::set_caret(&mut u.app.session, 3, true).unwrap(); + u.frame(vec![Event::Copy]); + textedit::end(&mut u.app.session).unwrap(); + textedit::begin(&mut u.app.session, target, Some(6), false).unwrap(); + u.frame(vec![Event::Paste("Red".into())]); + assert_eq!(text(&u, target).characters, "TargetRed"); + assert_eq!(color_at(&u, target, 6), figcraft_color::Color::from_hex("#FF0000"), "the copied characters stay red"); + assert_eq!(color_at(&u, target, 0), figcraft_color::Color::from_hex("#000000"), "the target's own text stays black"); + assert_eq!(text(&u, target).style_at(6).font_size, 24.0); +} + +#[test] +fn a_copied_text_layer_pastes_into_an_edit_with_its_look() { + let (mut u, source, target) = red_source_and_black_target(); + u.app.session.execute("select.set", &json!({"ids": [source.0]})).unwrap(); + u.frame(vec![Event::Copy]); + textedit::begin(&mut u.app.session, target, Some(6), false).unwrap(); + u.frame(vec![Event::Paste("Red".into())]); + let t = text(&u, target); + assert_eq!(t.characters, "TargetRed"); + assert_eq!(t.style_at(6).font_size, 24.0); + assert_eq!(color_at(&u, target, 6), figcraft_color::Color::from_hex("#FF0000")); + assert_eq!(t.style_at(0).font_size, 12.0); +} + +#[test] +fn shift_cmd_v_pastes_the_characters_in_the_style_at_the_caret() { + let (mut u, target, _) = copy_the_bold_word(); + let held = Modifiers { shift: true, command: true, mac_cmd: true, ..Modifiers::NONE }; + let v = Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: true, repeat: false, modifiers: held }; + u.frame_with(vec![v], held); + let t = text(&u, target); + assert_eq!(t.characters, "TargetBold"); + assert!(t.runs.is_empty(), "the destination's look"); +} + +#[test] +fn shift_insert_is_an_ordinary_paste_and_keeps_the_formatting() { + let (mut u, target, _) = copy_the_bold_word(); + u.frame_with(vec![Event::Paste("Bold".into())], Modifiers::SHIFT); + let t = text(&u, target); + assert_eq!(t.characters, "TargetBold"); + assert_eq!(t.style_at(6).font_style, "Bold"); +} + +#[test] +fn the_chord_matches_the_style_though_its_keys_are_up_by_the_paste() { + let (mut u, target, _) = copy_the_bold_word(); + let chord = Modifiers { shift: true, command: true, mac_cmd: true, ..Modifiers::NONE }; + let v = Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: true, repeat: false, modifiers: chord }; + u.frame_with(vec![v, Event::Paste("Bold".into())], Modifiers::NONE); + let t = text(&u, target); + assert_eq!(t.characters, "TargetBold"); + assert!(t.runs.is_empty(), "the destination's look"); +} diff --git a/crates/ui-egui/src/variables_group_create_tests.rs b/crates/ui-egui/src/variables_group_create_tests.rs new file mode 100644 index 000000000..81ed67ef7 --- /dev/null +++ b/crates/ui-egui/src/variables_group_create_tests.rs @@ -0,0 +1,127 @@ +//! Variables made and named with a group shown in the Local variables window: Create variable +//! and Duplicate put the variable in that group, and renaming it in its row edits the part shown. +use egui::{Event, Key, Modifiers, PointerButton, Pos2}; +use figcraft_engine::Session; +use serde_json::json; + +use crate::layers_drag_tests::Ui; +use crate::live_tests::{flat, has_text, text_center, texts}; + +fn window_with_groups() -> Ui { + let mut s = Session::new(); + s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap(); + for n in ["space/sm", "color/brand"] { + s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": "number", "value": 1})).unwrap(); + } + let mut u = Ui::new(s); + u.app.ui.variables = Some(Default::default()); + settle(&mut u); + u +} + +fn settle(u: &mut Ui) { + for _ in 0..8 { + u.frame(vec![]); + } +} + +fn click(u: &mut Ui, p: Pos2, button: PointerButton) { + for pressed in [true, false] { + u.frame(vec![Event::PointerMoved(p), Event::PointerButton { pos: p, button, pressed, modifiers: Modifiers::NONE }]); + } + settle(u); +} + +fn leftmost(u: &mut Ui, s: &str) -> Pos2 { + let shapes = flat(&u.frame_output(vec![]).shapes); + let (_, at, size) = + texts(&shapes).into_iter().filter(|(t, ..)| t == s).min_by(|a, b| a.1.x.total_cmp(&b.1.x)).unwrap_or_else(|| panic!("{s} drawn")); + at + size / 2.0 +} + +fn names(u: &Ui) -> Vec { + let mut v: Vec = u.app.session.doc().unwrap().variables.variables.iter().map(|v| v.name.clone()).collect(); + v.sort(); + v +} + +fn shown(u: &mut Ui, s: &str) -> bool { + has_text(&flat(&u.frame_output(vec![]).shapes), s) +} + +#[test] +fn a_variable_created_with_a_group_shown_goes_into_that_group_and_keeps_it_when_named() { + let mut u = window_with_groups(); + let group = leftmost(&mut u, "space"); + click(&mut u, group, PointerButton::Primary); + assert!(!shown(&mut u, "brand"), "only the space group is shown"); + + let create = text_center(&flat(&u.frame_output(vec![]).shapes), "+ Create variable"); + click(&mut u, create, PointerButton::Primary); + let number = text_center(&flat(&u.frame_output(vec![]).shapes), "Number"); + click(&mut u, number, PointerButton::Primary); + assert_eq!(names(&u), ["color/brand", "space/Number", "space/sm"]); + + u.frame(vec![Event::Text("lg".into())]); + for pressed in [true, false] { + u.frame(vec![Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]); + } + settle(&mut u); + assert_eq!(names(&u), ["color/brand", "space/lg", "space/sm"], "naming it in its row keeps the group"); + assert!(shown(&mut u, "lg"), "and it is in the table shown"); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); +} + +#[test] +fn a_variable_duplicated_in_a_group_stays_in_it_and_in_view() { + let mut u = window_with_groups(); + let group = leftmost(&mut u, "space"); + click(&mut u, group, PointerButton::Primary); + let row = leftmost(&mut u, "sm"); + click(&mut u, row, PointerButton::Secondary); + let duplicate = text_center(&flat(&u.frame_output(vec![]).shapes), "Duplicate"); + click(&mut u, duplicate, PointerButton::Primary); + assert_eq!(names(&u), ["color/brand", "space/sm", "space/sm copy"]); + assert!(shown(&mut u, "sm copy")); +} + +fn create_number(u: &mut Ui) { + let create = text_center(&flat(&u.frame_output(vec![]).shapes), "+ Create variable"); + click(u, create, PointerButton::Primary); + let number = text_center(&flat(&u.frame_output(vec![]).shapes), "Number"); + click(u, number, PointerButton::Primary); +} + +fn type_and_enter(u: &mut Ui, typed: &str) { + u.frame(vec![Event::Text(typed.into())]); + for pressed in [true, false] { + u.frame(vec![Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]); + } + settle(u); +} + +#[test] +fn a_name_of_slashes_alone_leaves_the_variable_in_its_group() { + for typed in ["/", " / / "] { + let mut u = window_with_groups(); + let group = leftmost(&mut u, "space"); + click(&mut u, group, PointerButton::Primary); + create_number(&mut u); + type_and_enter(&mut u, typed); + assert_eq!(names(&u), ["color/brand", "space/Number", "space/sm"], "{typed:?}"); + } +} + +#[test] +fn a_new_collection_takes_its_first_variable_outside_the_group_shown_before() { + let mut u = window_with_groups(); + let group = leftmost(&mut u, "space"); + click(&mut u, group, PointerButton::Primary); + let heading = leftmost(&mut u, "Collections"); + let (_, at, _) = texts(&flat(&u.frame_output(vec![]).shapes)).into_iter().find(|(t, ..)| t == "Collections").unwrap(); + click(&mut u, Pos2::new(at.x - 16.0 + 200.0 - 20.0, heading.y), PointerButton::Primary); + assert_eq!(u.app.session.doc().unwrap().variables.collections.len(), 2, "the + by Collections made one"); + type_and_enter(&mut u, "Sizes"); + create_number(&mut u); + assert_eq!(names(&u), ["Number", "color/brand", "space/sm"]); +} diff --git a/crates/ui-egui/src/widgets/style_picker.rs b/crates/ui-egui/src/widgets/style_picker.rs index ca063abad..fb369fbca 100644 --- a/crates/ui-egui/src/widgets/style_picker.rs +++ b/crates/ui-egui/src/widgets/style_picker.rs @@ -160,6 +160,30 @@ pub struct Picker { y: f32, query: String, edit: Option, + /// Whose styles the list shows (the source menu over the list). + source: Source, +} + +/// The source menu's choice: every source, this file's styles, or one enabled library's (by +/// manifest id). +#[derive(Clone, Debug, Default, PartialEq)] +enum Source { + #[default] + All, + ThisFile, + Library(String), +} + +impl Source { + /// Whether the styles of `lib` (`None`: this file) are listed. + fn shows(&self, lib: Option<&PublishedLibrary>) -> bool { + match (self, lib) { + (Source::All, _) => true, + (Source::ThisFile, None) => true, + (Source::Library(id), Some(l)) => l.manifest.id == *id, + _ => false, + } + } } impl Picker { @@ -174,7 +198,7 @@ pub fn open(app: &mut FigApp, ui: &Ui, ids: &[NodeId], slot: StyleSlot) { // Opening the style picker closes the colour picker (it would linger beside it). crate::colorpicker::close(app); app.ui.style_picker_popover = None; - app.ui.style_picker = Some(Picker { slot, ids: ids.to_vec(), y, query: String::new(), edit: None }); + app.ui.style_picker = Some(Picker { slot, ids: ids.to_vec(), y, query: String::new(), edit: None, source: Source::All }); } /// Open the picker for `slot` of the selection (the control channel), optionally editing `style`. @@ -183,7 +207,7 @@ pub fn open_for_selection(app: &mut FigApp, slot: StyleSlot, style: Option<&str> let edit = style.and_then(|s| app.session.doc().ok()?.style(s).map(editing)); crate::colorpicker::close(app); app.ui.style_picker_popover = None; - app.ui.style_picker = Some(Picker { slot, ids, y: 140.0, query: String::new(), edit }); + app.ui.style_picker = Some(Picker { slot, ids, y: 140.0, query: String::new(), edit, source: Source::All }); } fn editing(s: &Style) -> Editing { @@ -522,6 +546,28 @@ fn offered<'a>(doc: &'a Document, lib: Option<&'a PublishedLibrary>, slot: Style } } +/// The source menu over the style list (shown when the file has libraries): All libraries, This +/// file, then each library by name, the chosen one ticked. +fn source_menu(ui: &mut Ui, libs: &[std::sync::Arc], source: &mut Source) { + let label = match source { + Source::All => tr("All libraries").to_string(), + Source::ThisFile => tr("This file").to_string(), + Source::Library(id) => libs.iter().find(|l| l.manifest.id == *id).map(|l| l.manifest.name.clone()).unwrap_or_default(), + }; + let resp = widgets::dropdown(ui, &label, W, None); + crate::right::menu_popup(&resp).width(W).show(|ui| { + let mut choices = vec![(Source::All, tr("All libraries").to_string()), (Source::ThisFile, tr("This file").to_string())]; + choices.extend(libs.iter().map(|l| (Source::Library(l.manifest.id.clone()), l.manifest.name.clone()))); + for (choice, name) in choices { + let mark = if *source == choice { "✓ " } else { " " }; + if crate::right::menu_item(ui, &format!("{mark}{name}"), "") { + *source = choice; + ui.close(); + } + } + }); +} + /// The style list: header, search, this file's and the libraries' styles by folder, and (colour /// slots) colour variables. fn listing(app: &FigApp, ui: &mut Ui, doc: &Document, p: &mut Picker, out: &mut Frame) { @@ -560,8 +606,20 @@ fn listing(app: &FigApp, ui: &mut Ui, doc: &Document, p: &mut Picker, out: &mut ui.add_space(4.0); let q = p.query.trim().to_lowercase(); let libs = crate::variable_ui::libraries(app, doc); - let mut sources: Vec<(Option<&PublishedLibrary>, Vec<&Style>)> = vec![(None, offered(doc, None, slot, &q))]; - for l in &libs { + if !libs.is_empty() { + source_menu(ui, &libs, &mut p.source); + ui.add_space(4.0); + } + if let Source::Library(id) = &p.source + && !libs.iter().any(|l| l.manifest.id == *id) + { + p.source = Source::All; + } + let mut sources: Vec<(Option<&PublishedLibrary>, Vec<&Style>)> = Vec::new(); + if p.source.shows(None) { + sources.push((None, offered(doc, None, slot, &q))); + } + for l in libs.iter().filter(|l| p.source.shows(Some(l))) { let list = offered(doc, Some(l), slot, &q); if !list.is_empty() { sources.push((Some(l.as_ref()), list)); @@ -1246,7 +1304,7 @@ fn edit_local(app: &mut FigApp, ui: &Ui, slot: StyleSlot, id: &str) { let edit = app.session.doc().ok().and_then(|d| d.style(id).map(editing)); crate::colorpicker::close(app); app.ui.style_picker_popover = None; - app.ui.style_picker = Some(Picker { slot, ids: app.session.selection(), y, query: String::new(), edit }); + app.ui.style_picker = Some(Picker { slot, ids: app.session.selection(), y, query: String::new(), edit, source: Source::All }); } /// `style.move` for the shown style `from` dropped at shown position `to` (`shown` in display diff --git a/crates/ui-egui/src/widgets/style_picker/tests.rs b/crates/ui-egui/src/widgets/style_picker/tests.rs index cdb4f3e99..7b69e32a9 100644 --- a/crates/ui-egui/src/widgets/style_picker/tests.rs +++ b/crates/ui-egui/src/widgets/style_picker/tests.rs @@ -573,3 +573,71 @@ fn style_picker_icon_buttons_paint_16pt() { assert!(paints_icon_at_button_size(&painted, icon), "{icon:?} is not 16 pt"); } } + +#[test] +fn a_reopened_files_text_styles_picker_lists_its_librarys_styles_without_the_assets_tab() { + let dir = std::env::temp_dir().join(format!("figcraft-picker-library-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let (library, file) = (dir.join("ds.figcraft"), dir.join("site.figcraft")); + let mut publisher = Session::new(); + publisher.execute("style.create", &json!({"type": "text", "name": "Display", "value": {"fontFamily": "Inter", "fontSize": 48}})).unwrap(); + publisher.execute("library.publish", &json!({})).unwrap(); + publisher.execute("file.saveAs", &json!({"path": library})).unwrap(); + let mut site = Session::new(); + site.execute("text.create", &json!({"text": "Hello", "x": 0, "y": 0})).unwrap(); + site.execute("style.create", &json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 14}})).unwrap(); + site.execute("library.add", &json!({"path": library})).unwrap(); + site.execute("file.saveAs", &json!({"path": file})).unwrap(); + + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": file})).unwrap(); + let text = reopened.doc().unwrap().nodes().find(|n| matches!(n.kind, figcraft_doc::NodeKind::Text(_))).unwrap().id; + reopened.execute("select.set", &json!({"ids": [text]})).unwrap(); + let mut u = crate::layers_drag_tests::Ui::new(reopened); + open_for_selection(&mut u.app, StyleSlot::Text, None); + for _ in 0..3 { + u.frame(vec![]); + } + let texts = drawn_texts(&mut u); + let _ = std::fs::remove_dir_all(&dir); + let (display, body) = ("48/Auto", "14/Auto"); + let shows = |texts: &[(String, Pos2)], s: &str| texts.iter().any(|(t, _)| t == s); + assert!(shows(&texts, display) && shows(&texts, body), "every source by default: {:?}", texts.iter().map(|t| &t.0).collect::>()); + + let choose = |u: &mut crate::layers_drag_tests::Ui, from: &str, to: &str| { + let at = text_at(&drawn_texts(u), from); + u.button(at, true); + u.button(at, false); + let texts = drawn_texts(u); + let item = texts.iter().rev().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == to).unwrap_or_else(|| panic!("{to} in the menu")).1; + u.button(item, true); + u.button(item, false); + drawn_texts(u) + }; + let texts = choose(&mut u, "All libraries", "This file"); + assert!(shows(&texts, body) && !shows(&texts, display), "This file: its own styles only"); + let texts = choose(&mut u, "This file", "Untitled"); + assert!(shows(&texts, display) && !shows(&texts, body), "a library: its styles only"); + assert!(u.app.ui.style_picker.is_some(), "choosing a source keeps the picker open"); +} + +#[test] +fn a_library_that_cant_be_read_is_tried_again_only_after_the_refresh_interval() { + let mut s = Session::new(); + s.doc_mut().unwrap().libraries_mut().enabled.push(figcraft_doc::LibraryLink { + id: "elsewhere".into(), + name: "Elsewhere".into(), + path: "file://server/share/ds.figcraft".into(), + relative: String::new(), + version: 0, + }); + let mut u = crate::layers_drag_tests::Ui::new(s); + let checked = |u: &crate::layers_drag_tests::Ui| u.ctx.data(|d| d.get_temp::(Id::unique("asset_libraries_checked"))); + u.frame(vec![]); + let first = checked(&u).expect("the first frame tries the library"); + for _ in 0..10 { + u.frame(vec![]); + } + assert_eq!(checked(&u), Some(first), "a refused library doesn't make every frame read again"); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 596d509f9..c1053062e 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -12,15 +12,16 @@ accounts). | Feature | Status | Notes | |---|---|---| +| 2026-11-18 | patch | M3: with two or more instances selected the Design panel showed no instance properties, so changing a variant or a property meant selecting each instance in turn. It now shows the variant, boolean, text and instance-swap properties they share (by name and type; a variant property lists the values every one of their sets has), each reading Mixed where their values differ, and a value chosen there is set on every selected instance in one step, as Figma does. A selection with any layer that isn't an instance shows none. Tests: `instances_shared_props_tests` | | 2026-11-11 | minor | M3, #2022: an instance lists only the properties its variant's layers use (its variant properties, slots, and the boolean, text and instance swap properties a layer of its current variant reads), as measured in Figma's web app: an instance of variant A lists `State` and `A label`, never `B label` or a property no layer reads. The set and its variants still list every definition, so unused ones can be deleted there. A long property name in the panel is cut to one line with an ellipsis, the full name on hover, instead of wrapping over the rows around it. Tests: `prop_order_tests::an_instance_lists_only_the_properties_its_variant_uses`, `component_props_reorder_tests::a_long_property_name_stays_on_one_line`, `prop_value_tests::a_set_keeps_each_named_text_definition_and_layers_read_their_own`. Grade unchanged. | | Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main; with two or more layers selected the Design panel header's component button opens a menu with Create component, Create multiple components (each layer its own component in place, one undo step) and Create component set (each layer a component, wrapped in place in a set 20 px around: variants `Property 1=` left to right, `prop=value` names kept, layers that all share a name give a set of that name with `Property 1=Default` variants; measured in Figma), one layer keeps the plain click (#2088) | | Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances | | What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it; an instance's own resizing (hug or fixed) follows its main's unless its size is overridden, measured: a plain instance turns Fixed when its main does (a child set to Fill along the hugging axis) and back to Hug with it, one whose width was typed keeps it, and Fill in its own auto layout parent is its own | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | | What it doesn't: position, rotation, constraints and absolute or grid placement of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out (Delete on a layer inside an instance hides it instead of removing it, as the help center says it does); the instance itself resizes and its layers follow the main's constraints | | Component sets / variants, add variant, switch | done | Combine as variants is in the Object menu, and the canvas and layers context menu and the Design panel offer it when two or more main components are selected; Add variant on a main component not in a set yet makes it a set of itself and the new variant, one undo step (#903); components that are variants already aren't combined again (it used to put a set inside a set); combining gives every variant the component properties any of them had, so another variant's layers can be bound to one made before combining | -| A main's copy within its file is an instance of it: Duplicate, Alt-drag, Copy then Paste | done | a variant duplicated in its set stays a new variant and a whole set copies as a new set; only the copied roots become instances (a main inside a copied frame is copied as a main); Cut then Paste and pastes into other files keep the component (#892) | +| A main's copy within its file is an instance of it: Duplicate, Alt-drag, Copy then Paste | done | a variant duplicated in its set stays a new variant and a whole set copies as a new set; only the copied roots become instances (a main inside a copied frame is copied as a main); Cut then Paste keeps the component (#892); pasted into another file, a main the source file publishes as a library is an instance of it from that library, which gets enabled, and any other main is a copy of itself; copied variants pasted with their own set, or a variant or layer in it, selected join the set as new variants, while other pastes into a set, Paste over and Paste to replace still make an instance | | A component can't contain its own instance, directly or through other components | done | refused with the loop named (creating, placing, swapping, switching variants, moving, pasting, an instance-swap value); each variant counts as its own component, so a variant may hold a sibling variant's instance unless that one leads back to it; a dropped instance lands on the page; a file holding a loop opens with one instance detached and a note, any other file unchanged; a loop merged in a live session stops expanding where an instance would show itself again (#1084) | -| Switching variants keeps overrides where names match and both variants had the same value; text layers keep theirs | done | | +| Switching variants keeps overrides where names match and both variants had the same value; text layers keep theirs | done | a text layer the other variant nests in other frames is matched by its name when one layer on each side has it | | Default variant: the top-left one (new instances, Assets thumbnail, generated code) | done | | | Variant property order (names rewritten), duplicate combinations reported | done | drag a property in the Properties section to reorder it, one undo step (#679), or `component.editProperty {index}`; a variant value too long for its field ends with an ellipsis and shows whole on hover (#2368) | | Properties: boolean, text, instance swap (preferred values), variant | done | listed in the order they were made, a rename keeping the place (#1536; the shared ones don't reorder by drag yet); every component menu scrolls past 320 pt, the default of an instance-swap property's too (#1338); the instance-swap menus (an instance's property and swap menus, a property's default, the playground) open with a search field that filters by name as you type, with Up, Down and Enter to pick and Escape to clear then close; the slot and preferred components menus have no search yet; an instance lists the properties its variant's layers use, so a set with one text property per variant shows one text field per instance (#2022; measured in Figma's web app, 2026-11-11); long names are cut to one line, the full name on hover | @@ -65,6 +66,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Editing a style updates its layers; detach and delete keep values; editing a styled property unlinks that style | done | an edited fill/stroke/effect/grid list or text chars unlink; applying a style replaces variables bound to what it sets; text styles on text layers only | | Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) | | Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style (a face name from a string variable, or a numeric weight from a number variable, which picks the nearest face and a variable font's `wght` axis), size, line height and letter spacing, the rest through the command; a bound line height is applied in pixels, as the reference tool does (measured 2026-11-10) | +| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); Create variable makes the variable in the group shown, and a row's rename edits the name's last part; the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 | | Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); variables keep the order they are put in: Move up / Move down (Alt+↑ / Alt+↓) on a row and Sort A to Z / Z to A on a collection or group, numbers by value (`variable.move`, `variable.sort`, #2633); the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 | | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | @@ -80,6 +82,12 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-23 | minor | M3: a main component copied from a library file and pasted into another file is an instance of it from that library, which gets enabled in that file, as pasting an instance of it already was and as Figma does with a published component. It used to paste a copy of the main, a new component of that file unlinked from the library. A variant pastes as an instance of that variant. A component the library doesn't offer (hidden from publishing, or added since the last publish) and a main from a file that publishes no library still paste as a copy. Test: `library::tests::a_main_pasted_from_its_library_file_is_an_instance_of_it`. Numbers unchanged | +| 2026-11-19 | patch | M3: copying a variant and pasting with that variant, a layer in it or its set selected pasted an instance on the page. Copied variants of one set now paste into that set as new variants (deep copies, as Duplicate makes), under the copied variants where they are now, below the lowest variant with the gap of 20 that Add variant leaves, and the set grows to hold them. Every other paste of a copied main still makes an instance: with nothing selected, into another set, a main that isn't a variant pasted with a set selected, Paste over and Paste to replace on a variant, and an explicit `parent` (even the variant's own set). Tests: `pasting_a_variant_with_its_set_selected_adds_a_variant_below_the_others`, `a_variant_pasted_into_its_set_after_the_set_moved_lands_under_the_variant`, `a_variant_pasted_with_another_set_selected_is_an_instance`, `a_main_that_is_no_variant_pasted_with_a_set_selected_is_an_instance`, `a_variant_pasted_with_its_own_set_as_an_explicit_parent_is_an_instance`, `pasting_over_or_replacing_a_variant_makes_an_instance_of_the_copied_variant` | +| 2026-11-22 | patch | M3: switching an instance to another variant put back the variant's own text in place of the text typed into it when the two variants nest that text layer in different frames (`text › Label` in one, `div › text › Label` in the other), because the typed layer was matched to the new variant's by name path only. Now a text layer of the new variant nothing else matched takes the old text layer of the same name, when exactly one layer on each side has that name; layers inside nested instances still go by their own mains. Two layers of one name stay unmatched, since either could be the one typed into. Test: `typed_text_stays_across_variants_that_nest_it_differently`. Grade unchanged. | +| 2026-11-19 | patch | M3: overrides found by comparing a layer with its main (`rebase_instance`: linking instances after a Figma or REST import, detaching an outer instance, restoring a main) counted values only, so a layer bound to a variable the main layer doesn't bind, resolving to the main's colour, wasn't an override; the next copy or edit of the main (a library update reaching another file) reset it to the main's unbound paint. Icons inside buttons of a design system imported from Figma lost their colour variable this way in the files using it. A binding that differs from the main's is now an override there, and an edit that sets the value back to the main's (hiding and showing the fill) no longer clears an override the binding still makes; `fill` and `fills/0/color` count as one binding. Tests: `nested_binding_tests` | +| 2026-11-19 | patch | M3: with a group selected in the Local variables window, + Create variable named the new variable without the group, so it went to the collection's top level and the table, showing the group, didn't show it; only All variables did. It's now made in the group shown (`space/Number`), as in Figma, where duplicating already kept the group. Renaming a variable in its row edited its whole name while the row shows the last part, so typing a name over a new grouped variable moved it out of the group; the field now edits the part shown and keeps the group (the Edit variable window still edits the whole name), and ignores a name of slashes alone. Creating a collection clears the group shown. Tests: `variables_group_create_tests` | +| 2026-11-18 | patch | M3: enabled libraries were read only while the Assets panel showed, so after a file was opened the Design panel's style pickers offered none of their styles (a library's text styles read "No text styles yet") until the Assets tab had been opened. They are refreshed from the app's background tick now, a local library not read yet at once. The style picker has a source menu under its search field, as in Figma: All libraries (the default), This file, or one enabled library. Test: `style_picker::tests::a_reopened_files_text_styles_picker_lists_its_librarys_styles_without_the_assets_tab` | | 2026-11-27 | minor | M3, #2633: variables in the Local variables window stayed in creation order. A row's menu has Move up and Move down (Alt+↑ / Alt+↓ with one row selected), moving it past its neighbour in its group; a collection's and a group's menus have Sort A to Z and Sort Z to A, by name with each run of digits compared as a number, so `50, 100, 200 … 950` come in that order. The order is the stored one, so files, exports and the variable pickers follow it. New commands `variable.move {variables, before?}` and `variable.sort {collection, group?, descending?}`, one undo step each. Drag to reorder is not built. Tests: `variables_editor_tests::moving_variables_reorders_their_collection_only_and_undoes`, `variables_editor_tests::sorting_orders_numbers_by_value_within_the_group_asked`. Grade unchanged. | | 2026-11-19 | patch | M3, #2414: a kit's style used by a component of a second library reached a file linking both as a second, unbound copy (`::S:1`) frozen in the kit's default mode, so a mode set on the kit's collection didn't colour it (from two hops on, every such style). Publishing now keeps the variables the published styles bind and where the file's copies of other libraries' styles, variables and collections came from; importing files such a copy under that library when the file links it, so it is the file's own bound copy. Test: `library_style_hops_tests::a_kit_style_through_another_library_is_the_kits_bound_copy`; the issue's four-file chain renders Brand and Alt everywhere. Grade unchanged. | | 2026-11-19 | patch | M3, #2349: with one variant of a set selected, the Design panel's variant property dropdowns showed the set's default values, and choosing a value set the default, so the variants swapped places. They now show the selected variant's own values (hover: "This variant's value"), and choosing one renames that variant only; with the set selected they still set its default. Test: `variant_own_value_tests::a_selected_variants_dropdown_shows_and_sets_its_own_value`. Grade unchanged. | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index b8a01b210..605e1ab69 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-24 · **Change:** minor (a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -199,6 +199,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| | 2026-11-24 | minor | M8: SVG, PNG, PDF and Android Vector Drawable exports were bigger than what they show around strokes on lines, vectors and polygons. The export took its size from the renderer's bounds, which leave room for a stroke's mitre at the miter limit (4 × the weight on a vector) whatever its corners, so a 24 × 24 icon frame whose outlined strokes stay inside it exported at 26 × 26 to 30 × 25, its content moved off the frame's origin. The export now measures each layer's fill and stroke outlines as drawn (joins, caps and alignment included, a mitre only where a corner keeps one; a dashed stroke as a solid one too, so where the dashes fall doesn't change the size), and grows that by the layer's effects; text and drop shadows with a spread keep the renderer's bounds. The renderer's own bounds are unchanged. Tests: `export_bounds_tests` (3). Numbers unchanged | +| 2026-11-23 | patch | M7: Save as to another file left the tab showing the old name unless that name was Untitled or the old file's own name (#935). So a file opened from an import (`.fig`, `.penpot`, `.sketch`), which carries its source's name and has no file yet, kept that name after being saved as `Other.figcraft`, and so did a file renamed here. Now saving to another file always names the document, its tab and the saved file's stored name after the new file, as a desktop app's document window does. Saving to the same file keeps a name given here, so a name with characters a file name can't hold (`aa: design system`) stays until Save as. Test: `save_format_tests::saving_to_another_file_names_the_document_after_it`. | | 2026-11-20 | patch | M6, #2501 follow-up: JPG export inherited 4:2:0 chroma subsampling from the `craft-image-codecs` defaults when #2501 moved it to the shared encoder, so fine colour detail blurred. It asks for 4:4:4 again, as before the cutover (#2521). Tests: `render::tests::jpeg_export_keeps_full_chroma`, and `export_formats_and_what_each_keeps` checks an 8 × 8 corner block clear of the ellipse. Numbers unchanged. | | 2026-11-19 | patch | M6, #2468 follow-up: SVG import checks its input with craft-svg (`tree::parse`, `tree::image_resolver`), so FigCraft's own byte scanners (`too_wide`, `too_deep`, `nesting`) and `import/budget.rs` were dead code, and `main` failed `cargo fmt` and clippy. They are removed; the budget and hostile-input tests now run against craft-svg's `tree::Limits` (documents nest at most 256 levels deep, references followed, where FigCraft's scanner allowed 512). No behaviour change beyond #2468. | | 2026-11-19 | patch | M6, #2441: REST import warned "variables bound to `fills` (`effects`, `textRangeFills`) are not supported and were skipped" for layers that lost nothing: those node-level lists repeat the variables each gradient stop, effect and paint binds itself, which are read. The warning now names such a list only when it holds a variable none of them bound, so the warnings left mean a real loss. Test: `rest::proto_variable_tests::node_level_lists_the_paints_and_effects_bind_are_not_reported`. Numbers unchanged. | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 89ddd48b7..b8096f3ff 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware and platform parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; unused; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; under Wayland a minimised window answers control and MCP requests in about half a second instead of timing out after 60 s (#1906); images copied in other apps paste in the browser (#492); text reads only the fallback fonts it draws with; `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); a batch keeps one undo snapshot, not one per step (#1099); one depth cap bounds a whole render, pattern sources included, and render threads get 8 MiB stacks (#1082); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); macOS: the Quit menu and ⌘Q ask about unsaved changes (#857); egui/eframe 0.37 dependency migration; hidden-window screenshot deadlines; zoom previews; hidden windows answer control requests; macOS file opening, the Windows start-up message, Linux packaging; copy and paste in the browser; Windows QA pass; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; pen pressure for the Pencil and brushes on Windows and from browser styluses; macOS: quitting ends the process once everything is kept, avoiding the Touch Bar teardown crash (#781); Linux and BSD clipboard: images under Wayland, reads time out; minimised windows under Wayland; window controls on Wayland without server decorations; canvas textures on device pixels) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (a zoom in shows the image on screen enlarged instead of a coarse preview, so a pinch stays sharp; the browser build uses team libraries and plugin directories on a server; unused; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; under Wayland a minimised window answers control and MCP requests in about half a second instead of timing out after 60 s (#1906); images copied in other apps paste in the browser (#492); text reads only the fallback fonts it draws with; `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); a batch keeps one undo snapshot, not one per step (#1099); one depth cap bounds a whole render, pattern sources included, and render threads get 8 MiB stacks (#1082); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); macOS: the Quit menu and ⌘Q ask about unsaved changes (#857); egui/eframe 0.37 dependency migration; hidden-window screenshot deadlines; zoom previews; hidden windows answer control requests; macOS file opening, the Windows start-up message, Linux packaging; copy and paste in the browser; Windows QA pass; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; pen pressure for the Pencil and brushes on Windows and from browser styluses; macOS: quitting ends the process once everything is kept, avoiding the Touch Bar teardown crash (#781); Linux and BSD clipboard: images under Wayland, reads time out; minimised windows under Wayland; window controls on Wayland without server decorations; canvas textures on device pixels) · **Target:** Figma Design (desktop app 126.10.7) How FigCraft uses hardware and which platforms it runs on, against Figma. Figma's desktop app is Electron with a GPU helper process; its canvas renders on the GPU (WebGL, with WebGPU rolling out @@ -12,7 +12,7 @@ since 2025). FigCraft renders the canvas on the CPU and presents it through wgpu | Feature | Figma | FigCraft (macOS / Windows / Linux / web) | Hours | |---|---|---|---| -| Canvas rendering | GPU | CPU (tiny-skia), banded across cores, retained (re-renders only what an edit or pan touches), levels of detail below 50% zoom, images drawn from the smallest copy that holds the size they show, down to 256 px (#1483); when renders from scratch are slow, a new zoom shows the whole view coarsely first, then refines it (#312); shown through wgpu (WebGPU or WebGL2 in the browser) | 30–60 for a GPU path | +| Canvas rendering | GPU | CPU (tiny-skia), banded across cores, retained (re-renders only what an edit or pan touches), levels of detail below 50% zoom, images drawn from the smallest copy that holds the size they show, down to 256 px (#1483); when renders from scratch are slow, a zoom out, a zoom in past 4× or one to where the image on screen doesn't reach shows the whole view coarsely first, then refines it (#312), and a zoom in up to 4× inside the image on screen (a preview too) shows that image, enlarged, until the refined one; shown through wgpu (WebGPU or WebGL2 in the browser) | 30–60 for a GPU path | | Effects (blurs, glass, noise) | GPU | CPU | in the above | | HiDPI / Retina | yes | yes (all); a canvas image rendered at the screen's density is placed on whole device pixels, so fractional pans, zooms and display scales don't blur it (#359; geometry tests, the snapping not judged by eye) | — | | Wide-gamut display (Display P3) | yes, on capable displays | colours stored and exported in P3; the screen shows sRGB: eframe/egui-wgpu 0.37 configure an 8-bit sRGB surface with no colour space option, although wgpu 30 can present Display P3 or extended sRGB on Metal, DX12, Vulkan and WebGPU (see gaps #18). The colour picker warns about colours outside sRGB and View ▸ Soft-proof sRGB stripes them on the canvas | 2–5 | @@ -50,6 +50,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import). | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Zoom in without coarse previews (#312 follow-up): a zoom in to at most 4× the image on screen, inside the area it covers, shows that image enlarged until the refined one comes, measured from what the screen shows, a preview included; it is at least as sharp as a preview with a quarter of the pixels each way. During a pinch or a held zoom each step used to get a preview and drop its refined image for the next step's, so the canvas stayed coarse until the zoom stopped. Zoom outs, other pages and larger zoom ins still get previews. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. | | 2026-11-10 | patch | M10, #1343 (also #1422, #2233): Windows: the window no longer draws below a hidden caption. FigCraft draws its own title bar on Windows and opens undecorated windows, but winit 0.30 still gives them `WS_CAPTION` and `WS_BORDER`; on some systems the desktop compositor reserves that caption, so the content was drawn about 30 px low (a black band above it) while clicks kept the client coordinates and landed above what was drawn. A per-frame step (`apps/figcraft/src/window_frame.rs`, safe `winsafe` calls, Windows only) clears `WS_CAPTION` and `WS_BORDER` from every FigCraft window, the main one and the others, keeping the sizing border and window buttons so edge resizing and snap work, and writes only when a style changed (winit puts them back on maximize and restore). The same fix as DesignCraft #2139 and PhotoCraft #2401; the maximize-to-work-area trim from DesignCraft is left for a later change. Not run on a Windows machine that shows the offset: the style math and the per-frame hook are tested, the window itself needs a live check. Tests: `window_frame_tests`. Numbers unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index 71bbaffc2..88fa9dcac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -413,6 +413,8 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match. | `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}}`. | | `design_context {ids?, scope?, depth?, maxNodes?, maxBytes?}` | Everything needed to build a design in one read: see [Design context](#design-context). | | `export_assets {ids?, dir?, dryRun?}` | Write the selection's images and vectors into `dir` as files named by their content: see [Asset handoff](#asset-handoff). | +| `component_mappings {ids?, unmapped?, root?}` | Which code component each design component is: `import`, `name`, `source` (and `sourceFound` under `root`, default the server's folder), a ready `snippet`, `properties` with variants, and `values` that need translating. | +| `sync_mappings {direction, path?}` | Apply a code repository's `figcraft.connect.json` to the open design (`import`) or write the design's mappings to it (`export`); `path` defaults to that file in the server's folder. | | `select {ids}` | Replace the selection (`[]` deselects). | | `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?, colorProfile?, 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; png, jpg and webp: `colorProfile` is `sameAsFile` (default: the document's profile), `srgb` or `displayP3`, the pixels converted (out-of-gamut colors clip) and the file tagged for it (PNG: `sRGB` chunk, or ICC and `cICP` for Display P3; JPG: ICC profile; WebP: ICC profile for Display P3, none for sRGB) (SVG, XML and RGB PDF output are always sRGB; PDF with `cmyk` is DeviceCMYK). 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. | @@ -452,7 +454,7 @@ Each layer in `nodes` has `id`, `name`, `type` and: with the `name` of each. `explicit` holds the value they resolved to. - `unsupported`: `{property, why}` for what has no direct CSS equivalent. The value stays in `explicit`. - `code`: for a component or instance connected to code, per language, `{language, importPath, name, - code}`, with the instance's own values in `code`. A connected instance stops there: `childCount` + source?, notes?, code}`, with the instance's own values in `code`. A connected instance stops there: `childCount` says what it holds, and `get_node` reads it. - `children`, or `childCount` where the tree stops. @@ -819,9 +821,10 @@ on; `key` resolves keys the way the canvas does. Commands behind keys: it is larger; the choice is kept. In the browser the interface always follows the browser's zoom. - `pref.autoSave {on?}`: files that have a path save themselves a few seconds after they change (off by default; the desktop app's timer does it, so scripts still call `file.save`). -- `pref.startOnHome {on?}`: the desktop app starts on the Home screen instead of in a new file - (off by default; files named on the command line still open, and `--control` starts in a new - file anyway, so control callers have a document). +- `pref.startOnHome {on?}`: the desktop app starts on the Home screen instead of reopening the + files open when it last quit (off by default; with nothing to reopen it starts on the Home screen + too; files named on the command line still open, and with nothing open `--control` starts in a new + file, so control callers have a document). - `pref.language {language: system|en|bs|cs|ru|es|es-419|fr|de|pt-BR|ja|ka|ko|sv|vi|zh-Hans|zh-Hant|…}`: the app's interface language, applied live ("system": the OS or browser language; a language without a catalog shows English). Command ids, labels and every result stay English. @@ -1086,6 +1089,8 @@ name and sets them this way); same library, components the other file publishes as a library are used from it (and that library is enabled when the other file is saved), and other mains stay behind: the instance shows a missing main (`component.restoreMain` makes it a main here). + A main component copied from a file that publishes it as a library pastes as an instance of + it from that library (enabled the same way); a main that library doesn't offer pastes as a copy. ### Team libraries @@ -1138,7 +1143,8 @@ most when it can't be reached). the instance itself (its layers follow the main's constraints) or edit the main. - **Variants**: `instance.setProperties {ids?, properties}` switching variants keeps an override where the layer's name path matches and both variants had the same value for that property; - text layers keep all theirs. The default variant (`instance.create` with a set, the Assets + text layers keep all theirs, and a text layer the other variant nests elsewhere is matched by + its name when one layer on each side has it. The default variant (`instance.create` with a set, the Assets thumbnail) is the one in the set's top-left corner; `component.editProperty {name, default}` moves the chosen variant there, `{name, index}` reorders variant properties (the variants' names follow). `component.properties` on a set reports `conflicts`: variants sharing one @@ -1889,11 +1895,20 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path `@acme/ui` gives `import { Button } from "@acme/ui";` then ``. `codeConnect.remove {id?, language?}` (no language: all). `codeConnect.export {path?}` → `{text, links}` (or writes the file): `{version: 1, links: [{component, language, - importPath, name, template}]}`, sorted, meant to live in the code repository as - `figcraft.connect.json`; `codeConnect.import {json | path}` → `{linked, warnings}` links each + importPath, name, template, source?, values?, notes?}]}`, sorted, meant to live in the code + repository as `figcraft.connect.json` (writing a file that's there keeps its other top-level keys + and the links of components this design doesn't have, so several designs can share one file; a + file there that isn't a connect file it can read is left alone and the export refused); `codeConnect.import {json | path}` → `{linked, warnings}` links each entry to every component or set with that name (one undo step; at most 5,000 links and 4 MB; - templates up to 4,000 characters, names 100, import paths 300; invalid entries are skipped with a - warning). `get_node` lists a component's links as `codeLinks`. In the app, the Inspect tab's + templates up to 4,000 characters, names 100, import paths 300; invalid entries, a malformed `values` + among them, are skipped with a warning). A link can also say where the code component lives (`source`, a path inside the + repository), what a property's design values are called in code (`values`: + `{"Variant": {"Primary": "primary"}}`, so `{Variant}` renders `primary`; a value without an entry + keeps its design name; `{Variant ? "a" : "b"}` still reads the design's value) and `notes`, through `codeConnect.set`, the file and the Inspect tab. + `codeConnect.list {ids?, unmapped?, root?}` → `{components: [{id, name, type, mapped, properties, + links: [{language, importPath, import, name, template, snippet, source?, sourceFound?, values?, + notes?}]}], mapped, unmapped}` answers which code component each design component is; with `root` + it says whether each `source` exists there. `get_node` lists a component's links as `codeLinks`. In the app, the Inspect tab's Connect to code section edits them in the Code section's language, with a live preview and a Connected badge. An editor extension isn't needed: agents and editors read the same snippets through this server. Plugins whose manifest asks only for `read` also run from the Inspect tab, @@ -2202,7 +2217,8 @@ turned off 0°. `cmd` while resizing a frame ignores its children's constraints (they stay where they are) and, as in every drag, turns snapping off. Moves snap to edges, centres and equal spacing (the gaps show in `tool.overlay.guides` with labels); with the pixel grid on, moves and resizes land on - whole pixels. + whole pixels. Frames, sections, components and instances always land on whole pixels of their + parent, with the pixel grid off too and after a snap to a layer off the grid. Tool failures come back as results with `isError: true` and a message; protocol problems (unknown tool, malformed JSON, wrong parameter types) are JSON-RPC errors. Nothing crashes the server. diff --git a/docs/roadmap.md b/docs/roadmap.md index 896fa9bd1..389ef400f 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # FigCraft roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (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; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (a zoom in shows the image on screen enlarged instead of a coarse preview, so a pinch stays sharp; 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; the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; compact layer trees with fields and outline (M0.9, part of #996); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a panic in a grouped closure outside any command rolls the group back like a failed group: documents, selection, undo and redo, history limit and journal as before (#1085); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); M8: mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); M2: components can't contain their own instances, directly or through others; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); M0.9: optional batch continue-on-error with per-step outcomes (#1386); Alt pressed during a drag duplicates (#1385); variables in paint props (M3, #1000); finding layers without selecting them (M0.9, part of #996); the attached MCP server reads the app's replies with a 512 MiB bound (#1113); a failed batch keeps the undo steps it undid (#1410); Arabic draft catalog; Android Vector Drawable export; a selected unfilled shape drags over a filled layer below it (#1370); text truncation fills the last line, survives resizing, and auto height takes Max lines (#1375, #1376, #1377); M11 widget fields and property menus; M12 Boards: timer and voting; Installed weights of an embedded font family (#1246); `.sketch` import, best effort; Adobe Fonts found on macOS (#298); M12 Boards; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below) · **Target:** Figma Design (desktop app 126.10.7) Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and [`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours @@ -77,6 +77,7 @@ blockers. | Date | Change | Summary | |---|---|---| | 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-10 | minor | Zoom in without coarse previews (#312 follow-up): a zoom in to at most 4× the image on screen, inside the area it covers, shows that image enlarged until the refined one comes, measured from what the screen shows, a preview included; it is at least as sharp as a preview with a quarter of the pixels each way. During a pinch or a held zoom each step used to get a preview and drop its refined image for the next step's, so the canvas stayed coarse until the zoom stopped. Zoom outs, other pages and larger zoom ins still get previews. | | 2026-11-19 | minor | M12, #2237 (step 1 of 4): code blocks in the document and engine. `board.codeBlock` places a dark panel of monospace text as tall as its lines, `board.setLanguage` picks one of 16 languages, and `board.nextSticky` makes the next block beside it; the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. 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`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 206c802fd..21e141240 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -371,7 +371,8 @@ Hours in this narrative are the builders' estimates; the tables above supersede Instance swap properties have preferred values (offered first). Alt-drop from the Assets panel onto an instance swaps it (same-set instance preferred, highlighted while dragging); instances pasted into other files follow their mains (library copies shared, published components used - from their library, other mains left behind as a restorable missing main). The Assets panel lays + from their library, other mains left behind as a restorable missing main), and a main pasted + from its library file is an instance of it from that library. The Assets panel lays out only the tiles in view and renders thumbnails as they show (cached, re-rendered only for changed components). A behaviour suite from the public documentation checks overrides (what an instance takes, what it refuses: geometry, constraints and resizing of its layers, its auto diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 968e735d0..c7476fbd8 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-19 · **Change:** minor (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); a dragged layer is drawn from a sprite that moves with its outline (#2033); the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); Type settings ▸ Details ▸ Position sets the selected text layers to superscript or subscript, or neither (#2338); Shift with the Pencil, Marker or Highlighter draws one straight segment from where the stroke started, at the nearest 45° step, as the Line tool and the Pen do (#2447); the Design panel's header names a selected component or component set, after its icon, instead of only its type (#2347); dragging near the canvas edge pans the view toward it, as measured in Figma: 40 px/s for each px within about 15 px of the edge, 600 px/s at it, for moving layers, the selection box, drawing and prototype connections (#2015); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (M4: the eyedropper colours the stroke of a layer that has only a stroke, samples for an open colour picker from the shortcut too, and shows the colour under it beside the pointer; Shift with a double-click goes a level deeper and keeps the rest of the selection, so layers nested in neighbouring artboards can be selected together; M1: Frame selection makes a frame without a fill; M1: centred auto-width text keeps its middle as it grows and shrinks; M1: a drag on a section's background, or on the background of a frame in it, draws a marquee; the Layers panel's eye and padlock stay at the list's right edge, and a name takes at most 400 pt; in vector edit mode, deleting a point selects the next one on its path, so Delete pressed again goes on along it; the hover and selection outline of a curved layer bends smoothly instead of showing straight pieces; text copied while editing, or a whole text layer copied, pastes into a text edit with its formatting and its layer's colour, and Shift+Cmd/Ctrl+V (also Alt+Cmd/Ctrl+V) pastes it in the style at the caret; crop mode: the layer's sides and corners crop its image in an auto layout frame too, up to the image's edges, change a locked ratio (Shift keeps it), the image's own corners scale freely with Shift proportional as a resize does, and crop mode and vector edit mode end each other; after a click on a layer row the arrow keys nudge the selection, or move a layer in an auto layout flow one place, as in Figma; the rows take the arrows once they have the keyboard (F6); Shift+Cmd/Ctrl+V with several layers selected pastes after the last of them as seen: next in an auto layout frame's flow, else below the lowest or right of the rightmost, at the selection's own gap; Tab and Shift+Tab while editing a text layer go on to the next or previous text layer of its frame, in reading order, with all of its text selected; a file opens again on the page and at the view it was left at; the desktop app reopens the files open when it quit, in their tabs' order with the same one in front, and with nothing to reopen starts on the Home screen instead of in a new file; a dropdown, button menu or context menu in the panels that is taller than the window scrolls, so its last rows can be picked; frames, sections, components and instances move, resize and draw on whole pixels whatever Snap to pixel grid says and whatever they snap to, as Figma's help says; the pixel grid shows on a dark canvas and dark fills as well as on white, its lines one screen pixel wide in a light grey at a fifth of its strength, as measured in Figma; Shift+Cmd/Ctrl+' says at the bottom of the window whether snapping to the pixel grid is now on or off; Paste properties links the copied layer's colour, effect, grid and text styles and binds the variables it follows, and a frame's layout grids come along; links another file lacks paste as values; 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); a dragged layer is drawn from a sprite that moves with its outline (#2033); the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); Type settings ▸ Details ▸ Position sets the selected text layers to superscript or subscript, or neither (#2338); Shift with the Pencil, Marker or Highlighter draws one straight segment from where the stroke started, at the nearest 45° step, as the Line tool and the Pen do (#2447); the Design panel's header names a selected component or component set, after its icon, instead of only its type (#2347); dragging near the canvas edge pans the view toward it, as measured in Figma: 40 px/s for each px within about 15 px of the edge, 600 px/s at it, for moving layers, the selection box, drawing and prototype connections (#2015); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -23,7 +23,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Actions palette (Cmd+K, Cmd+/) | done | tabs: All (every command, grouped by menu, or Other; a command that needs parameters only through its menu item, and none twice under one label, #1574), Assets (components and styles) and Plugins & widgets; results ranked prefix first, then shortest, at most 60 rows; Up/Down move a highlight and Enter runs it; Recents list what was run from the palette (matching translated labels); one open/toggle path from every entry point (`palette_tests`). Ranking and the Assets results not compared with Figma's | | Context menus | done | canvas and layers; submenus as in the main menu below, and a right-click in a new spot starts a fresh menu (Select layer closed); Shift+F10 or the keyboard's Menu key opens them from the keyboard (at the focused layer row or below the canvas selection) and the menu takes the keyboard (`layers_keyboard_tests`) | | Home screen: Recents, Online and Templates | done (ours) | The sidebar switches between the three (`ui.set {homeSection}`). Online: your online files (see the collaboration checklist). Recents: new file, open, join with a code, open files, recent files (cards with the picture each file carries on its page colour, the file's icon, name and "Edited ... ago" or "File not found", full path on hover; or a Name, Last modified and Created table with sortable headers; sorted by name, creation or last change either way; grid or list and the sort kept in the preferences, `ui.set {homeRecentsView, homeRecentsSort, homeRecentsOrder}`; a click selects, a double-click or Enter opens, arrow keys move the selection; Open, Show in folder and Remove from recents on right-click), a Getting started card (six tips with their shortcuts from the keymap; its close button is remembered in the preferences and Help ▸ Getting started brings it back) and, while there are no recent files, four templates to start from. Templates: the eight starter templates as cards (thumbnail rendered from the document, cached per theme; name, description, kind and size), a search field and a kind filter, an empty state; Tab reaches every card and Enter opens it; cards and tabs are named for screen readers. A first run opens here. No Community files or drafts folder | -| Main menu from the logo | done | generated from `catalog.rs`; popups sized to content. Submenus open on the first frame their row is hovered (a click or the keyboard opens one at once; Figma's main menu measured 2026-11-07 with synthetic pointer events: median 11 ms to open, 13 ms to switch rows) and close at once when another row is hovered; while the pointer heads for an open submenu inside the triangle to its near edge, the rows it crosses don't take over, and resting 0.3 s on one hands over; closing the menu, however it closes, clears which submenus were open, so it reopens with none (`menu_aim_tests`, 10 tests; the open delay is measured; the safe triangle and its 0.3 s rest are still tuned by feel, and Figma's main menu showed no triangle at all in that measurement, so the aim is kept pending the maintainer's decision). A menu or submenu that would run past the window's bottom moves up to fit (never above the top), and one taller than the window scrolls with the wheel, the keyboard's focus kept in view; the context menu's submenus share this (#2217, `menu_overflow_tests`). Menu and palette items that need a value ask for it first: Create link, Offset path and Move to page in a dialog of the shared controls, the language, user name, server and nudge items in Preferences, Open recent on the home screen's Recents; File ▸ Rename edits the file name in place | +| Main menu from the logo | done | generated from `catalog.rs`; popups sized to content. Submenus open on the first frame their row is hovered (a click or the keyboard opens one at once; Figma's main menu measured 2026-11-07 with synthetic pointer events: median 11 ms to open, 13 ms to switch rows) and close at once when another row is hovered; while the pointer heads for an open submenu inside the triangle to its near edge, the rows it crosses don't take over, and resting 0.3 s on one hands over; closing the menu, however it closes, clears which submenus were open, so it reopens with none (`menu_aim_tests`, 10 tests; the open delay is measured; the safe triangle and its 0.3 s rest are still tuned by feel, and Figma's main menu showed no triangle at all in that measurement, so the aim is kept pending the maintainer's decision). A menu or submenu that would run past the window's bottom moves up to fit (never above the top), and one taller than the window scrolls with the wheel, the keyboard's focus kept in view; the context menu's submenus share this (#2217, `menu_overflow_tests`). The panels' dropdowns, button menus and context menus do the same: one taller than the window scrolls with the wheel or its scroll bar, as the Selection colors Styles menu with many colour variables did not. Menu and palette items that need a value ask for it first: Create link, Offset path and Move to page in a dialog of the shared controls, the language, user name, server and nudge items in Preferences, Open recent on the home screen's Recents; File ▸ Rename edits the file name in place | | Keyboard shortcuts panel | done | closes when the home screen shows (#548); docked, tabbed by group like the documentation, searchable, per-platform keycaps; held keys, gestures and presentation keys listed beside the bindings; a label too long for its column ends with "…" and shows in full on hover | | Several windows | partial | File ▸ New window, Open in new window on a tab, a tab dragged off the strip; screen-reader tree in the main window only; positions not restored | | Multiplayer avatars, Share button | missing | waits for multiplayer | @@ -76,7 +76,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | | Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) | -| Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; the pixel grid shows from 400% (`view_behaviour_tests`) | +| Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; frames, sections and components always do, also with snapping off or next to a layer off the grid, as the help says (`frames_land_on_whole_pixels_whatever_they_snap_to`); the pixel grid shows from 400% (`view_behaviour_tests`) | | Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: half a step a point (0.5 px; 0.5% of opacity, 0.5° of rotation), as measured in Figma on 2026-11-08 (a 12.2 px drag moved X by 6, a 61.2 px drag by 31; rotation by 6° and opacity by 5% for 12.2 px), ten times that with Shift (5 steps a point) and a tenth of that with Alt (0.05 steps a point; neither measured), each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; the Shift and Alt rates and the speed by height are not compared with Figma's, and the rotation scrub's direction is not confirmed; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837) | | 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 | @@ -99,7 +99,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn, an arc reaching along the whole of a segment whose other end is sharp and half of one whose other end is rounded too, so one rounded corner of a 100 × 100 square with radius 100 runs from one neighbour to the other, while the radius field keeps what was typed (#2334, `vector_radius_tests`, `vector_point_radius_tests`); Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | | Shape builder (Shift+M) on fills, strokes and open paths; variable width (Shift+W), one side with Alt | done | | | Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003); a boolean group takes a corner radius from the Design panel and from `node.set cornerRadius`: every sharp corner of its result rounds, convex and concave, layers inside keep their own radius and do not stack with it, a radius larger than the edges allow shrinks to fit while the field keeps the value typed, Flatten bakes the arcs and a mixed selection reads Mixed; measured in Figma's web app on 2026-11-10 (#2222; `crates/pathops/src/round_tests.rs`, `crates/render/src/boolean_radius_tests.rs`, `crates/engine/src/boolean_radius_tests.rs`, the boolean group test in `crates/ui-egui/src/field_tests.rs`). Pinned and not yet compared with Figma: corner smoothing on a boolean group draws the polygon profile between straight edges, a corner beside a curve stays within the curve piece next to it, and there is no radius handle on the canvas | -| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check | +| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); Tab and Shift+Tab while editing a text layer that isn't a list item go on to the next or previous text layer of its frame in reading order, all of its text selected, and do nothing at the last and the first (`text_tab_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check | | Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. At three levels (the text layer, a paragraph and a text style, per Explore text properties): the paragraph level is the caret's or the selection's paragraphs while editing (`text.wrapStyle`; the control follows them), or `start`/`end` on `node.set wrapStyle` (a paragraph's own style beats the layer's; setting the layer sets every paragraph again; Enter carries it to the new paragraph; inspect reports `lineWrapStyles` when paragraphs differ and CSS `text-wrap` only when they agree); the text-style level is a style's `wrapStyle` (shown read-only in the style editor, applied with the style, moved by `style.update`, unlinking when edited). The `.fig` import/export mapping stays open (#1827): a `.fig` export leaves the wrap styles out and a `.fig` import reads every text as Auto, so the wrap styles are lost through a `.fig` round trip. Test: `text_behaviour_tests::wrap_style_per_paragraph_overrides_the_layers`, `styles_behaviour_tests::text_styles_carry_the_wrap_style`, `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` | | Text: direction override (Text ▸ Text direction) | done | per paragraph (`ParaList::direction`: auto, ltr, rtl): Text ▸ Text direction ▸ Auto / Left to right / Right to left and `text.direction {direction, ids?}` set the edited paragraphs while editing, else every paragraph of the selected texts; `node.set textDirection` the layer's (or the chars `start`/`end` name); the Type settings control appears once a right-to-left script is in the text or a direction is forced; inspect reports `textDirection` when the paragraphs agree and `lineDirections` otherwise; Developer Mode's CSS writes `direction: ltr` or `rtl` when every paragraph is forced the same way (with `text-align: left` beside `rtl`, as Left is absolute on the canvas); `.fig` import and export carry each line's `sourceDirectionality`, read up to the paragraph count. Layout gives the paragraph its base level, so a forced right-to-left paragraph of Latin letters starts at the right, mirrors its list gutter and indent and orders its runs right to left, and a forced left-to-right paragraph of Hebrew the other way ("By default, Figma automatically handles text direction based on language detection. However, controls are available to override text direction per paragraph", "Go to Text > Text direction. Select Left to right or Right to left", Add right-to-left text). Not included: a direction in text styles (the article names none). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests` | | Text: superscript and subscript | done | `sups` / `subs` use the font's own glyphs where it has the feature and every letter or digit of the run gets one; otherwise the standard glyphs are drawn shrunk and raised or lowered by the font's OS/2 superscript and subscript metrics (0.65 em at 0.35 em up or 0.14 em down without them), and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says ("Figma draws a synthesized version by using the font's standard version of the character, shrinking it, and positioning it accordingly"; mixed glyphs "all update to the synthesized form for consistency"), #1828; tests `text::tests::superscript_native_or_synthesised_and_never_mixed`, `text_behaviour_tests::superscript_and_subscript_are_synthesised_without_glyphs_for_them`. Type settings ▸ Details ▸ Position (None, Superscript, Subscript) sets them on the selected layers (#2338); a range of characters can't be raised alone yet, as the features are the layer's | @@ -114,7 +114,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Item | Status | Notes | |---|---|---| -| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); Preferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`); Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all four sides, centred in that area, at a continuous zoom (measured in Figma's web app, 2026-11-09; `zoom_to_selection_leaves_forty_points_and_clears_the_toolbar`, `zoom_to_selection_on_a_wide_layer_is_limited_by_the_width`, `zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height`); Zoom to fit (Shift+1) keeps its 64 pt margin, margin not measured yet (`zoom_to_fit_is_unchanged`) | +| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); Preferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`); Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all four sides, centred in that area, at a continuous zoom (measured in Figma's web app, 2026-11-09; `zoom_to_selection_leaves_forty_points_and_clears_the_toolbar`, `zoom_to_selection_on_a_wide_layer_is_limited_by_the_width`, `zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height`); Zoom to fit (Shift+1) keeps its 64 pt margin, margin not measured yet (`zoom_to_fit_is_unchanged`). A file opens again on the page it showed and at its view, each of its pages at the view it was left at, when its tab closed or the app quit: kept in the preferences by path for the last 100 files, never in the file, so looking around doesn't change it | | Auto-pan when a drag holds the pointer near the canvas edge | done | measured in Figma (web, 100% zoom, held drags; #2015): while a drag holds the pointer within about 15 px of the canvas viewport's edge, or past it, the view pans toward that edge by itself at `40 x (15 - d)` screen px per second (d: px inside the edge, negative outside; 0 at 15 px or more, 120 at 12 px, about 280 at 8 px, 520 at 2 px, 600 at the edge and beyond), steadily while the pointer stays still, no acceleration; two edges (a corner) pan both axes, each by its own distance. Covers moving layers (once past the drag threshold), the selection box (once it has grown past it), drawing a shape and dragging a prototype connection out of a layer, so a link can reach a frame off screen; the layer, box, shape or connection follows the document point under the pointer. Not for resizing, rotating, the hand or Space panning, text selection or vector edits (not measured). Speed taken as screen px per second at every zoom (other zooms not measured). The rule is `ViewState::autopan_velocity`, applied each frame by the canvas (`view_autopan_tests`, `canvas_autopan_tests`, `proto_canvas`) | | Rulers and guides (drag out, move, remove; rotated frames; frame guides) | done | guides belong to the page or a top-level frame (a frame moved into another keeps its guides but they stop applying); a click selects one for Delete, the arrows or the context menu's Remove guide; Alt-drag drops a copy; Alt while dragging measures to the layers in the frame it crosses; ruler numbering checked by eye only | | Frame labels (rotated, right-to-left), size badge | done | | @@ -185,7 +185,7 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | Screen-reader names, roles, values, states (AccessKit) | done on desktop | browser: eframe doesn't send the tree yet | | Keyboard navigation: F6 regions, Tab within, focus ring | done | | | Layers panel from the keyboard: arrows, F2 / Cmd+R rename (the row gets the keyboard back), Shift+F10 context menu; 10k-layer lists | done | revealing a layer, expanding, collapsing and arrow keys timed in `cargo xtask bench` | -| Layers panel: long or deeply nested names | done | the list is as wide as its widest name needs and scrolls sideways, so a name reads in full without widening the sidebar (the reference app's Layers panel has a horizontal scrollbar); a drag released over the canvas drops nowhere; a name past 1200 pt still elides (`layers_wide_names_tests`, #1904) | +| Layers panel: long or deeply nested names | done | the list is as wide as its widest name needs and scrolls sideways, so a name reads in full without widening the sidebar (the reference app's Layers panel has a horizontal scrollbar); a drag released over the canvas drops nowhere; a name past 400 pt elides, and the eye and padlock stay at the edge of the list's view (`layers_wide_names_tests`, #1904) | | Reduced motion | done | system setting or preference | | WCAG AA contrast of secondary and accent text | done | disabled and dim text at least 3:1 against panels, fields and selected rows, selected text at least 3:1 on its highlight, in both themes (`theme::tests`, #890) | | Tested with VoiceOver, NVDA, Narrator, Orca | missing | human QA | @@ -214,6 +214,24 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged |---|---|---| | 2026-11-09 | patch | M8, #2033: a dragged layer moves with its outline: the layers a translate-only drag moves are drawn from a sprite (a texture rendered once at the start) at the same shift as the outline, and the base render, made once without them, is not asked for again until the drag ends (see the row "A dragged layer moves with its outline" for the conditions and trade-offs). | | 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured; a scale that would take an instance past 0.001 to 1000 times is refused. Tests: `scale_bound_values_tests`. | +| 2026-11-24 | patch | M4: Copy properties (Alt+Cmd/Ctrl+C) took a layer's values and left behind what they come from: a frame filled from a colour variable or a style pasted a plain colour, unlinked, and a pasted layer's own bindings stayed and could hold the old value over the pasted one. It now also carries the fill, stroke, effect, grid and text style links, the variables bound to what it copies (not size, auto layout spacing, visibility or text content) and a frame's layout grids; the pasted layer's bindings on what the copy carries give way, others stay. Pasted into another file (the copy came from another tab), or after its style was deleted, a link is left out, its values pasted and the layer's own link on them dropped. Tests: `paste_properties_tests` (4). | +| 2026-11-24 | patch | M3: Shift+Cmd/Ctrl+' turned Snap to pixel grid on or off without a sign, since nothing on the canvas changes until the next drag. A notice at the bottom now says "Snap to pixel grid on" or "off", from the shortcut, the menu and the Preferences row alike. Test: `shortcut_keys_tests::shift_cmd_quote_says_whether_snapping_to_the_pixel_grid_is_on`. | +| 2026-11-24 | patch | M3: the pixel grid was drawn in black at 7% and two pixels wide on a Retina screen, so it showed on white and hardly at all on the dark canvas or a dark fill. Its lines are now a light grey (190) at 20%, one screen pixel wide and on the screen's pixels: 242 on white and 78 on a grey of 50, as measured on Figma's grid (2026-11-24), so they darken a light colour and lighten a dark one. Test: `pixel_grid_tests` (800%, a 1x and a 2x screen, none below 400%). | +| 2026-11-24 | patch | M8: Figma's help says frames, sections and components always snap to the pixel grid, even with Snap to pixel grid off. In FigCraft they followed the setting like any layer, and a snap to a layer off the grid (a neighbour scaled or imported to 100.4) won over it (#2031), so a frame could land between pixels and the whole numbers inside it sat off the grid. Now a frame, section, component, component set or instance dragged, resized or drawn lands on whole pixels of its parent in either case; a frame off the grid lands on it once moved. Other layers keep the setting, and a snap to a layer still wins for them. Test: `transform_behaviour_tests::frames_land_on_whole_pixels_whatever_they_snap_to`. | +| 2026-11-23 | patch | M3: a menu opened from a panel (a dropdown, a button's menu such as the Selection colors Styles menu, a row's context menu) ran past the window's bottom when it had more rows than fit, and the rows below couldn't be reached: with many colour variables the Styles menu showed only the first ones. egui moves a popup to keep it in the window but doesn't shorten one taller than the window. `menu_popup`, `context_popup` and the row context menus now return a `Menu` whose rows scroll with the wheel or the scroll bar once they were taller than the window last frame, as the main menu's do (#2217); a menu that fits is laid out as before and still grows with its rows. A click on the scroll bar scrolls and leaves the menu open, and the row the keyboard is on keeps it when a resized window starts or stops the scrolling. Tests: `menu_scroll_tests` (the page's variable mode menu of a collection with 60 modes, and 25 for the resize). Numbers unchanged | +| 2026-11-24 | minor | M5: a file opens again where it was left, as Figma opens a file where you were. Closing its tab or quitting keeps the page it showed and each page's view (centre and zoom) in the preferences by path, for the last 100 files left; opening it shows that page at its view, and the canvas keeps the view instead of fitting the page when it gets its size. Each other page shows its view when it's opened. A page the file no longer has, a divider or a view the canvas can't show is left out, and the file opens fitted as before. Nothing goes into the file: looking around doesn't make it unsaved. Tests: `file_views::tests` (4). Numbers unchanged | +| 2026-11-20 | patch | The desktop app started in a new, empty file every time, whatever was open when it quit. It now opens those files again, in their tabs' order with the same one in front, as Figma's desktop app reopens its tabs; quitting keeps their paths with the preferences (files without one, such as new or imported files, and branch tabs are left out). A file named on the command line still opens and stays in front, a recovered copy keeps its one tab, a file gone since is skipped and one that won't open says why. With nothing to reopen the app starts on the Home screen; with a control port open (`--control`) it still starts in a new file, so control callers have a document. Preferences ▸ Start on the Home screen starts there instead of reopening the files. Tests: `reopen_tests` (4), `start_tests` (2). Numbers unchanged | +| 2026-11-20 | patch | M4: Tab while editing a text layer typed a tab character, and Shift+Tab did too, so filling in a form built from instances took a double-click into every label. Tab now ends editing and edits the next text layer with all of its text selected, so typing replaces it; Shift+Tab goes to the previous one. The order is reading order: rows top to bottom, each left to right, and two layers share a row when they overlap vertically by at least half the shorter one's height. The candidates are the text layers of the same top-level frame or group, at any depth and inside instances (what is typed there is the instance's override), that are visible and unlocked along with every layer around them; a text on the page or in a section goes to the text layers beside it there. At the last text Tab does nothing, and Shift+Tab at the first, with no wrapping. In a list item Tab still nests the item, in a code block it still types two spaces, and in a board object or a widget's field it still types a tab. The view doesn't follow a text that is off screen: nothing in the app scrolls a layer into view yet. Tests: `text_tab_tests`, `text_enter_tests::tab_edits_the_label_in_the_next_row_of_a_form` | +| 2026-11-20 | patch | M1: Shift+Cmd/Ctrl+V (Paste over selection) with several layers selected took the first one selected, so the copies landed among the others, after whichever was clicked first. It now pastes after the last selected layer as seen: in one auto layout frame, the last of them in the flow, the copies coming next; elsewhere below the lowest, as far below it as it is from the selected layers above it, or, for a row with nothing above its lowest layer, right of the rightmost at the row's gap, in that layer's parent just above it. One selected layer is unchanged. Tests: `paste_over_tests` (4). | +| 2026-11-19 | patch | M5: a click on a row in the Layers panel gave the arrow keys to the rows, so Up and Down moved the selection through the list and Left and Right opened and closed rows. A layer picked there couldn't be nudged, nor moved up or down its vertical auto layout frame. As in Figma, where a locked layer picked in the Layers panel is the one the arrows don't move (row of 2026-11-10), a clicked row now leaves the arrows to the canvas. Walking the rows with the arrows is still there for the keyboard: F6 into the Layers panel puts the keyboard on the selected row. Shift+F10 after a click still opens the menu at the row. Tests: `layers_keys_tests::a_clicked_row_leaves_the_arrows_to_the_canvas`, `down_on_a_clicked_row_moves_it_one_place_in_a_vertical_auto_layout`; the row-walking tests now reach the rows by F6 | +| 2026-11-18 | patch | M1, crop mode (Object ▸ Crop image, #1464): the layer's sides and corners (the Cmd/Ctrl resize crop) crop its image in an auto layout frame too, against the box the layout leaves, instead of squashing the picture; a side can go no further than the image's edge, so no empty strip opens inside the layer (Shift still keeps the ratio and Alt the centre there, and a crop the layout widens slides back along the image); a locked ratio doesn't hold the crop window and Shift keeps its ratio; the image's own corner handles scale it freely and in proportion with Shift, as a resize does (they were the other way round). Crop mode and vector edit mode end each other, and a double-click in crop mode stays in it: with both on, the injected Cmd/Ctrl turned a drag of the layer's side into the Bend tool and showed the selected points' box ("804 × 0"). Tests: `crop_image_tests` (5 new), `transform_behaviour_tests::command_crop_changes_a_locked_ratio_and_stops_at_the_images_edges`, `command_crop_stopped_by_the_image_keeps_the_ratio_with_shift_and_the_centre_with_alt`, `command_crop_slides_back_onto_the_image_when_layout_widens_the_layer`, `command_resize_crops_in_auto_layout_against_the_box_layout_leaves` | +| 2026-11-18 | patch | M4: text copied or cut while editing went to the clipboard as plain characters, so Cmd/Ctrl+V put it in the style at the caret and dropped its font, size, fills and text style; Alt+Cmd/Ctrl+V while editing did nothing. Cmd/Ctrl+V now pastes the characters with the formatting they were copied with while the clipboard still holds the text FigCraft copied (a link to a text style the file doesn't have is dropped, its look kept), and Alt+Cmd/Ctrl+V pastes the clipboard's characters in the style at the caret, as Paste and match style does. Characters coloured by their layer's fill keep that colour, and a whole text layer copied with Cmd/Ctrl+C pastes into a text edit the same way. Shift+Cmd/Ctrl+V while editing does what Alt+Cmd/Ctrl+V does; outside text editing it is still Paste over selection. Shift+Insert pastes as Cmd/Ctrl+V does, and an image fill on the copied characters brings its image into another file, as a pasted layer's does. Text copied in another app pastes as before. Tests: `text_paste_style_tests`, `textedit::tests::rich_text_pastes_its_runs_and_drops_a_link_to_a_style_this_file_lacks`, `textedit::tests::copied_characters_bring_the_image_their_fill_uses_into_another_file` | +| 2026-11-18 | patch | M8: in vector edit mode, deleting a selected point (Delete or Backspace, or Shift+Delete to heal) left nothing selected, so deleting several points along a path meant clicking each one first. The point that followed the deleted one along its path is now selected, the one before it when the deleted point ended the path, so Delete pressed again goes on along it; points and segments cut to the clipboard still leave nothing selected. Test: `vector_behaviour_tests::deleting_a_point_selects_the_next_one_on_its_path` | +| 2026-11-15 | patch | M1: in a section, a press on the section's background or on the background of a frame in it picked up the section or the frame, so a drag moved it and nothing inside could be marked out. An unselected section with layers, and a frame with layers directly in a section, now act like a top-level frame's background: a click deselects and a drag draws a marquee. The marquee selects among the section's layers as one on the page does among the page's, or inside the frame it starts in. With Cmd/Ctrl held the drag draws the deep marquee, on a selected artboard or section too instead of moving it; a Cmd/Ctrl click without a drag still selects the frame or section. A section moves by its name label, or by its body once selected. Test: `section_marquee_tests` | +| 2026-11-15 | patch | M1: typing in centred auto-width text kept its left edge, so the text crept to the right. It now keeps its middle, half of each width change going to each side, also when rotated, under the same conditions as right-aligned text keeps its right edge (#1477). Tests: `text_behaviour_tests` | +| 2026-11-15 | patch | M1: Frame selection (Alt+Cmd/Ctrl+G) gave the new frame the white fill a drawn frame gets, which covered the page behind the framed layers. It now has no fill; a frame drawn with the Frame tool keeps its white fill. Test: `frames_behaviour_tests` | +| 2026-11-18 | patch | M1: a double-click with Shift held, on a layer in another artboard than the selected one, left only that artboard's layer selected, so layers nested in neighbouring artboards couldn't be selected together. It now goes a level deeper as a double-click does and keeps the rest of the selection: the selected layer it went into, or the layer a click would select there, is replaced by the one a level below, as in Figma. Where nothing on that branch is selected it starts beside the selection, just inside the deepest layer the branch shares with a selected one, so a Shift double-click on the next row of a list adds that row's label beside the selected label instead of collapsing the selection to the list. The selection it works from is the one before the double-click's two clicks, which Shift had already toggled. Test: `shift_double_click_tests` | +| 2026-11-15 | patch | M4: the eyedropper (I, Ctrl+C on macOS) gave a selected layer that had only a stroke a new fill. Such a layer now takes the colour on its stroke; other layers take it on their fill as before, and a mixed selection changes in one undo step. With a colour picker open on a fill or a stroke, the shortcut samples for that paint, as the picker's own eyedropper button does. A swatch beside the pointer shows the colour under it, read from the canvas image already on screen. Tests: `eyedropper_stroke_tests`, `colorpicker_eyedropper_tests` | | 2026-11-19 | patch | M4, #2338: superscript and subscript were drawn (#1868) but nothing in the interface set them. Type settings ▸ Details now starts with Position: None, Superscript (X²) or Subscript (X₂), for the selected text layers, through `text.setFeatures` (`sups`, `subs`; choosing one clears the other). It shows the layers' current position, none when they differ. Raising a range of characters on its own needs per-run features and is left for a separate change. Test: `typography::variable_tests::details_position_sets_superscript_subscript_or_neither`. | | 2026-11-19 | patch | M1, #2447: Shift did nothing with the Pencil: a stroke stayed freehand while the Line tool and the Pen keep theirs to 45° steps. With Shift held, the Pencil (and the Marker and Highlighter) now draws one straight segment from where the stroke started to the pointer, at the nearest 45° step; the preview shows it. A Shift-click without a move draws nothing, as before. Tests: `pencil_shift_tests`. | | 2026-11-19 | patch | M3, #2347: with one component or component set selected, the Design panel's header said only "Component" or "Component set", so the selected one's name was only in the Layers panel. It now shows the name after a component icon (cut short with an ellipsis clear of the quick actions), with the type, and the whole name when cut, on hover. Other layers keep their type. Test: `component_header_tests::the_header_names_the_selected_component_or_set`. | @@ -222,6 +240,8 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | 2026-11-19 | patch | M5, #2360: with a frame selected, a drag that starts on one of its children moves the frame and a click selects the child (a press on a layer inside a selected one drags the selection), as in Figma; Cmd/Ctrl, Shift and layers outside the frame are unchanged. | | 2026-11-18 | patch | M5, #2372: the arrow keys move a layer along the canvas axes inside a rotated parent (the step was applied along the parent's axes, so Down moved a child of a frame rotated 90 degrees sideways); auto layout children are unchanged | | 2026-11-18 | patch | M1, #2355: Cmd/Ctrl+V with one layer inside a frame selected pasted the copy onto the page on top of the frame; it now goes into the layer's parent just above it (in an auto layout frame, the item after it, so the layout grows), keeping today's behaviour for a page-level layer, several layers, an instance's children and a board atom. Tests: `paste_sibling_tests` (5) | +| 2026-11-18 | patch | M1, #1506 follow-up: the hover and selection outline of an ellipse, a vector or a rounded corner was flattened into lines up to 0.5 pt from the curve on screen, so it turned up to 22° at a time on a 65 by 50 ellipse at 100% and showed straight pieces around it. It is now flattened to 0.02 pt at any zoom, so it stays within 0.1 pt of the curve. A path with more than 200 curves is flattened coarser as the count grows, up to the old 0.5 pt at 5,000: the outline is flattened again each frame the view moves or the layer is hovered and every point is tessellated each frame, and at 0.02 pt a vector of 5,000 curves took about 5 to 9 ms more per frame in a release build. Tests: `outline_tests::a_selected_ellipses_outline_stays_on_the_curve_at_any_zoom`, `outline_tests::a_heavy_vectors_outline_keeps_the_points_it_had` | +| 2026-11-18 | patch | M3, #1904 follow-up: a text layer named after a paragraph made the Layers list over 1000 pt wide, and the eye and padlock sat at the far end of each row, so hiding a layer meant scrolling sideways. They now sit at the right edge of the list's view, with the name clipped under them while they show (hover, or a hidden or locked layer), and a name takes at most 400 pt instead of 1200, which still holds a variant name like `Size=small, Type=primary, State=default, Icon=leading, Width=full` in full. A row nested so deep that its disclosure triangle would sit under them keeps them at its end, and a row a held sweep has taken in keeps its name clipped; an ordinary row's eye is where it was. Tests: `the_eye_of_a_long_named_layer_sits_at_the_panels_edge_and_is_clickable`, `a_paragraph_named_text_layer_widens_the_list_no_more_than_the_name_cap`, `the_eye_of_an_ordinary_row_stays_where_it_was`, `a_swept_long_named_row_keeps_its_name_clipped_before_the_eye`, `the_disclosure_triangle_of_a_deeply_nested_row_is_not_under_the_padlock` | | 2026-11-08 | minor | M8, #2109: in vector edit mode the Align commands (`align.left` to `align.bottom`, Alt+A/H/D/W/V/S) and Distribute horizontal and vertical spacing act on the selected points when neither `ids` nor `id` is given (either one targets layers), as in Figma (measured in Figma on 2026-11-08): each point moves along one axis only, to its box's left, horizontal centre, right, top, vertical centre or bottom, and distribute spaces the points evenly between the outermost two in order along the axis; handles go with their vertex, a single point stays, with no point selected nothing moves (the layer is not aligned to its frame, as measured in Figma), and one undo restores them. The Design panel draws the alignment row first, with a Distribute menu from three points. Numbers unchanged. | | 2026-11-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | | 2026-11-17 | patch | M8: each page keeps its view in a session: going back to a page (the Pages list, `page.select`, Previous/Next page) shows it where it was left instead of fitting it again; a new page is still fitted, and going to the page shown moves nothing (`page_view_tests`) |