diff --git a/ROADMAP.md b/ROADMAP.md index ca5abbbe7..b392b7d41 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -368,6 +368,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). |---|---|---| | 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged | | 2026-11-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/services.rs b/apps/figcraft/src/services.rs index 4b14c316e..e4f949c51 100644 --- a/apps/figcraft/src/services.rs +++ b/apps/figcraft/src/services.rs @@ -535,6 +535,12 @@ impl Services for Desktop { Some((w, h, img.bytes.into_owned())) } #[cfg(target_os = "macos")] + fn clipboard_image_file(&mut self) -> Option { + let files = self.clipboard.as_mut()?.get().file_list().ok()?; + let [path] = files.as_slice() else { return None }; + image::ImageFormat::from_path(path).ok()?.reading_enabled().then(|| path.clone()) + } + #[cfg(target_os = "macos")] fn clipboard_get_png(&mut self) -> Option> { let board = objc2_app_kit::NSPasteboard::generalPasteboard(); let png = board.dataForType(&objc2_foundation::NSString::from_str(MACOS_PASTEBOARD_PNG))?; diff --git a/crates/collab-net/src/host.rs b/crates/collab-net/src/host.rs index c7180708c..6d51a051c 100644 --- a/crates/collab-net/src/host.rs +++ b/crates/collab-net/src/host.rs @@ -84,6 +84,16 @@ impl Host { if cfg.view_token.as_deref().is_some_and(|v| same_secret(v, &cfg.token)) { return Err(io::Error::other("the view-only secret is the same as the edit secret")); } + // The file's review settings stay inside the limits this build keeps: clients apply every + // arriving value against them, so a file past them (written by an older or looser build) + // would break everyone who joins. The host trims them first (`design.configure`). + let over = cfg.doc.design_review.over_limits(); + if !over.is_empty() { + let list = over.iter().map(|(what, have, max)| format!("{have} {what} (this build keeps at most {max})")).collect::>().join(", "); + return Err(io::Error::other(format!( + "this file can't be shared: its design review settings hold {list}; trim them with design.configure (or reset the settings), then share again" + ))); + } let listener = match TcpListener::bind(cfg.addr) { Ok(l) => l, Err(e) if e.kind() == io::ErrorKind::AddrInUse && cfg.any_port_if_taken => TcpListener::bind(SocketAddr::new(cfg.addr.ip(), 0))?, diff --git a/crates/collab-net/src/hub/conn.rs b/crates/collab-net/src/hub/conn.rs index b5e41a64d..099071cc8 100644 --- a/crates/collab-net/src/hub/conn.rs +++ b/crates/collab-net/src/hub/conn.rs @@ -10,6 +10,9 @@ use super::{ /// How long a closing connection waits for the peer to hang up. const LINGER: Duration = Duration::from_secs(2); +/// How long the non-blocking accept loop sleeps when no connection is queued. +const ACCEPT_POLL: Duration = Duration::from_millis(20); + /// Signals (cursor chat, spotlight) a client may send per second on average, and in a burst; /// beyond that they are dropped. pub const SIGNAL_RATE: f64 = 20.0; @@ -91,12 +94,14 @@ pub(super) struct Shared { pub(super) fn accept(listener: &TcpListener, hub: &Sender, stop: &AtomicBool, open: &Arc, limits: NetLimits, shared: Shared) { let mut next = 0u64; - for stream in listener.incoming() { - if stop.load(Ordering::SeqCst) { - break; - } - let stream = match stream { - Ok(s) => s, + while !stop.load(Ordering::SeqCst) { + let stream = match listener.accept() { + Ok((s, _)) => s, + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + std::thread::sleep(ACCEPT_POLL); + continue; + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => { // Out of sockets or similar: don't spin. log::warn!("live session: accept failed: {e}"); @@ -104,6 +109,15 @@ pub(super) fn accept(listener: &TcpListener, hub: &Sender, stop: &AtomicB continue; } }; + if stop.load(Ordering::SeqCst) { + break; + } + // Accepted sockets inherit O_NONBLOCK from the listener on BSD/macOS; `serve` uses + // blocking reads and writes with explicit timeouts. + if let Err(e) = stream.set_nonblocking(false) { + log::warn!("live session: can't set accepted socket blocking: {e}"); + continue; + } if open.load(Ordering::Relaxed) >= limits.max_connections { log::info!("live session: too many connections; refusing one"); continue; diff --git a/crates/collab-net/src/hub/hosting.rs b/crates/collab-net/src/hub/hosting.rs index df8fd9756..914fc9e22 100644 --- a/crates/collab-net/src/hub/hosting.rs +++ b/crates/collab-net/src/hub/hosting.rs @@ -1,10 +1,10 @@ use super::backend::Backend; use super::conn::{Shared, accept}; -use super::limits::{PerAddress, loopback}; +use super::limits::PerAddress; use super::queue::{Blocks, HubIn, InFlight}; use super::{ Arc, AtomicBool, AtomicUsize, ClientMsg, Duration, HashMap, Hub, Inbox, Instant, JoinHandle, MAX_NAME, NetLimits, Ordering, Presence, Readers, - Room, Sender, Server, SocketAddr, TcpListener, TcpStream, channel, io, + Room, Sender, Server, SocketAddr, TcpListener, channel, io, }; /// The person hosting an app session: in the file's session without a socket. @@ -48,6 +48,7 @@ impl Hosting { pub(crate) fn start(listener: TcpListener, backend: B, limits: NetLimits, local: Option) -> io::Result { let addr = listener.local_addr()?; + listener.set_nonblocking(true)?; let in_flight = InFlight(Arc::default()); let mut hub = Hub { backend, @@ -169,15 +170,8 @@ impl Hosting { if let Some(t) = self.hub_thread.take() { let _ = t.join(); } - // The accept loop checks the flag after each connection: wake it with one. - let wake = if self.addr.ip().is_unspecified() { SocketAddr::new(loopback(self.addr), self.addr.port()) } else { self.addr }; - let woke = TcpStream::connect_timeout(&wake, Duration::from_secs(1)).is_ok(); if let Some(t) = self.accept_thread.take() { - if woke { - let _ = t.join(); - } else { - log::warn!("live session: couldn't wake the accept loop; it ends with the next connection"); - } + let _ = t.join(); } // Readers end once their writers have closed the sockets. let deadline = Instant::now() + Duration::from_secs(2); @@ -202,3 +196,53 @@ impl Drop for Open { self.0.fetch_sub(1, Ordering::Relaxed); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::hub::{Admission, Closing}; + + struct Noop; + + impl Backend for Noop { + fn admit(&mut self, _file: &str, _token: &str) -> Result { + Err("no".into()) + } + + fn open(&mut self, _file: &str) -> Result { + Err("no".into()) + } + + fn closing(&self) -> Closing { + Closing::Ended + } + } + + /// Stopping a wildcard (`0.0.0.0`) host must return even when another listener already holds + /// `127.0.0.1` on the same port (allowed on BSD/macOS under `SO_REUSEADDR`), and must not + /// connect to that loopback listener. + #[test] + fn stopping_a_wildcard_host_returns_when_loopback_shares_the_port() { + let shadow = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = shadow.local_addr().unwrap().port(); + let (wildcard, shadowed) = match TcpListener::bind(("0.0.0.0", port)) { + Ok(l) => (l, true), + Err(_) if !cfg!(any(target_os = "freebsd", target_os = "macos")) => (TcpListener::bind("0.0.0.0:0").unwrap(), false), + Err(e) => panic!("expected BSD dual-bind on 0.0.0.0:{port} alongside 127.0.0.1:{port}: {e}"), + }; + let mut hosting = Hosting::serve(wildcard, Noop, NetLimits::default()).unwrap(); + let (tx, rx) = channel(); + std::thread::spawn(move || { + hosting.stop(); + let _ = tx.send(()); + }); + assert!(rx.recv_timeout(Duration::from_secs(3)).is_ok(), "Hosting::stop() hung with a loopback listener on port {port}"); + if shadowed { + shadow.set_nonblocking(true).unwrap(); + assert!( + shadow.accept().is_err_and(|e| e.kind() == io::ErrorKind::WouldBlock), + "Hosting::stop() must not poke another listener on 127.0.0.1:{port}" + ); + } + } +} diff --git a/crates/collab-net/src/hub/limits.rs b/crates/collab-net/src/hub/limits.rs index 663697906..c3a0e6442 100644 --- a/crates/collab-net/src/hub/limits.rs +++ b/crates/collab-net/src/hub/limits.rs @@ -1,4 +1,4 @@ -use super::{Access, Arc, HashMap, IpAddr, Ipv6Addr, Mutex, PoisonError, SocketAddr}; +use super::{Access, Arc, HashMap, IpAddr, Ipv6Addr, Mutex, PoisonError}; /// What a link lets a hello do. #[derive(Clone, Debug, PartialEq, Eq)] @@ -21,11 +21,6 @@ pub fn ip_key(ip: IpAddr) -> IpAddr { } } -/// The loopback address of `addr`'s family. -pub(super) fn loopback(addr: SocketAddr) -> std::net::IpAddr { - if addr.is_ipv6() { std::net::Ipv6Addr::LOCALHOST.into() } else { std::net::Ipv4Addr::LOCALHOST.into() } -} - /// A block of addresses: its first address and its prefix length (2001:db8:: as a /64 and as a /// /48 are different blocks). pub type Block = (IpAddr, u8); diff --git a/crates/collab-net/src/loopback_tests.rs b/crates/collab-net/src/loopback_tests.rs index dadda9ef4..7af598bf9 100644 --- a/crates/collab-net/src/loopback_tests.rs +++ b/crates/collab-net/src/loopback_tests.rs @@ -290,6 +290,39 @@ fn a_view_token_lets_people_look_and_not_edit() { host.stop(); } +/// A file whose review settings are past this build's limits is not hosted: joining clients +/// would refuse the value when it reaches them. The error names the lists and the way out. +#[test] +fn a_file_with_review_settings_past_the_limits_is_not_shared() { + use figcraft_doc::{DesignReview, MAX_DISABLED, MAX_RADII}; + + let probe = Probe::new(); + let mut doc = Document::new("Shared file"); + doc.repair(); + doc.design_review = DesignReview { + radii: (0..MAX_RADII + 1).map(|i| i as f64).collect(), + disabled: (0..MAX_DISABLED + 1).map(|i| format!("rule.{i}")).collect(), + ..Default::default() + }; + let cfg = HostConfig { + addr: SocketAddr::from(([127, 0, 0, 1], 0)), + any_port_if_taken: false, + file: FILE.into(), + token: TOKEN.into(), + view_token: None, + doc, + name: "Hana".into(), + limits: fast_limits(), + core: Limits::default(), + }; + let e = Host::start(cfg, probe.inbox.clone()).err().expect("settings past the limits are refused"); + let text = e.to_string(); + assert!(text.contains("can't be shared"), "{text}"); + assert!(text.contains(&format!("{} corner radii (this build keeps at most {MAX_RADII})", MAX_RADII + 1)), "{text}"); + assert!(text.contains(&format!("{} disabled rules", MAX_DISABLED + 1)), "{text}"); + assert!(text.contains("design.configure"), "{text}"); +} + #[test] fn unreachable_hosts_fail_at_once() { // A port nothing listens on. diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 6ebe9e0e4..555ed3e33 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -230,6 +230,11 @@ pub enum DocProp { Vote, /// Ended votes' results kept in the file, oldest first (whole). VoteHistory, + /// The file's design review settings (`design.configure`). + /// + /// Kept last: the wire encodes a variant's position, so adding one before it would shift the + /// existing properties. + DesignReview, } /// A document-level entry, by id. @@ -331,6 +336,19 @@ impl Change { Change::Create { .. } | Change::Set { .. } | Change::Delete { .. } => false, } } + + /// Whether this writes the file's design review settings: a batch carrying one can't be read + /// by a peer that doesn't announce [`crate::message::DESIGN_REVIEW`], so the server keeps it + /// out of what it sends them ([`Self::without_design_review`]). + pub(crate) fn is_design_review(&self) -> bool { + matches!(self, Change::SetDoc { prop: DocProp::DesignReview, .. }) + } + + /// `changes` without the review-setting edits: what an older peer reads of a batch (its other + /// edits, order kept), or of a catch-up delta or snapshot. + pub(crate) fn without_design_review(changes: Vec) -> Vec { + changes.into_iter().filter(|c| !c.is_design_review()).collect() + } } impl Entry { diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index bb81d0b1b..32edaba7c 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use std::sync::Arc; use figcraft_color::{Color, Paint}; -use figcraft_doc::{Comment, DevSnapshot, Document, ImageData, Message, Node, NodeId, NodeKind, Style, StyleKind}; +use figcraft_doc::{Comment, DesignPreset, DevSnapshot, Document, ImageData, MAX_DISABLED, Message, Node, NodeId, NodeKind, Style, StyleKind}; use crate::change::{Change, DocProp, Entry, Json, Prop}; use crate::replica::{Mode, Replica}; @@ -48,6 +48,65 @@ fn property_edits_send_only_what_changed() { assert!(round_trip(&a, a.document()).is_empty(), "nothing changed"); } +#[test] +fn design_review_settings_round_trip_and_reach_a_snapshot() { + let (a, _, _, _) = setup(); + let mut b = a.document().clone(); + b.design_review.preset = DesignPreset::Strict; + b.design_review.grid = 8.0; + let changes = round_trip(&a, &b); + assert!(changes.contains(&Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() })); + let snapshot = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + assert!(snapshot.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "a snapshot carries the review settings"); +} + +#[test] +fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() { + let (a, _, _, _) = setup(); + // An edit peer trying to hand the file tens of thousands of radii is refused at apply. + let mut b = a.document().clone(); + b.design_review.preset = DesignPreset::Strict; + b.design_review.grid = 8.0; + b.design_review.radii = (0..40).map(|i| i as f64).collect(); + b.design_review.brand = vec![Color::from_rgb8_const(1, 2, 3); 40]; + b.design_review.disabled = vec!["radius.off-scale".into()]; + let mut r = a.clone(); + let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; + let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string(); + assert!(err.contains("pass the 32 limit `design.configure` keeps"), "{err}"); + // A snapshot holding settings over the limits (an old file's) opens clamped to what fits: + // the preset, grid and disabled rules exactly as saved, the lists to the limit. + let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert!(clamped, "the settings needed clamping, and the caller is told"); + assert_eq!(left_out, 0, "nothing needed leaving out"); + let cfg = &r2.document().design_review; + assert_eq!(cfg.preset, DesignPreset::Strict, "the preset survives"); + assert_eq!(cfg.grid, 8.0, "the grid survives"); + assert_eq!(cfg.disabled, vec!["radius.off-scale".to_string()], "the disabled rules survive"); + assert_eq!(cfg.radii, (0..32).map(|i| i as f64).collect::>(), "the radii keep their first 32"); + assert_eq!(cfg.brand, vec![Color::from_rgb8_const(1, 2, 3); 32], "the brand colours keep their first 32"); +} + +#[test] +fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them() { + let (a, _, _, _) = setup(); + let mut b = a.document().clone(); + b.design_review.disabled = (0..200).map(|i| format!("rule.{i}")).collect(); + let mut r = a.clone(); + let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; + let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string(); + assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}"); + // A snapshot with a longer list opens with the ones that fit, not without the settings. + let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert!(clamped); + assert_eq!(left_out, 0, "nothing needed leaving out"); + let cfg = &r2.document().design_review; + assert_eq!(cfg.disabled.len(), MAX_DISABLED, "the list keeps its first {MAX_DISABLED}"); + assert_eq!(cfg.disabled.first().map(String::as_str), Some("rule.0")); +} + #[test] fn creations_moves_reorders_and_deletions_round_trip() { let (a, page, frame, kids) = setup(); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index b590064df..ae7299511 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -353,6 +353,7 @@ doc_scalars! { Timer => timer, Vote => vote, VoteHistory => vote_history, + DesignReview => design_review, } /// Keyed maps (no order): changed and added entries are put, missing ones removed. @@ -402,12 +403,48 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result apply_indexed(doc, change, &mut Index::default()) } +/// Clamp the review settings a snapshot carries to the limits this build keeps, in place, and say +/// whether it changed them: an older or looser snapshot may hold longer radii, brand or disabled +/// lists, and the file opens with what fits — the preset, grid and the rest of each list exactly +/// as saved. An ordinary edit is refused instead (`apply_indexed`), and a peer that can't read the +/// settings at all gets them left out of what the server sends +/// (`Change::without_design_review`). +pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) -> bool { + let mut clamped_any = false; + for c in changes { + if let Change::SetDoc { prop: DocProp::DesignReview, value } = c + && let Ok(config) = value.read::("design review") + && !config.over_limits().is_empty() + { + let mut clamped = config; + clamped.radii.truncate(figcraft_doc::MAX_RADII); + clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS); + clamped.disabled.truncate(figcraft_doc::MAX_DISABLED); + if let Ok(v) = Json::of(&clamped) { + *value = v; + clamped_any = true; + } + } + } + clamped_any +} + /// Apply a document-level change, with the keyed lists' positions kept in `index` between the /// changes of one batch. Returns whether it can change which pages are listed (the library store /// page is never listed). pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Index) -> Result { match change { Change::SetDoc { prop, value } => { + // A peer's review settings stay inside the limits `design.configure` enforces, so an + // edit cannot smuggle in tens of thousands of radii, accents or rule ids for every + // check to scan. An oversized value arrives only in an old snapshot, and the snapshot + // path clamps it (`clamp_snapshot_design_review`). + if *prop == DocProp::DesignReview { + let config: figcraft_doc::DesignReview = value.read("design review")?; + if let Some((what, have, max)) = config.over_limits().first() { + return Err(Error::Invalid(format!("design review: {have} {what} pass the {max} limit `design.configure` keeps"))); + } + } if set_scalar(doc, *prop, value)? { return Ok(*prop == DocProp::Libraries); } diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index 1ba0896aa..f74108099 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -34,9 +34,15 @@ pub const COMMENTS: &str = "comments"; /// read it). pub const PACKED: &str = "packed"; +/// The word a client puts in its [`Hello::client_version`] when it reads +/// [`DocProp::DesignReview`](crate::DocProp::DesignReview): a server keeps review-setting changes +/// out of the batches, catch-up deltas and snapshots it sends to clients that don't say so +/// (older ones couldn't decode the variant at all). +pub const DESIGN_REVIEW: &str = "design-review"; + /// The `client_version` this build announces: its version, then what it reads beyond the protocol. pub fn client_version() -> String { - format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED}", env!("CARGO_PKG_VERSION")) + format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW}", env!("CARGO_PKG_VERSION")) } /// Whether `client_version` announces `word`. @@ -64,6 +70,11 @@ pub fn reads_packed(client_version: &str) -> bool { announces(client_version, PACKED) } +/// A [`Hello::client_version`] that announces [`DESIGN_REVIEW`]. +pub fn reads_design_review(client_version: &str) -> bool { + announces(client_version, DESIGN_REVIEW) +} + /// Join a file's session. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Hello { diff --git a/crates/collab/src/reconnect_tests.rs b/crates/collab/src/reconnect_tests.rs index a5998feea..af13b5042 100644 --- a/crates/collab/src/reconnect_tests.rs +++ b/crates/collab/src/reconnect_tests.rs @@ -291,6 +291,91 @@ fn random_drops_and_reconnects_converge() { assert!(snapshots > 0, "no reconnect needed a snapshot"); } +/// A session saved by a build with larger review limits restores with them clamped. Its saved +/// batches still hold the value past the limits, so a resuming client catches up with the +/// snapshot: replaying the log would hand it a change this build refuses. +#[test] +fn a_restored_session_with_clamped_settings_catches_up_by_snapshot() { + use crate::change::{Change, DocProp, Json}; + use figcraft_doc::{DesignReview, MAX_RADII}; + + let mut s = Server::new(base(), "tok", Limits::default()); + let mut a = join(&mut s); + // `b` joined but misses the review batch: it resumes from the log, which is where the old + // build's over-limit value still sits. + let mut b = join(&mut s); + let m = edit(&mut a, |d| d.design_review.grid = 8.0).unwrap(); + let out = s.receive(a.id(), m); + deliver(&mut a, &out); + b.disconnect(); + let mut state = s.state().unwrap(); + assert_eq!(state.log.len(), 1, "the review batch is in the log"); + + // An older build wrote more radii than this one keeps, in the snapshot and in the batch. + let wide = DesignReview { grid: 8.0, radii: (0..MAX_RADII + 8).map(|i| i as f64).collect(), ..Default::default() }; + let value = Json::of(&wide).unwrap(); + for c in state.snapshot.iter_mut().chain(state.log.iter_mut().flat_map(|a| a.changes.iter_mut())) { + if let Change::SetDoc { prop: DocProp::DesignReview, value: v } = c { + *v = value.clone(); + } + } + + let mut restored = Server::restore(state, "tok", Limits::default()).unwrap(); + assert_eq!(restored.document().design_review.radii.len(), MAX_RADII, "the snapshot keeps what fits"); + let ClientMsg::Hello(h) = b.reconnect(hello()) else { panic!() }; + let (id, out) = restored.join(h).unwrap(); + assert_eq!(id, b.id(), "a reconnecting client keeps its id"); + assert!( + matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })), + "a clamped session hands out the snapshot, not a batch past the limits: {out:?}" + ); + deliver(&mut b, &out); + assert_eq!(b.seq(), restored.seq()); + assert_eq!(b.document().design_review.radii.len(), MAX_RADII, "the client takes what the session has"); + // The client that already had the batch catches up with the same snapshot, so both sides + // agree on the clamped value. + let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() }; + let (_, out) = restored.join(h).unwrap(); + deliver(&mut a, &out); + assert_eq!(a.document(), b.document()); +} + +/// The same fixture inside the limits keeps resuming from the log: the snapshot catch-up above is +/// for settings this build had to change, not for review settings as such. +#[test] +fn a_restored_session_within_the_limits_resumes_from_the_log() { + use crate::change::{Change, DocProp, Json}; + use figcraft_doc::DesignReview; + + let mut s = Server::new(base(), "tok", Limits::default()); + let mut a = join(&mut s); + let mut b = join(&mut s); + let m = edit(&mut a, |d| d.design_review.grid = 8.0).unwrap(); + let out = s.receive(a.id(), m); + deliver(&mut a, &out); + b.disconnect(); + let mut state = s.state().unwrap(); + let narrow = DesignReview { grid: 8.0, radii: (0..20).map(|i| i as f64).collect(), ..Default::default() }; + let value = Json::of(&narrow).unwrap(); + for c in state.snapshot.iter_mut().chain(state.log.iter_mut().flat_map(|a| a.changes.iter_mut())) { + if let Change::SetDoc { prop: DocProp::DesignReview, value: v } = c { + *v = value.clone(); + } + } + + let mut restored = Server::restore(state, "tok", Limits::default()).unwrap(); + assert_eq!(restored.document().design_review.radii.len(), 20, "the snapshot needs no clamping"); + let ClientMsg::Hello(h) = b.reconnect(hello()) else { panic!() }; + let (_, out) = restored.join(h).unwrap(); + assert!( + matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Delta(_), .. })), + "a session that needed no clamping resumes from its log: {out:?}" + ); + deliver(&mut b, &out); + assert_eq!(b.seq(), restored.seq()); + assert_eq!(b.document().design_review.radii.len(), 20); +} + #[test] fn resume_needs_the_issued_secret() { let mut s = Server::new(base(), "tok", Limits { max_peers: 2, ..Limits::default() }); diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index 547f0f59b..eee844eb5 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -72,19 +72,24 @@ impl Replica { /// Rebuild a replica from a [`snapshot`](Self::snapshot). pub fn from_snapshot(changes: &[Change]) -> Result { - Self::from_snapshot_leaving_out(changes).map(|(r, _)| r) + Self::from_snapshot_leaving_out(changes).map(|(r, _, _)| r) } /// [`from_snapshot`](Self::from_snapshot), and how many image entries it left out: a /// snapshot saved before the image checks may hold one they refuse, and opens without it. - pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize), Error> { + /// Review settings past the current limits are clamped to them, not dropped (see + /// [`docprops::clamp_snapshot_design_review`]); the last value says whether that happened, + /// because a session whose settings had to be clamped can no longer replay its saved batches + /// for clients that resume (they hold the value past the limits). + pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize, bool), Error> { let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; let mut changes = changes.to_vec(); + let clamped = docprops::clamp_snapshot_design_review(&mut changes); let left_out = r.apply_kept(&mut changes, Change::is_image)?; if r.doc.pages.is_empty() { return Err(Error::Invalid("a snapshot needs a page".into())); } - Ok((r, left_out)) + Ok((r, left_out, clamped)) } /// Apply `changes` strictly. When they don't apply together — history written under older diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 0f11792b7..638491aaf 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -8,7 +8,8 @@ use serde::{Deserialize, Serialize}; use crate::change::{Change, Entry, Family, Prop, Target}; use crate::message::{ - Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_signals, + Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_design_review, + reads_signals, }; use crate::replica::{Mode, Replica, create_change}; use crate::{Error, Limits, docprops, same_secret}; @@ -86,6 +87,10 @@ pub struct Server { journal: Option>, /// The connected clients that read signals (cursor chat, spotlight). signals: BTreeSet, + /// The connected clients that read the design review settings (`DocProp::DesignReview`): a + /// peer that doesn't announce them can't decode the variant, so the server keeps review + /// edits out of everything it sends them. + design_review: BTreeSet, /// Who spotlights now (a newcomer is told). spotlight: Option, /// Saved history this server restored or replayed left image entries out (or may give a @@ -146,6 +151,7 @@ impl Server { limited: BTreeMap::new(), journal: None, signals: BTreeSet::new(), + design_review: BTreeSet::new(), spotlight: None, resync: false, } @@ -169,7 +175,7 @@ impl Server { /// reconnect with their ids). A log that doesn't lead up to the sequence number is dropped /// (clients then catch up with a snapshot). pub fn restore(state: SessionState, token: impl Into, limits: Limits) -> Result { - let (replica, left_out) = Replica::from_snapshot_leaving_out(&state.snapshot)?; + let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(&state.snapshot)?; let mut server = Server::new(replica.document().clone(), token, limits); server.state = replica; server.session = state.session; @@ -189,9 +195,11 @@ impl Server { // History saved before the image checks may hold image entries they refuse. The snapshot // opens without them, and a saved log putting images may give a resuming client other // bytes under a key it holds, which this state can't check: either way resuming clients - // catch up with the snapshot. + // catch up with the snapshot. The same holds for review settings this build had to clamp: + // a saved batch still carries the value past the limits, and a resuming client would + // refuse it, so the clamped snapshot is what everyone catches up with. let puts_images = state.log.iter().flat_map(|a| &a.changes).any(Change::is_image); - server.resync = left_out > 0 || puts_images; + server.resync = left_out > 0 || puts_images || review_clamped; if contiguous && state.log.last().is_none_or(|a| a.seq == state.seq) { for a in state.log { server.remember(a); @@ -333,12 +341,16 @@ impl Server { } // The log holds every batch after `floor`. let floor = self.log.front().map_or(self.seq, |a| a.seq.saturating_sub(1)); + let reads_design_review = reads_design_review(&hello.client_version); let catch_up = match resume { Some(r) if !self.resync && r.seq <= self.seq && r.seq >= floor => { CatchUp::Delta(self.log.iter().filter(|a| a.seq > r.seq).cloned().collect()) } _ => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?), }; + // A peer that doesn't read the review settings can't decode them: its catch-up carries + // everything else. + let catch_up = filter_catch_up(catch_up, reads_design_review); let (id, secret) = match resume { Some(r) => (r.client_id, *self.secrets.entry(r.client_id).or_insert(r.secret)), None => { @@ -374,9 +386,20 @@ impl Server { } else { self.signals.remove(&id); } + if reads_design_review { + self.design_review.insert(id); + } else { + self.design_review.remove(&id); + } Ok((id, outs)) } + /// Whether every connected peer reads the design review settings: then a batch goes out as + /// one message, the common case. + fn everyone_reads_design_review(&self) -> bool { + self.peers.keys().all(|id| self.design_review.contains(id)) + } + /// Whether `r` may take its client id back: it carries the secret that id was given with, or /// (after a restart, which forgets secrets) a secret for an id nobody is connected as. fn may_resume(&self, r: &Resume) -> bool { @@ -393,6 +416,7 @@ impl Server { self.acked.remove(&id); self.limited.remove(&id); self.signals.remove(&id); + self.design_review.remove(&id); if self.spotlight == Some(id) { self.spotlight = None; } @@ -430,7 +454,7 @@ impl Server { let acc = Accepted { seq: self.seq, author: from, batch_id, changes }; self.remember(acc.clone()); self.note(Journal::Accepted(acc.clone())); - vec![Outgoing::All(ServerMsg::Changes(acc))] + self.relay_changes(acc) } Err(e) => { self.note(Journal::Refused { client: from, batch_id }); @@ -482,6 +506,31 @@ impl Server { } } + /// Send an accepted batch to every connected peer. A peer that doesn't read the review + /// settings can't decode them, so it gets the same batch (its seq, batch id and the peer's + /// own accounting included) with those edits left out and everything else in order. + fn relay_changes(&self, acc: Accepted) -> Vec { + if !acc.changes.iter().any(Change::is_design_review) || self.everyone_reads_design_review() { + return vec![Outgoing::All(ServerMsg::Changes(acc))]; + } + // Every peer hears the batch, even one with nothing left for it: the batch still carries + // the next sequence number, and a peer that skipped it would reject its next ordinary + // batch as out of order. + self.peers + .keys() + .copied() + .map(|id| { + if self.design_review.contains(&id) || id == acc.author { + Outgoing::To(id, ServerMsg::Changes(acc.clone())) + } else { + let mut filtered = acc.clone(); + filtered.changes = Change::without_design_review(filtered.changes); + Outgoing::To(id, ServerMsg::Changes(filtered)) + } + }) + .collect() + } + /// Client `from` is called `name` from now on (cleaned): everyone, itself too, hears it as its /// `PeerJoined`, and newcomers' welcomes list it so. fn rename(&mut self, from: u32, name: String) -> Vec { @@ -704,3 +753,23 @@ pub fn weight(changes: &[Change]) -> usize { }) .fold(0, usize::saturating_add) } + +/// A catch-up a peer that doesn't read the design review settings can decode: the review-setting +/// edits are left out of a delta and out of a snapshot, everything else as it was. +fn filter_catch_up(cu: CatchUp, reads_design_review: bool) -> CatchUp { + if reads_design_review { + return cu; + } + match cu { + CatchUp::Delta(list) => CatchUp::Delta( + list.into_iter() + .map(|mut a| { + a.changes = Change::without_design_review(a.changes); + a + }) + .collect(), + ), + CatchUp::Snapshot(changes) => CatchUp::Snapshot(Change::without_design_review(changes)), + packed => packed, + } +} diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs index aafff946d..8979cb213 100644 --- a/crates/collab/src/server_tests.rs +++ b/crates/collab/src/server_tests.rs @@ -2,8 +2,8 @@ use figcraft_doc::{Document, Node, NodeId, NodeKind}; -use crate::change::{Change, Entry, Json, Prop}; -use crate::message::{ClientMsg, Hello, PROTOCOL, Presence, ServerMsg}; +use crate::change::{Change, DocProp, Entry, Json, Prop}; +use crate::message::{CatchUp, ClientMsg, Hello, PROTOCOL, Presence, ServerMsg, client_version, reads_design_review}; use crate::replica::Mode; use crate::{Client, Limits, NoRecompute, Outgoing, Server}; @@ -39,6 +39,22 @@ fn for_client(out: &[Outgoing], to: u32) -> Vec { .collect() } +/// A hello whose `client_version` says exactly `version` (what an older or newer build announces). +fn hello_of(version: &str) -> Hello { + Hello { client_version: version.to_string(), ..hello("tok") } +} + +/// The changes an `Accepted` relay or catch-up carries, or none. +fn accepted_changes(msgs: &[ServerMsg]) -> Vec<&Change> { + msgs.iter() + .filter_map(|m| match m { + ServerMsg::Changes(a) => Some(a.changes.iter().collect::>()), + _ => None, + }) + .flatten() + .collect() +} + fn edit(c: &mut Client, f: impl FnOnce(&mut Document)) -> ClientMsg { let mut d = c.document().clone(); f(&mut d); @@ -364,3 +380,177 @@ fn junk_batches_never_panic_and_never_corrupt_the_document() { assert!(s.document().validate().is_empty(), "{:?}", s.document().validate()); } } + +#[test] +fn the_client_version_announces_the_design_review() { + assert!(reads_design_review(&client_version())); + assert!(!reads_design_review("0.18.0 signals hosting comments packed")); +} + +/// A capable editor, a peer built before the review existed, and a mixed batch: the old peer +/// hears the same batch without the review-setting edit, the new peer hears it whole. +#[test] +fn a_review_edit_reaches_only_the_peers_that_read_it() { + let (d, _, _) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // One batch: rename the document (everyone) and set the review grid (capable peers only). + let batch = vec![ + Change::SetDoc { prop: DocProp::Name, value: Json::of("Renamed").unwrap() }, + Change::SetDoc { prop: DocProp::DesignReview, value: Json(serde_json::json!({"preset": "strict", "grid": 8.0})) }, + ]; + let out = s.receive(capable.id(), ClientMsg::Changes { base_seq: s.seq(), batch_id: 1, changes: batch }); + let for_old = for_client(&out, old.id()); + assert!(accepted_changes(&for_old).iter().all(|c| !c.is_design_review()), "the old peer's copy carries no review edit: {:?}", for_old); + assert!( + accepted_changes(&for_old).iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), + "the old peer still hears the rename: {:?}", + for_old + ); + let for_new = for_client(&out, capable.id()); + assert_eq!(accepted_changes(&for_new).len(), 2, "the capable peer hears both: {for_new:?}"); + + // A capable newcomer's catch-up (a fresh join, so a snapshot) carries the settings. + let (_, out) = s.join(hello("tok")).unwrap(); + let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) = + out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. }))) + else { + panic!("no welcome"); + }; + let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") }; + assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "{changes:?}"); + + // An old newcomer's catch-up carries none, and still has the rename. + let (_, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) = + out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. }))) + else { + panic!("no welcome"); + }; + let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") }; + assert!(changes.iter().all(|c| !c.is_design_review()), "{changes:?}"); + assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), "{changes:?}"); +} + +/// A review-only batch advances the server sequence for every peer. An older peer must still be +/// sent the accepted batch, empty as it is, or it falls a sequence behind and refuses what +/// follows. +#[test] +fn a_review_only_batch_keeps_an_older_peer_in_step() { + let (d, _, frame) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let mut capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let mut old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // Only the review settings change, so this batch has nothing for the older peer. + let msg = edit(&mut capable, |d| d.design_review.grid = 8.0); + let ClientMsg::Changes { changes, .. } = &msg else { panic!("not a batch") }; + assert!(!changes.is_empty() && changes.iter().all(Change::is_design_review), "review only: {changes:?}"); + let out = s.receive(capable.id(), msg); + assert_eq!(s.seq(), 1); + let to_old = for_client(&out, old.id()); + let empty = to_old.iter().any(|m| matches!(m, ServerMsg::Changes(a) if a.changes.is_empty())); + assert!(empty, "the older peer is told the batch happened: {to_old:?}"); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in to_old { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + + // The next ordinary edit still lands for it. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "After", 0.0, 0.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(1), "the new node is there"); +} + +/// The same batch through the other catch-up path: a peer that was away comes back with a delta, +/// and the review-only batch is there as an accepted batch with nothing in it for it, so its +/// sequence carries on and the edits after it apply. +#[test] +fn a_review_only_batch_is_an_empty_delta_for_a_peer_that_was_away() { + let (d, _, frame) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let mut capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let mut old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // One ordinary edit, so the peer's resume point sits before the review-only batch. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "Before", 0.0, 0.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), 1); + + // It drops; only the review settings change while it is away. + old.disconnect(); + let msg = edit(&mut capable, |d| d.design_review.grid = 8.0); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(s.seq(), 2); + + // It comes back: the delta holds the batch, empty, and its sequence carries on. + let ClientMsg::Hello(h) = old.reconnect(hello_of("0.18.0 signals hosting comments packed")) else { + panic!("not a hello"); + }; + let (id, out) = s.join(h).unwrap(); + assert_eq!(id, old.id()); + let welcome = out + .into_iter() + .find_map(|o| match o { + Outgoing::To(to, w @ ServerMsg::Welcome { .. }) if to == id => Some(w), + _ => None, + }) + .unwrap_or_else(|| panic!("no welcome")); + assert!( + matches!(&welcome, ServerMsg::Welcome { catch_up: CatchUp::Delta(list), .. } if list.len() == 1 && list[0].changes.is_empty()), + "{welcome:?}" + ); + old.receive(welcome, &NoRecompute).unwrap(); + assert_eq!(old.seq(), s.seq()); + + // And the next ordinary edit still applies. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "After", 0.0, 20.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(2), "both nodes are there"); +} diff --git a/crates/doc/src/design_review.rs b/crates/doc/src/design_review.rs new file mode 100644 index 000000000..9aefbbff6 --- /dev/null +++ b/crates/doc/src/design_review.rs @@ -0,0 +1,129 @@ +//! The design system a file's review follows: how strict it is, the spacing grid, the radii it +//! accepts and the brand accents it knows (`design.configure`). +//! +//! Kept in the document, so a file carries its settings for everyone who opens it, and the audit, +//! the fixer and CI all read the same values. + +use figcraft_color::Color; +use serde::{Deserialize, Serialize}; + +/// How strict `design.audit` is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum DesignPreset { + /// The rules that catch the usual AI-generated tells. + #[default] + Recommended, + /// Recommended plus the judgment calls (too many accent colours, frames without auto layout). + Strict, + /// Only the findings that keep a design usable: contrast, the type floor, gradient text and + /// clipped text. + Accessibility, +} + +impl DesignPreset { + pub const ALL: [Self; 3] = [Self::Recommended, Self::Strict, Self::Accessibility]; + + pub fn id(self) -> &'static str { + match self { + Self::Recommended => "recommended", + Self::Strict => "strict", + Self::Accessibility => "accessibility", + } + } + + pub fn from_id(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "recommended" | "default" => Some(Self::Recommended), + "strict" => Some(Self::Strict), + "accessibility" | "a11y" => Some(Self::Accessibility), + _ => None, + } + } +} + +/// The smallest and largest spacing grid a file may set. +pub const GRID_MIN: f64 = 1.0; +pub const GRID_MAX: f64 = 64.0; + +/// Most radii and brand colours a file keeps. +pub const MAX_RADII: usize = 32; +pub const MAX_BRAND_COLORS: usize = 32; + +/// Most rules a file turns off. The rule catalog is smaller than this: the cap keeps a hand-edited +/// or older file from carrying thousands of ids every review would read. +pub const MAX_DISABLED: usize = 64; + +/// A file's design review settings. The default is the recommended preset on a 4px grid with the +/// 4px radius scale and no brand palette. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct DesignReview { + pub preset: DesignPreset, + /// The spacing and radius grid in pixels (`0`: 4). A value outside [`GRID_MIN`]..=[`GRID_MAX`] + /// reads as the default. + pub grid: f64, + /// The corner radii the design uses, in pixels. Empty: any multiple of the grid from the grid + /// up, or a pill. + pub radii: Vec, + /// The brand's accent colours: they don't count as stray accents (`color.accents`). + pub brand: Vec, + /// Rule ids this file turns off. + pub disabled: Vec, +} + +impl DesignReview { + /// Whether the settings are the default ones (nothing to save). + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// The grid in pixels, with invalid values read as 4. + pub fn grid(&self) -> f64 { + if self.grid.is_finite() && (GRID_MIN..=GRID_MAX).contains(&self.grid) { self.grid } else { 4.0 } + } + + /// The lists that hold more than this build keeps, as `(what, how many, the cap)`. Sharing a + /// file with any of these is refused (`collab.share`), an arriving edit is refused + /// (`figcraft_collab`), and a saved snapshot opens with what fits instead. + pub fn over_limits(&self) -> Vec<(&'static str, usize, usize)> { + [ + ("corner radii", self.radii.len(), MAX_RADII), + ("brand colours", self.brand.len(), MAX_BRAND_COLORS), + ("disabled rules", self.disabled.len(), MAX_DISABLED), + ] + .into_iter() + .filter(|(_, have, max)| have > max) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_round_trip_by_id() { + for p in DesignPreset::ALL { + assert_eq!(DesignPreset::from_id(p.id()), Some(p)); + } + assert_eq!(DesignPreset::from_id("a11y"), Some(DesignPreset::Accessibility)); + assert_eq!(DesignPreset::from_id("loud"), None); + } + + #[test] + fn a_default_file_does_not_serialize_the_settings_and_junk_grid_reads_as_four() { + let doc = crate::Document::new("Untitled"); + let json = serde_json::to_value(&doc).unwrap(); + assert!(json.get("designReview").is_none(), "{json}"); + let mut settings = DesignReview::default(); + assert!(settings.is_default()); + settings.grid = -3.0; + assert_eq!(settings.grid(), 4.0); + settings.grid = f64::NAN; + assert_eq!(settings.grid(), 4.0); + settings.grid = 8.0; + assert_eq!(settings.grid(), 8.0); + assert!(!settings.is_default()); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 0ee52f7ad..c83c7eb85 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -14,6 +14,7 @@ mod board_mindmap; mod board_route; pub mod colors; pub mod comments; +pub mod design_review; pub mod facilitation; pub mod geometry; pub mod handoff; @@ -34,6 +35,7 @@ pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; +pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_DISABLED, MAX_RADII}; pub use facilitation::*; pub use figcraft_color as color; pub use figcraft_geom as geom; @@ -233,6 +235,9 @@ pub struct Document { /// Image adjustment presets saved in this file. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub image_presets: Vec, + /// The design system and rules this file's review follows (`design.configure`). + #[serde(default, skip_serializing_if = "DesignReview::is_default")] + pub design_review: DesignReview, /// Annotation categories (`None`: [`AnnotationCategory::defaults`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub annotation_categories: Option>, @@ -289,6 +294,7 @@ impl Document { published: None, color_profile: ColorProfile::Srgb, image_presets: Vec::new(), + design_review: DesignReview::default(), annotation_categories: None, dev_snapshots: BTreeMap::new(), timer: None, 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/sync.rs b/crates/engine/src/assets/components/sync.rs index d7781db7e..1cda4aaa3 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -521,8 +521,14 @@ pub fn keep_text_overrides(doc: &mut Document, inst: NodeId) { /// Where auto layout places and sizes a rebuilt copy `n` of main layer `orig`, keep the old /// copy's `o` values (an instance's auto layout re-flows from its own content, so they usually /// differ from the main's): unchanged layers then stay unchanged, and auto layout re-flows wherever -/// something that sizes or places layers did change. +/// something that sizes or places layers did change. Only when `o` mirrored `orig` itself: a layer +/// matched to another variant's layer (or a new one) takes its geometry from it, so the re-flow +/// starts from the new main's consistent state instead of re-applying the resize to children that +/// already hold new-main sizes (which stretched them twice). fn keep_laid_out(doc: &Document, orig: &Node, o: &Node, n: &mut Node) { + if o.source != Some(orig.id) { + return; + } if o.parent != n.parent || o.overrides.contains("size") || o.overrides.contains("position") { return; } diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index 359c58bb4..d4cba2115 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -44,6 +44,7 @@ pub const NODE_KEYS: &[&str] = &[ "fontFamily", "fontSize", "fontStyle", + "fontWeight", "fontVariations", "gridCell", "grids", @@ -435,6 +436,7 @@ fn text_props(t: &TextData, o: &mut serde_json::Map, options: &In }); insert_prop(o, options, "fontFamily", || json!(t.style.font_family)); insert_prop(o, options, "fontStyle", || json!(t.style.font_style)); + insert_prop(o, options, "fontWeight", || json!(t.style.weight())); insert_prop(o, options, "fontSize", || json!(t.style.font_size)); if !t.style.variations.is_empty() { insert_prop(o, options, "fontVariations", || json!(t.style.variations)); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 9f739969a..d7efe0b13 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -109,6 +109,7 @@ fn registry() -> &'static Registry { list.extend(crate::dev_resources::specs()); list.extend(crate::dev_measurements::specs()); list.extend(crate::distance::specs()); + list.extend(crate::design::specs()); list.extend(crate::collab::specs()); list.extend(crate::branches::specs()); list.extend(crate::plugins::specs()); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 435c3422a..5d23d6d02 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -1,7 +1,7 @@ //! Creating nodes. use figcraft_color::{ImageFilters, ImageScaleMode, Paint}; -use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, TextAutoResize, TextData, VectorNetwork}; +use figcraft_doc::{Document, Node, NodeId, NodeKind, Sizing, StrokeCap, TextAutoResize, TextData, VectorNetwork}; use figcraft_geom::Point; use serde_json::{Value, json}; @@ -99,7 +99,7 @@ pub fn specs() -> Vec { spec!( "text.create", "Text", - "{text | characters, x, y, parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontFamily, …), select? (default true)}", + "{text | characters, x?, y? (ignored inside an auto layout parent unless props.absolute is true, which keeps the transform they set), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}", true, |s, p| { create_kind(s, p, "text") } ), @@ -275,7 +275,9 @@ pub fn create(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?; let pn = doc.get(parent)?; if !pn.kind.is_container() { - return Err(bad(cmd, format!("{parent} can't contain layers"))); + let name = pn.name.trim(); + let what = if name.is_empty() { pn.kind.type_name().to_string() } else { format!("{} \"{}\"", pn.kind.type_name(), name) }; + return Err(bad(cmd, format!("{parent} ({what}) can't contain layers"))); } if base == "Section" && !doc.takes_sections(parent) { return Err(bad(cmd, "sections go on the page or in other sections")); @@ -371,6 +373,24 @@ pub fn create(s: &mut Session, p: &Value) -> Result { doc.insert(node, parent, index)?; if let Some(Value::Object(props)) = get(p, "props") { super::props::apply(cmd, doc, nid, props)?; + // An auto layout frame hugs the axes the caller left unset — the incumbent's default, and + // the difference between a card and a 100pt-tall box that silently clips its rows. + // Explicit width/height and explicit sizing keep their fixed/fill behaviour. + if doc.node(nid).is_some_and(|n| n.layout.is_some()) { + let asked = |axis: &str, keys: &[&str]| { + let long = if axis == "h" { "width" } else { "height" }; + let short = if axis == "h" { "w" } else { "h" }; + num(p, long).is_some() || props.contains_key(long) || props.contains_key(short) || keys.iter().any(|k| props.contains_key(*k)) + }; + if let Some(n) = doc.node_mut(nid) { + if !asked("h", &["sizingH", "layoutSizingHorizontal"]) { + n.child_layout.sizing_h = Sizing::Hug; + } + if !asked("v", &["sizingV", "layoutSizingVertical"]) { + n.child_layout.sizing_v = Sizing::Hug; + } + } + } } if boolean(p, "select").unwrap_or(true) { ds.selection = vec![nid]; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index cc2391ef5..84bd44779 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -72,6 +72,7 @@ fn node_find(s: &mut Session, p: &Value) -> Result { let text = filter("text")?; let component = filter("component")?; let kind = filter("type")?; + let orphaned = get(p, "orphaned").map(|v| v.as_bool().ok_or_else(|| bad(cmd, "`orphaned` must be a boolean"))).transpose()?; if let Some(kind) = &kind && !LAYER_TYPES.iter().any(|t| t.eq_ignore_ascii_case(kind)) { @@ -100,6 +101,7 @@ fn node_find(s: &mut Session, p: &Value) -> Result { || component.as_ref().is_some_and( |q| !matches!(&n.kind, NodeKind::Instance { component, .. } if doc.node(*component).is_some_and(|c| fold(&c.name).contains(q))), ) + || orphaned.is_some_and(|want| !matches!(&n.kind, NodeKind::Instance { component, .. } if doc.contains(*component) != want)) { continue; } @@ -115,7 +117,7 @@ pub fn specs() -> Vec { vec![ spec!("edit.undo", "Undo", "{}", false, |s, _| Ok(json!({"undone": s.undo()?}))), spec!("edit.redo", "Redo", "{}", false, |s, _| Ok(json!({"redone": s.redo()?}))), - spec!("edit.delete", "Delete", "{ids?}", true, delete), + spec!("edit.delete", "Delete", "{ids?} → {deleted, hidden, orphaned? (surviving instances that lost their main)}", true, delete), spec!( "edit.duplicate", "Duplicate", @@ -347,7 +349,7 @@ pub fn specs() -> Vec { spec!( "node.find", "Find layers", - "{root? (strict descendants; default current page), name?, type? (canonical layer type), text?, component? (main component name), limit? (0-10000; default 100)}: every filter must match; name, text and component are case-insensitive substrings, type is exact (any case); returns {ids, total} and does not select", + "{root? (strict descendants; default current page), name?, type? (canonical layer type), text?, component? (main component name), orphaned?: bool (instances without a main if true, with a main if false), limit? (0-10000; default 100)}: every filter must match; name, text and component are case-insensitive substrings, type is exact (any case); returns {ids, total} and does not select", false, node_find ), @@ -356,7 +358,14 @@ pub fn specs() -> Vec { "Move layer into", "{ids?, parent, index? (final position among parent's children, bottom first; default top)}", true, - reparent + |s, p| reparent(s, p, "node.reparent", false) + ), + spec!( + "layers.reparent", + "Move layer into", + "{ids (in the destination's stored child order), parent, index? (final position among parent's children, bottom first; default top)}", + true, + |s, p| reparent(s, p, "layers.reparent", true) ), spec!("node.reorder", "Reorder layer", "{id, index}", true, |s, p| { let i = req_id("node.reorder", p, "id")?; @@ -616,6 +625,26 @@ fn delete(s: &mut Session, p: &Value) -> Result { Ok(json!({"deleted": ids, "hidden": hidden})) } +/// Add only instances that still exist after the delete and instance synchronisation. +pub(crate) fn report_orphaned_instances(result: &mut Value, before: &Document, after: &Document) { + let removed: BTreeSet<_> = after + .changed_ids(before, usize::MAX) + .unwrap_or_default() + .into_iter() + .filter(|&id| !after.contains(id) && matches!(before.node(id).map(|n| &n.kind), Some(NodeKind::Component { .. }))) + .collect(); + if removed.is_empty() { + return; + } + let orphaned: Vec<_> = + after.nodes().filter(|n| matches!(&n.kind, NodeKind::Instance { component, .. } if removed.contains(component))).map(|n| n.id).collect(); + if !orphaned.is_empty() + && let Some(result) = result.as_object_mut() + { + result.insert("orphaned".into(), json!(orphaned)); + } +} + /// Layers duplicated last (Duplicate or Alt-drag) and their copies, in the same order. While the /// copies are the selection, Duplicate places the next copies as far from them as they are from /// their sources, measured then (their move and turn, not their size): so moving or turning the diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index c5ce462a4..ba284a96c 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, @@ -438,7 +440,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 +467,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/props.rs b/crates/engine/src/cmd/edit/props.rs index 5bd6710af..5d956abc3 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -268,12 +268,13 @@ pub(super) fn stroke_brush(s: &mut Session, p: &Value) -> Result { ok() } -pub(super) fn reparent(s: &mut Session, p: &Value) -> Result { - let ids = req_targets("node.reparent", s, p)?; - let parent = req_id("node.reparent", p, "parent")?; - let index = opt_index("node.reparent", p, "index")?; +pub(super) fn reparent(s: &mut Session, p: &Value, cmd: &str, keep_order: bool) -> Result { + let ids = req_targets(cmd, s, p)?; + let parent = req_id(cmd, p, "parent")?; + let index = opt_index(cmd, p, "index")?; let doc = s.doc_mut()?; - let ids = z_sorted(doc, &roots(doc, &ids)); + let roots = roots(doc, &ids); + let ids = if keep_order { roots } else { z_sorted(doc, &roots) }; // `index` is where the first moved layer ends up among the parent's children (bottom first), // counted after the move, the way `node.reorder` counts it. The layers land together, keeping // their order, under the sibling that stays put and ends up just after them (none: on top). @@ -445,20 +446,58 @@ fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Re } }; if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills && to_regions) { + let (nw, nh) = s.doc().ok().and_then(|d| d.node(id)).map_or((100.0, 100.0), |n| (n.width, n.height)); + let image_dims = s.doc().ok().and_then(|d| match &new_paint { + Some(figcraft_color::Paint { kind: figcraft_color::PaintKind::Image(img), .. }) + if img.scale_mode == figcraft_color::ImageScaleMode::Crop => + { + d.images.get(&img.image).map(|data| (f64::from(data.width), f64::from(data.height))) + } + _ => None, + }); edit_region_fills(s.doc_mut()?, id, ®ions, |list| { if list.is_empty() { list.push(figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)); } let at = idx.unwrap_or(list.len().saturating_sub(1)); let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) }; + let old = slot.clone(); edit_slot(slot); + if let Some((iw, ih)) = image_dims + && let figcraft_color::PaintKind::Image(img) = &mut slot.kind + && img.scale_mode == figcraft_color::ImageScaleMode::Crop + { + match &old.kind { + figcraft_color::PaintKind::Image(old_img) if old_img.image == img.image => { + if old_img.rotation != img.rotation { + img.crop = None; + img.crop = Some(img.placement_crop(iw, ih, nw, nh)); + } else if img.crop.is_none() { + img.crop = Some(old_img.placement_crop(iw, ih, nw, nh)); + } else if regions.len() > 1 && old_img.scale_mode == figcraft_color::ImageScaleMode::Crop { + img.crop = old_img.crop; + } + } + _ => { + if img.crop.is_none() { + img.crop = Some(img.placement_crop(iw, ih, nw, nh)); + } + } + } + } Ok(()) })?; return ok(); } + let image_dims = s.doc().ok().and_then(|d| match &new_paint { + Some(figcraft_color::Paint { kind: figcraft_color::PaintKind::Image(img), .. }) if img.scale_mode == figcraft_color::ImageScaleMode::Crop => { + d.images.get(&img.image).map(|data| (f64::from(data.width), f64::from(data.height))) + } + _ => None, + }); let doc = s.doc_mut()?; - for i in ids { - let n = doc.get_mut(i)?; + for i in &ids { + let n = doc.get_mut(*i)?; if fills { crate::cmd::lists::take_character_fills(n); } @@ -470,6 +509,28 @@ fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Re let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) }; let old = slot.clone(); edit_slot(slot); + if let Some((iw, ih)) = image_dims + && let figcraft_color::PaintKind::Image(img) = &mut slot.kind + && img.scale_mode == figcraft_color::ImageScaleMode::Crop + { + match &old.kind { + figcraft_color::PaintKind::Image(old_img) if old_img.image == img.image => { + if old_img.rotation != img.rotation { + img.crop = None; + img.crop = Some(img.placement_crop(iw, ih, n.width, n.height)); + } else if img.crop.is_none() { + img.crop = Some(old_img.placement_crop(iw, ih, n.width, n.height)); + } else if ids.len() > 1 && old_img.scale_mode == figcraft_color::ImageScaleMode::Crop { + img.crop = old_img.crop; + } + } + _ => { + if img.crop.is_none() { + img.crop = Some(img.placement_crop(iw, ih, n.width, n.height)); + } + } + } + } crate::cmd::lists::rebind_edited_paint(n, fills, at, &old); if fills { n.styles.fill = None; 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/props.rs b/crates/engine/src/cmd/props.rs index 94b681381..b9f6949f0 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -23,7 +23,7 @@ clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, paddi mainAlign (min|center|max, or the auto gaps spaceBetween|spaceAround|spaceEvenly), crossAlign (min|center|max|baseline: first text baselines, horizontal layouts), contentAlign (wrapped lines: auto = packed where crossAlign says | spaceBetween), wrap (rows of a horizontal layout, columns of a vertical one), strokesIncluded (the frame's inside stroke takes up space), reverseZ (canvas stacking: true = first on top), \ columnGap / rowGap (aliases of gap / crossGap), gridColumns, gridRows, columnTracks / rowTracks ([120 | \"1fr\" | \"auto\" | {sizing, value}]), \ gridColumn / gridRow (0-based cell anchor, null = auto), gridColumnSpan, gridRowSpan, gridAlignH / gridAlignV (a grid child's alignment in its cell: min|center|max, auto/null = the frame's), sizingH / sizingV (fixed|hug|fill), \ -absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, \ +absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, fontWeight (a number: 400 Regular, 600 Semi Bold — the nearest face the family has), \ fontSize, lineHeight (auto|px|\"150%\"), letterSpacing (px|\"2%\"), textAlign (left|center|right|justified), textAlignVertical, textAutoResize \ (widthAndHeight|height|none|truncate), textDecoration, textDecorationStyle (solid|dotted|wavy), textDecorationThickness / textDecorationOffset \ (auto|px|\"10%\" of the font size; the offset runs from the baseline down to an underline's top edge), textDecorationSkipInk (underlines break around descenders), \ 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 +509,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 1194af4eb..d24be7ef6 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -616,12 +616,22 @@ fn hides_children(n: &figcraft_doc::Node, dimmed: bool) -> bool { dimmed || !n.visible || n.hides_contents() } +fn vertical_flow(n: &figcraft_doc::Node) -> bool { + n.layout.as_ref().is_some_and(|layout| layout.mode == figcraft_doc::LayoutMode::Vertical) +} + +/// Follow a vertical flow from top to bottom; elsewhere start at the top of the stacking order. +fn panel_children(n: &figcraft_doc::Node) -> impl Iterator { + let mut children = n.children.iter(); + let forward = vertical_flow(n); + std::iter::from_fn(move || if forward { children.next() } else { children.next_back() }) +} + fn collect(doc: &Document, id: NodeId, depth: usize, dimmed: bool, locked: bool, expanded: &BTreeSet, out: &mut Vec) { let Some(n) = doc.node(id) else { return }; let dim_kids = !n.is_page() && hides_children(n, dimmed); let lock_kids = locked || n.locked; - // Layers panel lists top of the stack first. - for c in n.children.iter().rev() { + for c in panel_children(n) { let Some(cn) = doc.node(*c) else { continue }; let has_kids = !cn.children.is_empty() || matches!(cn.kind, NodeKind::BooleanOp { .. }); out.push(Row { id: *c, depth, has_kids, dimmed: dim_kids, locked_above: lock_kids }); @@ -631,10 +641,10 @@ fn collect(doc: &Document, id: NodeId, depth: usize, dimmed: bool, locked: bool, } } -/// Layers whose name contains `q` (lowercase), top of the stack first, as a flat list. +/// Layers whose name contains `q` (lowercase), in panel order as a flat list. fn matching(doc: &Document, id: NodeId, q: &str, out: &mut Vec) { let Some(n) = doc.node(id) else { return }; - for c in n.children.iter().rev() { + for c in panel_children(n) { let Some(cn) = doc.node(*c) else { continue }; let name = if cn.name.is_empty() { cn.kind.label() } else { cn.name.as_str() }; if name.to_lowercase().contains(q) { @@ -983,26 +993,29 @@ fn select_clicked(app: &mut FigApp, rows: &[Row], sel: &[NodeId], id: NodeId, m: /// Drops `moving` on `target` (`zone`: 0 into it, -1 above, 1 below), unless Dev Mode refuses /// (a drag started in the design can end after a switch to it). -fn drop_layers(app: &mut FigApp, doc: &Document, moving: &[NodeId], target: NodeId, zone: i8) { +fn drop_layers(app: &mut FigApp, doc: &Document, rows: &[Row], moving: &[NodeId], target: NodeId, zone: i8) { if crate::menus::dev_mode_refuses(app, "node.reparent") { return; } - let ids = moving.to_vec(); - match zone { - 0 => { - app.run("node.reparent", json!({"ids": ids, "parent": target})); - } - z => { - // Above in the list = higher z = after the target among siblings. - if let Some(parent) = doc.node(target).and_then(|n| n.parent) { - let idx = doc.index_in_parent(target).unwrap_or(0); - let gap = if z < 0 { idx + 1 } else { idx }; - // `index` is the final position: the dragged layers below the gap leave it. - let below = doc.node(parent).map_or(0, |p| p.children.iter().take(gap).filter(|c| ids.contains(c)).count()); - app.run("node.reparent", json!({"ids": ids, "parent": parent, "index": gap - below})); - } - } + let parent = if zone == 0 { Some(target) } else { doc.node(target).and_then(|n| n.parent) }; + let Some(parent) = parent.and_then(|id| doc.node(id)) else { return }; + let forward = vertical_flow(parent); + let mut pending: BTreeSet<_> = moving.iter().copied().collect(); + let index = (zone != 0).then(|| { + let idx = doc.index_in_parent(target).unwrap_or(0); + // Above means before the target in a vertical flow, after it in a stack. + let gap = if (zone < 0) != forward { idx + 1 } else { idx }; + // `index` is the final position: the dragged layers below the gap leave it. + let below = parent.children.iter().take(gap).filter(|c| pending.contains(c)).count(); + gap - below + }); + // Keep the displayed order of the moved rows. A selection can include a layer outside + // the current list (for example, under a collapsed row); include it after the listed rows. + let mut ids: Vec<_> = rows.iter().map(|row| row.id).chain(moving.iter().copied()).filter(|id| pending.remove(id)).collect(); + if !forward { + ids.reverse(); } + 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 @@ -1411,7 +1424,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { d.remove::<(NodeId, f64)>(Id::unique("layer_drag_hold")); }); if let (Some(_), Some((target, zone))) = (dragging, drop) { - drop_layers(app, &doc, &moving, target, zone); + drop_layers(app, &doc, &rows, &moving, target, zone); } } if let Ok(ds) = app.session.ds_mut() { diff --git a/crates/ui-egui/src/panels/right/menu.rs b/crates/ui-egui/src/panels/right/menu.rs index 8f6e7f7fd..9cfdc0e3e 100644 --- a/crates/ui-egui/src/panels/right/menu.rs +++ b/crates/ui-egui/src/panels/right/menu.rs @@ -116,12 +116,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 +207,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/paste_image_tests.rs b/crates/ui-egui/src/paste_image_tests.rs index 122227501..008ebcb61 100644 --- a/crates/ui-egui/src/paste_image_tests.rs +++ b/crates/ui-egui/src/paste_image_tests.rs @@ -28,6 +28,7 @@ const HELD: [Held; 3] = [Held::Ours, Held::Text, Held::Image]; #[derive(Default)] struct Clip { + file: Option, text: Option, image: Option<(u32, u32, Vec)>, png: Option>, @@ -46,6 +47,9 @@ impl Services for Desktop { fn clipboard_get_image(&mut self) -> Option<(u32, u32, Vec)> { self.0.borrow().image.clone() } + fn clipboard_image_file(&mut self) -> Option { + self.0.borrow().file.clone() + } fn clipboard_get_png(&mut self) -> Option> { self.0.borrow().png.clone() } @@ -193,6 +197,18 @@ fn cmd_v_pastes_an_image_copied_elsewhere() { assert_eq!(w.named("Pasted image"), 2, "and again"); } +#[test] +fn a_copied_image_file_pastes_its_contents_even_when_the_clipboard_offers_a_filename_and_icon() { + let mut w = Win::new(); + let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/app-icon/figcraft-48.png"); + *w.clip.borrow_mut() = Clip { file: Some(file.clone()), text: Some("figcraft-48.png".into()), image: Some((2, 2, vec![255; 16])), png: None }; + w.cmd_v(); + let doc = w.app.session.doc().unwrap(); + assert_eq!(w.named("Pasted image"), 1); + let stored = doc.images.values().next().expect("an image on the canvas"); + assert_eq!(stored.bytes.as_slice(), std::fs::read(file).unwrap()); +} + #[test] fn cmd_v_fills_a_selected_oval_without_adding_a_layer() { let mut w = Win::new(); 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/popover.rs b/crates/ui-egui/src/popover.rs index 82886227d..f105f2662 100644 --- a/crates/ui-egui/src/popover.rs +++ b/crates/ui-egui/src/popover.rs @@ -124,6 +124,11 @@ impl Popover { } } + /// The id of the header's drag handle: a drag there moves the panel, not a value in it. + pub fn header_drag_id(&self) -> Id { + self.id.with("drag") + } + /// `width` points wide instead of [`WIDTH`]. pub fn width(mut self, width: f32) -> Self { self.width = width.max(1.0); diff --git a/crates/ui-egui/src/popup_width_tests.rs b/crates/ui-egui/src/popup_width_tests.rs index 6c34f7f46..bcc6890fe 100644 --- a/crates/ui-egui/src/popup_width_tests.rs +++ b/crates/ui-egui/src/popup_width_tests.rs @@ -102,3 +102,54 @@ fn right_panel_dropdown_menus_fit_the_panel() { assert!(menu.width() <= app.ui.right_width, "menu {menu:?} fits the {} px panel", app.ui.right_width); assert!(menu.max.x <= SCREEN.x && menu.min.x >= panel_left - 8.0, "menu {menu:?} inside the window, under the panel"); } + +#[test] +fn preferences_language_menu_stays_aligned_to_dropdown() { + use egui::accesskit::Role; + + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1920.0, 1080.0)); + for mirrored in [false, true] { + let mut app = FigApp::new(Session::new(), Box::new(NoServices)); + app.ui.preferences = true; + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut t = 0.0; + let mut frame = |app: &mut FigApp, events: Vec| { + t += 1.0 / 60.0; + let raw = RawInput { screen_rect: Some(screen), time: Some(t), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| app.ui(ui)); + out.textures_delta.clear(); + out + }; + for _ in 0..3 { + frame(&mut app, vec![]); + } + // Set after viewport_setup's first-frame language init so it is not overwritten. + app.ui.mirrored = mirrored; + for _ in 0..2 { + frame(&mut app, vec![]); + } + assert_eq!(ctx.global_style().right_to_left, mirrored); + let out = frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; + let combo = + nodes.into_iter().map(|(_, n)| n).find(|n| n.role() == Role::ComboBox && n.value() == Some("System")).expect("the Language dropdown"); + let b = combo.bounds().expect("Language dropdown bounds"); + let dropdown = Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)); + let at = dropdown.center(); + frame(&mut app, press(at, true)); + frame(&mut app, press(at, false)); + for _ in 0..3 { + frame(&mut app, vec![]); + } + let shown = menus(&ctx); + let [menu] = shown.as_slice() else { panic!("one Language menu open (mirrored={mirrored}): {shown:?}") }; + assert!(menu.height() <= 360.0, "Language menu should scroll instead of spanning screen (mirrored={mirrored}): {menu:?}"); + assert!(screen.contains_rect(*menu), "Language menu should fit inside screen (mirrored={mirrored}): {menu:?}"); + if mirrored { + assert!((menu.max.x - dropdown.max.x).abs() <= 2.0, "RTL Language menu {menu:?} should align to dropdown right {dropdown:?}"); + } else { + assert!((menu.min.x - dropdown.min.x).abs() <= 2.0, "LTR Language menu {menu:?} should align to dropdown left {dropdown:?}"); + } + } +} 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/services.rs b/crates/ui-egui/src/services.rs index b5a997a85..50b2ffdf9 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -47,6 +47,10 @@ pub trait Services { fn clipboard_get_image(&mut self) -> Option<(u32, u32, Vec)> { None } + /// One supported raster image copied as a file, separate from its clipboard icon or filename. + fn clipboard_image_file(&mut self) -> Option { + None + } fn clipboard_get_png(&mut self) -> Option> { None } 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/widgets/colorpicker.rs b/crates/ui-egui/src/widgets/colorpicker.rs index 662e4ba24..3ab7cb8fb 100644 --- a/crates/ui-egui/src/widgets/colorpicker.rs +++ b/crates/ui-egui/src/widgets/colorpicker.rs @@ -760,21 +760,6 @@ fn blend_row(ui: &mut Ui, app: &mut FigApp, target: &PickerTarget, paint: &mut P }); } -/// The layer and fill index to crop on the canvas (`image.crop`) when Crop is chosen for `target`: -/// one layer's image fill as the Fill section shows it (a text's characters' shared fills -/// included). Strokes, several layers at once and the regions selected in vector edit mode have -/// no crop mode, so for them Crop only sets the paint's mode. -pub(crate) fn crop_on_canvas(app: &FigApp, target: &PickerTarget) -> Option<(NodeId, usize)> { - let PickerTarget::Paint { fills: true, index, ids } = target else { return None }; - let [id] = ids[..] else { return None }; - if figcraft_engine::vectoredit::selected_region_fills(&app.session, id).is_some() { - return None; - } - let doc = app.session.doc().ok()?; - let shown = figcraft_engine::cmd::lists::character_fills(doc.node(id)?)?; - matches!(shown.get(*index)?.kind, PaintKind::Image(_)).then_some((id, *index)) -} - /// The image paint's scale mode, rotation, colour profile, presets and filter sliders. fn image_controls(app: &mut FigApp, ui: &mut Ui, target: &PickerTarget, paint: &mut Paint, mut img: ImagePaint, t: &Tokens) { ui.horizontal(|ui| { @@ -788,25 +773,18 @@ fn image_controls(app: &mut FigApp, ui: &mut Ui, target: &PickerTarget, paint: & (tr("Tile"), ImageScaleMode::Tile), ] { if crate::right::menu_item(ui, l, "") { - match crop_on_canvas(app, target).filter(|_| m == ImageScaleMode::Crop) { - // Crop for a layer's own image fill is Crop image (#2150): the picture keeps - // its place and crop mode takes the canvas, closing the picker, so its - // handles crop it as they do when crop mode comes from the menu. - Some((id, index)) => { - app.run("image.crop", json!({"ids": [id], "index": index})); - } - None => { - img.scale_mode = m; - paint.kind = PaintKind::Image(img.clone()); - write(app, target, paint, false); - } - } + img.scale_mode = m; + paint.kind = PaintKind::Image(img.clone()); + write(app, target, paint, false); ui.close(); } } }); if icons::button(ui, Icon::Rotate, 24.0, false, tr("Rotate 90°")).clicked() { img.rotation = (img.rotation + 1) % 4; + if img.scale_mode == ImageScaleMode::Crop { + img.crop = None; + } paint.kind = PaintKind::Image(img.clone()); write(app, target, paint, false); } diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index a3e9ccae5..0e121656c 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -148,7 +148,14 @@ As built: A diff gives new keys only to the children that need them (the longest run of old keys that is still increasing keeps its keys) and re-spaces a parent whose keys would grow past 48 characters. - **Document-level objects covered now**: the file name, the current page, document colours, the - colour profile, image presets, annotation categories and library data (whole values); styles, + colour profile, image presets, annotation categories, the design review settings + (`DocProp::DesignReview`, sent only to clients whose `client_version` announces + `design-review`; a client that doesn't gets every batch, catch-up delta and snapshot without + them, and an accepted batch still reaches it when nothing of it is left, so sequence numbers + never skip; a snapshot saved with longer lists opens clamped to the limits `design.configure` + keeps, and a session restored from such a snapshot catches every resuming client up with that + snapshot, since its saved batches still hold the value past the limits; a host refuses to share + a file whose settings are already past the limits) and library data (whole values); styles, comment threads, variable collections and variables (one entry per id plus the order of ids; the whole list when ids aren't unique); dev-mode snapshots (per layer); images (per content hash, the encoded bytes as base64; as an entry applies the claim is checked: every key is diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index 0443708c0..3ba24ab7f 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -1,6 +1,8 @@ # Dev Mode parity > **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; 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 Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) +> +> **2026-11-24 patch:** vector code export uses a self-contained SVG asset instead of inventing a box around its bounds: web markup embeds the node-local SVG as a data URI inside a node-sized wrapper with the SVG's painted bounds, and CSS, SwiftUI and ArkUI no longer draw a rectangle from the path stroke (#2270). **Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect to the code components of a repository (with their imports, also inside generated layer trees), @@ -10,6 +12,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Feature | Status | Notes | |---|---|---| +| 2026-11-24 | patch | Vector code export drew a path's stroke as a box border around its bounds (#2270). CSS, HTML, React, Vue, Leptos and Tailwind no longer invent that border or a rectangular fill; the markup targets embed node-local SVG data URIs, so nested vectors need no external export and URL fragments cannot break them. A node-sized wrapper keeps layout, rotation and opacity, while the inner image uses the SVG's painted bounds with visible overflow. The SVG owns shadows and layer blur, so wrapper CSS does not apply them twice; standalone CSS and ordinary shapes keep theirs. SwiftUI and ArkUI no longer put a rectangle stroke around their vector image either. Ordinary box and ellipse strokes are unchanged. Tests: `dev::codegen::tests::vector_code_uses_its_svg_asset_not_a_box_border`, `dev::codegen::tests::vector_assets_are_self_contained_and_leptos_literals_escape`, `dev::codegen::tests::vector_asset_keeps_stroke_overflow_inside_a_node_sized_wrapper`, `dev::codegen::tests::vector_markup_does_not_duplicate_svg_effects`; real CLI checks nested assets, rotation/opacity, 24→28 stroke bounds and single-application effects | | 2026-11-12 | patch | SwiftUI, Compose and Flutter code export kept one colour per layer (the bottom visible solid, or a gradient's first stop) and dropped every other fill (#2271). Now each writes every visible solid and gradient fill of a frame, group, rectangle or ellipse, in paint order, and a gradient as a gradient. SwiftUI chains `.background(...)` with the top fill first, since each one goes behind the ones before it (a rectangle or ellipse fills with the bottom paint and lays a copy of the shape over it for each paint above). Compose chains `Modifier.background(...)` with the bottom fill first, since each one draws over the ones before it (a linear gradient snaps to eight directions, radial and angular ones sit at the box's centre). Flutter keeps the top fill in the `Container` and wraps each fill under it in a `DecoratedBox`, the bottom fill outermost and the drop shadow on the outermost box. A layer with one solid fill gives the same code as before; a lone gradient is now a gradient, not its first stop's colour. Still not written: image and pattern fills in the native targets, ArkUI (one background and one gradient per component, so a stack needs extra nodes) and text with several fills. The incumbent's iOS and Android output wasn't measured: the order follows how each platform paints. Percentages and hours unchanged | | 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why | @@ -30,6 +33,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Date | Change | Summary | |---|---|---| +| 2026-11-24 | patch | Vector code export embeds a self-contained SVG asset, not a rectangle made from the path's stroke (#2270). Percentages and hours unchanged. | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Code: CSS, iOS (SwiftUI), Android (Compose), Flutter. | | 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged | | 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6636db615..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 @@ -39,7 +39,7 @@ and prototype interactions are still unchecked there. | BMP | — | yes | | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). On macOS, pasting a single supported raster file copied in Finder places the file’s image on the canvas. Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | ## Export @@ -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/mcp.md b/docs/mcp.md index 15d1b2846..9e4c0b2ec 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -410,6 +410,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. | @@ -449,7 +451,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. @@ -1886,11 +1888,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, diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 13fda27c1..27a492d33 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,10 +1,10 @@ # Parity checklist -> **Generated:** 2026-10-21 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-11-25 by `cargo xtask parity`. Do not edit by hand. -FigCraft commands registered for the incumbent's main menu and toolbar (575 commands in the engine). +FigCraft commands registered for the incumbent's main menu and toolbar (652 commands in the engine). -**212 / 212 menu items (100.0%)** +**215 / 215 menu items (100.0%)** Every catalog item has a command. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6ede4cfc3..ec0a575ce 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-24 · **Change:** minor (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; 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 (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: @@ -214,6 +214,9 @@ 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-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`. | diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index f32928930..fe6a6c3bf 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -17,6 +17,15 @@ set -u APPDIR="$(dirname "$(readlink -f "$0")")" DESK_ID=ai.storyteller.figcraft +refresh_icon_cache() { + if command -v gtk-update-icon-cache >/dev/null 2>&1; then + # A per-user hicolor directory need not have index.theme; -t permits that. + gtk-update-icon-cache -f -t "$1" >/dev/null 2>&1 || true + elif command -v gtk4-update-icon-cache >/dev/null 2>&1; then + gtk4-update-icon-cache -f -t "$1" >/dev/null 2>&1 || true + fi +} + integrate() { case "${FIGCRAFT_NO_DESKTOP_INTEGRATION:-}" in 1 | true | yes) return 0 ;; @@ -63,12 +72,26 @@ integrate() { src_icons="$APPDIR/usr/share/icons/hicolor" [ -d "$src_icons" ] || return 0 icons="$data/icons/hicolor" - (cd "$src_icons" && find . -type f) | while IFS= read -r rel; do - mkdir -p "$icons/$(dirname "$rel")" 2>/dev/null || continue - if ! cmp -s "$src_icons/$rel" "$icons/$rel"; then - cp "$src_icons/$rel" "$icons/$rel" 2>/dev/null || true + (cd "$src_icons" && find . -type f) | { + changed=false + while IFS= read -r rel; do + mkdir -p "$icons/$(dirname "$rel")" 2>/dev/null || continue + if ! cmp -s "$src_icons/$rel" "$icons/$rel"; then + if cp "$src_icons/$rel" "$icons/$rel" 2>/dev/null; then + changed=true + fi + fi + done + cache="$icons/icon-theme.cache" + if [ "$changed" = false ] && [ -f "$cache" ]; then + if [ -n "$(find "$icons" -type f -name "$DESK_ID.*" -newer "$cache" 2>/dev/null)" ]; then + changed=true + fi fi - done + if [ "$changed" = true ]; then + refresh_icon_cache "$icons" + fi + } } # The CLI is headless and its stdout may be a protocol stream (`cli mcp`): no diff --git a/packaging/linux/ai.storyteller.figcraft.desktop b/packaging/linux/ai.storyteller.figcraft.desktop index c739d6a47..4e7fab698 100644 --- a/packaging/linux/ai.storyteller.figcraft.desktop +++ b/packaging/linux/ai.storyteller.figcraft.desktop @@ -1,8 +1,11 @@ [Desktop Entry] Type=Application Name=FigCraft +Name[ru]=FigCraft GenericName=Interface Design Tool +GenericName[ru]=Инструмент для дизайна интерфейсов Comment=Design and prototype user interfaces +Comment[ru]=Дизайн и прототипирование пользовательских интерфейсов Exec=figcraft %U TryExec=figcraft Icon=ai.storyteller.figcraft @@ -11,4 +14,5 @@ StartupNotify=true StartupWMClass=ai.storyteller.figcraft Categories=Graphics;2DGraphics;VectorGraphics;X-Design; Keywords=design;interface;ui;ux;prototype;wireframe;mockup;vector;layout;components; +Keywords[ru]=дизайн;интерфейс;ui;ux;прототип;вайрфрейм;макет;вектор;вёрстка;верстка;компоненты; MimeType=application/x-figcraft;image/svg+xml;image/png;image/jpeg;application/x-sketch;x-scheme-handler/figcraft; diff --git a/packaging/linux/ai.storyteller.figcraft.metainfo.xml.in b/packaging/linux/ai.storyteller.figcraft.metainfo.xml.in index 43618eb18..1c4391230 100644 --- a/packaging/linux/ai.storyteller.figcraft.metainfo.xml.in +++ b/packaging/linux/ai.storyteller.figcraft.metainfo.xml.in @@ -1,4 +1,5 @@ + @@ -7,6 +8,7 @@ MIT OR Apache-2.0 FigCraft Design and prototype user interfaces + Дизайн и прототипирование пользовательских интерфейсов Learning Machines LLC @@ -16,13 +18,25 @@ on an infinite canvas with frames, auto layout and constraints, build reusable components and variants, and link screens into clickable prototypes.

