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

# Conflicts:
#	docs/ui-parity.md
This commit is contained in:
bflatastic committed 2026-11-27 14:38:04 +07:00
commit bb02b6ff09
104 files changed
+9925 -286

No files matched your search

+1
View File
@@ -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 |
+6
View File
@@ -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<PathBuf> {
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<Vec<u8>> {
let board = objc2_app_kit::NSPasteboard::generalPasteboard();
let png = board.dataForType(&objc2_foundation::NSString::from_str(MACOS_PASTEBOARD_PNG))?;
+10
View File
@@ -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::<Vec<_>>().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))?,
+20 -6
View File
@@ -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<HubIn>, stop: &AtomicBool, open: &Arc<AtomicUsize>, 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<HubIn>, 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;
+54 -10
View File
@@ -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<B: Backend>(listener: TcpListener, backend: B, limits: NetLimits, local: Option<Local>) -> io::Result<Hosting> {
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<Admission, String> {
Err("no".into())
}
fn open(&mut self, _file: &str) -> Result<Server, String> {
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}"
);
}
}
}
+1 -6
View File
@@ -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);
+33
View File
@@ -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.
+18
View File
@@ -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<Self>) -> Vec<Self> {
changes.into_iter().filter(|c| !c.is_design_review()).collect()
}
}
impl Entry {
+60 -1
View File
@@ -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::<Vec<_>>(), "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();
+37
View File
@@ -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<bool, Error>
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<Change>) -> bool {
let mut clamped_any = false;
for c in changes {
if let Change::SetDoc { prop: DocProp::DesignReview, value } = c
&& let Ok(config) = value.read::<figcraft_doc::DesignReview>("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<bool, Error> {
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);
}
+12 -1
View File
@@ -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 {
+85
View File
@@ -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() });
+8 -3
View File
@@ -72,19 +72,24 @@ impl Replica {
/// Rebuild a replica from a [`snapshot`](Self::snapshot).
pub fn from_snapshot(changes: &[Change]) -> Result<Replica, Error> {
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
+74 -5
View File
@@ -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<Vec<Journal>>,
/// The connected clients that read signals (cursor chat, spotlight).
signals: BTreeSet<u32>,
/// 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<u32>,
/// Who spotlights now (a newcomer is told).
spotlight: Option<u32>,
/// 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<String>, limits: Limits) -> Result<Server, Error> {
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<Outgoing> {
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<Outgoing> {
@@ -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,
}
}
+192 -2
View File
@@ -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<ServerMsg> {
.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::<Vec<_>>()),
_ => 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");
}
+129
View File
@@ -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<Self> {
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<f64>,
/// The brand's accent colours: they don't count as stray accents (`color.accents`).
pub brand: Vec<Color>,
/// Rule ids this file turns off.
pub disabled: Vec<String>,
}
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());
}
}
+6
View File
@@ -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<ImagePreset>,
/// 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<Vec<AnnotationCategory>>,
@@ -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,
+9
View File
@@ -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<String, BTreeMap<String, String>>,
/// 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
+7 -1
View File
@@ -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;
}
+2
View File
@@ -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<String, Value>, 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));
+1
View File
@@ -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());
+23 -3
View File
@@ -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<CommandSpec> {
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<Value> {
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<Value> {
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];
+32 -3
View File
@@ -72,6 +72,7 @@ fn node_find(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
|| 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<CommandSpec> {
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<CommandSpec> {
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<CommandSpec> {
"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<Value> {
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
+105 -7
View File
@@ -127,6 +127,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
// 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<Value> {
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<Value> {
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<String, Value> =
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<Value> {
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 {
+68 -7
View File
@@ -268,12 +268,13 @@ pub(super) fn stroke_brush(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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, &regions, |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;
+2 -3
View File
@@ -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<String>) -> Result<Value> {
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<String>) -> Result<Value> {
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);
+1 -1
View File
@@ -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), \
+204
View File
@@ -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"), "<Button />\n");
}
#[test]
fn a_link_names_its_source_and_translates_variant_values() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button state={State} />",
"source": "src/ui/button.tsx", "values": {"State": {"Hover": "hovered"}}, "notes": "Primary action"}),
);
let instance = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert!(code(&mut s, instance, "react").contains(r#"state="hovered""#), "{}", code(&mut s, instance, "react"));
// A value without a mapping keeps the design's name.
let plain = idv(&ex(&mut s, "instance.create", json!({"component": set})));
assert!(code(&mut s, plain, "react").contains(r#"state="Default""#));
}
#[test]
fn a_source_outside_the_repository_is_refused() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let c = card(&mut s);
for source in ["../up.tsx", "/etc/passwd", "a\\b.tsx", "a/../../b.tsx"] {
let e = s.execute("codeConnect.set", &json!({"id": c, "source": source})).unwrap_err();
assert!(e.to_string().contains("source"), "{source}: {e}");
}
assert!(s.execute("codeConnect.set", &json!({"id": c, "values": 3})).is_err());
assert!(s.execute("codeConnect.set", &json!({"id": c, "source": "src/card.tsx"})).is_ok());
}
#[test]
fn the_new_fields_survive_a_trip_through_the_file() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "template": "<Button />", "source": "src/b.tsx", "values": {"State": {"Hover": "h"}}, "notes": "n"}),
);
let text = ex(&mut s, "codeConnect.export", json!({}))["text"].as_str().unwrap().to_string();
let mut other = Session::new();
ex(&mut other, "file.new", json!({}));
let (set2, _) = button(&mut other);
assert_eq!(ex(&mut other, "codeConnect.import", json!({"json": text}))["linked"], 1);
let link = &other.doc().unwrap().node(set2).unwrap().code_links[0];
assert_eq!((link.source.as_str(), link.notes.as_str()), ("src/b.tsx", "n"));
assert_eq!(link.values["State"]["Hover"], "h");
}
#[test]
fn a_file_from_before_stays_as_it_was() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
let v = ex(&mut s, "codeConnect.export", json!({}));
let parsed: Value = serde_json::from_str(v["text"].as_str().unwrap()).unwrap();
let keys: Vec<&String> = parsed["links"][0].as_object().unwrap().keys().collect();
assert_eq!(keys, ["component", "importPath", "language", "name", "template"], "no new keys unless they're used");
}
#[test]
fn listing_answers_what_an_agent_asks() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-list-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/button.tsx"), "").unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
let c = card(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button />", "source": "src/button.tsx"}),
);
let v = ex(&mut s, "codeConnect.list", json!({"root": dir}));
assert_eq!((v["mapped"].as_u64(), v["unmapped"].as_u64()), (Some(1), Some(1)));
let b = v["components"].as_array().unwrap().iter().find(|e| e["id"] == json!(set)).unwrap();
assert_eq!(b["links"][0]["import"], r#"import { Button } from "@/ui/button";"#);
assert_eq!(b["links"][0]["sourceFound"], true);
assert!(b["links"][0]["snippet"].as_str().unwrap().contains("<Button"));
assert!(b["properties"].as_array().unwrap().iter().any(|p| p["type"] == "variant"));
let only = ex(&mut s, "codeConnect.list", json!({"unmapped": true}));
assert_eq!(only["components"][0]["id"], json!(c));
// A layer leads to the component it uses, a frame to those it holds.
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert_eq!(ex(&mut s, "codeConnect.list", json!({"ids": [i]}))["components"][0]["id"], json!(set));
ex(&mut s, "codeConnect.set", json!({"id": set, "source": "src/gone.tsx"}));
assert_eq!(ex(&mut s, "codeConnect.list", json!({"root": dir, "ids": [set]}))["components"][0]["links"][0]["sourceFound"], false);
}
#[test]
fn exporting_keeps_what_other_designs_put_in_the_file() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-others-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("figcraft.connect.json");
std::fs::write(&path, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Other","language":"react","name":"Other","template":"<Other />"},{"component":"Button","language":"react","name":"Old","template":"<Old />"}]}"#).unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
ex(&mut s, "codeConnect.export", json!({"path": path}));
let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
let names: Vec<&str> = v["links"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Button", "Other"], "this design's link wins, the other design's stays");
assert_eq!(v["project"]["name"], "shop", "keys the command doesn't own stay");
}
#[test]
fn listing_refuses_a_malformed_target_rather_than_reading_the_selection() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "select.set", json!({"ids": [set]}));
for p in [json!({"id": "not-an-id"}), json!({"ids": [set, "nope"]}), json!({"ids": "1"}), json!({"ids": [999_999]})] {
assert!(s.execute("codeConnect.list", &p).is_err(), "{p}");
}
}
/// A set called `name` with a variant `prop=value` for each of `values`. Returns (set, variants).
fn set_of(s: &mut Session, name: &str, prop: &str, values: &[&str]) -> (NodeId, Vec<NodeId>) {
let variants: Vec<NodeId> = values
.iter()
.enumerate()
.map(|(k, v)| {
let f = idv(&ex(s, "frame.create", json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 40, "name": format!("{prop}={v}")})));
idv(&ex(s, "component.create", json!({"ids": [f]})))
})
.collect();
let set = idv(&ex(s, "component.combineVariants", json!({"ids": variants.clone()})));
ex(s, "node.set", json!({"id": set, "props": {"name": name}}));
(set, variants)
}
#[test]
fn a_condition_reads_the_designs_value_not_its_name_in_code() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, variants) = set_of(&mut s, "Toggle", "State", &["On", "Off"]);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Toggle", "template": "{State ? \"enabled\" : \"disabled\"} {State}"}));
let off = idv(&ex(&mut s, "instance.create", json!({"component": variants[1]})));
assert!(code(&mut s, off, "react").starts_with("disabled"), "{}", code(&mut s, off, "react"));
// `inactive` reads as true, but the condition is about the design's Off.
ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Off": "inactive"}}}));
let out = code(&mut s, off, "react");
assert!(out.starts_with("disabled") && out.contains("inactive"), "{out}");
}
#[test]
fn a_mapping_keyed_by_a_name_it_cant_use_is_reported() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
let r = ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "template": "<Button state={State} />", "values": {"state": {"Hover": "hovered"}}}),
);
assert!(r.to_string().contains("\"state\""), "the lowercase key does nothing, so it's named: {r}");
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert!(code(&mut s, i, "react").contains(r#"state="Hover""#));
let r = ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Hover": "hovered"}}}));
assert!(!r.to_string().contains("\"State\""), "{r}");
}
#[test]
fn an_import_with_malformed_values_keeps_the_link_there() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />", "values": {"State": {"Hover": "h"}}}));
let links = json!([{"component": "Button", "language": "react", "name": "Other", "template": "<Other />", "values": {"State": {"Hover": 7}}}]);
let r = ex(&mut s, "codeConnect.import", json!({"json": {"version": 1, "links": links}}));
assert_eq!(r["linked"], 0, "{r}");
assert!(r["warnings"][0].as_str().unwrap().contains("values"), "{r}");
let link = &s.doc().unwrap().node(set).unwrap().code_links[0];
assert_eq!((link.name.as_str(), link.values["State"]["Hover"].as_str()), ("Button", "h"));
}
#[test]
fn exporting_over_a_file_it_cant_read_is_refused() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-unread-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
let big = vec![b' '; 4 * 1024 * 1024 + 1];
for (name, bytes) in [("broken.json", b"{\"links\": [".to_vec()), ("list.json", b"[]".to_vec()), ("big.json", big)] {
let path = dir.join(name);
std::fs::write(&path, &bytes).unwrap();
assert!(s.execute("codeConnect.export", &json!({"path": path})).is_err(), "{name}");
assert_eq!(std::fs::read(&path).unwrap(), bytes, "{name} is left as it was");
}
// A file that isn't there yet is written.
let new = dir.join("figcraft.connect.json");
let _ = std::fs::remove_file(&new);
ex(&mut s, "codeConnect.export", json!({"path": new}));
assert!(new.exists());
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1417,3 +1417,50 @@ fn a_failing_create_set_leaves_no_components_behind() {
assert_eq!(snapshot(&s), before);
assert_eq!(s.selection(), selection);
}
/// One variant of a tab bar: an auto layout root holding an "Inner" fill frame with an absolute
/// stretched "BG" and `tabs` flow children. Returns the component.
fn tabs_variant(s: &mut Session, name: &str, x: f64, root_w: f64, tabs: usize) -> NodeId {
let root = idv(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": root_w, "height": 100, "name": name})));
ex(s, "node.set", json!({"id": root, "props": {"layout": "horizontal", "padding": 10, "mainAlign": "center"}}));
let inner_w = root_w - 20.0;
let inner = idv(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": inner_w, "height": 80, "parent": root, "name": "Inner"})));
ex(s, "node.set", json!({"id": inner, "props": {"layout": "horizontal", "sizingH": "fill", "sizingV": "fixed", "gap": 0, "padding": 0}}));
let bg = idv(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": inner_w, "height": 80, "parent": inner, "props": {"name": "BG"}})));
ex(s, "node.set", json!({"id": bg, "props": {"absolute": true, "constraints": {"horizontal": "leftRight", "vertical": "topBottom"}}}));
for t in 0..tabs {
ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 60, "height": 80, "parent": inner, "props": {"name": format!("Tab{t}")}}));
}
idv(&ex(s, "component.create", json!({"ids": [root]})))
}
/// (root, inner, bg) widths and the bg's left edge of an instance of a [`tabs_variant`].
fn tabs_geometry(s: &Session, inst: NodeId) -> (f64, f64, f64, f64) {
let inner = kids(s, inst).into_iter().find(|c| node(s, *c).name == "Inner").unwrap();
let bg = kids(s, inner).into_iter().find(|c| node(s, *c).name == "BG").unwrap();
let [.., x, _] = node(s, bg).transform.as_coeffs();
(node(s, inst).width, node(s, inner).width, node(s, bg).width, x)
}
#[test]
fn switching_variants_re_lays_out_stretched_children_like_a_fresh_instance() {
let mut s = Session::new();
let narrow = tabs_variant(&mut s, "Tabs=2", 0.0, 200.0, 2);
let wide = tabs_variant(&mut s, "Tabs=4", 300.0, 400.0, 4);
let set = idv(&ex(&mut s, "component.combineVariants", json!({"ids": [narrow, wide]})));
let i = idv(&ex(&mut s, "instance.create", json!({"component": set, "x": 0, "y": 300})));
assert_eq!(component_of(&s, i), narrow, "the top-left variant is the default");
// Growing: switching to the wider variant lays out like an instance made from it directly.
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Tabs": "4"}}));
let direct = idv(&ex(&mut s, "instance.create", json!({"component": wide, "x": 500, "y": 300})));
assert_eq!(tabs_geometry(&s, i), tabs_geometry(&s, direct), "switched matches a fresh wide instance");
let (_, inner, bg, x) = tabs_geometry(&s, i);
assert_eq!((bg, x), (inner, 0.0), "the stretched background exactly fits its frame");
// Shrinking back: same, the other way.
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Tabs": "2"}}));
let direct = idv(&ex(&mut s, "instance.create", json!({"component": narrow, "x": 500, "y": 500})));
assert_eq!(tabs_geometry(&s, i), tabs_geometry(&s, direct), "switched matches a fresh narrow instance");
let (_, inner, bg, x) = tabs_geometry(&s, i);
assert_eq!((bg, x), (inner, 0.0), "the stretched background exactly fits its frame");
healthy(&s);
}
File diff suppressed because it is too large. Load diff
+334
View File
@@ -0,0 +1,334 @@
//! `design.fix`: repair the findings `design.audit` marks fixable, as one undo step.
//!
//! Every repair is the safe, unambiguous one the audit already suggested: spacing snapped to the
//! 4px grid, radii to the scale, heavy headings to Semi Bold, italic and negative tracking removed,
//! glows taken out, shadow colours neutralised and strong borders thinned. Content rules (copy,
//! naming) and gradients are left alone: those need a decision, not arithmetic.
use std::collections::{BTreeMap, BTreeSet};
use figcraft_color::{Color, PaintKind};
use figcraft_doc::{DesignPreset, Document, EffectKind, LayoutMode, LetterSpacing, Node, NodeId, NodeKind, TextData, TextStyle};
use serde_json::{Value, json};
use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color};
/// Fix what `roots` made fixable among `filter`'s rules. With `exact_ids`, only findings on those
/// layers are repaired, not findings on their descendants. The walk stops at `max_nodes` nodes.
pub(crate) fn run(
doc: &mut Document,
roots: &[NodeId],
anchor: Option<NodeId>,
anchor_path: &str,
scope: &str,
preset: Option<DesignPreset>,
filter: Option<&BTreeSet<String>>,
exact_ids: Option<&[NodeId]>,
max_nodes: usize,
dry_run: bool,
) -> Value {
let settings = Settings::new(doc, preset);
let before = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes);
// A truncated walk would repair only the visited prefix and stay silent about the rest: the
// caller would leave with a "fixed" file that never was whole. Say so instead of guessing.
if before.truncated {
return json!({
"scope": scope,
"dryRun": dry_run,
"changed": 0,
"skipped": 0,
"truncated": true,
"byRule": {},
"before": tally(&before, &settings),
"after": tally(&before, &settings),
});
}
let targets: Vec<(NodeId, &'static str)> = before
.findings
.iter()
.filter(|f| f.fixable && settings.enabled(f.rule))
.filter(|f| filter.is_none_or(|set| set.contains(f.rule)))
.filter(|f| exact_ids.is_none_or(|ids| ids.contains(&f.node)))
.map(|f| (f.node, f.rule))
.collect();
let mut by_rule: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut changed = 0usize;
let mut skipped = 0usize;
if dry_run {
changed = targets.len();
for (_, rule) in &targets {
*by_rule.entry(*rule).or_default() += 1;
}
} else {
for (id, rule) in &targets {
match apply(doc, *id, rule, &settings) {
Some(true) => {
changed += 1;
*by_rule.entry(*rule).or_default() += 1;
}
_ => skipped += 1,
}
}
}
let after = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes);
json!({
"scope": scope,
"dryRun": dry_run,
"changed": changed,
"skipped": skipped,
"truncated": false,
"byRule": by_rule,
"before": tally(&before, &settings),
"after": tally(&after, &settings),
})
}
fn tally(report: &Report, settings: &Settings) -> Value {
let shown: Vec<&super::audit::Finding> = report.findings.iter().filter(|f| settings.enabled(f.rule)).collect();
let mut counts = [0usize; 3];
for f in &shown {
counts[f.severity.index()] += 1;
}
let score = (100.0 - shown.iter().map(|f| f.severity.penalty()).sum::<f64>()).clamp(0.0, 100.0).round();
json!({
"score": score,
"counts": {"high": counts[2], "medium": counts[1], "low": counts[0]},
"nodes": report.nodes,
"findings": shown.len(),
})
}
/// Apply one finding's repair. `None` when the layer is gone or the repair does not apply to it;
/// `Some(false)` when it applied to nothing (a no-op the caller counts as skipped).
fn apply(doc: &mut Document, id: NodeId, rule: &str, settings: &Settings) -> Option<bool> {
if rule == "color.contrast" {
return apply_contrast(doc, id);
}
let n = doc.node_mut(id)?;
match rule {
"spacing.off-grid" => apply_spacing(n, settings),
"radius.off-scale" => {
if ["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) {
return Some(false);
}
apply_radius(n, settings)
}
"type.weight" | "type.italic" | "type.negative-tracking" => {
if text_styled(n) || ["fontSize", "fontStyle", "fontWeight", "letterSpacing"].iter().any(|k| n.bound.contains_key(*k)) {
return Some(false);
}
match rule {
"type.weight" => apply_text(n, cap_weight),
"type.italic" => apply_text(n, unitalic),
_ => apply_text(n, zero_tracking),
}
}
"color.glow" | "color.colored-shadow" => {
if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) {
return Some(false);
}
if rule == "color.glow" { apply_glow(n) } else { apply_neutral_shadows(n) }
}
"color.border-opacity" => {
if n.styles.stroke.is_some() || n.bound.keys().any(|k| k.starts_with("strokes/")) {
return Some(false);
}
apply_border(n)
}
_ => Some(false),
}
}
/// A text layer whose type comes from a text style (the whole layer or one run).
fn text_styled(n: &Node) -> bool {
match &n.kind {
NodeKind::Text(t) => n.styles.text.is_some() || t.style.style_id.is_some() || t.runs.iter().any(|r| r.style.style_id.is_some()),
_ => false,
}
}
/// Darken (or lighten, on a dark backdrop) the text colour until it reaches the WCAG ratio. The
/// hue is kept as far as the blend allows; when even black or white cannot reach the ratio, the
/// text is left as it is and counted as skipped.
fn apply_contrast(doc: &mut Document, id: NodeId) -> Option<bool> {
let n = doc.node(id)?;
let NodeKind::Text(t) = &n.kind else { return Some(false) };
if n.styles.fill.is_some() || n.bound.keys().any(|k| k.starts_with("fills/")) {
return Some(false);
}
let fg = text_color(n, t)?;
let bg = backdrop(doc, n)?;
let size = t.style.font_size;
let large = size >= 24.0 || (size >= 18.0 && t.style.weight() >= 700);
let need = if large { 3.0 } else { 4.5 };
if fg.contrast(bg) >= need {
return Some(false);
}
let fixed = accessible(fg, bg, need);
if fixed.contrast(bg) < need {
return Some(false);
}
let n = doc.node_mut(id)?;
let NodeKind::Text(t) = &mut n.kind else { return Some(false) };
let paints = match &mut t.style.fills {
Some(fills) => fills,
None => &mut n.fills,
};
let paint = paints.iter_mut().rev().find(|p| p.visible && matches!(&p.kind, PaintKind::Solid { .. }))?;
paint.opacity = 1.0;
if let PaintKind::Solid { color } = &mut paint.kind {
*color = fixed.with_alpha(fg.a);
Some(true)
} else {
Some(false)
}
}
/// The closest shade of `fg` towards black (light backdrop) or white (dark backdrop) that meets
/// `need` against `bg`, by bisection.
fn accessible(fg: Color, bg: Color, need: f32) -> Color {
let target = if bg.luminance() > 0.5 { Color::BLACK } else { Color::WHITE };
let (mut lo, mut hi) = (0.0f32, 1.0f32);
let mut best = target;
for _ in 0..24 {
let t = (lo + hi) / 2.0;
let c = Color::new(fg.r + (target.r - fg.r) * t, fg.g + (target.g - fg.g) * t, fg.b + (target.b - fg.b) * t, 1.0);
if c.contrast(bg) >= need {
best = c;
hi = t;
} else {
lo = t;
}
}
best
}
fn apply_spacing(n: &mut Node, settings: &Settings) -> Option<bool> {
// Any spacing binding owns the whole layout value: fixing one field next to a token would
// leave a mixed layout and is not what the audit promised.
if [
"gap",
"columnGap",
"rowGap",
"crossGap",
"padding",
"paddingHorizontal",
"paddingVertical",
"paddingTop",
"paddingRight",
"paddingBottom",
"paddingLeft",
]
.iter()
.any(|k| n.bound.contains_key(*k))
{
return Some(false);
}
let al = n.layout.as_mut()?;
let mut changed = false;
if al.mode != LayoutMode::Grid {
let gap = settings.snap(al.gap);
if (gap - al.gap).abs() > 1e-6 {
al.gap = gap;
changed = true;
}
if al.wrap {
let cross = settings.snap(al.cross_gap);
if (cross - al.cross_gap).abs() > 1e-6 {
al.cross_gap = cross;
changed = true;
}
}
}
for side in &mut al.padding {
let value = settings.snap(*side);
if (value - *side).abs() > 1e-6 {
*side = value;
changed = true;
}
}
Some(changed)
}
fn apply_radius(n: &mut Node, settings: &Settings) -> Option<bool> {
let (w, h) = (n.width, n.height);
let pill = w.min(h);
let mut changed = false;
for r in &mut n.corners.radii {
if *r > 0.01 && !settings.radius_ok(*r, w, h) {
*r = if pill > 0.0 && (*r - pill / 2.0).abs() <= 1.0 { pill / 2.0 } else { settings.snap_radius(*r) };
changed = true;
}
}
Some(changed)
}
/// Run `f` over a text layer's base style and its runs; true when any style changed.
fn apply_text(n: &mut Node, f: fn(&mut TextStyle) -> bool) -> Option<bool> {
let NodeKind::Text(t) = &mut n.kind else { return Some(false) };
let TextData { style, runs, .. } = t;
let mut changed = f(style);
for run in runs {
changed |= f(&mut run.style);
}
Some(changed)
}
fn cap_weight(s: &mut TextStyle) -> bool {
if s.font_size >= 20.0 && s.weight() > 600 {
s.set_font_style("Semi Bold");
true
} else {
false
}
}
fn unitalic(s: &mut TextStyle) -> bool {
if !s.italic() {
return false;
}
let words: Vec<&str> = s.font_style.split_whitespace().filter(|w| !w.eq_ignore_ascii_case("italic")).collect();
let name = if words.is_empty() { "Regular".to_string() } else { words.join(" ") };
s.set_font_style(name);
true
}
fn zero_tracking(s: &mut TextStyle) -> bool {
let px = s.letter_spacing.resolve(s.font_size);
if s.font_size > 0.0 && s.font_size < 24.0 && px.is_finite() && px < -0.01 {
s.letter_spacing = LetterSpacing::Percent(0.0);
true
} else {
false
}
}
fn apply_glow(n: &mut Node) -> Option<bool> {
let before = n.effects.len();
n.effects.retain(|e| !is_glow(e));
Some(n.effects.len() != before)
}
fn apply_neutral_shadows(n: &mut Node) -> Option<bool> {
let mut changed = false;
for e in &mut n.effects {
if let EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) = &mut e.kind
&& is_colored_shadow(s)
{
s.color = Color::new(0.0, 0.0, 0.0, s.color.a);
changed = true;
}
}
Some(changed)
}
fn apply_border(n: &mut Node) -> Option<bool> {
let mut changed = false;
for p in &mut n.strokes {
if p.visible && p.opacity > 0.08 {
p.opacity = 0.08;
changed = true;
}
}
Some(changed)
}
+476
View File
@@ -0,0 +1,476 @@
//! Design review: deterministic checks for the usual AI-generated interface tells.
//!
//! `design.audit` reads a selection, a page or the whole document and reports what a designer
//! would fix first — spacing off the 4px grid, radii outside the scale, too many type sizes,
//! gradient text, glows, low-contrast text, emoji labels. It changes nothing. `design.fix` (the
//! planned follow-up) repairs the findings marked `fixable`.
//!
//! The rules are our own reading of the public "unslop" checklist (CC BY 4.0, heydamir/unslop):
//! only the ideas, no text or assets from it.
mod audit;
mod fix;
mod rules;
#[cfg(test)]
mod tests;
use std::collections::{BTreeMap, BTreeSet};
use figcraft_doc::{CollectionId, DesignPreset, DesignReview, Document, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII, ModeId, NodeId};
use serde_json::{Value, json};
use crate::cmd::CommandSpec;
use crate::params;
use crate::{EngineError, Result, Session, bad, spec};
use rules::{RULES, Severity, presets_of, rule};
pub fn specs() -> Vec<CommandSpec> {
vec![
spec!(
"design.audit",
"Check design",
"{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them), limit?: 1000-1000000 (nodes before the report says truncated; default 50000)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, limit, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated, unchecked: [{rule, reason, layers?}]} reads the design and reports the AI-slop tells; changes nothing (unchecked names the rules the run could not check: truncated, or a measure cap)",
false,
audit_cmd
),
spec!(
"design.fix",
"Fix design",
"{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), limit?: 1000-1000000 (nodes the walk looks at; default 50000), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone",
true,
fix_cmd
),
spec!(
"design.assert",
"Assert design",
"{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000), allowSkipped?: bool (default false; passes a gate naming a rule the file disables or its preset excludes — never a truncated audit or a measure cap)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit could not check a rule it asked for (truncated at the node limit it ran with, past a measure cap, or skipped by the file's settings: what it did not reach is unchecked, so narrow the scope, filter the rules or raise `limit`); read-only, for CI",
false,
assert_cmd
),
spec!(
"design.configure",
"Configure design review",
"{preset?: recommended|strict|accessibility, grid?: 1-64 (px, default 4), radii?: [px] (empty: the grid scale and a pill), brand?: [colour] (accent colours the file owns), disabled?: [rule ids] (rules off in this file), reset?: bool} → {preset, grid, radii, brand, disabled} changes the file's design review settings in one undo step; audit, fix and assert use them from then on",
true,
configure_cmd
),
spec!(
"design.rules",
"List design rules",
"{} → {rules: [{id, severity, fixable, description, presets}], presets: [{id, description}]}",
false,
|_, _| Ok(json!({
"rules": RULES.iter().map(|r| json!({
"id": r.id,
"severity": r.severity.id(),
"fixable": r.fixable,
"description": r.description,
"presets": presets_of(r.id),
})).collect::<Vec<_>>(),
"presets": DesignPreset::ALL.iter().map(|p| json!({
"id": p.id(),
"description": preset_description(*p),
})).collect::<Vec<_>>(),
}))
),
]
}
fn audit_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let (label, roots, anchor, path) = scope_of(s, "design.audit", p)?;
let min = severity_arg("design.audit", p)?;
let filter = filter_arg("design.audit", p)?;
let preset = preset_arg("design.audit", p)?;
let modes = modes_arg("design.audit", p, s.doc()?)?;
let limit = limit_arg("design.audit", p)?;
Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes, limit))
}
fn fix_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let (label, roots, anchor, path) = scope_of(s, "design.fix", p)?;
let filter = filter_arg("design.fix", p)?;
let preset = preset_arg("design.fix", p)?;
let exact = params::boolean(p, "exact").unwrap_or(false);
let exact_ids = if exact { ids_arg("design.fix", p)? } else { None };
let limit = limit_arg("design.fix", p)?;
let dry = params::boolean(p, "dryRun").unwrap_or(false);
// A dry run or a fix that changes nothing must not mark the file unsaved or add an undo step:
// work on a copy and put it back only when it differs.
let mut doc = s.doc()?.clone();
let result = fix::run(&mut doc, &roots, anchor, &path, &label, preset, filter.as_ref(), exact_ids.as_deref(), limit, dry);
if !dry && s.doc()? != &doc {
*s.doc_mut()? = doc;
}
Ok(result)
}
/// `design.assert`: a read-only gate for CI. Returns the score when the design passes; an error
/// that names the counts when it does not.
fn assert_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let (label, roots, anchor, path) = scope_of(s, "design.assert", p)?;
let filter = filter_arg("design.assert", p)?;
let fail_on = severity_named("design.assert", p, "failOn", Severity::High)?;
let preset = preset_arg("design.assert", p)?;
let modes = modes_arg("design.assert", p, s.doc()?)?;
let min_score = match params::get(p, "minScore") {
None => 0.0,
Some(v) => match params::f64_of(v) {
Some(v) if (0.0..=100.0).contains(&v) => v,
_ => return Err(bad("design.assert", "`minScore` must be a number between 0 and 100")),
},
};
// The score covers the whole review (as the window shows it); only findings at or above
// `failOn` fail the gate.
let limit = limit_arg("design.assert", p)?;
let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes, limit);
let failing: Vec<&Value> = report["findings"]
.as_array()
.map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect())
.unwrap_or_default();
let score = report["score"].as_f64().unwrap_or(0.0);
// A truncated audit checked only the first nodes of the scope: what it did not reach is
// unchecked, so it can never prove a design passes (a white-on-white label past the cap
// would sail through as score 100).
if report["truncated"].as_bool() == Some(true) {
let nodes = report["nodes"].as_u64().unwrap_or(0);
return Err(EngineError::Other(format!(
"design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or raise `limit`, then assert again"
)));
}
// A gate naming a rule the file disabled or its preset leaves out is asking for a check the
// run does not do: refused, unless the caller passes `allowSkipped` to accept exactly that —
// it does not waive a truncated audit or a measure cap, which stay unchecked evidence.
let allow_skipped = params::boolean(p, "allowSkipped").unwrap_or(false);
let skipped: Vec<&str> = report["unchecked"]
.as_array()
.map(|v| {
v.iter()
.filter(|e| matches!(e["reason"].as_str(), Some("disabled") | Some("preset")))
.filter_map(|e| e["rule"].as_str())
.filter(|rule| filter.as_ref().is_none_or(|set| set.contains(*rule)))
.collect()
})
.unwrap_or_default();
if !skipped.is_empty() && !allow_skipped {
return Err(EngineError::Other(format!(
"design review failed: the file's settings skip {} (disabled by the file, or not in the preset it checks with), so a gate naming it checked nothing for it; check the file's design.configure, gate with a preset that includes it, or pass allowSkipped to accept the skip",
skipped.join(", ")
)));
}
// What the audit reported as unchecked, restricted to the rules this gate asked for. The
// audit names each rule it could not check (`limit` truncation is handled above with its own
// advice), so a cap added there fails this gate without a list here to keep in step.
let unchecked: Vec<&str> = report["unchecked"]
.as_array()
.map(|v| {
v.iter()
.filter(|e| e["reason"].as_str() == Some("measure-cap"))
.filter_map(|e| e["rule"].as_str())
.filter(|rule| filter.as_ref().is_none_or(|set| set.contains(*rule)))
.collect()
})
.unwrap_or_default();
if !unchecked.is_empty() {
return Err(EngineError::Other(format!(
"design review failed: the audit did not measure all of {} on this scope (past the per-run measure cap), so what it skipped is unchecked; audit a smaller scope, then assert again",
unchecked.join(", ")
)));
}
if !failing.is_empty() || score < min_score {
let mut by_rule: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
for f in &failing {
if let Some(rule) = f["rule"].as_str() {
*by_rule.entry(rule).or_default() += 1;
}
}
let rules: Vec<String> = by_rule.iter().take(4).map(|(rule, count)| format!("{rule} ×{count}")).collect();
let detail = if rules.is_empty() { String::new() } else { format!(" ({})", rules.join(", ")) };
return Err(EngineError::Other(format!(
"design review failed: score {score:.0}, {} finding(s) at {} or above{detail}",
failing.len(),
fail_on.id()
)));
}
Ok(json!({"ok": true, "score": score, "counts": report["counts"]}))
}
fn severity_named(cmd: &str, p: &Value, key: &str, default: Severity) -> Result<Severity> {
match params::string(p, key).map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) {
None => Ok(default),
Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`{key}` must be low, medium or high, not `{s}`"))),
}
}
/// The `limit` parameter: how many nodes one audit walk may look at before the report says
/// `truncated`. Default 50,000; a CI gate over a huge file may raise it, never past the hard cap.
fn limit_arg(cmd: &str, p: &Value) -> Result<usize> {
let Some(v) = params::get(p, "limit") else { return Ok(audit::MAX_NODES) };
let Some(n) = params::f64_of(v) else { return Err(bad(cmd, "`limit` must be a whole number of nodes between 1,000 and 1,000,000")) };
if !n.is_finite() || n.fract() != 0.0 || !(1_000.0..=(audit::MAX_LIMIT as f64)).contains(&n) {
return Err(bad(cmd, "`limit` must be a whole number of nodes between 1,000 and 1,000,000"));
}
Ok(n as usize)
}
fn preset_arg(cmd: &str, p: &Value) -> Result<Option<DesignPreset>> {
match params::string(p, "preset").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) {
None => Ok(None),
Some(s) => {
DesignPreset::from_id(&s).map(Some).ok_or_else(|| bad(cmd, format!("`preset` must be recommended, strict or accessibility, not `{s}`")))
}
}
}
fn preset_description(preset: DesignPreset) -> &'static str {
match preset {
DesignPreset::Recommended => "The usual AI-generated tells",
DesignPreset::Strict => "Recommended plus accent colours and frames without auto layout",
DesignPreset::Accessibility => "Contrast, the type floor, gradient text and clipped text only",
}
}
/// The variable modes a run resolves colours in: `{collection: mode}`, by id or by name.
fn modes_arg(cmd: &str, p: &Value, doc: &Document) -> Result<BTreeMap<CollectionId, ModeId>> {
let Some(v) = params::get(p, "modes") else { return Ok(BTreeMap::new()) };
let Value::Object(map) = v else { return Err(bad(cmd, "`modes` must be an object of collection → mode")) };
if map.len() > 64 {
return Err(bad(cmd, "at most 64 collections in `modes`"));
}
let mut out = BTreeMap::new();
for (collection_key, mode_value) in map {
let Some(mode_key) = mode_value.as_str().map(str::trim).filter(|s| !s.is_empty()) else {
return Err(bad(cmd, "`modes` values must be mode ids or names"));
};
let Some(collection) = doc.variables.collection(collection_key.trim()) else {
return Err(bad(cmd, format!("unknown collection `{collection_key}`")));
};
let Some(mode) = collection.find_mode(mode_key) else {
return Err(bad(cmd, format!("unknown mode `{mode_key}` in `{}`", collection.name)));
};
out.insert(collection.id.clone(), mode.id.clone());
}
Ok(out)
}
/// `design.configure`: change the file's design system and rules in one undo step.
fn configure_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let mut config = if params::boolean(p, "reset").unwrap_or(false) { DesignReview::default() } else { s.doc()?.design_review.clone() };
if let Some(preset) = preset_arg("design.configure", p)? {
config.preset = preset;
}
if let Some(v) = params::get(p, "grid") {
let grid = params::f64_of(v)
.filter(|g| g.is_finite() && (GRID_MIN..=GRID_MAX).contains(g))
.ok_or_else(|| bad("design.configure", format!("`grid` must be a number from {GRID_MIN} to {GRID_MAX}")))?;
config.grid = grid;
}
if let Some(v) = params::get(p, "radii") {
let Value::Array(items) = v else { return Err(bad("design.configure", "`radii` must be an array of numbers")) };
if items.len() > MAX_RADII {
return Err(bad("design.configure", format!("at most {MAX_RADII} radii")));
}
let mut radii = Vec::new();
for item in items {
let r = params::f64_of(item)
.filter(|r| r.is_finite() && (0.0..=999.0).contains(r))
.ok_or_else(|| bad("design.configure", "each radius must be a number from 0 to 999"))?;
radii.push((r * 100.0).round() / 100.0);
}
radii.sort_by(f64::total_cmp);
radii.dedup_by(|a, b| (*a - *b).abs() <= 1e-6);
config.radii = radii;
}
if let Some(v) = params::get(p, "brand") {
let Value::Array(items) = v else { return Err(bad("design.configure", "`brand` must be an array of colours")) };
if items.len() > MAX_BRAND_COLORS {
return Err(bad("design.configure", format!("at most {MAX_BRAND_COLORS} brand colours")));
}
let mut brand = Vec::new();
for item in items {
let color = params::color_of(item).ok_or_else(|| bad("design.configure", "each brand colour must be a colour"))?;
if color.a > 0.05 {
brand.push(color);
}
}
config.brand = brand;
}
if let Some(v) = params::get(p, "disabled") {
let Value::Array(items) = v else { return Err(bad("design.configure", "`disabled` must be an array of rule ids")) };
let mut ids = BTreeSet::new();
for item in items {
let Some(id) = item.as_str().map(str::trim) else {
return Err(bad("design.configure", "`disabled` must be an array of rule ids"));
};
if rule(id).is_none() {
return Err(bad("design.configure", format!("unknown rule `{id}` (run design.rules for the list)")));
}
ids.insert(id.to_string());
}
config.disabled = ids.into_iter().collect();
}
if s.doc()?.design_review == config {
return Ok(settings_json(&config));
}
let doc = s.doc_mut()?;
doc.design_review = config;
Ok(settings_json(&doc.design_review))
}
fn settings_json(config: &DesignReview) -> Value {
let brand: Vec<String> = config
.brand
.iter()
.map(|c| {
let rgba = c.to_rgba8();
format!("#{:02X}{:02X}{:02X}", rgba[0], rgba[1], rgba[2])
})
.collect();
json!({
"preset": config.preset.id(),
"grid": config.grid(),
"radii": config.radii,
"brand": brand,
"disabled": config.disabled,
})
}
/// The layers a command works on, its scope label, the layer aggregate findings point at and that
/// layer's path.
/// The `ids` parameter, parsed without collapsing ancestors: `exact` needs the layers the caller
/// listed, while the walk uses their top-most roots.
fn ids_arg(cmd: &str, p: &Value) -> Result<Option<Vec<NodeId>>> {
let Some(v) = params::get(p, "ids") else { return Ok(None) };
let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) };
let mut ids = Vec::new();
for item in items {
let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) };
ids.push(id);
}
Ok(Some(ids))
}
fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec<NodeId>, Option<NodeId>, String)> {
let doc = s.doc()?;
// `ids` names the layers directly (the review window fixes only the findings the user kept).
// An empty or unknown id checks nothing, which a CI gate must not mistake for a pass.
if let Some(ids) = ids_arg(cmd, p)? {
if ids.is_empty() {
return Err(bad(cmd, "`ids` is empty: name at least one layer to audit, or drop `ids` for the selection, page or document"));
}
let missing: Vec<String> = ids.iter().filter(|id| doc.node(**id).is_none()).map(|id| id.to_string()).collect();
if !missing.is_empty() {
return Err(bad(cmd, format!("`ids` names layers that do not exist: {}", missing.join(", "))));
}
let roots = top_most(doc, &ids);
let anchor = roots.first().copied();
let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default();
return Ok(("selection".into(), roots, anchor, path));
}
let scope = scope_arg(cmd, p)?;
let selection = s.selection();
let page = s.page()?;
// An explicitly empty selection checks nothing either; only the implicit default falls back
// to the page. A CI gate must not read an unchecked scope as a pass.
if scope.as_deref() == Some("selection") && selection.is_empty() {
return Err(bad(cmd, "nothing is selected: name `ids`, pick a scope of page or document, or select the layers to audit"));
}
let (roots, label, anchor, path) = match scope.as_deref() {
None if selection.is_empty() => (vec![page], "page", Some(page), node_label(doc, page)),
None => selection_scope(doc, &selection),
Some("selection") => selection_scope(doc, &selection),
Some("page") => (vec![page], "page", Some(page), node_label(doc, page)),
Some("document") => {
let roots = doc.pages.clone();
let anchor = roots.first().copied();
let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default();
(roots, "document", anchor, path)
}
Some(other) => return Err(bad(cmd, format!("`scope` must be selection, page or document, not `{other}`"))),
};
Ok((label.to_string(), roots, anchor, path))
}
fn selection_scope(doc: &Document, selection: &[NodeId]) -> (Vec<NodeId>, &'static str, Option<NodeId>, String) {
let roots = top_most(doc, selection);
let anchor = roots.first().copied();
let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default();
(roots, "selection", anchor, path)
}
fn scope_arg(cmd: &str, p: &Value) -> Result<Option<String>> {
let Some(v) = params::get(p, "scope") else { return Ok(None) };
let Value::String(s) = v else { return Err(bad(cmd, "`scope` must be a string")) };
let s = s.trim().to_ascii_lowercase();
if s.is_empty() {
return Ok(None);
}
if matches!(s.as_str(), "selection" | "page" | "document") {
Ok(Some(s))
} else {
Err(bad(cmd, format!("`scope` must be selection, page or document, not `{s}`")))
}
}
fn severity_arg(cmd: &str, p: &Value) -> Result<Severity> {
match params::string(p, "minSeverity").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) {
None => Ok(Severity::Low),
Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`minSeverity` must be low, medium or high, not `{s}`"))),
}
}
fn filter_arg(cmd: &str, p: &Value) -> Result<Option<BTreeSet<String>>> {
let Some(v) = params::get(p, "rules") else { return Ok(None) };
let Value::Array(items) = v else { return Err(bad(cmd, "`rules` must be an array of rule ids")) };
// A filter that names nothing checks nothing: a gate would pass over a review that never
// ran, the same way a truncated audit would.
if items.is_empty() {
return Err(bad(
cmd,
"`rules` names no rule, so nothing would be checked; list at least one (design.rules has them) or leave `rules` out to check them all",
));
}
let mut set = BTreeSet::new();
for item in items {
let Some(s) = item.as_str() else { return Err(bad(cmd, "`rules` must be an array of rule ids")) };
let id = s.trim();
if rule(id).is_none() {
return Err(bad(cmd, format!("unknown rule `{id}` (run design.rules for the list)")));
}
set.insert(id.to_string());
}
Ok(Some(set))
}
/// Selected layers without the ones whose ancestor is selected too: their subtrees would be
/// audited twice.
fn top_most(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut out: Vec<NodeId> = Vec::new();
for id in ids {
if out.contains(id) {
continue;
}
let mut parent = doc.node(*id).and_then(|n| n.parent);
let mut depth = 0;
let mut nested = false;
while let Some(pid) = parent {
if depth > 256 {
break;
}
if ids.contains(&pid) {
nested = true;
break;
}
parent = doc.node(pid).and_then(|n| n.parent);
depth += 1;
}
if !nested {
out.push(*id);
}
}
out
}
fn node_label(doc: &Document, id: NodeId) -> String {
doc.node(id).map(|n| n.name.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Layer {}", id.0))
}
+132
View File
@@ -0,0 +1,132 @@
//! The rules `design.audit` checks, with the severity and fixability the report carries.
use figcraft_doc::DesignPreset;
/// How much a finding matters: `High` first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Severity {
Low,
Medium,
High,
}
impl Severity {
pub(crate) fn id(self) -> &'static str {
match self {
Severity::Low => "low",
Severity::Medium => "medium",
Severity::High => "high",
}
}
pub(crate) fn from_id(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"low" => Some(Severity::Low),
"medium" | "med" => Some(Severity::Medium),
"high" => Some(Severity::High),
_ => None,
}
}
/// `0` for low, `1` for medium, `2` for high.
pub(crate) fn index(self) -> usize {
match self {
Severity::Low => 0,
Severity::Medium => 1,
Severity::High => 2,
}
}
/// The points a finding of this severity takes off the score.
pub(crate) fn penalty(self) -> f64 {
match self {
Severity::Low => 0.5,
Severity::Medium => 2.0,
Severity::High => 5.0,
}
}
}
/// One check: what it looks for, how much it matters and whether `design.fix` can repair it.
pub(crate) struct Rule {
pub id: &'static str,
pub severity: Severity,
/// The planned fixer can change this without guessing (see `docs/design-review.md`).
pub fixable: bool,
pub description: &'static str,
}
pub(crate) const RULES: &[Rule] = &[
Rule { id: "spacing.off-grid", severity: Severity::Medium, fixable: true, description: "Auto layout gap or padding is not on the 4px grid" },
Rule { id: "radius.off-scale", severity: Severity::Low, fixable: true, description: "A corner radius is not on the 4px scale or a pill" },
Rule { id: "type.sizes", severity: Severity::Medium, fixable: false, description: "More than five font sizes in one scope" },
Rule { id: "type.families", severity: Severity::Medium, fixable: false, description: "More than two font families in one scope" },
Rule { id: "type.weight", severity: Severity::Low, fixable: true, description: "A heading uses a weight above 600" },
Rule { id: "type.italic", severity: Severity::Low, fixable: true, description: "Interface text is italic" },
Rule { id: "type.too-small", severity: Severity::Medium, fixable: false, description: "Body text is smaller than 11px" },
Rule { id: "type.negative-tracking", severity: Severity::Low, fixable: true, description: "Small text has negative letter spacing" },
Rule { id: "color.gradient", severity: Severity::Medium, fixable: false, description: "A shape is filled or stroked with a gradient" },
Rule { id: "color.gradient-text", severity: Severity::High, fixable: false, description: "Text is painted with a gradient" },
Rule {
id: "color.glow",
severity: Severity::Medium,
fixable: true,
description: "A shadow has no offset and a large blur, so it reads as a glow",
},
Rule { id: "color.colored-shadow", severity: Severity::Low, fixable: true, description: "A shadow has a visible hue instead of a neutral" },
Rule { id: "color.border-opacity", severity: Severity::Low, fixable: true, description: "A border is more opaque than a hairline" },
Rule { id: "color.contrast", severity: Severity::High, fixable: true, description: "Text contrast is below 4.5:1 (3:1 for large text)" },
Rule { id: "color.accents", severity: Severity::Medium, fixable: false, description: "More than two accent colours in one scope (Strict)" },
Rule { id: "token.hardcoded-color", severity: Severity::Low, fixable: false, description: "A colour matches a variable but is not bound to it" },
Rule {
id: "token.hardcoded-number",
severity: Severity::Low,
fixable: false,
description: "A spacing, radius, size or opacity value matches a variable but is not bound",
},
Rule { id: "icon.emoji", severity: Severity::Low, fixable: false, description: "Text or a layer name contains an emoji" },
Rule { id: "copy.exclamation", severity: Severity::Low, fixable: false, description: "Interface copy uses an exclamation mark" },
Rule { id: "copy.trailing-period", severity: Severity::Low, fixable: false, description: "A short label ends with a period" },
Rule { id: "copy.hype", severity: Severity::Low, fixable: false, description: "Copy uses hype words such as \"AI-powered\"" },
Rule { id: "naming.auto", severity: Severity::Low, fixable: false, description: "A layer still has its default auto name (Frame 12)" },
Rule { id: "detail.shadow-count", severity: Severity::Low, fixable: false, description: "Shadows and blurs sit on too many layers" },
Rule {
id: "layout.no-auto-layout",
severity: Severity::Low,
fixable: false,
description: "A frame or component with several children has no auto layout (Strict)",
},
Rule {
id: "layout.text-overflow",
severity: Severity::High,
fixable: false,
description: "A fixed-width text box is shorter than the text it holds, so it clips or overlaps",
},
Rule {
id: "layout.clipped",
severity: Severity::High,
fixable: false,
description: "A fixed-size auto layout frame clips children that overflow it, so they are invisible",
},
];
pub(crate) fn rule(id: &str) -> Option<&'static Rule> {
RULES.iter().find(|r| r.id == id)
}
/// Whether `preset` checks `id`. Recommended and Strict check every rule except the Strict-only
/// ones; Accessibility checks only the findings that keep a design usable.
pub(crate) fn enabled(id: &str, preset: DesignPreset) -> bool {
match preset {
DesignPreset::Recommended => !matches!(id, "color.accents" | "layout.no-auto-layout"),
DesignPreset::Strict => true,
DesignPreset::Accessibility => {
matches!(id, "color.contrast" | "color.gradient-text" | "type.too-small" | "layout.text-overflow" | "layout.clipped")
}
}
}
/// The presets that check `id`, for `design.rules`.
pub(crate) fn presets_of(id: &str) -> Vec<&'static str> {
DesignPreset::ALL.iter().copied().filter(|p| enabled(id, *p)).map(DesignPreset::id).collect()
}
File diff suppressed because it is too large. Load diff
+26
View File
@@ -407,3 +407,29 @@ fn a_join_stopped_at_its_budget_says_so() {
let (some, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 3);
assert_eq!((some.len(), complete), (3, false), "{some:?}");
}
#[test]
fn code_links_keep_their_value_names_and_carry_source_and_notes() {
let mut s = session();
let variants: Vec<_> = ["small", "extra_large"]
.iter()
.map(|v| {
let f = node(&mut s, json!({"type": "frame", "name": format!("Size={v}"), "width": 80, "height": 32}));
id(&s.execute("component.create", &json!({"ids": [f]})).unwrap())
})
.collect();
let set = id(&s.execute("component.combineVariants", &json!({"ids": variants})).unwrap());
s.execute(
"codeConnect.set",
&json!({"id": set, "name": "Button", "template": "<Button size={Size} />", "source": "src/button.tsx",
"notes": "Use for main actions", "values": {"Size": {"extra_large": "xl"}}}),
)
.unwrap();
let instance = id(&s.execute("instance.create", &json!({"component": variants[1]})).unwrap());
let v = context(&mut s, json!({"ids": [instance]}));
let link = &v["components"][set.to_string()]["codeLinks"][0];
assert_eq!(link["values"]["Size"]["extra_large"], "xl", "a design value keeps its name: {link}");
let code = &only(&v)["code"][0];
assert_eq!((code["source"].as_str(), code["notes"].as_str()), (Some("src/button.tsx"), Some("Use for main actions")), "{code}");
assert!(code["code"].as_str().unwrap().contains("xl"), "{code}");
}
+181 -16
View File
@@ -26,6 +26,11 @@ pub const MAX_TEMPLATE: usize = 4_000;
pub const MAX_NAME: usize = 100;
/// Longest import path (chars).
pub const MAX_IMPORT: usize = 300;
/// Longest source path, and notes (chars).
pub const MAX_SOURCE: usize = 300;
pub const MAX_NOTES: usize = 2_000;
/// Most properties with mapped values on a link, and values on each.
const MAX_MAPPED: usize = 100;
/// Most links a connect file holds.
pub const MAX_FILE_LINKS: usize = 5_000;
/// Largest connect file read (bytes).
@@ -377,6 +382,8 @@ fn html_text(s: &str) -> String {
/// `link`'s template with `values` (one per parameter of `c`), every line prefixed by `pad`.
pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)], link: &CodeLink, lang: CodeLang, pad: &str) -> String {
// A value is written as code calls it; a condition reads the design's own value.
let coded = &in_code(values, link);
let mut out = String::new();
// A quoted attribute stays open across substitutions: `title="{a} {b}"` must treat both
// placeholders as attribute values, not text after the first one.
@@ -391,7 +398,7 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
vue_attr = None;
}
}
Piece::Value { name, inner } => match find(c, values, name) {
Piece::Value { name, inner } => match find(c, coded, name) {
Some((p, v)) => {
let e = expr(doc, c, p, v, lang);
// JSX and `view!`: a plain string reads best as an attribute value, anything
@@ -454,6 +461,12 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
out.lines().map(|l| if l.is_empty() { "\n".to_string() } else { format!("{pad}{l}\n") }).collect()
}
/// `values` with each design value the link names turned into what code calls it.
fn in_code(values: &[(String, Value)], link: &CodeLink) -> Vec<(String, Value)> {
let code = |prop: &str, v: &Value| link.values.get(prop)?.get(v.as_str()?).cloned();
values.iter().map(|(prop, v)| (prop.clone(), code(prop, v).map_or_else(|| v.clone(), Value::String))).collect()
}
/// A starting template: the code component called with every property (but slots) passed.
fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
let params: Vec<&str> = c.params.iter().filter(|p| p.kind != ParamKind::Slot).map(|p| p.ident.as_str()).collect();
@@ -469,6 +482,15 @@ fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
}
}
/// Why `source` can't name a file in a code repository: it goes down from the repository's root.
fn check_source(source: &str) -> std::result::Result<(), String> {
let plain = source.chars().count() <= MAX_SOURCE
&& !source.contains('\\')
&& !source.chars().any(char::is_control)
&& std::path::Path::new(source).components().all(|c| matches!(c, std::path::Component::Normal(_) | std::path::Component::CurDir));
if plain { Ok(()) } else { Err(format!("source: a path inside the code repository, up to {MAX_SOURCE} characters")) }
}
/// Checks a link: its name, import path and template. Returns the placeholder names that aren't
/// properties of `c` (kept as written).
pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Result<Vec<String>, String> {
@@ -500,6 +522,14 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
_ => format!("importPath: a module or package name (letters, digits, _ and .), up to {MAX_IMPORT} characters"),
});
}
check_source(&link.source)?;
if link.notes.chars().count() > MAX_NOTES {
return Err(format!("notes: up to {MAX_NOTES} characters"));
}
let long = |s: &String| s.chars().count() > MAX_NAME;
if link.values.len() > MAX_MAPPED || link.values.values().any(|m| m.len() > MAX_MAPPED || m.iter().any(|(k, v)| long(k) || long(v))) {
return Err(format!("values: at most {MAX_MAPPED} properties of {MAX_MAPPED} values, each up to {MAX_NAME} characters"));
}
let t = &link.template;
if t.trim().is_empty() || t.chars().count() > MAX_TEMPLATE || t.chars().any(|ch| ch.is_control() && !"\n\t\r".contains(ch)) {
return Err(format!("template: the snippet, up to {MAX_TEMPLATE} characters"));
@@ -515,6 +545,12 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
unknown.push(name.to_string());
}
}
// `in_code` reads a mapping by property name, so a key that is only a parameter name does nothing.
for prop in link.values.keys() {
if !c.params.iter().any(|p| p.prop == *prop) && !unknown.iter().any(|u| u == prop) {
unknown.push(prop.clone());
}
}
Ok(unknown)
}
@@ -557,12 +593,103 @@ fn store(doc: &mut Document, owner: NodeId, link: CodeLink) -> Result<()> {
Ok(())
}
/// The variant properties of component or set `owner`, with their values.
pub fn variants(doc: &Document, owner: NodeId) -> Vec<(String, Vec<String>)> {
main_of(doc, owner)
.and_then(|m| describe(doc, m))
.map(|c| c.params.iter().filter_map(|p| if let ParamKind::Variant(v) = &p.kind { Some((p.prop.clone(), v.clone())) } else { None }).collect())
.unwrap_or_default()
}
/// A link as the connect file holds it.
fn link_json(component: &str, l: &CodeLink) -> Value {
let mut v = link_fields(l);
v["component"] = json!(component);
v
}
/// A link's own fields, as the connect file and `inspect.designContext` give them: its keys are
/// the file's, and a mapping's property names and values stay as written.
pub(crate) fn link_fields(l: &CodeLink) -> Value {
let mut v = json!({"language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template});
if !l.source.is_empty() {
v["source"] = json!(l.source);
}
if !l.values.is_empty() {
v["values"] = json!(l.values);
}
if !l.notes.is_empty() {
v["notes"] = json!(l.notes);
}
v
}
/// The components and sets `ids` are, use or hold (every one in the file without `ids`).
fn listed(doc: &Document, ids: Option<&[NodeId]>) -> Vec<NodeId> {
let mut out: Vec<NodeId> = match ids {
None => doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.id).collect(),
Some(ids) => ids.iter().flat_map(|i| doc.subtree(*i)).filter_map(|i| owner(doc, i)).collect(),
};
out.sort_unstable();
out.dedup();
out
}
/// What an agent needs to use a component: its code link for each language, or that it has none.
fn entry(doc: &Document, id: NodeId, root: Option<&str>) -> Option<Value> {
let n = doc.node(id)?;
let links: Vec<Value> = n
.code_links
.iter()
.map(|l| {
let lang = CodeLang::from_id(&l.language);
let mut v = link_fields(l);
v["import"] = json!(lang.map(|k| import_line(l, k)));
v["snippet"] = json!(lang.and_then(|k| connected_code(doc, id, k, l)));
if let Some(root) = root.filter(|_| !l.source.is_empty()) {
v["sourceFound"] = json!(crate::file_access::exists(std::path::Path::new(root).join(&l.source)));
}
v
})
.collect();
Some(json!({
"id": id,
"name": n.name,
"type": n.kind.type_name(),
"mapped": !links.is_empty(),
"properties": crate::cmd::component::describe_props(doc, id)["properties"],
"links": links,
}))
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "codeConnect.list";
let doc = s.doc()?;
// Anything named must be layers; nothing named lists every component in the file.
let named = get(p, "ids").is_some() || get(p, "id").is_some();
let ids = if named { Some(crate::params::req_targets(cmd, s, p)?) } else { None };
let root = text(cmd, p, "root")?;
let unmapped = crate::params::boolean(p, "unmapped").unwrap_or(false);
let all: Vec<Value> = listed(doc, ids.as_deref()).into_iter().filter_map(|id| entry(doc, id, root.as_deref())).collect();
let count = |m: bool| all.iter().filter(|e| e["mapped"] == m).count();
let (mapped, missing) = (count(true), count(false));
let components: Vec<Value> = all.into_iter().filter(|e| !unmapped || e["mapped"] == false).collect();
Ok(json!({"components": components, "mapped": mapped, "unmapped": missing}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
spec!(
"codeConnect.list",
"List code connections",
"{ids? | id? (the components those layers are, use or hold; default every component in the file), unmapped? (only those without a link), root? (the code repository: says if each link's source is there)} → {components: [{id, name, type, mapped, properties, links: [{language, importPath, import, name, template, snippet, source?, sourceFound?, values?, notes?}]}], mapped, unmapped}",
false,
list
),
spec!(
"codeConnect.set",
"Connect to code",
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property)} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property), source? (the file, relative to the code repository), values? ({property: {design value: code value}}), notes?} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
true,
|s, p| {
let cmd = "codeConnect.set";
@@ -578,7 +705,13 @@ pub fn specs() -> Vec<CommandSpec> {
None => old.template,
};
let import_path = text(cmd, p, "importPath")?.map_or(old.import_path, |i| i.trim().to_string());
let link = CodeLink { language: lang.id().into(), import_path, name, template };
let source = text(cmd, p, "source")?.map_or(old.source, |v| v.trim().to_string());
let notes = text(cmd, p, "notes")?.unwrap_or(old.notes);
let values = match get(p, "values") {
None => old.values,
Some(v) => serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "values: {property: {design value: code value}}"))?,
};
let link = CodeLink { language: lang.id().into(), import_path, name, template, source, values, notes };
let unknown = check(&c, &link, lang).map_err(|e| bad(cmd, e))?;
let code = connected_code(doc, id, lang, &link);
store(s.doc_mut()?, owner, link)?;
@@ -610,27 +743,34 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"codeConnect.export",
"Export code connections",
"{path? (write it there, e.g. figcraft.connect.json in the code repository)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template}]}, sorted → {text, links} or {path, links}",
"{path? (write it there, e.g. figcraft.connect.json in the code repository; other top-level keys of a file already there stay, and so do the links of components this file doesn't have; a file there it can't read is left alone and the export refused)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template, source?, values?, notes?}]}, sorted → {text, links} or {path, links}",
false,
|s, p| {
let cmd = "codeConnect.export";
let path = text(cmd, p, "path")?;
let doc = s.doc()?;
let mut links: Vec<Value> = doc
.nodes()
.filter(|n| owner(doc, n.id) == Some(n.id))
.flat_map(|n| {
n.code_links.iter().map(|l| {
json!({"component": n.name, "language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template})
})
})
.collect();
let mut links: Vec<Value> =
doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).flat_map(|n| n.code_links.iter().map(|l| link_json(&n.name, l))).collect();
let key =
|v: &Value| (v["component"].as_str().unwrap_or_default().to_string(), v["language"].as_str().unwrap_or_default().to_string());
links.sort_by_key(key);
let count = links.len();
let text =
serde_json::to_string_pretty(&json!({"version": VERSION, "links": links})).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
// The file also holds the project's settings and the links of other designs: only
// the links of this file's components are this command's.
let old = match path.as_deref() {
Some(path) => kept_keys(cmd, path)?,
None => serde_json::Map::new(),
};
let here: Vec<&str> = doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.name.as_str()).collect();
let others = old.get("links").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
links.extend(others.iter().filter(|l| !l.get("component").and_then(Value::as_str).is_some_and(|c| here.contains(&c))).cloned());
links.sort_by_key(key);
let mut file = json!({"version": VERSION, "links": links});
if let Some(fields) = file.as_object_mut() {
for (k, v) in old {
fields.entry(k).or_insert(v);
}
}
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
match path {
Some(path) => {
crate::cmd::file::write(&path, text.as_bytes())?;
@@ -650,6 +790,18 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// The top-level keys of the connect file at `path`, none when there is no file. A file that
/// can't be read as one is an error: writing over it would lose what it holds.
fn kept_keys(cmd: &str, path: &str) -> Result<serde_json::Map<String, Value>> {
if !crate::file_access::exists(path) {
return Ok(serde_json::Map::new());
}
match serde_json::from_slice(&crate::cmd::file::read_capped(path, MAX_FILE)?) {
Ok(Value::Object(fields)) => Ok(fields),
_ => Err(bad(cmd, format!("{path} isn't a connect file it can read, so it was left as it is"))),
}
}
fn import(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "codeConnect.import";
let parse_json = |b: &[u8]| serde_json::from_slice::<Value>(b).map_err(|e| bad(cmd, format!("not JSON: {e}")));
@@ -688,11 +840,24 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
));
continue;
};
let values = match e.get("values") {
None | Some(Value::Null) => Default::default(),
Some(v) => match serde_json::from_value(v.clone()) {
Ok(values) => values,
Err(_) => {
warnings.push(format!("link {}: values: {{property: {{design value: code value}}}}, all strings", i + 1));
continue;
}
},
};
let link = CodeLink {
language: lang.id().into(),
import_path: field("importPath").unwrap_or_default().to_string(),
name: name.into(),
template: template.into(),
source: field("source").unwrap_or_default().to_string(),
values,
notes: field("notes").unwrap_or_default().to_string(),
};
let matches = owners.get(component).cloned().unwrap_or_default();
if matches.is_empty() {
+124
View File
@@ -384,6 +384,10 @@ fn stroke_color(n: &Node) -> Option<Color> {
/// The CSS borders a solid stroke makes: one `border`, or with individual stroke sides a border
/// on each side that has a weight.
fn css_borders(doc: &Document, n: &Node, t: &mut Tokens) -> Vec<(String, String)> {
// A vector's stroke belongs to its path, not to a rectangle around its bounding box.
if matches!(n.kind, NodeKind::Vector { .. }) {
return Vec::new();
}
let Some(c) = stroke_color(n) else { return Vec::new() };
let Some(sides) = n.stroke.sides else {
let weight = tok(doc, n, &["strokeWeight"], format!("{}px", num(n.stroke.weight)), t);
@@ -573,6 +577,126 @@ mod tests {
assert!(!css.contains("gradient"), "{css}");
}
fn embedded_svgs(code: &str) -> Vec<String> {
use base64::Engine as _;
code.split("data:image/svg+xml;base64,")
.skip(1)
.map(|rest| {
let b64 = rest.split('"').next().unwrap();
String::from_utf8(base64::engine::general_purpose::STANDARD.decode(b64).unwrap()).unwrap()
})
.collect()
}
#[test]
fn vector_code_uses_its_svg_asset_not_a_box_border() {
let mut s = Session::new();
let icon =
id_of(&s.execute("frame.create", &json!({"name": "icon", "width": 24, "height": 24, "props": {"fill": "none"}})).unwrap()["id"]).unwrap();
let check = id_of(&s.execute("vector.create", &json!({"path": "M4 12 L10 18 L20 6", "parent": icon, "name": "check", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 2}})).unwrap()["id"]).unwrap();
s.doc_mut().unwrap().get_mut(check).unwrap().fills = vec![Paint::solid(Color::WHITE)];
let doc = s.doc().unwrap();
let html = code_for(doc, icon, CodeLang::Html);
assert!(html.contains("<div class=\"check\">"), "node wrapper: {html}");
assert!(html.contains("<img class=\"check-asset\" src=\"data:image/svg+xml;base64,"), "{html}");
assert!(html.contains("alt=\"check\""), "{html}");
assert!(!html.contains("border: 2px solid"), "{html}");
assert!(!html.contains("background:"), "the vector's fill belongs to its SVG, not its box: {html}");
let opaque = embedded_svgs(&html);
assert_eq!(opaque.len(), 1, "{html}");
assert!(opaque[0].contains("<path") && opaque[0].contains("#1F3A68"), "{:?}", opaque[0]);
for lang in [CodeLang::React, CodeLang::Vue, CodeLang::Leptos, CodeLang::Tailwind] {
let code = code_for(doc, icon, lang);
assert!(code.contains("<img") && code.contains("src=\"data:image/svg+xml;base64,"), "{}: {code}", lang.id());
assert!(!code.contains("border: 2px solid") && !code.contains("border-[2px]"), "{}: {code}", lang.id());
}
let css = code_for(doc, icon, CodeLang::Css);
assert!(!css.contains("border: 2px solid"), "{css}");
let swift = code_for(doc, icon, CodeLang::SwiftUi);
assert!(swift.contains("Image(\"check\")"), "{swift}");
assert!(!swift.contains(".overlay(RoundedRectangle"), "{swift}");
let ark = code_for(doc, icon, CodeLang::ArkUi);
assert!(!ark.contains(".border({"), "{ark}");
// CSS owns the node's rotation and opacity, so the embedded asset must not bake them in.
s.doc_mut().unwrap().get_mut(check).unwrap().opacity = 0.5;
s.doc_mut().unwrap().get_mut(check).unwrap().transform = figcraft_geom::Affine::rotate(30f64.to_radians());
let transformed = code_for(s.doc().unwrap(), icon, CodeLang::Html);
assert!(transformed.contains("opacity: 0.5;"), "{transformed}");
assert!(transformed.contains("transform: rotate("), "{transformed}");
assert_eq!(embedded_svgs(&transformed), opaque, "the asset stays node-local and opaque: {transformed}");
let rectangle =
id_of(&s.execute("shape.rectangle", &json!({"parent": icon, "props": {"stroke": "#1F3A68", "strokeWeight": 2}})).unwrap()["id"]).unwrap();
assert!(code_for(s.doc().unwrap(), rectangle, CodeLang::Css).contains("border: 2px solid"), "box strokes remain");
}
#[test]
fn vector_assets_are_self_contained_and_leptos_literals_escape() {
let mut s = Session::new();
let icon = id_of(&s.execute("frame.create", &json!({"name": "Icons", "width": 24, "height": 24})).unwrap()["id"]).unwrap();
for name in ["Check Icon", "Check Icon", r"icon\q", "check#dark"] {
s.execute("vector.create", &json!({"path": "M4 12 L10 18 L20 6", "parent": icon, "name": name, "props": {"fill": "none"}})).unwrap();
}
let html = code_for(s.doc().unwrap(), icon, CodeLang::Html);
assert_eq!(embedded_svgs(&html).len(), 4, "nested vectors need no separate filesystem export: {html}");
assert!(!html.contains("src=\"check#dark.svg\""), "{html}");
let leptos = code_for(s.doc().unwrap(), icon, CodeLang::Leptos);
assert!(leptos.contains("alt=\"icon\\\\q\""), "{leptos}");
}
#[test]
fn vector_asset_keeps_stroke_overflow_inside_a_node_sized_wrapper() {
let mut s = Session::new();
let badge = id_of(
&s.execute(
"vector.create",
&json!({"path": "M0 0 H24 V24 H0 Z", "name": "badge", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 2}}),
)
.unwrap()["id"],
)
.unwrap();
s.doc_mut().unwrap().get_mut(badge).unwrap().stroke.miter_limit = 1.0;
let html = code_for(s.doc().unwrap(), badge, CodeLang::Html);
assert!(html.contains("<div class=\"badge\">"), "node-sized wrapper: {html}");
assert!(html.contains("<img class=\"badge-asset\""), "inner asset: {html}");
assert!(html.contains("overflow: visible;"), "stroke is not clipped: {html}");
assert!(html.contains("left: -2px;") && html.contains("top: -2px;"), "asset offset: {html}");
assert!(html.contains("width: 28px;") && html.contains("height: 28px;"), "asset keeps its bounds: {html}");
assert!(html.contains("max-width: none;"), "the wrapper cannot shrink the asset: {html}");
let svg = embedded_svgs(&html);
assert_eq!(svg.len(), 1, "{html}");
assert!(svg[0].contains("width=\"28\" height=\"28\""), "{}", svg[0]);
let tailwind = code_for(s.doc().unwrap(), badge, CodeLang::Tailwind);
assert!(tailwind.contains("overflow-visible") && tailwind.contains("max-w-none"), "{tailwind}");
assert!(tailwind.contains("w-7") && tailwind.contains("h-7"), "28px on the spacing scale: {tailwind}");
}
#[test]
fn vector_markup_does_not_duplicate_svg_effects() {
let mut s = Session::new();
let vector = id_of(
&s.execute("vector.create", &json!({"path": "M0 0 H24 V24 H0 Z", "name": "effect icon", "props": {"fill": "#FFFFFF"}})).unwrap()["id"],
)
.unwrap();
s.doc_mut().unwrap().get_mut(vector).unwrap().effects = vec![
figcraft_doc::Effect { kind: EffectKind::LayerBlur(figcraft_doc::Blur::uniform(8.0)), visible: true },
figcraft_doc::Effect { kind: EffectKind::DropShadow(Shadow { radius: 4.0, offset: (3.0, 4.0), ..Default::default() }), visible: true },
];
let html = code_for(s.doc().unwrap(), vector, CodeLang::Html);
assert!(!html.contains("filter: blur(") && !html.contains("box-shadow:"), "the SVG owns these effects: {html}");
let svg = embedded_svgs(&html);
assert_eq!(svg.len(), 1, "{html}");
assert!(svg[0].contains("feGaussianBlur") && svg[0].contains("feOffset"), "{}", svg[0]);
let standalone = code_for(s.doc().unwrap(), vector, CodeLang::Css);
assert!(standalone.contains("filter: blur(4px)") && standalone.contains("box-shadow:"), "standalone CSS is unchanged: {standalone}");
let rectangle = id_of(&s.execute("shape.rectangle", &json!({"name": "ordinary", "width": 24, "height": 24})).unwrap()["id"]).unwrap();
s.doc_mut().unwrap().get_mut(rectangle).unwrap().effects = s.doc().unwrap().node(vector).unwrap().effects.clone();
let ordinary = code_for(s.doc().unwrap(), rectangle, CodeLang::Html);
assert!(ordinary.contains("filter: blur(4px)") && ordinary.contains("box-shadow:"), "ordinary shapes keep CSS effects: {ordinary}");
}
#[test]
fn swiftui_and_compose_for_an_auto_layout_card() {
let mut s = Session::new();
+1 -1
View File
@@ -216,7 +216,7 @@ fn arkui_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
}
}
// Ellipses take their stroke as a shape attribute (above).
if !matches!(n.kind, NodeKind::Ellipse { .. })
if !matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Vector { .. })
&& let Some(c) = stroke_color(n)
{
mods.push(format!(".border({{ width: {}, color: {} }})", num(n.stroke.weight), ark_color(c)));
+22 -5
View File
@@ -126,6 +126,16 @@ pub(super) fn css(doc: &Document, id: NodeId) -> String {
/// The CSS declarations for `n`'s own look and size, one per line; `hug` leaves out the width
/// and/or height (they follow the content). Bound variables become `var(--name, value)`.
pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool)) -> String {
css_decls_impl(doc, n, t, hug, false)
}
/// The declarations around an embedded vector image: its SVG owns shadows and layer blur, so
/// only the markup wrapper omits those. Standalone CSS and ordinary shapes keep them.
pub(crate) fn css_decls_for_markup(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool)) -> String {
css_decls_impl(doc, n, t, hug, true)
}
fn css_decls_impl(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool), vector_svg: bool) -> String {
let px = |v: f64| format!("{}px", num(v));
let mut out = String::new();
let mut put = |key: &str, value: String| out.push_str(&format!("{key}: {value};\n"));
@@ -188,7 +198,12 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
// One `background` with every visible fill as a layer, top first (a document's fills run
// bottom to top, as the renderer paints them). CSS allows a plain colour only as the last
// layer, so a solid above another fill becomes a one-colour gradient.
let visible: Vec<(usize, &figcraft_color::Paint)> = n.fills.iter().enumerate().filter(|(_, p)| p.visible).collect();
let visible: Vec<(usize, &figcraft_color::Paint)> = if matches!(n.kind, NodeKind::Vector { .. }) {
// The SVG carries the path's fills; an image's box must not get a rectangular one.
Vec::new()
} else {
n.fills.iter().enumerate().filter(|(_, p)| p.visible).collect()
};
let layers: Vec<String> = visible
.iter()
.enumerate()
@@ -217,7 +232,7 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
for (key, value) in css_borders(doc, n, t) {
put(&key, value);
}
effect_decls(n, &mut put);
effect_decls(n, &mut put, vector_svg && matches!(n.kind, NodeKind::Vector { .. }));
if let NodeKind::Text(tx) = &n.kind {
text_decls(doc, n, tx, t, &mut put);
}
@@ -274,12 +289,14 @@ fn layout_decls(doc: &Document, n: &Node, l: &figcraft_doc::AutoLayout, t: &mut
}
}
/// Shadows and blurs of `n`.
fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String)) {
/// Shadows and blurs of `n`. `svg_owned` leaves shadows and layer blur to the embedded SVG;
/// backdrop filters stay in CSS because the self-contained asset has no outer page behind it.
fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String), svg_owned: bool) {
let shadows: Vec<String> = n
.effects
.iter()
.filter(|e| e.visible)
.filter(|e| !(svg_owned && matches!(e.kind, EffectKind::DropShadow(_) | EffectKind::InnerShadow(_))))
.filter_map(|e| match &e.kind {
EffectKind::DropShadow(s) => {
Some(format!("{}px {}px {}px {}px {}", num(s.offset.0), num(s.offset.1), num(s.radius), num(s.spread), s.color.to_css()))
@@ -296,7 +313,7 @@ fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String)) {
for e in n.effects.iter().filter(|e| e.visible) {
match e.kind {
// CSS blurs are uniform: a progressive blur has no CSS equivalent and is left out.
EffectKind::LayerBlur(ref b) if !b.is_progressive() => put("filter", format!("blur({}px)", num(b.radius / 2.0))),
EffectKind::LayerBlur(ref b) if !svg_owned && !b.is_progressive() => put("filter", format!("blur({}px)", num(b.radius / 2.0))),
EffectKind::BackgroundBlur(ref b) if !b.is_progressive() => put("backdrop-filter", format!("blur({}px)", num(b.radius / 2.0))),
// CSS has no refraction: the frost is the nearest.
EffectKind::Glass(ref g) => put("backdrop-filter", format!("blur({}px)", num(g.sanitized().frost / 2.0))),
+63 -2
View File
@@ -1,4 +1,6 @@
use super::css::{Tokens, css_decls};
use base64::Engine as _;
use super::css::{Tokens, css_decls_for_markup};
use super::{CodeLang, Ctx, Document, LayoutMode, Node, NodeId, NodeKind, Param, Sizing, indent, num, with_v_if};
// ------------------------------------------------------------------ HTML and React markup
@@ -85,6 +87,24 @@ fn html_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('\n', "<br>")
}
/// A layer name in a quoted markup attribute, with line breaks flattened.
fn attr_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace(['\n', '\r'], " ")
}
/// A vector as a self-contained SVG asset and its local painted bounds. CSS owns the node's
/// placement and opacity, so the embedded geometry is node-local and fully opaque. No filesystem
/// export or URL escaping is needed, and nested vectors work exactly like top-level ones.
fn vector_data_uri(doc: &mut Document, n: &Node) -> Option<(String, figcraft_geom::Rect)> {
let node = doc.get_mut(n.id).ok()?;
node.parent = None;
node.transform = figcraft_geom::Affine::IDENTITY;
node.opacity = 1.0;
let bounds = figcraft_render::export_bounds(doc, n.id)?;
let svg = figcraft_svg::export_svg(doc, &[n.id], &Default::default())?;
Some((format!("data:image/svg+xml;base64,{}", base64::engine::general_purpose::STANDARD.encode(svg)), bounds))
}
/// Text as JSX children: HTML escapes, braces as expressions, line breaks as `<br />`.
fn jsx_text(s: &str) -> String {
let mut out = String::new();
@@ -147,6 +167,8 @@ pub(crate) struct Markup<'c, 'a> {
/// With `fluid`, other layers at least this share of the root's width are fluid too (a
/// divider, a banner image); smaller ones (icons) keep their size. Default: none.
pub fluid_leaves: f64,
/// Lazily cloned once for node-local SVG assets, not once per vector.
asset_doc: Option<Document>,
}
/// How `n` sits in its parent: in the flex flow, or placed at its position.
@@ -175,6 +197,18 @@ fn placement_decls(n: &Node, parent: Option<&Node>, root: bool, in_flow: bool) -
decls
}
/// Extra declarations around an embedded vector image. The inner SVG can be larger than the
/// node box, so the wrapper must establish positioning in flex flow and leave overflow visible.
fn vector_wrapper_decls(n: &Node, in_flow: bool, own: &mut String) {
if !matches!(n.kind, NodeKind::Vector { .. }) {
return;
}
own.push_str("overflow: visible;\n");
if in_flow {
own.push_str("position: relative;\n");
}
}
impl<'c, 'a> Markup<'c, 'a> {
pub fn new(ctx: &'c Ctx<'a>, lang: CodeLang) -> Self {
Markup {
@@ -192,6 +226,7 @@ impl<'c, 'a> Markup<'c, 'a> {
inline: false,
fluid: false,
fluid_leaves: f64::INFINITY,
asset_doc: None,
}
}
@@ -290,6 +325,30 @@ impl<'c, 'a> Markup<'c, 'a> {
}
}
/// A node-sized wrapper and its inner SVG image. The inner rule uses the exported bounds,
/// so strokes and effects keep their size and can overflow the wrapper without clipping.
fn vector_element(&mut self, n: &Node, depth: usize, path: &str, class: &str, attr: &str, pad: &str, attrs: &str) {
let root_doc = self.ctx.doc;
let asset = vector_data_uri(self.asset_doc.get_or_insert_with(|| root_doc.clone()), n);
let bounds = asset.as_ref().map(|(_, b)| *b).unwrap_or_else(|| n.local_rect());
let asset_class = class_name(&format!("{class} asset"), "asset", &mut self.used);
let asset_decls = format!(
"display: block;\nposition: absolute;\nleft: {}px;\ntop: {}px;\nwidth: {}px;\nheight: {}px;\nmax-width: none;\n",
num(bounds.x0),
num(bounds.y0),
num(bounds.width()),
num(bounds.height())
);
self.rule(&format!("{path}/$svg"), &asset_class, asset_decls);
// Leptos attributes are Rust string literals; the other targets use HTML escaping.
let lang = self.lang;
let quote = |value: &str| if lang == CodeLang::Leptos { format!("{value:?}") } else { format!("\"{}\"", attr_escape(value)) };
let src = asset.map(|(uri, _)| format!(" src={}", quote(&uri))).unwrap_or_default();
let alt = quote(&n.name);
let inner = self.pad(depth + 1);
self.markup.push_str(&format!("{pad}<div {attr}=\"{class}\"{attrs}>\n{inner}<img {attr}=\"{asset_class}\"{src} alt={alt} />\n{pad}</div>\n"));
}
fn element(&mut self, n: &Node, parent: Option<&Node>, depth: usize, path: &str) {
let doc = self.ctx.doc;
let root = n.id == self.ctx.root;
@@ -319,7 +378,7 @@ impl<'c, 'a> Markup<'c, 'a> {
}
let hugs = n.layout.is_some() || matches!(n.kind, NodeKind::Text(_));
let hug = (hugs && n.child_layout.sizing_h == Sizing::Hug, hugs && n.child_layout.sizing_v == Sizing::Hug);
let mut own = css_decls(doc, n, &mut self.tokens, hug);
let mut own = css_decls_for_markup(doc, n, &mut self.tokens, hug);
let page = self.ctx.doc.node(self.ctx.root).map_or(f64::INFINITY, |r| r.width);
if self.fluid && (n.layout.is_some() || matches!(n.kind, NodeKind::Text(_)) || (!root && n.width >= page * self.fluid_leaves)) {
// Full width, or sized by the flex row (`flex: 1`): no cap needed.
@@ -328,6 +387,7 @@ impl<'c, 'a> Markup<'c, 'a> {
if n.layout.is_none() && !n.children.is_empty() && !root && in_flow {
own.push_str("position: relative;\n");
}
vector_wrapper_decls(n, in_flow, &mut own);
decls.push_str(&own);
self.rule(path, &class, decls);
// The root's variant attributes, and a Vue `v-if` guard, ride on the open tag.
@@ -339,6 +399,7 @@ impl<'c, 'a> Markup<'c, 'a> {
}
let open = |tag: &str| format!("{pad}<{tag} {attr}=\"{class}\"{attrs}>");
match &n.kind {
NodeKind::Vector { .. } => self.vector_element(n, depth, path, &class, attr, &pad, &attrs),
NodeKind::Text(t) => {
let body = self.text_body(n, t);
self.markup.push_str(&format!("{}{body}</p>\n", open("p")));
+3 -1
View File
@@ -192,7 +192,9 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
mods.push(format!(".frame(width: {w}, height: {h})"));
}
}
if let Some(c) = stroke_color(n) {
if !matches!(n.kind, NodeKind::Vector { .. })
&& let Some(c) = stroke_color(n)
{
mods.push(format!(
".overlay(RoundedRectangle(cornerRadius: {corner}).stroke({}, lineWidth: {}))",
bound(&["stroke"], swift_color(c)),
+9 -2
View File
@@ -178,7 +178,14 @@ fn code(doc: &Document, id: NodeId) -> Vec<Value> {
.filter_map(|l| {
let lang = CodeLang::from_id(&l.language)?;
let snippet = code_connect::connected_code(doc, id, lang, l)?;
Some(json!({"language": l.language, "importPath": l.import_path, "name": l.name, "code": snippet}))
// The snippet already holds the template and the values it maps.
let mut v = code_connect::link_fields(l);
if let Some(o) = v.as_object_mut() {
o.remove("template");
o.remove("values");
}
v["code"] = json!(snippet);
Some(v)
})
.collect()
}
@@ -355,7 +362,7 @@ fn components_json(doc: &Document, ids: &BTreeSet<NodeId>) -> Value {
v["description"] = json!(description);
}
if !n.code_links.is_empty() {
v["codeLinks"] = camel(serde_json::to_value(&n.code_links).unwrap_or(Value::Null));
v["codeLinks"] = json!(n.code_links.iter().map(code_connect::link_fields).collect::<Vec<_>>());
}
out.insert(id.to_string(), v);
}
+2
View File
@@ -274,8 +274,10 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> {
("width", "100%") => kw("w-full"),
("width", v) => one(spacing("w", v)),
("height", v) => one(spacing("h", v)),
("max-width", "none") => kw("max-w-none"),
("max-width", v) => one(format!("max-w-{}", arb(v))),
("min-height", v) => one(format!("min-h-{}", arb(v))),
("overflow", "visible") => kw("overflow-visible"),
("margin-inline", "auto") => kw("mx-auto"),
("gap", v) => one(spacing("gap", v)),
("padding", v) => padding(v),
@@ -116,6 +116,7 @@ fn empty_options_keep_the_main_tree_and_document_output() {
"fontFamily": "Synthetic",
"fontSize": 18.0,
"fontStyle": "Bold",
"fontWeight": 700,
"height": 24.0,
"id": 3,
"letterSpacing": "1",
+3
View File
@@ -16,6 +16,7 @@ mod canvas;
pub mod catalog;
pub mod cmd;
mod content;
mod design;
mod dev;
pub mod events;
mod extensions;
@@ -697,6 +698,8 @@ mod export_bounds_tests;
#[cfg(test)]
mod page_view_tests;
#[cfg(test)]
mod paste_properties_tests;
#[cfg(test)]
mod selection_reorder_tests;
#[cfg(test)]
mod selection_spacing_tests;
+23
View File
@@ -471,3 +471,26 @@ fn joining_takes_a_code_of_either_kind_or_a_link() {
assert_eq!((&r["status"], &r["reason"]), (&json!("failed"), &json!("No session with that code")));
assert_eq!(s.message.as_deref(), Some("No session with that code"));
}
/// A file whose review settings are past this build's limits is not shared, hosted or published:
/// joining clients apply arriving values against the limits they were built with, so a file
/// written by a looser build would break them. Nothing reaches the link; the error names the
/// lists and the way out.
#[test]
fn a_file_past_the_review_limits_is_not_shared() {
use figcraft_doc::{DesignReview, MAX_RADII};
let mut s = Session::new();
s.doc_mut().unwrap().design_review = DesignReview { radii: (0..MAX_RADII + 1).map(|i| i as f64).collect(), ..Default::default() };
for (cmd, p) in [
("collab.host", json!({})),
("collab.share", json!({"via": "local"})),
("collab.share", json!({"via": "online", "server": "wss://s.example/"})),
("collab.publish", json!({"server": "wss://s.example/"})),
] {
let e = err(&mut s, cmd, p);
assert!(e.contains("can't be shared"), "{cmd}: {e}");
assert!(e.contains(&format!("{} corner radii (this build keeps at most {MAX_RADII})", MAX_RADII + 1)), "{cmd}: {e}");
assert!(e.contains("design.configure"), "{cmd}: {e}");
}
}
+27
View File
@@ -99,6 +99,33 @@ fn node_find_instances_match_main_name_and_visit_actual_children_only() {
found(&mut s, json!({"root": inst, "text": "original"}), &[]);
found(&mut s, json!({"root": inst, "text": "changed"}), &[child]);
found(&mut s, json!({}), &[main, original, inst, child, broken]);
found(&mut s, json!({"orphaned": true}), &[broken]);
found(&mut s, json!({"orphaned": false}), &[inst]);
found(&mut s, json!({"orphaned": true, "name": "other"}), &[]);
assert!(s.execute("node.find", &json!({"orphaned": "true"})).is_err());
}
#[test]
fn deleting_a_component_reports_only_the_instances_it_leaves_orphaned() {
let mut s = Session::new();
let page = s.page().unwrap();
let frame = add(&mut s, page, NodeKind::Frame, "With a main");
let main = add(&mut s, frame, NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "Main");
let other_main =
add(&mut s, page, NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "Other");
let deleted = idv(&ex(&mut s, "instance.create", json!({"component": main, "parent": frame})));
let survivor = idv(&ex(&mut s, "instance.create", json!({"component": main})));
let linked = idv(&ex(&mut s, "instance.create", json!({"component": other_main})));
let first = ex(&mut s, "edit.delete", json!({"ids": [other_main]}));
assert_eq!(first["orphaned"], json!([linked]));
let result = ex(&mut s, "edit.delete", json!({"ids": [frame]}));
assert_eq!(result["orphaned"], json!([survivor]));
assert!(!s.doc().unwrap().contains(deleted));
found(&mut s, json!({"orphaned": true}), &[survivor, linked]);
ex(&mut s, "edit.undo", json!({}));
found(&mut s, json!({"orphaned": true}), &[linked]);
}
#[test]
+116
View File
@@ -0,0 +1,116 @@
//! Copy properties and Paste properties (Alt+Cmd/Ctrl+C and V) carry what a layer's look comes
//! from as well as its values: its colour, effect and grid styles, the variables bound to what is
//! copied and a frame's layout grids. A link the file pasted into doesn't have is left out.
use figcraft_doc::{LayoutGrid, NodeId};
use serde_json::{Value, json};
use crate::Session;
fn id(v: Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn frame(s: &mut Session, x: f64) -> NodeId {
id(s.execute("frame.create", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap())
}
fn copy_onto(s: &mut Session, from: NodeId, to: NodeId) {
s.execute("edit.copyProperties", &json!({"id": from})).unwrap();
s.execute("edit.pasteProperties", &json!({"ids": [to]})).unwrap();
}
#[test]
fn a_frame_pastes_its_styles_variables_and_layout_grids() {
let mut s = Session::new();
let (a, b, c) = (frame(&mut s, 0.0), frame(&mut s, 200.0), frame(&mut s, 400.0));
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
for (name, value) in [("surface", "#FF0000"), ("other", "#0000FF")] {
s.execute("variable.create", &json!({"collection": "Tokens", "name": name, "type": "color", "value": value})).unwrap();
}
s.execute("variable.create", &json!({"collection": "Tokens", "name": "radius", "type": "number", "value": 16})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "cornerRadius", "variable": "radius"})).unwrap();
s.execute("node.set", &json!({"ids": [a], "props": {"grids": [serde_json::to_value(LayoutGrid::default()).unwrap()]}})).unwrap();
// B is bound to another colour, which the paste replaces.
s.execute("variable.bind", &json!({"ids": [b], "field": "fills/0/color", "variable": "other"})).unwrap();
let shadow = s.execute("style.create", &json!({"type": "effect", "name": "Shadow", "value": [{"type": "dropShadow"}]})).unwrap()["id"].clone();
let green = s.execute("style.create", &json!({"type": "paint", "name": "Green", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("style.apply", &json!({"ids": [c], "style": green})).unwrap();
s.execute("style.apply", &json!({"ids": [c], "style": shadow})).unwrap();
copy_onto(&mut s, a, b);
let (na, nb) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(b).unwrap().clone());
assert_eq!(nb.bound.get("fills/0/color"), na.bound.get("fills/0/color"), "the fill follows the same variable");
assert_eq!(nb.bound.get("cornerRadius"), na.bound.get("cornerRadius"), "and so do the corners");
assert_eq!(nb.corners.radii, [16.0; 4]);
assert_eq!(nb.grids, na.grids, "a frame's layout grids come along");
copy_onto(&mut s, c, a);
let (na, nc) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(c).unwrap().clone());
assert_eq!(na.styles.fill, nc.styles.fill, "the fill style is linked");
assert!(nc.styles.effect.is_some() && na.styles.effect == nc.styles.effect, "the effect style too");
assert!(!na.bound.contains_key("fills/0/color"), "the style replaces the fill's variable");
assert!(!na.bound.contains_key("cornerRadius"), "C's corners aren't bound, so A's aren't any more");
assert!(na.grids.is_empty(), "nor has it layout grids");
assert_eq!(na.fills, nc.fills);
}
#[test]
fn links_another_file_lacks_paste_as_values() {
let mut s = Session::new();
let a = frame(&mut s, 0.0);
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
s.execute("variable.create", &json!({"collection": "Tokens", "name": "surface", "type": "color", "value": "#FF0000"})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
let st = s.execute("style.create", &json!({"type": "paint", "name": "Line", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("node.set", &json!({"ids": [a], "props": {"strokes": [{"type": "solid", "color": "#000000"}]}})).unwrap();
s.execute("style.apply", &json!({"ids": [a], "style": st, "target": "stroke"})).unwrap();
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
let copied = s.doc().unwrap().node(a).unwrap().clone();
s.execute("file.new", &json!({})).unwrap();
let b = frame(&mut s, 0.0);
// This file's own style and variable come out with the copied ids: they are not the copied ones.
s.execute("variable.createCollection", &json!({"name": "Theirs"})).unwrap();
s.execute("variable.create", &json!({"collection": "Theirs", "name": "ink", "type": "color", "value": "#0000FF"})).unwrap();
s.execute("style.create", &json!({"type": "paint", "name": "Ink", "value": "#0000FF"})).unwrap();
let doc = s.doc().unwrap();
let vid = copied.bound["fills/0/color"].as_str();
assert!(doc.style(st.as_str().unwrap()).is_some() && doc.variables.get_by_id(vid).is_some(), "the ids are taken here");
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
let nb = s.doc().unwrap().node(b).unwrap();
assert_eq!((nb.fills.clone(), nb.strokes.clone()), (copied.fills, copied.strokes), "the values arrive");
assert!(nb.bound.is_empty() && nb.styles.fill.is_none() && nb.styles.stroke.is_none(), "{:?} {:?}", nb.bound, nb.styles);
}
#[test]
fn a_missing_style_unlinks_the_layers_own() {
let mut s = Session::new();
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
// B's own style gives the same colour, so the paste changes no value that would unlink it.
let gone = s.execute("style.create", &json!({"type": "paint", "name": "Gone", "value": "#00FF00"})).unwrap()["id"].clone();
let own = s.execute("style.create", &json!({"type": "paint", "name": "Own", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("style.apply", &json!({"ids": [a], "style": gone, "target": "stroke"})).unwrap();
s.execute("style.apply", &json!({"ids": [b], "style": own, "target": "stroke"})).unwrap();
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
s.execute("style.delete", &json!({"style": gone})).unwrap();
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
let nb = s.doc().unwrap().node(b).unwrap();
assert!(nb.styles.stroke.is_none(), "A's strokes had no style here, so B's aren't linked: {:?}", nb.styles);
}
#[test]
fn a_binding_on_what_the_copy_doesnt_carry_stays() {
let mut s = Session::new();
let a = frame(&mut s, 0.0);
let t = id(s.execute("text.create", &json!({"text": "Hi", "x": 0, "y": 200})).unwrap());
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
s.execute("variable.create", &json!({"collection": "Tokens", "name": "body", "type": "number", "value": 18})).unwrap();
s.execute("variable.bind", &json!({"ids": [t], "field": "fontSize", "variable": "body"})).unwrap();
let before = s.doc().unwrap().node(t).unwrap().bound.get("fontSize").cloned();
copy_onto(&mut s, a, t);
let nt = s.doc().unwrap().node(t).unwrap();
assert!(before.is_some() && nt.bound.get("fontSize") == before.as_ref(), "a frame carries no font size: {:?}", nt.bound);
}
+7
View File
@@ -109,6 +109,9 @@ pub struct Prefs {
/// files opened or made later start with them. Missing: the toggle's default.
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub view: BTreeMap<String, bool>,
/// Design review ignores, by document path: whole rule ids and `rule@layer` entries.
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub design_review_ignored: BTreeMap<String, Vec<String>>,
/// The board canvas's background grid (`board.grid`).
#[serde(deserialize_with = "crate::board_grid::read")]
pub board_grid: crate::board_grid::BoardGrid,
@@ -162,6 +165,7 @@ impl Default for Prefs {
home_sort: "modified".into(),
home_order: "desc".into(),
view: BTreeMap::new(),
design_review_ignored: BTreeMap::new(),
board_grid: Default::default(),
recent_actions: Vec::new(),
team_libraries: Vec::new(),
@@ -197,6 +201,9 @@ pub struct Clipboard {
pub images: std::collections::BTreeMap<String, figcraft_doc::ImageData>,
/// Copied properties (Copy properties / Paste properties).
pub props: Option<Value>,
/// The file the copied properties came from: their style and variable ids name its styles and
/// variables, and in another file the same ids can name unrelated ones.
pub props_source_doc: u64,
/// A copied fill or stroke row (`fill.copy`, `stroke.copy`): whether it's a fill, and the paint.
pub paint: Option<(bool, figcraft_color::Paint)>,
/// The stroke settings (`weight`, alignment, sides…) copied with a stroke's paint.
+13 -3
View File
@@ -94,7 +94,7 @@ fn assert_save_state_unchanged(s: &Session, before: &DocState, recent: &[String]
}
#[test]
fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
fn saving_to_another_file_names_the_document_after_it() {
let mut files = SaveFiles::new();
let path = files.path("Redis.figcraft");
let copy = files.path("Redis copy.figcraft");
@@ -111,9 +111,19 @@ fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
s.execute("file.saveAs", &json!({"path": copy.to_string_lossy()})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Redis copy");
s.execute("file.rename", &json!({"name": "Chosen title"})).unwrap();
s.execute("file.rename", &json!({"name": "Chosen: title"})).unwrap();
s.execute("file.save", &json!({})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Chosen: title", "saving to the same file keeps a name given here");
s.execute("file.saveAs", &json!({"path": manual_copy.to_string_lossy()})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Chosen title");
assert_eq!(s.ds().unwrap().doc.name, "Other", "a name given here too");
assert_eq!(figcraft_format::load_bytes(&std::fs::read(&manual_copy).unwrap()).unwrap().0.name, "Other");
// A file without one on disk yet: imported, here with its source's name.
let imported = files.path("Imported.figcraft");
let mut i = Session::new();
i.execute("file.rename", &json!({"name": "ШИМ"})).unwrap();
i.execute("file.saveAs", &json!({"path": imported.to_string_lossy()})).unwrap();
assert_eq!(i.ds().unwrap().doc.name, "Imported");
}
#[test]
+7 -3
View File
@@ -107,9 +107,9 @@ impl Session {
.and_then(|v| self.check_live_access(id, &before).map(|()| v))
.and_then(|v| self.check_finite_geometry(id, &before).map(|()| v))
// Normalising is part of the command: a panic in it rolls the edit back too (#1085).
.and_then(|v| {
.and_then(|mut v| {
guard::run(id, || {
self.normalize_edit(spec, &before);
self.normalize_edit(spec, &before, &mut v);
Ok(v)
})
});
@@ -229,13 +229,17 @@ impl Session {
/// Normalise what a command changed in the document it ran on (text boxes, groups, instances,
/// auto layout…).
fn normalize_edit(&mut self, spec: &CommandSpec, before: &Option<(Arc<Document>, Vec<NodeId>, NodeId, u64)>) {
fn normalize_edit(&mut self, spec: &CommandSpec, before: &Option<(Arc<Document>, Vec<NodeId>, NodeId, u64)>, result: &mut Value) {
let Some((bdoc, _, _, uid)) = before else { return };
let deletes = spec.id == "edit.delete" || (spec.id == "edit.repeat" && self.last_command.as_ref().is_some_and(|(id, _)| id == "edit.delete"));
let Some(ds) = self.docs.iter_mut().find(|d| d.uid == *uid) else { return };
// Saving may adopt the chosen filename as the document title. The encoded snapshot is
// already final; normalising it again would detach it from the saved baseline.
if !Arc::ptr_eq(&ds.doc, bdoc) && !matches!(spec.id, "file.save" | "file.saveAs") {
normalize(ds.doc_mut(), bdoc);
if deletes {
cmd::edit::report_orphaned_instances(result, bdoc, &ds.doc);
}
}
}
+20
View File
@@ -36,6 +36,24 @@ pub(super) fn unavailable(cmd: &str) -> EngineError {
)
}
/// A file whose review settings are past this build's limits can't be shared or published:
/// every joining client applies arriving values against the limits it was built with, so a file
/// written by an older or looser build would break them (and no build silently trims what the
/// file's author set). The error names the lists and the way out.
fn check_sharable(cmd: &str, doc: &figcraft_doc::Document) -> Result<()> {
let over = doc.design_review.over_limits();
if over.is_empty() {
return Ok(());
}
let list = over.iter().map(|(what, have, max)| format!("{have} {what} (this build keeps at most {max})")).collect::<Vec<_>>().join(", ");
Err(bad(
cmd,
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"
),
))
}
/// `collab.host`: host the open file (on this machine unless `p` says where) with an invite link.
pub(super) fn host(s: &mut Session, p: &Value) -> Result<Value> {
start_host(s, "collab.host", p, Bind::Local, false, false)?;
@@ -57,6 +75,7 @@ fn start_host(s: &mut Session, cmd: &str, p: &Value, bind: Bind, short: bool, vi
Some(other) => other.parse::<IpAddr>().map(Bind::Addr).map_err(|_| bad(cmd, "`bind` must be \"local\", \"lan\" or an IP address"))?,
};
let (doc, uid) = s.ds().map(|ds| (ds.doc.clone(), ds.uid))?;
check_sharable(cmd, &doc)?;
let opts = HostOptions { port, bind, name: display_name(&s.prefs), doc, short, view };
let (id, info) = s.live.start(cmd, |l, id| l.host(id, opts).map_err(|e| EngineError::Other(format!("couldn't start the live session: {e}"))))?;
s.live.open(Live { id, status: Status::Live, info: Some(info), doc_uid: Some(uid), tab: Some(uid), ..Live::default() });
@@ -75,6 +94,7 @@ pub(super) fn publish(s: &mut Session, p: &Value) -> Result<Value> {
fn start_publish(s: &mut Session, cmd: &str, server: &str, p: &Value, share: bool) -> Result<SessionId> {
let key = string(p, "key").map(|k| k.trim().to_string()).filter(|k| !k.is_empty());
let (doc, uid) = s.ds().map(|ds| (ds.doc.clone(), ds.uid))?;
check_sharable(cmd, &doc)?;
let name = string(p, "name").map(|n| n.trim().chars().filter(|c| !c.is_control()).take(256).collect::<String>()).filter(|n| !n.is_empty());
let me = display_name(&s.prefs);
let opts = PublishOptions { server: server.trim().to_string(), key, name: name.unwrap_or_else(|| doc.name.clone()), me, doc, share };
@@ -217,6 +217,124 @@ fn ordinary_resize_and_scale_keep_image_fill_settings() {
}
}
#[test]
fn crop_mode_image_resizing_without_cmd_morphs_and_with_cmd_crops() {
use figcraft_doc::color::{ImageScaleMode, PaintKind};
let mut s = session();
let layer = image_layer(&mut s);
// Set the image fill mode to Crop without an explicit crop: fill.set initializes placement crop.
let mut fills = s.doc().unwrap().node(layer).unwrap().fills.clone();
let PaintKind::Image(img) = &mut fills[0].kind else { panic!("image fill") };
img.scale_mode = ImageScaleMode::Crop;
img.crop = None;
ex(&mut s, "fill.set", json!({"ids": [layer], "index": 0, "paint": fills[0]}));
// Verify fill.set initialized img.crop with placement crop.
let initial_node = s.doc().unwrap().node(layer).unwrap().clone();
let PaintKind::Image(img) = &initial_node.fills[0].kind else { panic!("image fill") };
let Some(initial_crop) = img.crop else { panic!("crop initialized") };
let before = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
assert_eq!((before.width(), before.height()), (200, 100));
// 1. Resize without Cmd (normal resize from bottom edge: 100 -> 50).
// The layer height shrinks to 50, but img.crop stays unchanged, stretching/squishing the image.
s.pointer(&ev(PointerKind::Down, Point::new(100.0, 100.0), NONE)).unwrap();
s.pointer(&ev(PointerKind::Move, Point::new(100.0, 50.0), NONE)).unwrap();
s.pointer(&ev(PointerKind::Up, Point::new(100.0, 50.0), NONE)).unwrap();
assert_eq!(size(&s, layer), (200.0, 50.0));
let n = s.doc().unwrap().node(layer).unwrap().clone();
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
assert_eq!(img.crop, Some(initial_crop), "normal resize leaves crop transform unchanged");
let morphed = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
assert_eq!((morphed.width(), morphed.height()), (200, 50));
// 2. Resize with Cmd from right edge: 200 -> 100.
// The layer width shrinks to 100, and img.crop is updated so the pixels stay stationary on page (cropping).
s.pointer(&ev(PointerKind::Down, Point::new(200.0, 25.0), CMD)).unwrap();
s.pointer(&ev(PointerKind::Move, Point::new(100.0, 25.0), CMD)).unwrap();
s.pointer(&ev(PointerKind::Up, Point::new(100.0, 25.0), CMD)).unwrap();
assert_eq!(size(&s, layer), (100.0, 50.0));
let n = s.doc().unwrap().node(layer).unwrap().clone();
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
assert_ne!(img.crop, Some(initial_crop), "Cmd resize updates crop transform");
let cropped = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
assert_eq!((cropped.width(), cropped.height()), (100, 50));
// The remaining 100x50 pixels match the top-left 100x50 of morphed (pixels stayed still in layer space).
for y in 0..50usize {
assert_eq!(&cropped.data()[y * 400..(y + 1) * 400], &morphed.data()[y * 800..y * 800 + 400], "row {y}: stationary cropped pixels");
}
}
#[test]
fn multi_layer_crop_mode_selection_computes_placement_per_node() {
use figcraft_doc::color::{ImageScaleMode, PaintKind};
let mut s = session();
let layer1 = image_layer(&mut s); // 200 x 100
let layer2 = id(&ex(&mut s, "shape.rectangle", json!({"x": 300, "y": 0, "width": 100, "height": 100})));
// Choose Crop mode on both layers simultaneously via fill.set with crop: None (as the picker does).
let mut fill = s.doc().unwrap().node(layer1).unwrap().fills[0].clone();
let PaintKind::Image(img) = &mut fill.kind else { panic!("image fill") };
img.scale_mode = ImageScaleMode::Crop;
img.crop = None;
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": fill}));
// Verify both layers received crop transforms tailored to their own dimensions, not stretched.
let n1 = s.doc().unwrap().node(layer1).unwrap().clone();
let n2 = s.doc().unwrap().node(layer2).unwrap().clone();
let PaintKind::Image(img1) = &n1.fills[0].kind else { panic!("image fill") };
let PaintKind::Image(img2) = &n2.fills[0].kind else { panic!("image fill") };
let crop1 = img1.crop.expect("layer1 crop initialized");
let crop2 = img2.crop.expect("layer2 crop initialized");
// layer1 (200x100) and layer2 (100x100) have different aspect ratios, so their crop transforms must differ.
assert_ne!(crop1, crop2, "differently sized layers must have distinct crop transforms");
// Both should match expected placement crop for their respective dimensions (iw=200, ih=100 from image_layer):
assert_eq!(crop1, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
assert_eq!(crop2, [0.5, 0.0, 0.0, 1.0, 0.25, 0.0]);
// Rotate 90° on the multi-selection (as the picker's Rotate button does):
let mut rot_fill = n1.fills[0].clone();
let PaintKind::Image(img) = &mut rot_fill.kind else { panic!("image fill") };
img.rotation = 1;
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": rot_fill}));
let n1_rot = s.doc().unwrap().node(layer1).unwrap().clone();
let n2_rot = s.doc().unwrap().node(layer2).unwrap().clone();
let PaintKind::Image(img1_rot) = &n1_rot.fills[0].kind else { panic!("image fill") };
let PaintKind::Image(img2_rot) = &n2_rot.fills[0].kind else { panic!("image fill") };
let crop1_rot = img1_rot.crop.expect("layer1 rotated crop initialized");
let crop2_rot = img2_rot.crop.expect("layer2 rotated crop initialized");
assert_ne!(crop1_rot, crop2_rot, "differently sized layers must have distinct rotated crop transforms");
assert_eq!(crop1_rot, [1.0, 0.0, 0.0, 0.25, 0.0, 0.375]);
assert_eq!(crop2_rot, [1.0, 0.0, 0.0, 0.5, 0.0, 0.25]);
// Shared filter edit on multi-selection in Crop mode (e.g. Exposure slider):
let mut filter_fill = n1_rot.fills[0].clone();
let PaintKind::Image(img) = &mut filter_fill.kind else { panic!("image fill") };
img.filters.exposure = 0.5;
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": filter_fill}));
let n1_filt = s.doc().unwrap().node(layer1).unwrap().clone();
let n2_filt = s.doc().unwrap().node(layer2).unwrap().clone();
let PaintKind::Image(img1_filt) = &n1_filt.fills[0].kind else { panic!("image fill") };
let PaintKind::Image(img2_filt) = &n2_filt.fills[0].kind else { panic!("image fill") };
// Both layers keep their distinct crop transforms; neither is overwritten by the other.
assert_eq!(img1_filt.crop, Some(crop1_rot));
assert_eq!(img2_filt.crop, Some(crop2_rot));
assert_eq!(img1_filt.filters.exposure, 0.5);
assert_eq!(img2_filt.filters.exposure, 0.5);
}
#[test]
fn command_crop_preserves_each_image_fill_and_leaves_tiles() {
use figcraft_doc::color::{Color, ImageScaleMode, Paint, PaintKind};
+14 -6
View File
@@ -18,7 +18,7 @@ pub struct PromptDef {
pub defaults: &'static [(&'static str, &'static str)],
}
const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text; call screenshot at the end and look at it. Fix anything that is off before finishing, then report the ids of the frames you made.";
const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made or changed.";
pub const PROMPTS: &[PromptDef] = &[
PromptDef {
@@ -30,7 +30,7 @@ pub const PROMPTS: &[PromptDef] = &[
PromptArg { name: "device", description: "Frame preset (default \"iPhone 16\"; see run_command frame.presets)", required: false },
PromptArg { name: "brand_color", description: "Primary colour (default #3B5BDB)", required: false },
],
template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [14,24,14,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Bold text inside).\n4. Keep spacing on an 8-point grid and text left-aligned.{verify}",
template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Semi Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [16,24,16,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Semi Bold text inside). Name every layer by what it is.\n4. Keep spacing on an 8-point grid, text left-aligned, and no emoji in the interface.{verify}",
defaults: &[("device", "iPhone 16"), ("brand_color", "#3B5BDB")],
},
PromptDef {
@@ -41,7 +41,7 @@ pub const PROMPTS: &[PromptDef] = &[
PromptArg { name: "name", description: "Design system name (default \"Core\")", required: false },
PromptArg { name: "primary", description: "Primary colour (default #3B5BDB)", required: false },
],
template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": <id>}; text styles likewise from text layers (Heading 32 Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": <id>} and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}",
template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": <id>}; text styles likewise from text layers (Heading 32 Semi Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": <id>} and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}",
defaults: &[("name", "Core"), ("primary", "#3B5BDB")],
},
PromptDef {
@@ -51,10 +51,18 @@ pub const PROMPTS: &[PromptDef] = &[
args: &[
PromptArg { name: "product", description: "What the page sells", required: true },
PromptArg { name: "width", description: "Page width (default 1440)", required: false },
PromptArg { name: "accent", description: "Accent colour (default #7048E8)", required: false },
PromptArg { name: "accent", description: "Accent colour (default #2563EB)", required: false },
],
template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Bold headline, an 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft dropShadow effect, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text).\n3. Use batch to apply repeated styling to several ids in one undo step.\n4. Finish with sizingV hug on the page frame so it fits its content.{verify}",
defaults: &[("width", "1440"), ("accent", "#7048E8")],
template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Semi Bold headline, a 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft neutral dropShadow, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text, no lower than #6B7280).\n3. Name every layer by what it is. Use one accent, one neutral ramp and at most three text colours; no emoji, gradient text or glows.\n4. Use batch to apply repeated styling to several ids in one undo step.\n5. Finish with sizingV hug on the page frame so it fits its content.{verify}",
defaults: &[("width", "1440"), ("accent", "#2563EB")],
},
PromptDef {
name: "design_review",
title: "Review a design",
description: "Audit the selection, page or document for the usual AI-generated UI tells, fix the mechanical ones, then use judgment for copy, naming, gradients and overflow; re-audit and report what a person still has to decide.",
args: &[PromptArg { name: "target", description: "selection, page or document (default page)", required: false }],
template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}",
defaults: &[("target", "page")],
},
PromptDef {
name: "prototype_flow",
+5 -1
View File
@@ -51,8 +51,12 @@ screenshot returns a PNG of the page or of given layers to look at. undo/redo st
Comments: comment.list returns threads (text, anchor node id, frame, page, x/y, replies); fix open ones, \
reply with what changed, then resolve (a reply reopens a thread). To react to new feedback, call \
wait_for_changes {after, timeoutMs} and pass the returned cursor back. \
Design review: design.audit {scope} reports spacing, radii, type, colour, contrast, copy and naming findings \
with severities; design.fix repairs the fixable ones as one undo step; design.rules lists the rules and \
presets; design.configure {preset, grid, radii, brand, disabled} sets the file's design system, and \
design.assert {failOn, minScore} is a read-only CI gate. \
Resources: figcraft://document, figcraft://node/{id}, figcraft://command/{id}, figcraft://comments. \
prompts/list has workflows, including fix_comments.";
prompts/list has workflows, including fix_comments and design_review.";
/// An MCP server bound to one backend.
pub struct Server {
+53
View File
@@ -102,6 +102,8 @@ pub const TOOL_NAMES: &[&str] = &[
"get_node",
"design_context",
"export_assets",
"component_mappings",
"sync_mappings",
"select",
"export",
"screenshot",
@@ -126,6 +128,8 @@ const DOCUMENT_TOOLS: &[&str] = &[
"get_node",
"design_context",
"export_assets",
"component_mappings",
"sync_mappings",
"select",
"export",
"screenshot",
@@ -286,6 +290,33 @@ fn tools() -> Vec<Value> {
),
false,
),
tool(
"component_mappings",
"Component mappings",
"Which code component each design component is: its import, code name, source file, a ready snippet, its properties and variants, and which design values need translating. Check this before writing a component: reuse a mapped one, never recreate it. `unmapped` lists those with no code component yet.",
obj(
json!({
"ids": ids_schema("Layers: the components they are, use or hold (default every component in the file)"),
"unmapped": boolean("Only components without a mapping"),
"root": string("The code repository, to check each link's source file is there (default where this server runs)")
}),
&[],
),
true,
),
tool(
"sync_mappings",
"Sync mappings with a repository",
"Apply a code repository's figcraft.connect.json to the open design (`import`, one undo step), or write the design's mappings to it (`export`, keeping its other keys and the links of components this design doesn't have). Run `import` first when component_mappings shows less than the repository should have.",
obj(
json!({
"direction": {"type": "string", "enum": ["import", "export"], "description": "import: file to design. export: design to file"},
"path": string("The file (default figcraft.connect.json where this server runs)")
}),
&["direction"],
),
false,
),
tool(
"select",
"Select layers",
@@ -490,6 +521,26 @@ fn export_assets(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResu
exec(b, "file.exportAssets", Value::Object(params)).map(|v| ToolResult::json(&v))
}
/// `codeConnect.list`, checking source files against `root`, else where this server runs.
fn component_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
let mut params = a.clone();
let root = std::path::absolute(s_arg(a, "root")?.unwrap_or(".")).map_err(|e| format!("root: {e}"))?;
params.insert("root".into(), json!(root.to_string_lossy()));
exec(b, "codeConnect.list", Value::Object(params)).map(|v| ToolResult::json(&v))
}
/// `codeConnect.import` or `.export` with a code repository's connect file, made absolute here: an
/// attached app runs in another folder.
fn sync_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
let command = match s_arg(a, "direction")? {
Some("import") => "codeConnect.import",
Some("export") => "codeConnect.export",
_ => return Err("`direction`: import or export".into()),
};
let path = std::path::absolute(s_arg(a, "path")?.unwrap_or("figcraft.connect.json")).map_err(|e| format!("path: {e}"))?;
exec(b, command, json!({"path": path.to_string_lossy()})).map(|v| ToolResult::json(&v))
}
fn wait_for_changes(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
b.call("events.poll", Value::Object(a.clone())).map(|v| ToolResult::json(&v))
}
@@ -637,6 +688,8 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
"get_node" => get_node(b, &a),
"design_context" => design_context(b, &a),
"export_assets" => export_assets(b, &a),
"component_mappings" => component_mappings(b, &a),
"sync_mappings" => sync_mappings(b, &a),
"select" => select(b, &a),
"export" => export(b, &a),
"screenshot" => screenshot(b, &a),
+37
View File
@@ -0,0 +1,37 @@
//! `component_mappings` and `sync_mappings` against a code repository's connect file.
use serde_json::{Value, json};
use crate::common::Client;
fn repo(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("figcraft-mcp-connect-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::canonicalize(dir).unwrap()
}
#[test]
fn mappings_travel_through_a_repositorys_file() {
let dir = repo("travel");
let mut c = Client::new();
let frame = c.create(json!({"type": "frame", "name": "Tag", "width": 80, "height": 24}));
let main = c.run("component.create", json!({"ids": [frame]}))["id"].clone();
let file = dir.join("figcraft.connect.json");
std::fs::write(&file, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Tag","language":"react","importPath":"@/ui/tag","name":"Tag","template":"<Tag />","source":"src/tag.tsx"}]}"#).unwrap();
let before = c.ok("component_mappings", json!({"unmapped": true, "root": dir}));
assert_eq!(before["unmapped"], 1);
c.ok("sync_mappings", json!({"direction": "import", "path": file}));
let after = c.ok("component_mappings", json!({"ids": [main], "root": dir}));
let link = &after["components"][0]["links"][0];
assert_eq!(link["import"], r#"import { Tag } from "@/ui/tag";"#);
assert_eq!(link["sourceFound"], false, "src/tag.tsx isn't there yet");
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/tag.tsx"), "").unwrap();
assert_eq!(c.ok("component_mappings", json!({"ids": [main], "root": dir}))["components"][0]["links"][0]["sourceFound"], true);
c.ok("sync_mappings", json!({"direction": "export", "path": file}));
let written: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
assert_eq!(written["project"]["name"], "shop", "keys the export doesn't own stay");
assert_eq!(written["links"][0]["source"], "src/tag.tsx");
assert!(c.err("sync_mappings", json!({"direction": "sideways"})).contains("import or export"));
}
+2
View File
@@ -8,6 +8,8 @@ mod agent_tasks;
mod attached;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::disallowed_methods)]
mod automation_roots;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod code_connect;
#[allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+4 -1
View File
@@ -219,13 +219,16 @@ fn prompts_list_and_get() {
let mut c = Client::new();
let r = c.rpc("prompts/list", json!({}));
let names: Vec<&str> = r["result"]["prompts"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect();
assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "prototype_flow", "fix_comments", "watch_comments"]);
assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments"]);
let r = c.rpc("prompts/get", json!({"name": "mobile_screen", "arguments": {"screen": "login"}}));
let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap();
assert!(text.contains("login") && text.contains("iPhone 16") && text.contains("#3B5BDB") && !text.contains("{device}"));
assert_eq!(c.rpc("prompts/get", json!({"name": "mobile_screen"}))["error"]["code"], -32602);
assert_eq!(c.rpc("prompts/get", json!({"name": "nope"}))["error"]["code"], -32602);
assert_eq!(c.rpc("prompts/get", json!({"name": "landing_page", "arguments": {"product": ["x"]}}))["error"]["code"], -32602);
let r = c.rpc("prompts/get", json!({"name": "design_review", "arguments": {"target": "document"}}));
let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap();
assert!(text.contains("design.audit") && text.contains("\"document\"") && !text.contains("{target}"), "{text}");
let r = c.rpc("prompts/get", json!({"name": "prototype_flow"}));
assert!(r["result"]["messages"][0]["content"]["text"].as_str().unwrap().contains("Home, Details, Checkout"));
let r = c.rpc("prompts/get", json!({"name": "fix_comments", "arguments": {"auto_resolve": "no", "author": "Ada"}}));
+5
View File
@@ -392,6 +392,9 @@ name = "English"
"Ctrl+arrows" = "Ctrl+arrows"
"Ctrl+click" = "Ctrl+click"
"Ctrl+click a padding field" = "Ctrl+click a padding field"
"In code" = "In code"
"Source file" = "Source file"
"Variant value" = "Variant value"
"⌘ click a padding field" = "⌘ click a padding field"
"Ctrl+scroll" = "Ctrl+scroll"
"Current name" = "Current name"
@@ -1469,6 +1472,8 @@ name = "English"
"Small caps" = "Small caps"
"Smart animate" = "Smart animate"
"Snap to pixel grid" = "Snap to pixel grid"
"Snap to pixel grid off" = "Snap to pixel grid off"
"Snap to pixel grid on" = "Snap to pixel grid on"
"Social and slides" = "Social and slides"
"Social media" = "Social media"
"Social post sizes" = "Social post sizes"
File diff suppressed because it is too large. Load diff
+220
View File
@@ -1346,6 +1346,8 @@ name = "Русский"
"Small caps" = "Капитель"
"Smart animate" = "Smart animate"
"Snap to pixel grid" = "Привязка к пиксельной сетке"
"Snap to pixel grid off" = "Привязка к пиксельной сетке выключена"
"Snap to pixel grid on" = "Привязка к пиксельной сетке включена"
"Social and slides" = "Соцсети и слайды"
"Social media" = "Соцсети"
"Social post sizes" = "Размеры публикаций для соцсетей"
@@ -1864,6 +1866,183 @@ name = "Русский"
"⌘ click" = "⌘ нажатие"
"⌘ scroll" = "⌘ прокрутка"
"⌥ drag" = "⌥ перетаскивание"
"1 year" = "1 год"
"30 days" = "30 дней"
"90 days" = "90 дней"
"A layer in an auto layout frame is placed by its frame" = "Слой в Frame с автолейаутом размещается своим Frame"
"Allow and download" = "Разрешить и загрузить"
"Allow downloading fonts?" = "Разрешить загрузку шрифтов?"
"Alt+double-click an edge of an auto layout child" = "Alt+двойное нажатие по краю дочернего объекта автолейаута"
"Android Vector Drawable" = "Android Vector Drawable"
"Annotation" = "Аннотация"
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Все в вашей сети с этим кодом могут смотреть файл, но не менять его, пока это приложение открыто."
"Auto: as many words as fit on each line" = "Авто: столько слов, сколько помещается в строке"
"Auto: by the first letter with a direction" = "Авто: по первой букве, у которой есть направление"
"Balance" = "Баланс"
"Balance: every line close to the same length" = "Баланс: все строки примерно одной длины"
"Best effort" = "По возможности"
"Board grid" = "Сетка доски"
"Calculated from other variables; it follows them" = "Вычисляется из других переменных и следует за ними"
"Changed {date}" = "Изменено {date}"
"Check for Updates" = "Проверить обновления"
"Check for updates…" = "Проверить обновления…"
"Compare with" = "Сравнить с"
"Compatibility" = "Совместимость"
"Copied comments for AI" = "Комментарии скопированы для ИИ"
"Copy browser link" = "Копировать ссылку для браузера"
"Copy effect" = "Копировать эффект"
"Copy fill" = "Копировать заливку"
"Copy for AI" = "Копировать для ИИ"
"Copy link to page" = "Копировать ссылку на страницу"
"Copy stroke" = "Копировать обводку"
"Couldn't download {name}" = "Не удалось загрузить {name}"
"Couldn't reach {server} for its team list." = "Не удалось связаться с {server}, чтобы получить список команды."
"Crop image" = "Обрезать изображение"
"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓"
"Ctrl+click a padding field" = "Ctrl+нажатие по полю внутреннего отступа"
"Dart constants for Flutter…" = "Константы Dart для Flutter…"
"Delete {n} variables" = { one = "Удалить {n} переменную", few = "Удалить {n} переменные", many = "Удалить {n} переменных", other = "Удалить {n} переменных" }
"Detach calculation" = "Отвязать вычисление"
"Developer Mode only inspects: switch to Design (Shift+D) to edit" = "Режим разработчика только просматривает: чтобы редактировать, перейдите в «Дизайн» (Shift+D)"
"Disconnected. Reconnecting…" = "Соединение разорвано. Повторное подключение…"
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Соединение разорвано. Ваши правки остаются здесь и синхронизируются, когда связь восстановится. Повторное подключение…"
"Dismiss" = "Закрыть"
"Don't show this again" = "Больше не показывать"
"Double-click an edge of an auto layout frame" = "Двойное нажатие по краю Frame с автолейаутом"
"Download" = "Загрузить"
"Downloading… {percent}%" = "Загрузка… {percent}%"
"Drop to use this image" = "Перетащите, чтобы использовать это изображение"
"Duplicate group" = "Дублировать группу"
"Edit padding on all sides" = "Изменить внутренние отступы со всех сторон"
"Edit variables" = "Редактировать переменные"
"Enter / Shift+Enter" = "Enter / Shift+Enter"
"Everyone who reaches this server can open these files while they are shared." = "Все, кто имеет доступ к этому серверу, могут открывать эти файлы, пока они опубликованы."
"Exact only" = "Только точные"
"Expand the interface" = "Развернуть интерфейс"
"Exported {name}; {n} kinds of content were changed or left out" = { one = "Файл {name} экспортирован; {n} тип содержимого изменён или пропущен", few = "Файл {name} экспортирован; {n} типа содержимого изменены или пропущены", many = "Файл {name} экспортирован; {n} типов содержимого изменены или пропущены", other = "Файл {name} экспортирован; {n} типов содержимого изменены или пропущены" }
"Exported {n} files; some content was changed or left out" = { one = "Экспортирован {n} файл; часть содержимого изменена или пропущена", few = "Экспортировано {n} файла; часть содержимого изменена или пропущена", many = "Экспортировано {n} файлов; часть содержимого изменена или пропущена", other = "Экспортировано {n} файлов; часть содержимого изменена или пропущена" }
"Extra large" = "Очень крупный"
"FigCraft stopped because of an internal error." = "FigCraft остановился из-за внутренней ошибки."
"Format" = "Формат"
"Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "Бесплатные шрифты поступают из Google Fonts и Noto через jsDelivr и GitHub. Каждый файл сверяется с указателем шрифтов, прежде чем будет установлен в общую папку шрифтов программ Craft. Ничего не загружается, пока вы это не разрешите."
"Graph paper" = "Бумага в клетку"
"Hide UI" = "Скрыть интерфейс"
"Huge" = "Огромный"
"Ignore unsupported" = "Пропускать неподдерживаемое"
"Invert zoom direction" = "Инвертировать направление масштабирования"
"Joining live session…" = "Подключение к сеансу…"
"Large" = "Крупный"
"Leaving the prototype" = "Выход из прототипа"
"Left to right" = "Слева направо"
"Link copied: it opens the file in FigCraft" = "Ссылка скопирована: она открывает файл в FigCraft"
"Link copied: it opens the file in the browser" = "Ссылка скопирована: она открывает файл в браузере"
"Medium" = "Средний"
"Move out of any group" = "Вынести из любой группы"
"Move to group {group}" = "Переместить в группу {group}"
"Move up or down while dragging its label" = "Перемещать вверх или вниз, перетаскивая подпись"
"New from selection" = "Создать из выделения"
"No comments to copy" = "Нет комментариев для копирования"
"No scope is shared by all the selected variables" = "У выделенных переменных нет общей области применения"
"Nobody shares a file there now." = "Сейчас там никто не публикует файл."
"Not connected: {reason}. Your work is still in this tab." = "Нет соединения: {reason}. Ваша работа остаётся в этой вкладке."
"Not now" = "Не сейчас"
"Nothing changed since this version." = "С этой версии ничего не изменилось."
"Nothing counted yet" = "Пока ничего не подсчитано"
"Nothing to pick: the page is empty" = "Нечего выбрать: страница пуста"
"Past 30 days" = "За 30 дней"
"Past 90 days" = "За 90 дней"
"Past year" = "За год"
"Paste effect" = "Вставить эффект"
"Paste fill" = "Вставить заливку"
"Paste stroke" = "Вставить обводку"
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Выбор указанием: Tab и Shift+Tab переходят между слоями, Enter входит в слой, Shift+Enter выходит, Space выделяет, Escape отменяет"
"Pick select: into a layer, out to its parent" = "Выбор указанием: войти в слой, выйти к родителю"
"Pick select: next or previous layer" = "Выбор указанием: следующий или предыдущий слой"
"Pick select: select the picked layer" = "Выбор указанием: выделить указанный слой"
"Pretty" = "Аккуратно"
"Pretty: full lines, no one word alone on the last" = "Аккуратно: полные строки, без одного слова в последней"
"Reload the page to get back the unsaved files the browser had room for." = "Перезагрузите страницу, чтобы вернуть несохранённые файлы, для которых в браузере хватило места."
"Reload the page to get your unsaved files back." = "Перезагрузите страницу, чтобы вернуть несохранённые файлы."
"Reload the page to start again." = "Перезагрузите страницу, чтобы начать снова."
"Remove all auto layout" = "Убрать весь автолейаут"
"Removed since this version" = "Удалено с этой версии"
"Reset grid" = "Сбросить сетку"
"Retry now" = "Повторить сейчас"
"Right to left" = "Справа налево"
"Rotate a degree (Shift: 15)" = "Повернуть на градус (Shift: на 15)"
"Same as file ({profile})" = "Как в файле ({profile})"
"Save a copy…" = "Сохранить копию…"
"Scope" = "Область применения"
"Scope: all supported properties" = "Область применения: все поддерживаемые свойства"
"Scope: hidden from pickers" = "Область применения: скрыто в списках выбора"
"Scope: only {scope}" = "Область применения: только {scope}"
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Менять значение поля быстрее (2x) или медленнее (1/2, 1/4)"
"Scrubbing at 1/2" = "Изменение со скоростью 1/2"
"Scrubbing at 1/4" = "Изменение со скоростью 1/4"
"Scrubbing at 1x" = "Изменение со скоростью 1x"
"Scrubbing at 2x" = "Изменение со скоростью 2x"
"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Выделите строку, столбец или полную сетку из трёх и более слоёв вне потока автолейаута"
"Selection box: switch to pick select" = "Рамка выделения: переключиться на выбор указанием"
"Server key" = "Ключ сервера"
"Set as opening page" = "Сделать стартовой страницей"
"Set corner smoothing to 60%" = "Задать сглаживание углов 60%"
"Set fill container" = "Задать: заполнить контейнер"
"Set hug contents" = "Задать: по размеру содержимого"
"Shared by your team on {server}" = "Опубликовано вашей командой на {server}"
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Показать и перемещать перекрестие размещения (когда выбран его инструмент и ничего не выделено)"
"Small" = "Мелкий"
"Space" = "Space"
"Strong line every" = "Жирная линия каждые"
"Subscript" = "Нижний индекс"
"Superscript" = "Верхний индекс"
"Tab or Ctrl+Space again" = "Tab или Ctrl+Space ещё раз"
"Text direction" = "Направление текста"
"Text on a path" = "Текст по контуру"
"The bars are hidden. {shortcut} shows them again" = "Панели скрыты. {shortcut} показывает их снова"
"This link opens a website outside the prototype:" = "Эта ссылка открывает сайт вне прототипа:"
"This link opens your mail app to write a message:" = "Эта ссылка открывает почтовую программу, чтобы написать сообщение:"
"This server doesn't count detached instances" = "Этот сервер не считает отвязанные экземпляры"
"This server doesn't count insertions" = "Этот сервер не считает вставки"
"This server doesn't count styles and variables" = "Этот сервер не считает стили и переменные"
"This variant's value" = "Значение этого варианта"
"This version can't be read." = "Эту версию не удалось прочитать."
"This version doesn't have it: all of it is new." = "В этой версии этого нет: всё появилось позже."
"Update check is not supported in the web browser." = "Проверка обновлений в браузере не поддерживается."
"Upload from computer" = "Загрузить с компьютера"
"What changed since a saved version" = "Что изменилось с сохранённой версии"
"When marked ready" = "Когда отмечено готовым"
"Wrap style" = "Стиль переноса"
"Your unsaved files were too large for the browser to keep." = "Несохранённые файлы оказались слишком большими, чтобы браузер их сохранил."
"connector labels without a saved snapshot are centred on the line, without their background" = "подписи соединителей без сохранённого снимка центрируются на линии, без фона"
"elbowed and curved connectors without a saved path are routed afresh" = "ломаные и кривые соединители без сохранённого контура прокладываются заново"
"instance swap properties whose default component was past the layer limit were skipped" = "свойства замены экземпляра, у которых компонент по умолчанию выходил за предел слоёв, пропущены"
"instances whose component was past the layer limit were imported as frames" = "экземпляры, чей компонент выходил за предел слоёв, импортированы как Frame"
"invalid vector region fill paint list; layer fill used" = "недопустимый список заливок векторной области; использована заливка слоя"
"invalid vector region paints were skipped" = "недопустимые заливки векторной области пропущены"
"linked vector region fill styles keep resolved appearance; live style links were left out" = "связанные стили заливки векторной области сохраняют вычисленное оформление; живые связи стилей опущены"
"note or shape generated child has invalid bounds; child skipped" = "у сгенерированного потомка заметки или фигуры недопустимые границы; потомок пропущен"
"note or shape generated child is missing its style or bounds; child skipped" = "у сгенерированного потомка заметки или фигуры нет стиля или границ; потомок пропущен"
"note or shape generated children exceed the layer or nesting limit; remaining children skipped" = "сгенерированные потомки заметки или фигуры превышают предел слоёв или вложенности; остальные потомки пропущены"
"note or shape generated layout is missing or unsupported; using its outer frame" = "сгенерированная вёрстка заметки или фигуры отсутствует или не поддерживается; использован внешний Frame"
"shape generated outline is missing or damaged; using its rectangle" = "сгенерированный контур фигуры отсутствует или повреждён; использован её прямоугольник"
"sticky layers import as frames with their text" = "слои стикеров импортируются как Frame вместе со своим текстом"
"swapped instances whose previous component isn't in the file took the new component's look" = "заменённые экземпляры, чей прежний компонент отсутствует в файле, получили вид нового компонента"
"variable-bound vector region paints keep resolved appearance; live bindings were left out" = "привязанные к переменным заливки векторной области сохраняют вычисленное оформление; живые привязки опущены"
"vector region paint data exceeded import limits and was skipped" = "данные заливки векторной области превысили пределы импорта и пропущены"
"vector region references a missing fill style; layer fill used" = "векторная область ссылается на отсутствующий стиль заливки; использована заливка слоя"
"{count} in it now · Changed {date}" = "Сейчас в нём {count} · Изменено {date}"
"{insertions} · {detachments}" = "{insertions} · {detachments}"
"{name}, disconnected from its live session" = "{name}, отключён от сеанса"
"{n} detached" = { one = "{n} отвязан", few = "{n} отвязаны", many = "{n} отвязано", other = "{n} отвязано" }
"{n} inserted" = { one = "{n} вставлен", few = "{n} вставлены", many = "{n} вставлено", other = "{n} вставлено" }
"{period}: {counts}" = "{period}: {counts}"
"{used} · {detached}" = "{used} · {detached}"
"{used} · {inserted}" = "{used} · {inserted}"
"↵ / ⇧↵" = "↵ / ⇧↵"
"⇥ or ⌥ Space again" = "⇥ или ⌥ Space ещё раз"
"⌘ click a padding field" = "⌘ нажатие по полю внутреннего отступа"
"⌥ double-click an edge of an auto layout child" = "⌥ двойное нажатие по краю дочернего объекта автолейаута"
"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓"
[commands]
"align.bottom" = "Выровнять по нижнему краю"
@@ -2479,6 +2658,44 @@ name = "Русский"
"window.focus" = "Вывести окно на передний план"
"window.new" = "Новое окно"
"template.list" = "Список шаблонов"
"board.grid" = "Сетка доски"
"board.reshape" = "Изменить форму соединителя"
"collab.reconnect" = "Переподключить сеанс"
"comment.prompt" = "Копировать комментарии для ИИ"
"data.fill" = "Заполнить копии данными"
"effect.copy" = "Копировать эффект"
"effect.paste" = "Вставить эффект"
"file.fontReport" = "Проверить шрифты документа"
"file.markSaved" = "Отметить как сохранённый"
"fill.copy" = "Копировать заливку"
"fill.paste" = "Вставить заливку"
"font.download" = "Загрузить шрифт"
"font.downloads" = "Загрузки шрифтов"
"image.crop" = "Обрезать изображение"
"image.replace" = "Заменить изображение"
"layout.removeAll" = "Убрать весь автолейаут"
"library.check" = "Проверить обновления библиотек команды"
"pref.invertZoom" = "Инвертировать направление масштабирования"
"pref.uiScaleDown" = "Меньший интерфейс"
"pref.uiScaleReset" = "Размер интерфейса по умолчанию"
"pref.uiScaleUp" = "Больший интерфейс"
"proto.linkNotice" = "Уведомление перед переходом по ссылке"
"selection.createColorStyle" = "Создать стиль цвета из выделения"
"stroke.copy" = "Копировать обводку"
"stroke.paste" = "Вставить обводку"
"text.direction" = "Направление текста"
"text.directionAuto" = "Направление текста: авто"
"text.directionLtr" = "Направление текста: слева направо"
"text.directionRtl" = "Направление текста: справа налево"
"text.fit" = "Вписать текст в блок"
"text.openLink" = "Открыть ссылку"
"text.wrapStyle" = "Стиль переноса"
"tool.annotation" = "Аннотация"
"tool.crosshair" = "Переместить перекрестие размещения"
"tool.textOnPath" = "Текст по контуру"
"variable.extendCollection" = "Расширить коллекцию"
"view.minimize" = "Свернуть интерфейс"
"widget.hover" = "Виджет наведения"
[menu]
"bool.exclude" = "Исключение"
@@ -2512,3 +2729,6 @@ name = "Русский"
"view.themeDark" = "Тёмная"
"view.themeLight" = "Светлая"
"view.themeSystem" = "Системная"
"text.directionAuto" = "Авто"
"text.directionLtr" = "Слева направо"
"text.directionRtl" = "Справа налево"
+1 -1
View File
@@ -1574,7 +1574,7 @@ status = "draft — needs native review"
"Texts" = "உரைகள்"
"Texture" = "அமைப்பு"
"The bars are hidden. {shortcut} shows them again" = "பட்டைகள் மறைக்கப்பட்டுள்ளன. {shortcut} அவற்றை மீண்டும் காட்டும்"
"The destination document is unavailable. Nothing was imported." = "இலக்கு ஆவணம் கிடைக்கவில்லை. எதுவும் இறக்குமதி செய்யப்படவில்லை."
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "கேன்வாஸ் நிறங்களை sRGB இல் காட்டுகிறது; ஏற்றுமதி செய்த PNG, JPG, WebP கோப்புகள் Display P3 எனக் குறிக்கப்படும்."
"The destination document was closed. Nothing was imported." = "இலக்கு ஆவணம் மூடப்பட்டது. எதுவும் இறக்குமதி செய்யப்படவில்லை."
"The destination page was removed. Nothing was imported." = "இலக்குப் பக்கம் அகற்றப்பட்டது. எதுவும் இறக்குமதி செய்யப்படவில்லை."
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "கோப்பு சர்வரிலிருந்து நீக்கப்படும்: இனி யாரும் அங்கிருந்து அதைத் திறக்கவோ சேரவோ முடியாது, இதைச் செயல்தவிர்க்க முடியாது. திறந்திருக்கும் நகல்கள் அவற்றை வைத்திருப்பவர்களிடமே இருக்கும்."
+286
View File
@@ -1815,6 +1815,235 @@ name = "Türkçe"
"⌘ scroll" = "⌘ kaydırma"
"⌥ drag" = "⌥ sürükle"
"1 year" = "1 yıl"
"30 days" = "30 gün"
"90 days" = "90 gün"
"A layer in an auto layout frame is placed by its frame" = "Otomatik yerleşim çerçevesindeki bir katman, çerçevesi tarafından yerleştirilir"
"A layer on its own aligns to its frame: select more layers, or one in a frame" = "Tek başına bir katman çerçevesine hizalanır: daha fazla katman veya çerçeve içindeki bir katmanı seçin"
"Adding to {name}" = "{name} öğesine ekleniyor"
"All the fonts this file uses are installed" = "Bu dosyanın kullandığı tüm yazı tipleri yüklü"
"Allow and download" = "İzin ver ve indir"
"Allow downloading fonts?" = "Yazı tiplerinin indirilmesine izin verilsin mi?"
"Alt+double-click an edge of an auto layout child" = "Otomatik yerleşim alt öğesinin bir kenarına Alt+çift tıklayın"
"Android Vector Drawable" = "Android Vector Drawable"
"Annotation" = "Ek açıklama"
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Ağınızdaki bu koda sahip herkes, bu uygulama açık kaldığı sürece dosyayı değiştirmeden görüntüleyebilir."
"Auto: as many words as fit on each line" = "Otomatik: her satıra sığdığı kadar sözcük"
"Auto: by the first letter with a direction" = "Otomatik: yönü olan ilk harfe göre"
"Balance" = "Dengeli"
"Balance: every line close to the same length" = "Dengeli: her satır yaklaşık aynı uzunlukta"
"Best effort" = "En iyi uyum"
"Board grid" = "Pano ızgarası"
"Bottom padding" = "Alt iç boşluk"
"Calculated from other variables; it follows them" = "Diğer değişkenlerden hesaplanır; onları izler"
"Changed {date}" = "{date} tarihinde değiştirildi"
"Check for Updates" = "Güncellemeleri Denetle"
"Check for updates…" = "Güncellemeleri denetle…"
"Checking the fonts installed on this computer…" = "Bu bilgisayarda yüklü yazı tipleri denetleniyor…"
"Compare with" = "Şununla karşılaştır"
"Compatibility" = "Uyumluluk"
"Convert to frame" = "Çerçeveye dönüştür"
"Convert to section" = "Bölüme dönüştür"
"Copied comments for AI" = "Yorumlar yapay zeka için kopyalandı"
"Copy browser link" = "Tarayıcı bağlantısını kopyala"
"Copy effect" = "Efekti kopyala"
"Copy fill" = "Dolguyu kopyala"
"Copy for AI" = "Yapay zeka için kopyala"
"Copy link to page" = "Sayfa bağlantısını kopyala"
"Copy stroke" = "Konturu kopyala"
"Couldn't download the variables" = "Değişkenler indirilemedi"
"Couldn't download {name}" = "{name} indirilemedi"
"Couldn't reach {server} for its team list." = "Ekip listesi için {server} sunucusuna ulaşılamadı."
"Couldn't save automatically: {error}" = "Otomatik olarak kaydedilemedi: {error}"
"Crop image" = "Görseli kırp"
"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓"
"Ctrl+click a padding field" = "Bir iç boşluk alanına Ctrl+tıklayın"
"Dart constants for Flutter…" = "Flutter için Dart sabitleri…"
"Delete {n} variables" = { other = "{n} değişkeni sil" }
"Detach calculation" = "Hesaplamayı ayır"
"Developer Mode only inspects: switch to Design (Shift+D) to edit" = "Geliştirici Modu yalnızca inceler: düzenlemek için Tasarım (Shift+D) moduna geçin"
"Disconnected. Reconnecting…" = "Bağlantı kesildi. Yeniden bağlanılıyor…"
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Bağlantı kesildi. Düzenlemeleriniz burada kalır ve bağlantı geri geldiğinde eşitlenir. Yeniden bağlanılıyor…"
"Dismiss" = "Kapat"
"Don't show this again" = "Bunu bir daha gösterme"
"Double-click an edge of an auto layout frame" = "Otomatik yerleşim çerçevesinin bir kenarına çift tıklayın"
"Download" = "İndir"
"Downloading… {percent}%" = "İndiriliyor… %{percent}"
"Drop a .figcraft, .fig, .jam, .sketch, .json, .svg or image file." = "Bir .figcraft, .fig, .jam, .sketch, .json, .svg veya görsel dosyası bırakın."
"Drop to import" = "İçe aktarmak için bırakın"
"Drop to open" = "Açmak için bırakın"
"Drop to use this image" = "Bu görseli kullanmak için bırakın"
"Duplicate group" = "Grubu çoğalt"
"Edit padding on all sides" = "Tüm kenarlardaki iç boşluğu düzenle"
"Edit variables" = "Değişkenleri düzenle"
"Enter / Shift+Enter" = "Enter / Shift+Enter"
"Everyone who reaches this server can open these files while they are shared." = "Bu sunucuya erişebilen herkes, paylaşıldıkları sürece bu dosyaları açabilir."
"Exact only" = "Yalnızca birebir"
"Expand the interface" = "Arayüzü genişlet"
"Exported {name}; {n} kinds of content were changed or left out" = { other = "{name} dışa aktarıldı; {n} tür içerik değiştirildi veya dışarıda bırakıldı" }
"Exported {n} files; some content was changed or left out" = { other = "{n} dosya dışa aktarıldı; bazı içerikler değiştirildi veya dışarıda bırakıldı" }
"Extra large" = "Çok büyük"
"FigCraft couldn't open its window: {error}" = "FigCraft penceresini açamadı: {error}"
"FigCraft stopped because of an internal error." = "FigCraft bir iç hata nedeniyle durdu."
"FigCraft tried {apis}, then again with lower requirements on the power-saving GPU. Updating the graphics driver often helps." = "FigCraft {apis} ile denedi, ardından güç tasarruflu GPU üzerinde daha düşük gereksinimlerle yeniden denedi. Grafik sürücüsünü güncellemek genellikle yardımcı olur."
"Format" = "Biçim"
"Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "Ücretsiz yazı tipleri, jsDelivr ve GitHub aracılığıyla Google Fonts ve Noto'dan sağlanır. Her dosya, Craft uygulamalarının ortak kullandığı yazı tipi klasörüne yüklenmeden önce yazı tipi diziniyle karşılaştırılarak denetlenir. Siz izin verene kadar hiçbir şey indirilmez."
"Graph paper" = "Milimetrik kâğıt"
"Hide UI" = "Arayüzü gizle"
"Huge" = "Devasa"
"If it keeps happening, please report it at {link} with this message." = "Sorun devam ederse lütfen bu mesajla birlikte {link} adresinden bildirin."
"Ignore unsupported" = "Desteklenmeyenleri yoksay"
"Individual padding" = "Ayrı ayrı iç boşluk"
"Interface size" = "Arayüz boyutu"
"Invert zoom direction" = "Yakınlaştırma yönünü tersine çevir"
"Joining live session…" = "Canlı oturuma katılınıyor…"
"Large" = "Büyük"
"Leaving the prototype" = "Prototipten çıkılıyor"
"Left padding" = "Sol iç boşluk"
"Left to right" = "Soldan sağa"
"Link copied: it opens the file in FigCraft" = "Bağlantı kopyalandı: dosyayı FigCraft'ta açar"
"Link copied: it opens the file in the browser" = "Bağlantı kopyalandı: dosyayı tarayıcıda açar"
"Medium" = "Orta"
"Missing fonts" = "Eksik yazı tipleri"
"Move out of any group" = "Tüm grupların dışına taşı"
"Move to group {group}" = "{group} grubuna taşı"
"Move up or down while dragging its label" = "Etiketini sürüklerken yukarı veya aşağı hareket ettirin"
"New from selection" = "Seçimden yeni oluştur"
"No comments to copy" = "Kopyalanacak yorum yok"
"No files or templates match your search" = "Aramanızla eşleşen dosya veya şablon yok"
"No other pages" = "Başka sayfa yok"
"No scope is shared by all the selected variables" = "Seçili tüm değişkenlerin paylaştığı bir kapsam yok"
"Nobody shares a file there now." = "Şu anda orada kimse dosya paylaşmıyor."
"Not connected: {reason}. Your work is still in this tab." = "Bağlı değil: {reason}. Çalışmanız hâlâ bu sekmede."
"Not now" = "Şimdi değil"
"Nothing changed since this version." = "Bu sürümden bu yana hiçbir şey değişmedi."
"Nothing counted yet" = "Henüz sayılan bir şey yok"
"Nothing to pick: the page is empty" = "Seçilecek bir şey yok: sayfa boş"
"Opening the file…" = "Dosya açılıyor…"
"Opening {n} files as new files" = { other = "{n} dosya yeni dosya olarak açılıyor" }
"Other" = "Diğer"
"Past 30 days" = "Son 30 gün"
"Past 90 days" = "Son 90 gün"
"Past year" = "Son 1 yıl"
"Paste effect" = "Efekti yapıştır"
"Paste fill" = "Dolguyu yapıştır"
"Paste stroke" = "Konturu yapıştır"
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Katman seçici: Tab ve Shift+Tab katmanlar arasında gezinir, Enter katmanın içine girer, Shift+Enter dışına çıkar, Space seçer, Escape iptal eder"
"Pick select: into a layer, out to its parent" = "Katman seçici: katmanın içine gir, üst katmana çık"
"Pick select: next or previous layer" = "Katman seçici: sonraki veya önceki katman"
"Pick select: select the picked layer" = "Katman seçici: işaretlenen katmanı seç"
"Plugin" = "Eklenti"
"Plugins & widgets" = "Eklentiler ve widget'lar"
"Pretty" = "Düzenli"
"Pretty: full lines, no one word alone on the last" = "Dengeli: tam satırlar, son satırda tek sözcük kalmaz"
"Relative to your system's display scaling (100% is the system's own size). Document zoom is separate." = "Sisteminizin ekran ölçeklendirmesine göredir (%100 sistemin kendi boyutudur). Belge yakınlaştırması ayrıdır."
"Reload the page to get back the unsaved files the browser had room for." = "Tarayıcının yer ayırabildiği kaydedilmemiş dosyaları geri almak için sayfayı yeniden yükleyin."
"Reload the page to get your unsaved files back." = "Kaydedilmemiş dosyalarınızı geri almak için sayfayı yeniden yükleyin."
"Reload the page to start again." = "Yeniden başlamak için sayfayı yeniden yükleyin."
"Remove all auto layout" = "Tüm otomatik yerleşimleri kaldır"
"Remove {name} from session" = "{name} adlı kişiyi oturumdan kaldır"
"Removed since this version" = "Bu sürümden bu yana kaldırıldı"
"Reorder selection" = "Seçimi yeniden sırala"
"Reset grid" = "Izgarayı sıfırla"
"Retry now" = "Şimdi yeniden dene"
"Right padding" = "Sağ iç boşluk"
"Right to left" = "Sağdan sola"
"Rotate a degree (Shift: 15)" = "Bir derece döndür (Shift: 15)"
"Same as file ({profile})" = "Dosyayla aynı ({profile})"
"Save a copy…" = "Kopyasını kaydet…"
"Save files automatically" = "Dosyaları otomatik kaydet"
"Scope" = "Kapsam"
"Scope: all supported properties" = "Kapsam: desteklenen tüm özellikler"
"Scope: hidden from pickers" = "Kapsam: seçicilerden gizli"
"Scope: only {scope}" = "Kapsam: yalnızca {scope}"
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Bir alanı daha hızlı (2x) veya daha yavaş (1/2, 1/4) kaydırarak ayarlayın"
"Scrubbing at 1/2" = "1/2 hızında kaydırma"
"Scrubbing at 1/4" = "1/4 hızında kaydırma"
"Scrubbing at 1x" = "1x hızında kaydırma"
"Scrubbing at 2x" = "2x hızında kaydırma"
"Search files and templates" = "Dosya ve şablonlarda ara"
"Search pages" = "Sayfalarda ara"
"Search results" = "Arama sonuçları"
"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Otomatik yerleşim akışı dışında üç veya daha fazla katmandan oluşan bir satır, sütun veya tam ızgara seçin"
"Selection box: switch to pick select" = "Seçim kutusu: tıklayarak seçime geç"
"Server key" = "Sunucu anahtarı"
"Set as opening page" = "Açılış sayfası olarak ayarla"
"Set corner smoothing to 60%" = "Köşe yumuşatmayı %60 olarak ayarla"
"Set fill container" = "Kapsayıcıyı doldur olarak ayarla"
"Set hug contents" = "İçeriği sar olarak ayarla"
"Shared by your team on {server}" = "{server} üzerinde ekibiniz tarafından paylaşıldı"
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Yerleştirme artı işaretini göster ve taşı (aracı seçiliyken, hiçbir şey seçili değilken)"
"Small" = "Küçük"
"Space" = "Boşluk"
"Start on the Home screen" = "Ana ekranda başlat"
"Strong line every" = "Kalın çizgi aralığı"
"Subscript" = "Alt simge"
"Superscript" = "Üst simge"
"Tab or Ctrl+Space again" = "Tekrar Tab veya Ctrl+Space"
"Text direction" = "Metin yönü"
"Text on a path" = "Yol üzerinde metin"
"The bars are hidden. {shortcut} shows them again" = "Çubuklar gizli. {shortcut} bunları yeniden gösterir"
"The destination document is unavailable. Nothing was imported." = "Hedef belge kullanılamıyor. Hiçbir şey içe aktarılmadı."
"The destination document was closed. Nothing was imported." = "Hedef belge kapatılmış. Hiçbir şey içe aktarılmadı."
"The destination page was removed. Nothing was imported." = "Hedef sayfa kaldırılmış. Hiçbir şey içe aktarılmadı."
"The window is too small for {size}%, so the interface is drawn at {drawn}%. Make the window larger to use {size}%." = "Pencere %{size} için çok küçük olduğundan arayüz %{drawn} olarak çiziliyor. %{size} kullanmak için pencereyi büyütün."
"This file is too large to join here (up to {mb} MB)" = "Bu dosya buraya eklenmek için çok büyük (en fazla {mb} MB)"
"This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Bu dosya, bu bilgisayarda yüklü olmayan yazı tiplerini kullanıyor. Siz yükleyene kadar ilgili metinler yedek bir yazı tipiyle çizilir."
"This link opens a website outside the prototype:" = "Bu bağlantı prototip dışında bir web sitesi açar:"
"This link opens your mail app to write a message:" = "Bu bağlantı ileti yazmak için e-posta uygulamanızı açar:"
"This server doesn't count detached instances" = "Bu sunucu ayrılmış örnekleri saymaz"
"This server doesn't count insertions" = "Bu sunucu eklemeleri saymaz"
"This server doesn't count styles and variables" = "Bu sunucu stilleri ve değişkenleri saymaz"
"This variant's value" = "Bu varyantın değeri"
"This version can't be read." = "Bu sürüm okunamıyor."
"This version doesn't have it: all of it is new." = "Bu sürümde yok: tamamı yeni."
"Top padding" = "Üst iç boşluk"
"Try another search, or browse templates." = "Başka bir arama deneyin veya şablonlara göz atın."
"Update check is not supported in the web browser." = "Güncelleme denetimi web tarayıcısında desteklenmiyor."
"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "Grafik sürücüsünü güncellemek genellikle işe yarar. Yalnızca OpenGL kullanmak için FigCraft'ı Komut İstemi'nden şu komutla başlatın:"
"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "Grafik sürücüsünü güncellemek genellikle işe yarar. WGPU_BACKEND (vulkan, gl, metal) denenecek başka bir grafik API'sini belirtir."
"Upload from computer" = "Bilgisayardan yükle"
"Use your browser's zoom to change the interface size." = "Arayüz boyutunu değiştirmek için tarayıcınızın yakınlaştırma ayarını kullanın."
"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND ayarlı ve kullanılacak grafik API'sini belirtiyor; bu ayarı kaldırmak seçimi FigCraft'a bırakır."
"What changed since a saved version" = "Kaydedilmiş bir sürümden bu yana değişenler"
"When marked ready" = "Hazır olarak işaretlendiğinde"
"Widget" = "Widget"
"Wrap style" = "Satır kaydırma stili"
"Your unsaved files were too large for the browser to keep." = "Kaydedilmemiş dosyalarınız tarayıcının saklayabileceği boyuttan büyüktü."
"connector labels without a saved snapshot are centred on the line, without their background" = "kaydedilmiş anlık görüntüsü olmayan bağlayıcı etiketleri, arka planları olmadan çizginin ortasına hizalandı"
"elbowed and curved connectors without a saved path are routed afresh" = "kaydedilmiş yolu olmayan dirsekli ve kavisli bağlayıcılar yeniden yönlendirildi"
"instance swap properties whose default component was past the layer limit were skipped" = "varsayılan bileşeni katman sınırını aşan örnek değiştirme özellikleri atlandı"
"instances whose component was past the layer limit were imported as frames" = "bileşeni katman sınırını aşan örnekler çerçeve olarak içe aktarıldı"
"invalid vector region fill paint list; layer fill used" = "geçersiz vektör bölgesi dolgu boyası listesi; katman dolgusu kullanıldı"
"invalid vector region paints were skipped" = "geçersiz vektör bölgesi boyaları atlandı"
"linked vector region fill styles keep resolved appearance; live style links were left out" = "bağlı vektör bölgesi dolgu stilleri çözümlenmiş görünümü korur; canlı stil bağlantıları dışarıda bırakıldı"
"note or shape generated child has invalid bounds; child skipped" = "not veya şekil tarafından oluşturulan alt öğenin sınırları geçersiz; alt öğe atlandı"
"note or shape generated child is missing its style or bounds; child skipped" = "not veya şekil tarafından oluşturulan alt öğenin stili veya sınırları eksik; alt öğe atlandı"
"note or shape generated children exceed the layer or nesting limit; remaining children skipped" = "not veya şekil tarafından oluşturulan alt öğeler katman veya iç içe geçme sınırını aşıyor; kalan alt öğeler atlandı"
"note or shape generated layout is missing or unsupported; using its outer frame" = "not veya şekil tarafından oluşturulan yerleşim eksik veya desteklenmiyor; dış çerçevesi kullanılıyor"
"only in a text style or variable" = "yalnızca bir metin stilinde veya değişkende"
"shape generated outline is missing or damaged; using its rectangle" = "şekil tarafından oluşturulan dış hat eksik veya bozuk; dikdörtgeni kullanılıyor"
"slot layers without a matching slot property were imported as frames" = "eşleşen yuva özelliği olmayan yuva katmanları çerçeve olarak içe aktarıldı"
"sticky layers import as frames with their text" = "yapışkan not katmanları metinleriyle birlikte çerçeve olarak içe aktarılır"
"swapped instances whose previous component isn't in the file took the new component's look" = "önceki bileşeni dosyada bulunmayan değiştirilmiş örnekler yeni bileşenin görünümünü aldı"
"variable-bound vector region paints keep resolved appearance; live bindings were left out" = "değişkene bağlı vektör bölgesi boyaları çözümlenmiş görünümü korur; canlı bağlamalar dışarıda bırakıldı"
"vector region paint data exceeded import limits and was skipped" = "vektör bölgesi boya verileri içe aktarma sınırlarını aştığı için atlandı"
"vector region references a missing fill style; layer fill used" = "vektör bölgesi eksik bir dolgu stiline başvuruyor; katman dolgusu kullanıldı"
"{count} in it now · Changed {date}" = "Şu anda {count} · Değiştirilme: {date}"
"{insertions} · {detachments}" = "{insertions} · {detachments}"
"{name}, disconnected from its live session" = "{name}, canlı oturum bağlantısı kesildi"
"{n} detached" = { other = "{n} ayrıldı" }
"{n} inserted" = { other = "{n} eklendi" }
"{n} text layers" = { other = "{n} metin katmanı" }
"{percent}%" = "%{percent}"
"{period}: {counts}" = "{period}: {counts}"
"{used} · {detached}" = "{used} · {detached}"
"{used} · {inserted}" = "{used} · {inserted}"
"↵ / ⇧↵" = "↵ / ⇧↵"
"⇥ or ⌥ Space again" = "Tekrar ⇥ veya ⌥ Space"
"⌘ click a padding field" = "⌘ tuşuyla bir iç boşluk alanına tıklayın"
"⌥ double-click an edge of an auto layout child" = "⌥ tuşuyla otomatik yerleşim alt öğesinin bir kenarına çift tıklayın"
"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓"
[commands]
"align.bottom" = "Alta hizala"
"align.hcenter" = "Yatay merkezleri hizala"
@@ -2420,6 +2649,60 @@ name = "Türkçe"
"window.new" = "Yeni pencere"
"template.list" = "Şablonları listele"
"arrange.reorder" = "Yeniden sırala"
"board.codeBlock" = "Kod bloğu"
"board.grid" = "Pano ızgarası"
"board.mindMap" = "Zihin haritası"
"board.mindMapAdd" = "Zihin haritası düğümü ekle"
"board.reshape" = "Panoyu yeniden şekillendir"
"board.setLanguage" = "Kod dili"
"collab.reconnect" = "Yeniden bağlan"
"collab.removePerson" = "Kişiyi oturumdan kaldır"
"comment.prompt" = "Yorumları yapay zeka için kopyala"
"data.fill" = "Veri doldur"
"effect.copy" = "Efekti kopyala"
"effect.paste" = "Efekti yapıştır"
"file.fontReport" = "Yazı tipi raporu"
"file.markSaved" = "Kaydedildi olarak işaretle"
"fill.copy" = "Dolguyu kopyala"
"fill.paste" = "Dolguyu yapıştır"
"font.download" = "Yazı tipini indir"
"font.downloads" = "Yazı tipi indirmeleri"
"image.crop" = "Görseli kırp"
"image.replace" = "Görseli değiştir"
"inspect.designContext" = "Tasarım bağlamı"
"layout.removeAll" = "Tüm yerleşimleri kaldır"
"library.check" = "Kitaplığı denetle"
"object.convertToSection" = "Bölüme dönüştür"
"page.setOpening" = "Açılış sayfası olarak ayarla"
"pref.autoSave" = "Otomatik kaydet"
"pref.invertZoom" = "Yakınlaştırmayı ters çevir"
"pref.startOnHome" = "Ana sayfada başlat"
"pref.uiScale" = "Arayüz ölçeği"
"pref.uiScaleDown" = "Arayüz ölçeğini küçült"
"pref.uiScaleReset" = "Arayüz ölçeğini sıfırla"
"pref.uiScaleUp" = "Arayüz ölçeğini büyüt"
"proto.linkNotice" = "Prototip bağlantı bildirimi"
"selection.createColorStyle" = "Seçimden renk stili oluştur"
"stroke.copy" = "Konturu kopyala"
"stroke.paste" = "Konturu yapıştır"
"text.direction" = "Metin yönü"
"text.directionAuto" = "Metin yönü: Otomatik"
"text.directionLtr" = "Metin yönü: Soldan sağa"
"text.directionRtl" = "Metin yönü: Sağdan sola"
"text.fit" = "Metni sığdır"
"text.loadFont" = "Yazı tipini yükle"
"text.missingFonts" = "Eksik yazı tipleri"
"text.openLink" = "Bağlantıyı aç"
"text.refit" = "Metni yeniden sığdır"
"text.rescanFonts" = "Yazı tiplerini yeniden tara"
"text.wrapStyle" = "Metin kaydırma stili"
"tool.annotation" = "Ek açıklama aracı"
"tool.crosshair" = "Artı işareti aracı"
"tool.textOnPath" = "Yol üzerinde metin aracı"
"variable.extendCollection" = "Değişken koleksiyonunu genişlet"
"view.minimize" = "Simge durumuna küçült"
"widget.hover" = "Araç takımı üzerine gelme"
[menu]
"bool.exclude" = "Hariç tut"
"bool.flatten" = "Düzleştir"
@@ -2452,3 +2735,6 @@ name = "Türkçe"
"view.themeDark" = "Koyu"
"view.themeLight" = "Açık"
"view.themeSystem" = "Sistemi izle"
"text.directionAuto" = "Otomatik"
"text.directionLtr" = "Soldan sağa"
"text.directionRtl" = "Sağdan sola"
+14
View File
@@ -22,9 +22,23 @@ impl FigApp {
// `file.open`/`file.close`). Record that presentation before returning, so an in-flight
// screenshot admitted on the old file cannot accept pixels from the new one.
self.observe_presentation();
if let Ok(v) = &r {
self.note_snapping(id, v);
}
r.map_err(|e| self.failed(id, &e)).ok()
}
/// Snap to pixel grid turned on or off says which at the bottom, as in Figma: its shortcut
/// (Shift+Cmd/Ctrl+') changes nothing on the canvas until the next drag.
fn note_snapping(&mut self, id: &str, result: &Value) {
let msg = match (id, result.get("on").and_then(Value::as_bool)) {
("view.snapPixel", Some(true)) => crate::i18n::tr("Snap to pixel grid on"),
("view.snapPixel", Some(false)) => crate::i18n::tr("Snap to pixel grid off"),
_ => return,
};
self.toast(msg);
}
/// A programmatic command that changed the engine clipboard never wrote the system clipboard:
/// forget the old system mirror so a later user paste does not trust it as our own copy.
/// `before` is the layers generation captured before the command ran.
+38
View File
@@ -72,6 +72,44 @@ impl FigApp {
}
}
/// Whether the colour picker is being used right now for the selected layers' own look (a
/// paint, an effect, a text range or Selection colors): a drag on its value controls (the
/// palette, the hue and alpha sliders, a number field, the gradient bar and its stops), the
/// keyboard in one of its fields, the eyedropper sampling, or a drag of the canvas handles it
/// owns (gradient stops and handles, image crop). Only then does the canvas hide the selection
/// frame and a text's coloured selection, so the colour being chosen shows against the page.
/// Merely having the picker open, or pressing a button, a menu or a swatch, leaves it visible.
pub(crate) fn picker_hides_selection(&self, ctx: &egui::Context) -> bool {
let edits_selection = matches!(
self.ui.picker,
Some(
crate::colorpicker::PickerTarget::Paint { .. }
| crate::colorpicker::PickerTarget::Effect { .. }
| crate::colorpicker::PickerTarget::TextRange { .. }
| crate::colorpicker::PickerTarget::SelectionColor { .. }
)
);
if !edits_selection {
return false;
}
// The picker draws after the canvas, so its card comes from the previous frame.
let card = self.ui.picker_popover.as_ref();
// A drag changes the colour live; a press alone does not. Buttons, menus, swatches and the
// paint-type switches are clicks and must not hide the selection while held (they used to,
// which flickered it). Dragging the card by its header moves the popover, not the colour.
let header_drag = card.map(|c| c.header_drag_id());
let dragging = ctx.dragged_id().is_some_and(|id| header_drag != Some(id))
&& ctx.input(|i| i.pointer.any_down() && i.pointer.press_origin().is_some_and(|p| card.is_some_and(|c| c.rect.contains(p))));
// A value field keeps the keyboard after its click: hide until focus leaves the picker.
// Only a text edit counts: every clicked control takes focus in egui, and a focused
// palette square or swatch must not keep the selection hidden after the drag.
let typing = ctx.text_edit_focused()
&& ctx
.memory(|m| m.focused())
.is_some_and(|id| ctx.read_response(id).is_some_and(|r| card.is_some_and(|c| c.rect.contains_rect(r.rect))));
dragging || typing || self.session.tool.pick_only || crate::handles::gradient_dragging(ctx) || crate::handles::crop_dragging(ctx)
}
/// Leaving Design ends a pen path as Escape does and goes back to Move: Prototype and Inspect
/// don't draw (#307). Checked as the frame starts (the control channel) and after the panels
/// and shortcuts (the mode switcher, the tabs, Shift+E/Shift+D), before the canvas sees more.
+2 -2
View File
@@ -21,7 +21,7 @@ mod drag_sprite;
mod input;
pub(crate) use input::release_fields_for_press;
mod outline;
mod overlays;
pub(crate) mod overlays;
mod render;
mod rulers;
@@ -350,7 +350,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
Some((rect, _)) => crate::drop_overlay(&ctx, rect, tr("Drop to use this image")),
None => crate::drop_overlay(&ctx, ctx.content_rect(), label),
}
crate::guides::end_released(&ctx);
crate::guides::end_released(app, &ctx);
crate::live::track_pointer(app, &ctx);
app.sync_preedit();
// Retained rendering snaps the view outward and adds one pixel on each axis.
+32 -10
View File
@@ -229,13 +229,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
d.remove::<GuideDrag>(drag_id());
d.remove::<Placed>(preview_id());
});
// Released over its own ruler (the left one for a guide running down the screen): no
// guide (a moved one is removed).
let down = at.map_or(vertical, |g| {
let [a, b] = segment(app, &g, r);
(b.y - a.y).abs() >= (b.x - a.x).abs()
});
let on_ruler = if down { pos.x < r.min.x + RULER } else { pos.y < r.min.y + RULER };
let on_ruler = on_own_ruler(app, at, vertical, pos);
let page = app.session.ds().map(|d| d.page).ok();
let before = app.session.doc().ok().and_then(|d| match drag {
GuideDrag::Move { owner, index, .. } => d.node(owner).and_then(|n| n.guides().get(index)).map(|g| g.offset),
@@ -297,17 +291,45 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
false
}
/// Whether `pos` is over the ruler a guide comes back to, or past it: the left ruler for a guide
/// running down the screen, the top one otherwise. `at` is where the guide would land, if anywhere.
fn on_own_ruler(app: &FigApp, at: Option<Placed>, vertical: bool, pos: Pos2) -> bool {
let r = app.canvas.rect;
let down = at.map_or(vertical, |g| {
let [a, b] = segment(app, &g, r);
(b.y - a.y).abs() >= (b.x - a.x).abs()
});
if down { pos.x < r.min.x + RULER } else { pos.y < r.min.y + RULER }
}
/// Ends a guide drag whose button is up by the end of the frame without [`input`] taking the
/// release (released off the canvas, or over something on it): the gesture is dropped, so a later
/// click doesn't add or move a guide.
pub fn end_released(ctx: &egui::Context) {
/// click doesn't add or move a guide. A moved guide released past its own ruler is removed, as on
/// the ruler: the ruler is thin, and a drag back onto it often overshoots onto the panel beside it.
pub fn end_released(app: &mut FigApp, ctx: &egui::Context) {
if ctx.input(|i| i.pointer.primary_down()) {
return;
}
ctx.data_mut(|d| {
let (drag, at) = ctx.data_mut(|d| {
let taken = (d.get_temp::<GuideDrag>(drag_id()), d.get_temp::<Placed>(preview_id()));
d.remove::<GuideDrag>(drag_id());
d.remove::<Placed>(preview_id());
taken
});
let Some(GuideDrag::Move { owner, index, vertical, copy: false, .. }) = drag else { return };
// Where the button came up: a later move in the same frame, or a touch's end clearing the
// pointer, doesn't change it.
let released_at = ctx.input(|i| {
i.events.iter().rev().find_map(|e| match e {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(*pos),
_ => None,
})
});
let Some(pos) = released_at else { return };
if rulers_on(app) && on_own_ruler(app, at, vertical, pos) {
let page = app.session.ds().map(|d| d.page).ok();
app.run("guide.remove", owned(owner, page, json!({"index": index})));
}
}
/// Draw the page's and its frames' guides (under the rulers) and the one being dragged with its
+2 -2
View File
@@ -697,8 +697,8 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> Input {
}
}
if let Some((id, fills, index, _, rect)) = crop_target(app) {
// Crop mode: the layer's own resize handles crop it (the pointer events carry Cmd/Ctrl).
if app.ui.crop.is_some() && on_resize_handle(app, pos) {
// The layer's own resize handles resize/crop the layer, not the crop handles.
if on_resize_handle(app, pos) {
return Input::Ignored;
}
let Some(c) = crop_corners(app, id, rect) else { return Input::Ignored };
+20 -8
View File
@@ -124,7 +124,10 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec
}
// Selection.
let editing = ds.text_edit.clone();
if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() {
// While the colour picker is being used on the selection, hide its frame and handles so the
// colour being picked shows on the layer itself (a text's coloured selection would hide it
// too).
if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() && !app.picker_hides_selection(painter.ctx()) {
size_label = selection_overlay(app, painter, ds, &doc, &sel, zoom);
}
if app.session.tool.tool == ToolId::ShapeBuilder
@@ -171,22 +174,27 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec
labels
}
/// The pixel grid's lines: one screen pixel wide, a light grey at a fifth of its strength, so
/// they darken white and lighten a dark canvas or fill alike. Measured in Figma (2026-11-24):
/// 242 on white and 78 on a grey of 50, which this grey gives.
pub(crate) const PIXEL_GRID: Color32 = Color32::from_rgba_unmultiplied_const(190, 190, 190, 51);
/// Pixel grid at high zoom.
fn pixel_grid(app: &FigApp, painter: &egui::Painter) {
let r = app.canvas.rect;
let p0 = app.to_page(r.min);
let p1 = app.to_page(r.max);
let col = Color32::from_black_alpha(18);
let line = stroke(PIXEL_GRID, 1.0 / painter.pixels_per_point());
let mut x = p0.x.floor();
while x <= p1.x {
let s = app.to_screen(x, 0.0).x;
painter.line_segment([pos2(s, r.min.y), pos2(s, r.max.y)], stroke(col, 1.0));
let s = painter.round_to_pixel_center(app.to_screen(x, 0.0).x);
painter.line_segment([pos2(s, r.min.y), pos2(s, r.max.y)], line);
x += 1.0;
}
let mut y = p0.y.floor();
while y <= p1.y {
let s = app.to_screen(0.0, y).y;
painter.line_segment([pos2(r.min.x, s), pos2(r.max.x, s)], stroke(col, 1.0));
let s = painter.round_to_pixel_center(app.to_screen(0.0, y).y);
painter.line_segment([pos2(r.min.x, s), pos2(r.max.x, s)], line);
y += 1.0;
}
}
@@ -268,12 +276,16 @@ fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Do
let preedit = app.preedit_view();
let edoc: &Document = preedit.map(|p| &*p.doc).unwrap_or(doc);
let Some(text) = TextOnScreen::of(edoc, te.id) else { return };
// While the colour picker is being used on this text, its frame and coloured selection hide
// too: the selection colour tinted the very characters whose colour is being chosen. The
// caret stays.
let picking = app.picker_hides_selection(painter.ctx());
let layout = &text.layout;
if let Some(q) = node_quad(app, edoc, te.id) {
if !picking && let Some(q) = node_quad(app, edoc, te.id) {
quad(painter, q, stroke(accent(painter), 1.0));
}
let (a, b) = (te.caret.min(te.anchor), te.caret.max(te.anchor));
if a != b && preedit.is_none() {
if a != b && preedit.is_none() && !picking {
for q in text.selection(app, a, b) {
painter.add(Shape::convex_polygon(q.to_vec(), accent(painter).gamma_multiply(0.3), Stroke::NONE));
}
+14
View File
@@ -131,6 +131,11 @@ fn shows(code: &str, web: bool) -> bool {
// Arabic; keep the catalog out until an embedded Arabic fallback is supplied.
return figcraft_text::face_with_char('ع', &["Noto Sans Arabic"]).is_some();
}
if code.split(['-', '_']).next().is_some_and(|b| b.eq_ignore_ascii_case("he") || b.eq_ignore_ascii_case("iw")) {
// Desktop draws Hebrew with a system face (or bundled craft-fonts); the web leaves it out
// unless Noto Sans Hebrew is embedded (FIGCRAFT_EMBED_SCRIPTS=Hebr).
return figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]).is_some();
}
if code.split('-').next() == Some("ta") {
// Desktop draws Tamil with a system face (#2018); the web has none until craft-fonts
// carries Noto Sans Tamil.
@@ -233,6 +238,15 @@ mod tests {
assert_eq!(shows("ar-SA", true), face);
}
#[test]
fn the_web_offers_hebrew_only_with_its_face() {
assert!(shows("he", false), "desktop always lists Hebrew");
let face = figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]).is_some();
assert_eq!(shows("he", true), face);
assert_eq!(shows("he-IL", true), face);
assert_eq!(shows("iw-IL", true), face);
}
#[test]
fn the_web_offers_tamil_only_with_its_face() {
assert!(shows("ta", false), "desktop always lists Tamil");
@@ -372,3 +372,172 @@ fn a_gradient_drag_whose_gesture_closes_under_the_held_button_stops_editing() {
u.button(u.app.to_screen(180.0, 200.0), false);
}
}
/// Whether `shape` is painted in `col`, as a fill or a stroke.
fn painted_in(shape: &egui::Shape, col: egui::Color32) -> bool {
use egui::epaint::ColorMode;
match shape {
egui::Shape::Path(p) => p.fill == col || matches!(p.stroke.color, ColorMode::Solid(c) if c == col),
egui::Shape::Rect(r) => r.fill == col || r.stroke.color == col,
egui::Shape::LineSegment { stroke, .. } => stroke.color == col,
egui::Shape::Circle(c) => c.fill == col || c.stroke.color == col,
egui::Shape::Vec(v) => v.iter().any(|s| painted_in(s, col)),
_ => false,
}
}
/// How many shapes painted in `col` this frame draws inside `area`. On the page those are the
/// selection's frame, its handles and a text's coloured selection.
fn painted_around(out: &egui::FullOutput, area: egui::Rect, col: egui::Color32) -> usize {
out.shapes.iter().filter(|c| painted_in(&c.shape, col) && c.shape.visual_bounding_rect().intersects(area)).count()
}
/// A text layer's box on screen, with room for its handles.
fn text_area(u: &Ui, id: NodeId) -> egui::Rect {
let b = u.app.session.doc().unwrap().world_bounds(id).unwrap();
egui::Rect::from_two_pos(u.app.to_screen(b.x0, b.y0), u.app.to_screen(b.x1, b.y1)).expand(20.0)
}
fn selected_text(s: &mut Session) -> NodeId {
let id =
NodeId(s.execute("text.create", &json!({"text": "Hello", "x": 300, "y": 200, "props": {"fontSize": 48}})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id]})).unwrap();
id
}
// The colour picker only hides the selection while it is being used: opening it leaves the frame in
// view, and the press/drag on its controls hides it. A text makes this matter: its frame runs
// through the glyphs and its selection is tinted.
#[test]
fn a_selected_texts_frame_hides_only_while_its_colour_picker_is_used() {
let mut s = Session::new();
let text = selected_text(&mut s);
let mut u = Ui::new(s);
let area = text_area(&u, text);
let accent = crate::theme::canvas_accent(&u.ctx);
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "the selected text's frame shows");
let target = PickerTarget::Paint { fills: true, index: 0, ids: vec![text] };
u.app.open_picker(target.clone(), None);
for _ in 0..3 {
u.frame(vec![]);
}
assert_eq!(u.app.ui.picker, Some(target.clone()), "the picker is open");
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "an open picker alone leaves the frame in view");
// A press alone changes nothing; dragging the saturation/value square uses the picker.
let square = u.ctx.read_response(egui::Id::unique("cp_sv")).expect("the saturation/value square").rect;
let from = square.center();
let to = from + egui::vec2(12.0, 8.0);
u.button(from, true);
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "holding the palette still leaves the frame");
u.frame(vec![egui::Event::PointerMoved(to)]);
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "dragging the palette hides the frame");
u.button(to, false);
assert_eq!(u.app.ui.picker, Some(target), "releasing does not close the picker");
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "releasing brings the frame back");
// A button in the picker (the blend dropdown) is a click, not a value drag.
let button = egui::pos2(square.center().x, square.min.y - 30.0);
u.button(button, true);
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "holding a picker button leaves the frame");
u.button(button, false);
}
// The picker's header is its drag handle: moving the card is not choosing a colour.
#[test]
fn dragging_the_picker_by_its_header_does_not_hide_the_selection() {
let mut s = Session::new();
let text = selected_text(&mut s);
let mut u = Ui::new(s);
let area = text_area(&u, text);
let accent = crate::theme::canvas_accent(&u.ctx);
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
for _ in 0..3 {
u.frame(vec![]);
}
let header = u.app.ui.picker_popover.as_ref().expect("the picker is open").header.center();
let before = u.app.ui.picker_popover.as_ref().unwrap().rect;
u.button(header, true);
for k in 1..=5 {
u.frame(vec![egui::Event::PointerMoved(header - egui::vec2(0.0, 6.0 * k as f32))]);
}
assert!(u.app.ui.picker_popover.as_ref().unwrap().rect.min.y < before.min.y - 10.0, "the header drag moved the picker");
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "moving the picker leaves the frame in view");
u.button(header - egui::vec2(0.0, 30.0), false);
}
#[test]
fn a_texts_coloured_selection_hides_only_while_its_colour_picker_is_used() {
let mut s = Session::new();
let text = selected_text(&mut s);
// Select all of it: the selection highlight the colour picker's own layer would otherwise wear.
figcraft_engine::textedit::begin(&mut s, text, None, false).unwrap();
let mut u = Ui::new(s);
let area = text_area(&u, text);
let tint = crate::theme::canvas_accent(&u.ctx).gamma_multiply(0.3);
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "the text selection is tinted");
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
for _ in 0..3 {
u.frame(vec![]);
}
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "an open picker alone leaves it tinted");
let square = u.ctx.read_response(egui::Id::unique("cp_sv")).expect("the saturation/value square").rect;
let from = square.center();
let to = from + egui::vec2(10.0, 6.0);
u.button(from, true);
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "holding the palette still leaves the tint");
u.frame(vec![egui::Event::PointerMoved(to)]);
assert_eq!(painted_around(&u.frame_output(vec![]), area, tint), 0, "dragging the palette hides the tint");
u.button(to, false);
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "releasing brings the tint back");
}
// Typing a colour value counts as using the picker even when no mouse button is down.
#[test]
fn a_focused_colour_field_hides_the_selection_while_it_is_edited() {
let mut s = Session::new();
let text = selected_text(&mut s);
let mut u = Ui::new(s);
let area = text_area(&u, text);
let accent = crate::theme::canvas_accent(&u.ctx);
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
for _ in 0..3 {
u.frame(vec![]);
}
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "the frame shows while the picker is idle");
let hex = u.ctx.read_response(egui::Id::unique("cp_hex").with("click")).expect("the Hex field").rect;
u.button(hex.center(), true);
u.button(hex.center(), false);
for _ in 0..2 {
u.frame(vec![]);
}
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "a focused value field hides the frame");
u.frame(vec![egui::Event::Text("0".into())]);
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "and typing in it keeps the frame hidden");
}
// egui gives every clicked control the keyboard, a palette square and a swatch included. Only a
// text field means the picker is being used: a square that keeps focus must not keep the
// selection hidden after its drag ends.
#[test]
fn a_focused_palette_square_does_not_hide_the_selection() {
let mut s = Session::new();
let text = selected_text(&mut s);
let mut u = Ui::new(s);
let area = text_area(&u, text);
let accent = crate::theme::canvas_accent(&u.ctx);
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
for _ in 0..3 {
u.frame(vec![]);
}
// What egui does to a clicked square.
u.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("cp_sv")));
for _ in 0..2 {
u.frame(vec![]);
}
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "focus on a palette square leaves the frame in view");
}
+16 -38
View File
@@ -141,11 +141,11 @@ fn choose_mode(u: &mut Ui, shown: &str, item: &str) {
u.frame(vec![]);
}
/// Crop chosen as the image fill's mode in the colour picker enters crop mode, as Crop image does
/// (#2150): the picker closes, the picture keeps its place, and a corner handle then crops it
/// with the layer still selected. The other modes only set the mode.
/// Crop chosen as the image fill's mode in the colour picker sets the mode with a placement crop
/// (#2499): the picker stays open, crop mode on the canvas does not start, and dragging a corner
/// handle without Cmd resizes the layer and morphs/squishes the image.
#[test]
fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
fn crop_chosen_in_the_colour_picker_sets_mode_and_morphs_on_resize() {
let (mut u, layer, _) = setup();
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] });
for _ in 0..4 {
@@ -155,8 +155,8 @@ fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
assert_eq!(mode(&u, layer), (ImageScaleMode::Fit, None));
assert!(u.app.ui.picker.is_some() && u.app.ui.crop.is_none(), "Fit is only a mode");
choose_mode(&mut u, "Fit", "Crop");
assert_eq!(u.app.ui.crop, Some((layer, 0)), "crop mode on the image fill");
assert!(u.app.ui.picker.is_none(), "crop mode takes the canvas from the picker");
assert_eq!(u.app.ui.crop, None, "Crop in picker does not enter canvas crop mode");
assert!(u.app.ui.picker.is_some(), "picker stays open");
// The picture keeps its place: the crop is the one Crop image makes of the fitted image.
let (m, Some(before)) = mode(&u, layer) else { panic!("a crop where the picture was") };
assert_eq!(m, ImageScaleMode::Crop);
@@ -169,29 +169,18 @@ fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
assert_eq!(mode(&menu, other), (ImageScaleMode::Fit, None));
menu.app.run("image.crop", json!({}));
assert_eq!(mode(&menu, other), (ImageScaleMode::Crop, Some(before)));
// The bottom right corner, dragged in, crops the picture to the top left 3/4 of the layer.
// Close the picker to drag the canvas resize handles.
u.app.ui.picker = None;
u.frame(vec![]);
// Dragging the bottom right corner without Cmd resizes the layer to 150x75 and morphs/squishes the image.
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(150.0, 75.0));
u.drag_to(from, to);
u.button(to, false);
assert_eq!(u.app.session.selection(), vec![layer], "the layer stays selected");
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
assert!((n.width - 150.0).abs() < 1e-6 && (n.height - 75.0).abs() < 1e-6, "{} x {}", n.width, n.height);
let (_, Some(after)) = mode(&u, layer) else { panic!("a crop") };
assert!((after[0] - before[0] * 0.75).abs() < 1e-9 && (after[3] - before[3] * 0.75).abs() < 1e-9, "{before:?} -> {after:?}");
assert!((after[4] - before[4]).abs() < 1e-9 && (after[5] - before[5]).abs() < 1e-9, "the top left stays: {before:?} -> {after:?}");
// The picture's own corner, now outside the layer at (200, 100), scales the picture inside the
// layer, which keeps its size and its selection.
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(240.0, 120.0));
u.drag_to(from, to);
u.button(to, false);
assert_eq!(u.app.session.selection(), vec![layer], "the layer stays selected");
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
assert!((n.width - 150.0).abs() < 1e-6 && (n.height - 75.0).abs() < 1e-6, "the layer keeps its size: {} x {}", n.width, n.height);
let (_, Some(scaled)) = mode(&u, layer) else { panic!("a crop") };
// The picture grew from 200 x 100 to 240 x 120: the layer shows 5/6 of what it showed.
assert!((scaled[0] - after[0] * 5.0 / 6.0).abs() < 1e-6 && (scaled[3] - after[3] * 5.0 / 6.0).abs() < 1e-6, "{after:?} -> {scaled:?}");
assert_eq!(after, before, "normal resize without Cmd leaves crop transform unchanged to morph/squish");
}
/// The reporter's sequence (#2307): the colour picker open on an image fill held in Crop mode
@@ -206,12 +195,7 @@ fn crop_from_the_colour_picker_then_a_drag_on_the_image_moves_the_crop_not_the_l
u.frame(vec![]);
}
choose_mode(&mut u, "Fill", "Crop");
// Crop mode on the canvas ended (a click away from the image); the picker opens on the Crop fill.
u.app.ui.crop = None;
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] });
for _ in 0..4 {
u.frame(vec![]);
}
assert!(u.app.ui.picker.is_some());
let (_, Some(before)) = mode(&u, layer) else { panic!("a crop") };
let at = u.app.session.doc().unwrap().node(layer).unwrap().transform.as_coeffs();
let from = u.app.to_screen(100.0, 50.0);
@@ -267,7 +251,7 @@ fn image_at(u: &Ui, id: NodeId, fills: bool, region: Option<usize>) -> figcraft_
/// fill have nothing for Crop image to crop either.
#[test]
fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply() {
use crate::colorpicker::{PickerTarget, crop_on_canvas};
use crate::colorpicker::PickerTarget;
let picture = |u: &Ui, id: NodeId| u.app.session.doc().unwrap().node(id).unwrap().fills[0].clone();
// Opens the picker on `target`, chooses Crop and checks crop mode stays off.
let crop_only_sets_the_mode = |u: &mut Ui, target: PickerTarget, what: &str| {
@@ -288,7 +272,7 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
assert_eq!(image_at(&u, layer, false, None).scale_mode, ImageScaleMode::Crop);
assert_eq!(mode(&u, layer), (ImageScaleMode::Fill, None), "the fill is untouched");
// Two image layers at once: both take the mode.
// Two image layers at once: both take the mode, with each layer's crop sized to its own dimensions.
let (mut u, layer, rect) = setup();
let paint = picture(&u, layer);
u.app.run("fill.set", json!({"ids": [rect], "index": 0, "paint": paint}));
@@ -296,6 +280,8 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
crop_only_sets_the_mode(&mut u, PickerTarget::Paint { fills: true, index: 0, ids: vec![layer, rect] }, "two layers");
assert_eq!(mode(&u, layer).0, ImageScaleMode::Crop);
assert_eq!(mode(&u, rect).0, ImageScaleMode::Crop);
let (crop1, crop2) = (mode(&u, layer).1.unwrap(), mode(&u, rect).1.unwrap());
assert_ne!(crop1, crop2, "differently sized layers must have distinct placement crops without stretching");
// A region's own image fill in vector edit mode: the region's mode is set, the layer's image
// fill is untouched.
@@ -313,12 +299,4 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
crop_only_sets_the_mode(&mut u, PickerTarget::Paint { fills: true, index: 0, ids: vec![vector] }, "a region");
assert_eq!(image_at(&u, vector, true, Some(1)).scale_mode, ImageScaleMode::Crop);
assert_eq!(u.app.session.doc().unwrap().node(vector).unwrap().fills, layer_fills, "the layer's fills are untouched");
// A fill that isn't an image, and targets that aren't a layer's paint, have no crop on the canvas.
let (u, layer, rect) = setup();
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] }), Some((layer, 0)));
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 0, ids: vec![rect] }), None, "a solid fill");
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 1, ids: vec![layer] }), None, "no fill there");
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::PageBackground), None);
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Style { id: "S:1".into(), index: 0 }), None);
}
+10 -6
View File
@@ -348,13 +348,17 @@ pub fn show(app: &mut FigApp, ctx: &Context) {
let selected = langs().find(|(code, _)| on(code)).map_or(tr("System"), |(_, name)| name);
let resp = crate::widgets::dropdown(ui, selected, 220.0, None);
let mut pick = None;
crate::right::menu_popup(&resp).show(|ui| {
for (code, name) in langs() {
if crate::right::menu_check(ui, on(code), name, "") {
pick = Some(code);
ui.close();
// Vertical-only fallback: keep the menu anchored to the dropdown's start edge.
let alt = if ui.style().right_to_left { &[egui::RectAlign::TOP_END] } else { &[egui::RectAlign::TOP_START] };
crate::right::menu_popup(&resp).align_alternatives(alt).show(|ui| {
egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
for (code, name) in langs() {
if crate::right::menu_check(ui, on(code), name, "") {
pick = Some(code);
ui.close();
}
}
}
});
});
if let Some(code) = pick {
app.run("pref.language", json!({"language": code}));
+46
View File
@@ -72,6 +72,52 @@ fn a_guide_moved_off_the_canvas_doesnt_follow_a_later_click() {
assert_eq!(offsets(&u), released);
}
/// The ruler is a thin target: a guide released on it, or past it off the canvas (over the panel
/// beside the left ruler, or the bar above the top one), is removed.
#[test]
fn a_guide_dragged_back_onto_or_past_its_ruler_is_removed() {
for left in [false, true] {
for past in [false, true] {
let mut u = rulers();
let r = u.app.canvas.rect;
let inset = if past { -40.0 } else { 5.0 };
let ruler = if left { Pos2::new(r.min.x + inset, r.center().y) } else { Pos2::new(r.center().x, r.min.y + inset) };
let start = if left { Pos2::new(r.min.x + 5.0, r.min.y + 60.0) } else { Pos2::new(r.min.x + 60.0, r.min.y + 5.0) };
drag(&mut u, start, r.center());
assert_eq!(offsets(&u).len(), 1, "left ruler: {left}, past it: {past}");
drag(&mut u, r.center(), ruler);
assert!(offsets(&u).is_empty(), "left ruler: {left}, past it: {past}");
}
}
}
/// Where the button came up decides, not where the pointer went later in the same frame.
#[test]
fn a_guide_released_above_the_canvas_stays_when_the_pointer_then_moves_past_its_ruler() {
let mut u = rulers();
let r = u.app.canvas.rect;
drag(&mut u, Pos2::new(r.min.x + 5.0, r.min.y + 60.0), r.center());
let placed = offsets(&u);
u.button(r.center(), true);
let above = Pos2::new(r.center().x, r.min.y - 30.0);
u.frame(vec![Event::PointerMoved(above)]);
u.frame(vec![
Event::PointerButton { pos: above, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() },
Event::PointerMoved(Pos2::new(r.min.x - 40.0, above.y)),
]);
assert_eq!(offsets(&u), placed);
}
#[test]
fn a_guide_released_off_the_canvas_away_from_its_ruler_stays() {
let mut u = rulers();
let r = u.app.canvas.rect;
drag(&mut u, Pos2::new(r.min.x + 5.0, r.min.y + 60.0), r.center());
let placed = offsets(&u);
drag(&mut u, r.center(), Pos2::new(r.max.x + 40.0, r.center().y));
assert_eq!(offsets(&u), placed);
}
#[test]
fn a_ruler_drag_released_on_the_canvas_adds_one_guide() {
let mut u = rulers();
+53 -24
View File
@@ -102,9 +102,6 @@ pub(crate) fn file_row(ui: &Ui, t: &Tokens, r: Rect, resp: &Response, row: &File
if resp.hovered() {
ui.painter().rect_filled(r, CornerRadius::same(5), t.hover);
}
if let Some((icon, tint)) = row.mark {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 8.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
}
let (name_font, detail_font) = (regular(12.0), regular(row.detail_size));
let width = |s: &str, font: &egui::FontId| ui.painter().layout_no_wrap(s.to_string(), font.clone(), Color32::WHITE).size().x;
let room = (r.width() - 40.0).max(0.0);
@@ -120,8 +117,19 @@ pub(crate) fn file_row(ui: &Ui, t: &Tokens, r: Rect, resp: &Response, row: &File
widgets::elide_start_font(ui, row.detail, detail_room, detail_font.clone())
};
let cut = name != row.name || detail != row.detail;
ui.painter().text(pos2(r.min.x + 32.0, r.center().y), Align2::LEFT_CENTER, name, name_font, row.ink);
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, detail, detail_font, row.detail_ink);
if crate::i18n::right_to_left() {
if let Some((icon, tint)) = row.mark {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 24.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
}
ui.painter().text(pos2(r.max.x - 32.0, r.center().y), Align2::RIGHT_CENTER, name, name_font, row.ink);
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, detail, detail_font, row.detail_ink);
} else {
if let Some((icon, tint)) = row.mark {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 8.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
}
ui.painter().text(pos2(r.min.x + 32.0, r.center().y), Align2::LEFT_CENTER, name, name_font, row.ink);
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, detail, detail_font, row.detail_ink);
}
cut
}
@@ -144,30 +152,40 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) {
dropped(app, ui.ctx());
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.panel)).show(ui, |ui| {
let rect = ui.max_rect();
let left = Rect::from_min_size(rect.min, vec2(SIDEBAR, rect.height()));
ui.painter().line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.border));
sidebar(app, ui, &t, left);
let rtl = crate::i18n::right_to_left();
let side = if rtl {
Rect::from_min_size(pos2(rect.max.x - SIDEBAR, rect.min.y), vec2(SIDEBAR, rect.height()))
} else {
Rect::from_min_size(rect.min, vec2(SIDEBAR, rect.height()))
};
let border_x = if rtl { side.left() } else { side.right() };
ui.painter().line_segment([pos2(border_x, side.top()), pos2(border_x, side.bottom())], Stroke::new(1.0, t.border));
sidebar(app, ui, &t, side);
let main =
if rtl { Rect::from_min_max(rect.min, pos2(side.min.x, rect.max.y)) } else { Rect::from_min_max(pos2(side.max.x, rect.min.y), rect.max) };
if app.ui.home_view.file_query.trim().is_empty() && app.ui.home_view.section == Section::Online {
// Your online files lay themselves out in the area (and scroll their own list).
let area = Rect::from_min_max(pos2(left.max.x + 40.0, rect.min.y + 24.0), rect.max - vec2(40.0, 24.0));
let area = main.shrink2(vec2(40.0, 24.0));
crate::online::section(app, ui, area, &t);
opened_join(app);
return;
}
let main = Rect::from_min_max(pos2(left.max.x, rect.min.y), rect.max);
ui.scope_builder(egui::UiBuilder::new().max_rect(main), |ui| {
egui::ScrollArea::vertical().id_salt("home").auto_shrink([false, false]).show(ui, |ui| {
egui::Frame::NONE.inner_margin(egui::Margin::symmetric(40, 24)).show(ui, |ui| {
ui.spacing_mut().item_spacing = vec2(GAP, 0.0);
if app.ui.home_view.file_query.trim().is_empty() {
match app.ui.home_view.section {
Section::Templates => templates(app, ui, &t),
_ => recents(app, ui, &t),
let align = if rtl { egui::Align::Max } else { egui::Align::Min };
ui.with_layout(egui::Layout::top_down(align), |ui| {
ui.spacing_mut().item_spacing = vec2(GAP, 0.0);
if app.ui.home_view.file_query.trim().is_empty() {
match app.ui.home_view.section {
Section::Templates => templates(app, ui, &t),
_ => recents(app, ui, &t),
}
} else {
search_results(app, ui, &t);
opened_join(app);
}
} else {
search_results(app, ui, &t);
opened_join(app);
}
});
});
});
});
@@ -221,8 +239,13 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
ui.painter().rect_filled(r, CornerRadius::same(5), if current { t.selected_row } else { t.hover });
}
focus_ring(ui, t, r, &resp, 5);
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr(label), regular(12.0), t.text);
if crate::i18n::right_to_left() {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 26.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
ui.painter().text(pos2(r.max.x - 36.0, r.center().y), Align2::RIGHT_CENTER, tr(label), regular(12.0), t.text);
} else {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr(label), regular(12.0), t.text);
}
if resp.clicked() {
app.ui.home_view.section = section;
app.ui.home_view.file_query.clear();
@@ -241,10 +264,16 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
ui.painter().rect_filled(r, CornerRadius::same(5), if current { t.selected_row } else { t.hover });
}
focus_ring(ui, t, r, &resp, 5);
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr("Preferences"), regular(12.0), t.text);
let key_label = figcraft_engine::keymap::display("Cmd+,", crate::shortcuts::platform());
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, &key_label, regular(11.0), t.text_secondary);
if crate::i18n::right_to_left() {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 26.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
ui.painter().text(pos2(r.max.x - 36.0, r.center().y), Align2::RIGHT_CENTER, tr("Preferences"), regular(12.0), t.text);
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, &key_label, regular(11.0), t.text_secondary);
} else {
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr("Preferences"), regular(12.0), t.text);
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, &key_label, regular(11.0), t.text_secondary);
}
resp = resp.on_hover_text(format!("{} ({})", tr("Preferences"), key_label));
if resp.clicked() {
app.ui.preferences = !app.ui.preferences;
+3 -1
View File
@@ -95,7 +95,9 @@ const LATIN_AMERICA: &[&str] =
/// language the UI can't draw (CJK on the web without CJK faces built in) doesn't count.
fn resolve_one(want: &str) -> Option<usize> {
let tag = want.trim().split(['.', '@']).next().unwrap_or("").replace('_', "-");
let base = tag.split('-').next().unwrap_or("");
let raw_base = tag.split('-').next().unwrap_or("");
// Map the obsolete ISO 639-1 tag `iw` (still emitted by older Java/Android locales) to `he`.
let base = if raw_base.eq_ignore_ascii_case("iw") { "he" } else { raw_base };
let has = |subtags: &[&str]| tag.split('-').skip(1).any(|t| subtags.iter().any(|s| s.eq_ignore_ascii_case(t)));
let zh = |code: &str| {
LANGS.iter().position(|l| l.code.eq_ignore_ascii_case(code)).filter(|i| LANGS.get(*i).is_some_and(|l| crate::cjk::can_show(l.code)))
+41 -1
View File
@@ -584,11 +584,51 @@ fn right_to_left_languages_mirror_the_window() {
for code in ["en", "", "es-419", "zh-Hans", "tr", "ru", "arn", "hey"] {
assert!(!writes_right_to_left(code), "{code}");
}
// Every catalog that mirrors is one of them, and the Arabic one does.
// Every catalog that mirrors is one of them, and the Arabic and Hebrew ones do.
assert!(LANGS.iter().any(|l| l.code == "ar" && writes_right_to_left(l.code)));
assert!(LANGS.iter().any(|l| l.code == "he" && writes_right_to_left(l.code)));
assert!(!writes_right_to_left(LANGS[0].code), "English reads left to right");
}
#[test]
fn hebrew_tags_and_plurals() {
let he = LANGS.iter().position(|l| l.code == "he").expect("locales/he.toml is baked in");
assert_eq!(LANGS[he].name, "עברית");
for tag in ["he", "he-IL", "he_IL.UTF-8", "iw", "iw-IL", "iw_IL.UTF-8"] {
assert_eq!(resolve(tag, None), he, "{tag}");
assert_eq!(resolve("system", Some(tag)), he, "{tag}");
}
assert!(!plural_one(he, 0) && plural_one(he, 1) && !plural_one(he, 2) && !plural_one(he, 5));
let singular = fill(counted(he, "{n} layers", 1), &[("n", &1)]);
let dual = fill(counted(he, "{n} layers", 2), &[("n", &2)]);
assert_eq!(singular, "1 שכבה");
assert_eq!(dual, "2 שכבות");
}
#[test]
fn the_built_in_hebrew_face_draws_the_hebrew_catalog() {
if !figcraft_text::CRAFT_FONTS.iter().any(|f| f.family == "Noto Sans Hebrew" && f.style == "Regular") {
eprintln!("built without craft-fonts' Noto Sans Hebrew; skipping");
return;
}
let Some(face) = figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]) else {
panic!("the supplied Noto Sans Hebrew face must draw Hebrew");
};
let he = &LANGS[LANGS.iter().position(|l| l.code == "he").unwrap()];
let letters: BTreeSet<char> = he
.ui
.iter()
.chain(he.commands)
.chain(he.menu)
.flat_map(|(_, t)| forms(t))
.flat_map(str::chars)
.filter(|c| matches!(u32::from(*c), 0x05D0..=0x05EA))
.collect();
assert!(letters.len() >= 27);
let missing: String = letters.iter().filter(|c| !face.has_char(**c)).collect();
assert!(missing.is_empty(), "Hebrew catalog glyphs missing from the embedded face: {missing:?}");
}
#[test]
fn the_built_in_arabic_face_draws_the_arabic_catalog() {
if !figcraft_text::CRAFT_FONTS.iter().any(|f| f.family == "Noto Sans Arabic" && f.style == "Regular") {
+91
View File
@@ -134,6 +134,97 @@ fn setup() -> (Ui, NodeId, NodeId, NodeId) {
(u, frame, child, rect)
}
#[test]
fn vertical_auto_layout_layers_follow_the_canvas_before_and_after_a_drop() {
let mut s = Session::new();
let frame = id(s.execute("node.create", &json!({"type": "frame", "width": 180, "height": 160, "props": {"layout": "vertical"}})).unwrap());
let rect = |s: &mut Session, name: &str| {
id(s.execute("node.create", &json!({"type": "rectangle", "parent": frame, "width": 80, "height": 30, "name": name})).unwrap())
};
let first = rect(&mut s, "First");
let second = rect(&mut s, "Second");
s.execute("select.none", &json!({})).unwrap();
let mut u = Ui::new(s);
u.app.ui.expanded.insert(frame);
let canvas_top = |u: &Ui, id: NodeId| u.app.session.doc().unwrap().world_bounds(id).unwrap().y0;
assert!(canvas_top(&u, first) < canvas_top(&u, second));
let (top, bottom) = (u.row_at(first), u.row_at(second));
assert!(top.y < bottom.y, "the Layers panel follows the vertical flow");
let above_first = top - vec2(0.0, 4.0);
u.drag_to(bottom, above_first);
u.button(above_first, false);
assert!(canvas_top(&u, second) < canvas_top(&u, first), "dropping above moves it up on the canvas");
assert!(u.row_at(second).y < u.row_at(first).y, "the Layers order follows the drop");
u.app.run("select.set", json!({"ids": [second]}));
u.ctx.enable_accesskit();
u.frame(vec![]);
let press = |u: &mut Ui, key| {
u.frame(
[true, false]
.into_iter()
.map(|pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() })
.collect(),
);
};
for _ in 0..4 {
press(&mut u, egui::Key::F6);
if u.app.ui.nav.region == crate::a11y::Region::Layers {
break;
}
}
assert_eq!(u.app.ui.nav.region, crate::a11y::Region::Layers);
press(&mut u, egui::Key::ArrowDown);
u.frame(vec![]);
assert_eq!(u.app.session.selection(), vec![first]);
assert_eq!(crate::a11y::focused_name(&u.ctx), "First");
}
#[test]
fn grouped_drop_between_vertical_and_stacked_rows_keeps_the_visible_order() {
for source_vertical in [true, false] {
let mut s = Session::new();
let container = |s: &mut Session, x, vertical| {
let props = if vertical { json!({"layout": "vertical"}) } else { json!({}) };
id(s.execute("node.create", &json!({"type": "frame", "x": x, "width": 180, "height": 160, "props": props})).unwrap())
};
let source = container(&mut s, 0, source_vertical);
let target = container(&mut s, 240, !source_vertical);
let rect = |s: &mut Session, parent, name| {
id(s.execute("node.create", &json!({"type": "rectangle", "parent": parent, "width": 80, "height": 30, "name": name})).unwrap())
};
let (a, b) = if source_vertical {
(rect(&mut s, source, "A"), rect(&mut s, source, "B"))
} else {
let b = rect(&mut s, source, "B");
(rect(&mut s, source, "A"), b)
};
let c = rect(&mut s, target, "C");
s.execute("select.set", &json!({"ids": [b, a]})).unwrap();
let mut u = Ui::new(s);
u.app.ui.expanded.extend([source, target]);
let top = u.row_at(a);
assert!(top.y < u.row_at(b).y);
let above_c = u.row_at(c) - vec2(0.0, 4.0);
u.drag_to(top, above_c);
u.button(above_c, false);
let (a_row, b_row, c_row) = (u.row_at(a), u.row_at(b), u.row_at(c));
assert!(a_row.y < b_row.y && b_row.y < c_row.y, "A, B, C in the destination (source vertical: {source_vertical})");
let doc = u.app.session.doc().unwrap();
assert!(doc.node(source).unwrap().children.is_empty());
let want = if source_vertical { vec![c, b, a] } else { vec![a, b, c] };
assert_eq!(doc.node(target).unwrap().children, want);
u.app.run("edit.undo", json!({}));
let doc = u.app.session.doc().unwrap();
assert_eq!(doc.node(a).unwrap().parent, Some(source));
assert_eq!(doc.node(b).unwrap().parent, Some(source));
assert_eq!(doc.node(target).unwrap().children, vec![c]);
}
}
#[test]
fn holding_over_a_collapsed_frame_opens_it_and_dropping_moves_the_layer_in() {
let (mut u, frame, child, rect) = setup();
+2
View File
@@ -232,6 +232,8 @@ mod pen_mode_tests;
#[cfg(test)]
mod perf_tests;
#[cfg(test)]
mod pixel_grid_tests;
#[cfg(test)]
mod plugin_panel_tests;
#[cfg(test)]
mod plugin_save_ui_tests;
+29 -13
View File
@@ -62,13 +62,32 @@ pub fn paste(app: &mut FigApp, event_text: Option<&str>, at: Option<(f64, f64)>)
// user's own text is pasted instead of the programmatic selection.
let ours = sys_text.is_some() && sys_text == app.ui.last_copy && app.ui.last_copy_generation == app.session.clipboard.layers_generation;
let (cx, cy) = at.or_else(|| app.session.ds().ok().map(|d| (d.view.cx, d.view.cy))).unwrap_or((0.0, 0.0));
if !ours {
if let Some((png, w, h)) = clipboard_png(app) {
let file = app.services.clipboard_image_file();
if file.is_some() || !ours {
// Finder also offers a filename and a TIFF icon. A copied image file supplies its own
// pixels; a read error must not turn it into a successful paste of the icon.
let image = if let Some(path) = file {
let read = figcraft_engine::file_access::read_capped(&path, figcraft_doc::ImageData::MAX_BYTES)
.map_err(|e| e.to_string())
.and_then(|bytes| with_pixel_size(bytes).ok_or_else(|| crate::unreadable(&path.to_string_lossy())));
match read {
Ok(image) => Some(image),
Err(why) => {
app.toast(why);
return;
}
}
} else {
clipboard_pixels(app)
};
if let Some((bytes, (w, h))) = image {
if dev_mode_refuses(app, "edit.paste") {
return;
}
use base64::Engine as _;
let b64 = base64::engine::general_purpose::STANDARD.encode(png);
let density = figcraft_format::pixel_density(&bytes);
let (w, h) = figcraft_format::placed_size(w, h, density, figcraft_engine::cmd::create::PLACED_IMAGE_MAX_SIDE);
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
// One selected layer that can have fills takes the image as its top fill.
if let [target] = app.session.selection()[..]
&& at.is_none()
@@ -135,16 +154,13 @@ fn paste_text(app: &mut FigApp, text: &str, (cx, cy): (f64, f64), center: bool)
}
}
/// The system clipboard's image as PNG bytes, with its size.
fn clipboard_png(app: &mut FigApp) -> Option<(Vec<u8>, f64, f64)> {
let clipboard_png = app.services.clipboard_get_png().filter(|png| png.len() <= crate::MAX_CLIPBOARD_PNG_BYTES);
let (png, (w, h)) = match clipboard_png.and_then(with_pixel_size) {
Some(readable) => readable,
None => with_pixel_size(encoded_clipboard_image(app)?)?,
};
let density = figcraft_format::pixel_density(&png);
let (w, h) = figcraft_format::placed_size(w, h, density, figcraft_engine::cmd::create::PLACED_IMAGE_MAX_SIDE);
Some((png, w, h))
/// The clipboard's encoded image and its pixel dimensions.
fn clipboard_pixels(app: &mut FigApp) -> Option<(Vec<u8>, (u32, u32))> {
app.services
.clipboard_get_png()
.filter(|png| png.len() <= crate::MAX_CLIPBOARD_PNG_BYTES)
.and_then(with_pixel_size)
.or_else(|| with_pixel_size(encoded_clipboard_image(app)?))
}
const MAX_PASTED_IMAGE_PIXELS: u64 = 100_000_000;
+48
View File
@@ -481,11 +481,21 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId
edit = Some(("name", v));
}
});
widgets::sublabels(ui, tr("Source file"), None);
row(ui, 32.0, |ui| {
let width = ui.available_width() - 2.0 * PAD;
if let Some(v) =
widgets::text_field(ui, Id::unique(("code_connect_source", owner, lang.id())), &link.source, width, "src/components/button.tsx")
{
edit = Some(("source", v));
}
});
widgets::sublabels(ui, tr("Template"), None);
if let Some(v) = widgets::multiline_field(ui, template_id(owner, lang), &link.template, "<Button size={size}>{label}</Button>", 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
+34 -21
View File
@@ -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<Item = &NodeId> {
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<NodeId>, out: &mut Vec<Row>) {
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<Row>) {
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() {
+56 -7
View File
@@ -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<crate::icons::Icon>, on: Option<bool>, 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:?}");
}
}
+16
View File
@@ -28,6 +28,7 @@ const HELD: [Held; 3] = [Held::Ours, Held::Text, Held::Image];
#[derive(Default)]
struct Clip {
file: Option<std::path::PathBuf>,
text: Option<String>,
image: Option<(u32, u32, Vec<u8>)>,
png: Option<Vec<u8>>,
@@ -46,6 +47,9 @@ impl Services for Desktop {
fn clipboard_get_image(&mut self) -> Option<(u32, u32, Vec<u8>)> {
self.0.borrow().image.clone()
}
fn clipboard_image_file(&mut self) -> Option<std::path::PathBuf> {
self.0.borrow().file.clone()
}
fn clipboard_get_png(&mut self) -> Option<Vec<u8>> {
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();
+66
View File
@@ -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%");
}
+5
View File
@@ -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);
+51
View File
@@ -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<Event>| {
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:?}");
}
}
}
+13 -4
View File
@@ -73,7 +73,12 @@ fn toast(app: &FigApp) -> &str {
}
fn expected_picker() -> Vec<(String, String, Vec<String>)> {
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<String>)> {
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());
+4
View File
@@ -47,6 +47,10 @@ pub trait Services {
fn clipboard_get_image(&mut self) -> Option<(u32, u32, Vec<u8>)> {
None
}
/// One supported raster image copied as a file, separate from its clipboard icon or filename.
fn clipboard_image_file(&mut self) -> Option<PathBuf> {
None
}
fn clipboard_get_png(&mut self) -> Option<Vec<u8>> {
None
}
+15 -2
View File
@@ -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");
}
+6 -28
View File
@@ -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);
}
+8 -1
View File
@@ -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
+4
View File
@@ -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 |
+3 -2
View File
@@ -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 shapesLine truncated
> **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 Line truncated
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. |
+16 -5
View File
@@ -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 `<text>`, `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 `<layer><suffix>.<format>`, 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 `<Button variant="primary" icon="none">{"Buy
now"}</Button>`. `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,
+3 -3
View File
@@ -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.
+4 -1
View File
@@ -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 (#Line truncated
> **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 stLine truncated
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`. |
+28 -5
View File
@@ -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
@@ -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;
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more