+

+ FigCraft — открытый нативный инструмент для дизайна и прототипирования интерфейсов. + Размещайте экраны на бесконечном холсте с помощью Frame, автолейаута и ограничений, + создавайте повторно используемые компоненты и варианты и связывайте экраны в + кликабельные прототипы. +

  • Frames, vector shapes, text and images on an infinite canvas
  • +
  • Frame, векторные фигуры, текст и изображения на бесконечном холсте
  • Auto layout and constraints for responsive designs
  • +
  • Автолейаут и ограничения для адаптивных макетов
  • Components, variants, shared styles and variables
  • +
  • Компоненты, варианты, общие стили и переменные
  • Prototyping with interactions and transitions, and a presentation mode
  • +
  • Прототипирование со взаимодействиями и переходами, режим презентации
  • Inspect panel with measurements and code snippets; SVG and PNG export
  • +
  • Панель «Инспектор» с измерениями и фрагментами кода; экспорт в SVG и PNG
  • Every action is a command, scriptable from a CLI, a JSON control channel and an MCP server
  • +
  • Каждое действие — это команда, которую можно вызывать из CLI, через управляющий канал JSON и сервер MCP
ai.storyteller.figcraft.desktop @@ -40,9 +54,13 @@ interface design + дизайн интерфейсов prototyping + прототипирование ui + ui wireframe + вайрфрейм #9fd3ff diff --git a/packaging/linux/ai.storyteller.figcraft.mime.xml b/packaging/linux/ai.storyteller.figcraft.mime.xml index b2190b216..0c57fdaf7 100644 --- a/packaging/linux/ai.storyteller.figcraft.mime.xml +++ b/packaging/linux/ai.storyteller.figcraft.mime.xml @@ -5,12 +5,14 @@ FigCraft document + Документ FigCraft Sketch document + Документ Sketch diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index 75625480b..b4861afaa 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -29,6 +29,27 @@ export APPIMAGE export HOME="$TMP/home" export XDG_DATA_HOME="$HOME/.local/share" mkdir -p "$HOME" +unset FIGCRAFT_NO_DESKTOP_INTEGRATION + +# Record icon-cache refreshes without requiring a desktop session or GTK install. +export REAL_CACHE_UPDATER +REAL_CACHE_UPDATER="$(command -v gtk-update-icon-cache || true)" +mkdir -p "$TMP/tools" +cat >"$TMP/tools/gtk-update-icon-cache" <<'EOF' +#!/bin/sh +printf '%s\n' "$*" >>"$CACHE_CALLS" +if [ "${CACHE_UPDATER_FAIL:-0}" = 1 ]; then + exit 1 +fi +if [ -n "$REAL_CACHE_UPDATER" ]; then + "$REAL_CACHE_UPDATER" "$@" +else + for dir do :; done + : >"$dir/icon-theme.cache" +fi +EOF +chmod +x "$TMP/tools/gtk-update-icon-cache" +export PATH="$TMP/tools:$PATH" CACHE_CALLS="$TMP/cache-calls" fail() { echo "FAIL: $*" >&2 @@ -53,10 +74,16 @@ if command -v desktop-file-validate >/dev/null; then desktop-file-validate "$DESKTOP" || fail "generated desktop entry is invalid" fi -# 3. Icons landed under the name the .desktop entry references. +# 3. Icons landed under the name the .desktop entry references and refreshed the cache. for f in "16x16/apps/$APP_ID.png" "256x256/apps/$APP_ID.png" "scalable/apps/$APP_ID.svg"; do [[ -f "$XDG_DATA_HOME/icons/hicolor/$f" ]] || fail "icon missing: $f" done +[[ -f "$CACHE_CALLS" ]] || fail "installed icons did not refresh the icon cache" +[[ "$(wc -l <"$CACHE_CALLS")" -eq 1 ]] || fail "icon cache refreshed more than once" +grep -Fxq -- "-f -t $XDG_DATA_HOME/icons/hicolor" "$CACHE_CALLS" || fail "wrong icon cache arguments" +if [[ -n "$REAL_CACHE_UPDATER" ]]; then + [[ -f "$XDG_DATA_HOME/icons/hicolor/icon-theme.cache" ]] || fail "GTK did not build the icon cache" +fi # 4. Idempotent: a second launch must not rewrite anything (inode unchanged). before="$(stat -c %i "$DESKTOP")" @@ -64,6 +91,7 @@ out="$("$APPDIR/AppRun")" || fail "second launch exited non-zero" [[ "$out" = "stub: " ]] || fail "second launch output: $out" after="$(stat -c %i "$DESKTOP")" [[ "$before" = "$after" ]] || fail "desktop entry rewritten although unchanged" +[[ "$(wc -l <"$CACHE_CALLS")" -eq 1 ]] || fail "unchanged icons refreshed the cache" # 5. Moving the AppImage refreshes Exec. mv "$APPIMAGE" "$TMP/moved.AppImage" @@ -110,4 +138,46 @@ out="$("$APPDIR/AppRun" cli)" || fail "bare cli launch exited non-zero" out="$("$APPDIR/AppRun" file.figcraft cli)" || fail "app launch with a later cli argument exited non-zero" [[ "$out" = "stub: file.figcraft cli" ]] || fail "later cli argument hijacked the launch: $out" +# 11. Pre-existing stale Hicolor cache is rebuilt even when icon bytes are unchanged, +# and a subsequent launch does not rebuild again. +rm -rf "$XDG_DATA_HOME" "$CACHE_CALLS" +"$APPDIR/AppRun" >/dev/null || fail "setup launch for stale-cache test exited non-zero" +touch -t 202001010000 "$XDG_DATA_HOME/icons/hicolor/icon-theme.cache" +: >"$CACHE_CALLS" +"$APPDIR/AppRun" >/dev/null || fail "stale-cache repair launch exited non-zero" +[[ "$(wc -l <"$CACHE_CALLS")" -eq 1 ]] || fail "stale icon-theme.cache was not refreshed" +grep -Fxq -- "-f -t $XDG_DATA_HOME/icons/hicolor" "$CACHE_CALLS" || fail "wrong stale-cache refresh arguments" +"$APPDIR/AppRun" >/dev/null || fail "post-repair launch exited non-zero" +[[ "$(wc -l <"$CACHE_CALLS")" -eq 1 ]] || fail "repaired icon-theme.cache refreshed again" + +# 12. A failing icon-cache updater never blocks the launch. +rm -rf "$XDG_DATA_HOME" "$CACHE_CALLS" +out="$(CACHE_UPDATER_FAIL=1 "$APPDIR/AppRun" ok)" || fail "failing icon-cache updater blocked launch" +[[ "$out" = "stub: ok" ]] || fail "failing icon-cache updater altered launch output: $out" + +# 13. GTK 4-only fallback: when gtk-update-icon-cache is unavailable, both AppRun +# and postinst.sh invoke gtk4-update-icon-cache with the expected arguments. +GTK4_BIN="$TMP/gtk4-only" +GTK4_CALLS="$TMP/gtk4-calls" +mkdir -p "$GTK4_BIN" +for cmd in dirname readlink mkdir sed cmp rm mv find cp; do + ln -s "$(command -v "$cmd")" "$GTK4_BIN/$cmd" +done +cat >"$GTK4_BIN/gtk4-update-icon-cache" <<'EOF' +#!/bin/sh +printf 'gtk4-update-icon-cache %s\n' "$*" >>"$GTK4_CALLS" +EOF +chmod +x "$GTK4_BIN/gtk4-update-icon-cache" + +rm -rf "$XDG_DATA_HOME" "$GTK4_CALLS" +out="$(PATH="$GTK4_BIN" GTK4_CALLS="$GTK4_CALLS" "$APPDIR/AppRun" gtk4)" || fail "GTK 4-only AppRun launch failed" +[[ "$out" = "stub: gtk4" ]] || fail "GTK 4-only AppRun altered launch output: $out" +[[ "$(wc -l <"$GTK4_CALLS")" -eq 1 ]] || fail "GTK 4-only AppRun did not invoke gtk4-update-icon-cache once" +grep -Fxq -- "gtk4-update-icon-cache -f -t $XDG_DATA_HOME/icons/hicolor" "$GTK4_CALLS" || fail "wrong GTK 4 AppRun arguments" + +: >"$GTK4_CALLS" +PATH="$GTK4_BIN" GTK4_CALLS="$GTK4_CALLS" "$HERE/postinst.sh" || fail "GTK 4-only postinst.sh failed" +[[ "$(wc -l <"$GTK4_CALLS")" -eq 1 ]] || fail "GTK 4-only postinst.sh did not invoke gtk4-update-icon-cache once" +grep -Fxq -- "gtk4-update-icon-cache -q -t -f /usr/share/icons/hicolor" "$GTK4_CALLS" || fail "wrong GTK 4 postinst.sh arguments" + echo "AppRun desktop integration ok" diff --git a/packaging/linux/postinst.sh b/packaging/linux/postinst.sh index 775e4df91..567d63c27 100755 --- a/packaging/linux/postinst.sh +++ b/packaging/linux/postinst.sh @@ -9,5 +9,7 @@ if command -v update-mime-database >/dev/null 2>&1; then fi if command -v gtk-update-icon-cache >/dev/null 2>&1; then gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true +elif command -v gtk4-update-icon-cache >/dev/null 2>&1; then + gtk4-update-icon-cache -q -t -f /usr/share/icons/hicolor || true fi exit 0