mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
Merge remote-tracking branch 'origin/main' into fix/kscale-bound-values-2090
Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> # Conflicts: # docs/components-parity.md # docs/ui-parity.md
This commit is contained in:
commit
08f346d0d7
54 files changed
+1958
-418
No files matched your search
Generated
+1
-1
@@ -1236,7 +1236,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectordrawable"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7#5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
]
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/figcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
|
||||
craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
|
||||
craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7" }
|
||||
# internal
|
||||
figcraft-geom = { path = "crates/geom" }
|
||||
figcraft-color = { path = "crates/color" }
|
||||
|
||||
+3
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
|
||||
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
|
||||
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
|
||||
@@ -365,6 +365,8 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 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-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
|
||||
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
|
||||
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
|
||||
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
|
||||
|
||||
@@ -152,6 +152,12 @@ impl<S: Socket> Driver<S> {
|
||||
None => self.done = true,
|
||||
}
|
||||
}
|
||||
exchange::Next::Tell(events, then) => {
|
||||
for e in events {
|
||||
self.inbox.push(e);
|
||||
}
|
||||
self.follow(*then, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,11 +7,17 @@
|
||||
//! Publishing ([`publish`]) uploads the document, makes the links and codes others join with when
|
||||
//! it shares, then joins the new file with its edit link; [`background`] sends the hosting and
|
||||
//! sharing requests the engine sends in the background (asking a server about its hosting,
|
||||
//! starting and stopping a share).
|
||||
//! starting and stopping a share) and those about team libraries and plugin directories;
|
||||
//! [`libraries`] the checks of a file's team libraries.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use figcraft_collab::message::{self, Admin, AdminReply, ClientMsg, HostInfo, Manage, OpenHosting, PROTOCOL, ServerMsg};
|
||||
use figcraft_collab::message::{
|
||||
self, Admin, AdminReply, ClientMsg, HostInfo, LibraryReply, LibraryReq, Manage, OpenHosting, OpenLibrary, OpenPlugins, PROTOCOL, PluginReply,
|
||||
PluginReq, ServerMsg,
|
||||
};
|
||||
use figcraft_engine::live::{Event, NetReply, NetRequest, Shared, Status};
|
||||
|
||||
use crate::invite::{Endpoint, Invite};
|
||||
@@ -21,7 +27,7 @@ use crate::requests::{self, Publish, REFUSED};
|
||||
pub(crate) struct Exchange {
|
||||
pub(crate) server: Endpoint,
|
||||
open: ClientMsg,
|
||||
requests: VecDeque<Admin>,
|
||||
requests: VecDeque<ClientMsg>,
|
||||
answers: Answers,
|
||||
/// The server let the connection in (its first answer came).
|
||||
ready: bool,
|
||||
@@ -35,6 +41,9 @@ pub(crate) struct Exchange {
|
||||
pub(crate) struct Answers {
|
||||
pub(crate) hosting: Option<HostInfo>,
|
||||
pub(crate) replies: Vec<AdminReply>,
|
||||
/// The answer on a library or plugin directory connection.
|
||||
pub(crate) library: Option<LibraryReply>,
|
||||
pub(crate) plugins: Option<PluginReply>,
|
||||
}
|
||||
|
||||
/// What follows an exchange's answers (or why it failed).
|
||||
@@ -46,6 +55,8 @@ pub(crate) enum Next {
|
||||
Ask(Box<Exchange>, Then),
|
||||
/// Done: tell the UI these, then join the file this invite names (`None`: nothing to join).
|
||||
Done(Vec<Event>, Option<Invite>),
|
||||
/// Tell the UI these now, then go on with what follows.
|
||||
Tell(Vec<Event>, Box<Next>),
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
@@ -61,7 +72,23 @@ impl Exchange {
|
||||
owner: owner.to_string(),
|
||||
}),
|
||||
};
|
||||
Self { server, open, requests: requests.into(), answers: Answers::default(), ready: false, asked: false }
|
||||
Self::opened(server, open, requests.into_iter().map(ClientMsg::Admin).collect())
|
||||
}
|
||||
|
||||
/// Ask the library of the file behind `invite` one thing.
|
||||
pub(crate) fn library(invite: Invite, req: LibraryReq) -> Self {
|
||||
let open = OpenLibrary { protocol: PROTOCOL, file: invite.file, token: invite.token, client_version: message::client_version() };
|
||||
Self::opened(invite.server, ClientMsg::OpenLibrary(open), VecDeque::from([ClientMsg::Library(req)]))
|
||||
}
|
||||
|
||||
/// Ask the plugin directory of `server` one thing, with its `key` (empty: only browsing).
|
||||
pub(crate) fn plugins(server: Endpoint, key: String, req: PluginReq) -> Self {
|
||||
let open = OpenPlugins { protocol: PROTOCOL, key, client_version: message::client_version() };
|
||||
Self::opened(server, ClientMsg::OpenPlugins(open), VecDeque::from([ClientMsg::Plugins(req)]))
|
||||
}
|
||||
|
||||
fn opened(server: Endpoint, open: ClientMsg, requests: VecDeque<ClientMsg>) -> Self {
|
||||
Self { server, open, requests, answers: Answers::default(), ready: false, asked: false }
|
||||
}
|
||||
|
||||
/// The connection's first message.
|
||||
@@ -81,7 +108,11 @@ impl Exchange {
|
||||
/// Why the exchange failed with `e`, as the app says it: a server older than open hosting
|
||||
/// can't read the opening.
|
||||
pub(crate) fn failed(&self, e: String) -> String {
|
||||
if self.ready || !matches!(self.open, ClientMsg::OpenHosting(_)) { e } else { requests::hosting_error(&self.server, e) }
|
||||
match self.open {
|
||||
ClientMsg::OpenHosting(_) if !self.ready => requests::hosting_error(&self.server, e),
|
||||
ClientMsg::OpenPlugins(_) if !self.ready => requests::directory_error(&self.server, e),
|
||||
_ => e,
|
||||
}
|
||||
}
|
||||
|
||||
/// Take in one message from the server: the next request to send, if one is due; an error
|
||||
@@ -99,13 +130,22 @@ impl Exchange {
|
||||
self.ready = true;
|
||||
self.answers.hosting = Some(*info);
|
||||
}
|
||||
ServerMsg::Library(r) if self.asked => self.answers.library = Some(*r),
|
||||
ServerMsg::Library(r) if !self.ready => match *r {
|
||||
LibraryReply::Ready { .. } => self.ready = true,
|
||||
other => return Err(format!("the server answered {other:?} instead of opening the library")),
|
||||
},
|
||||
ServerMsg::Plugins(r) if self.asked => self.answers.plugins = Some(*r),
|
||||
ServerMsg::Plugins(r) if !self.ready => match *r {
|
||||
PluginReply::Ready { .. } => self.ready = true,
|
||||
other => return Err(format!("the server answered {other:?} instead of opening its plugin directory")),
|
||||
},
|
||||
_ => return Err("the server sent something other than an answer".into()),
|
||||
}
|
||||
self.asked = false;
|
||||
Ok(self.requests.pop_front().map(|r| {
|
||||
self.asked = true;
|
||||
ClientMsg::Admin(r)
|
||||
}))
|
||||
let next = self.requests.pop_front();
|
||||
self.asked = next.is_some();
|
||||
Ok(next)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,9 +244,35 @@ fn codes(s: Sharing, links: requests::Links, then: LinksThen) -> Next {
|
||||
)
|
||||
}
|
||||
|
||||
/// The answer to a library request, from what its exchange got.
|
||||
fn library_reply(answers: Result<Answers, String>) -> Result<LibraryReply, String> {
|
||||
answers.and_then(|a| a.library.ok_or_else(|| "the server didn't answer".to_string()))
|
||||
}
|
||||
|
||||
/// Ask about the team libraries `jobs` `(link, request)`, in order, each on a connection of its
|
||||
/// own. A fetch's answer goes to the UI as it comes, before the next connection, as the desktop's
|
||||
/// does, so a slow or silent server further on holds no library back; the others' answers are left
|
||||
/// out (a report's says nothing, and an older server refuses it). `fetching` goes down at the end.
|
||||
pub(crate) fn libraries(mut jobs: VecDeque<(String, LibraryReq)>, fetching: Arc<AtomicBool>) -> Next {
|
||||
let Some((link, req)) = jobs.pop_front() else {
|
||||
fetching.store(false, Ordering::SeqCst);
|
||||
return Next::Done(Vec::new(), None);
|
||||
};
|
||||
let fetch = matches!(req, LibraryReq::Fetch { .. });
|
||||
let invite = Invite::parse(&link);
|
||||
let then = move |reply: Result<LibraryReply, String>| {
|
||||
let rest = libraries(jobs, fetching);
|
||||
if fetch { Next::Tell(vec![Event::Library { link, reply }], Box::new(rest)) } else { rest }
|
||||
};
|
||||
match invite {
|
||||
Err(e) => then(Err(e)),
|
||||
Ok(invite) => Next::Ask(Box::new(Exchange::library(invite, req)), Box::new(move |answers| then(library_reply(answers)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Background request `req` (answered as [`Event::Net`] with `job`), for the requests the
|
||||
/// browser sends: about a server's hosting, and changing who else gets into a file. `None` for
|
||||
/// the others.
|
||||
/// browser sends: about a server's hosting, changing who else gets into a file, its team libraries
|
||||
/// and its plugin directory. `None` for the others.
|
||||
pub(crate) fn background(job: u64, req: NetRequest) -> Option<Next> {
|
||||
let answer = move |reply: NetReply| Next::Done(vec![Event::Net { job, reply: Box::new(reply) }], None);
|
||||
Some(match req {
|
||||
@@ -231,6 +297,21 @@ pub(crate) fn background(job: u64, req: NetRequest) -> Option<Next> {
|
||||
share_links(Sharing { server, key, file, owner, revoke, create }, Box::new(move |r| answer(NetReply::Share(r))))
|
||||
}
|
||||
},
|
||||
NetRequest::Plugins { .. } | NetRequest::Library { .. } | NetRequest::Upload(_) => return None,
|
||||
NetRequest::Library { link, req } => match Invite::parse(&link) {
|
||||
Err(e) => answer(NetReply::Library(Err(e))),
|
||||
Ok(invite) => Next::Ask(Box::new(Exchange::library(invite, req)), Box::new(move |a| answer(NetReply::Library(library_reply(a))))),
|
||||
},
|
||||
NetRequest::Plugins { server, req } => match Endpoint::parse(&server) {
|
||||
Err(e) => answer(NetReply::Plugins(Err(e))),
|
||||
Ok((server, query)) => {
|
||||
let key = query.into_iter().find(|(k, _)| k == "key").map(|(_, v)| v).unwrap_or_default();
|
||||
let ex = Exchange::plugins(server, key.trim().to_string(), req);
|
||||
Next::Ask(
|
||||
Box::new(ex),
|
||||
Box::new(move |a| answer(NetReply::Plugins(a.and_then(|a| a.plugins.ok_or_else(|| "the server didn't answer".to_string()))))),
|
||||
)
|
||||
}
|
||||
},
|
||||
NetRequest::Upload(_) => return None,
|
||||
})
|
||||
}
|
||||
@@ -4,9 +4,13 @@
|
||||
//! background requests the browser can send.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use figcraft_collab::message::{self, Access, Admin, AdminReply, ClientMsg, FileInfo, HostInfo, LinkInfo, NewLink, Presence, ServerMsg};
|
||||
use figcraft_collab::message::{
|
||||
self, Access, Admin, AdminReply, ClientMsg, Detached, FileInfo, HostInfo, LibraryReply, LibraryReq, LinkInfo, NewLink, PluginReply, PluginReq,
|
||||
Presence, ServerMsg,
|
||||
};
|
||||
use figcraft_doc::{Document, NodeId};
|
||||
use figcraft_engine::live::{Event, NetReply, NetRequest, Shared, Status};
|
||||
|
||||
@@ -344,6 +348,111 @@ fn background_requests_ask_about_hosting_and_sharing() {
|
||||
let Some(Next::Done(events, None)) = exchange::background(1, bad) else { panic!("not answered at once") };
|
||||
assert!(matches!(events.as_slice(), [Event::Net { reply, .. }] if matches!(**reply, NetReply::Hosting(Err(_)) | NetReply::Share(Err(_)))));
|
||||
}
|
||||
let plugins = NetRequest::Plugins { server: SERVER.into(), req: figcraft_collab::message::PluginReq::List { query: String::new() } };
|
||||
assert!(exchange::background(1, plugins).is_none());
|
||||
}
|
||||
|
||||
fn library(r: LibraryReply) -> ServerMsg {
|
||||
ServerMsg::Library(Box::new(r))
|
||||
}
|
||||
|
||||
fn directory(r: PluginReply) -> ServerMsg {
|
||||
ServerMsg::Plugins(Box::new(r))
|
||||
}
|
||||
|
||||
fn link() -> String {
|
||||
format!("figcraft://join?host=127.0.0.1:47910&file={FILE}&token={TOKEN}")
|
||||
}
|
||||
|
||||
/// The browser opens a team library, asks, and takes the answer; failures come back as answers.
|
||||
#[test]
|
||||
fn background_requests_ask_a_team_library() {
|
||||
let ready = library(LibraryReply::Ready { access: Access::View });
|
||||
let req = |req| NetRequest::Library { link: link(), req };
|
||||
let (reply, sent) = background(req(LibraryReq::Usage), &[ready.clone(), library(LibraryReply::Usage(Vec::new()))]);
|
||||
assert!(matches!(reply, NetReply::Library(Ok(LibraryReply::Usage(u))) if u.is_empty()));
|
||||
assert!(matches!(sent.as_slice(), [ClientMsg::OpenLibrary(o), ClientMsg::Library(LibraryReq::Usage)] if o.file == FILE && o.token == TOKEN));
|
||||
// A refusal, and a link that isn't one.
|
||||
let (reply, _) = background(req(LibraryReq::Usage), &[ServerMsg::Refused { reason: "that link was revoked".into() }]);
|
||||
assert!(matches!(reply, NetReply::Library(Err(e)) if e.contains("revoked")));
|
||||
let bad = NetRequest::Library { link: "nope".into(), req: LibraryReq::Usage };
|
||||
let Some(Next::Done(events, None)) = exchange::background(1, bad) else { panic!("not answered at once") };
|
||||
assert!(matches!(events.as_slice(), [Event::Net { reply, .. }] if matches!(**reply, NetReply::Library(Err(_)))));
|
||||
// Anything but the opening's answer first is no answer.
|
||||
let (reply, _) = background(req(LibraryReq::Usage), &[library(LibraryReply::Empty)]);
|
||||
assert!(matches!(reply, NetReply::Library(Err(e)) if e.contains("instead of opening the library")));
|
||||
}
|
||||
|
||||
/// The browser asks a plugin directory, with the address's key when it has one.
|
||||
#[test]
|
||||
fn background_requests_ask_a_plugin_directory() {
|
||||
let ready = directory(PluginReply::Ready { publisher: true });
|
||||
let req = PluginReq::List { query: String::new() };
|
||||
let ask = NetRequest::Plugins { server: format!("{SERVER}?key=k3y"), req: req.clone() };
|
||||
let (reply, sent) = background(ask, &[ready, directory(PluginReply::List(Vec::new()))]);
|
||||
assert!(matches!(reply, NetReply::Plugins(Ok(PluginReply::List(entries))) if entries.is_empty()));
|
||||
assert!(matches!(sent.as_slice(), [ClientMsg::OpenPlugins(o), ClientMsg::Plugins(_)] if o.key == "k3y"));
|
||||
// A server from before directories can't read the opening.
|
||||
let older = NetRequest::Plugins { server: SERVER.into(), req };
|
||||
let (reply, _) = background(older, &[ServerMsg::Refused { reason: "that couldn't be read".into() }]);
|
||||
assert!(matches!(reply, NetReply::Plugins(Err(e)) if e.contains("has no plugin directory")));
|
||||
let bad = NetRequest::Plugins { server: "nope".into(), req: PluginReq::List { query: String::new() } };
|
||||
assert!(matches!(exchange::background(1, bad), Some(Next::Done(..))));
|
||||
}
|
||||
|
||||
/// A file's check of its team libraries runs its requests in order, each on a connection of its
|
||||
/// own; only fetches come back, whatever a report's answer, and a bad link doesn't stop the rest.
|
||||
#[test]
|
||||
fn a_library_check_runs_in_order_and_answers_only_its_fetches() {
|
||||
let fetch = LibraryReq::Fetch { have: None, usage: None };
|
||||
let jobs = vec![
|
||||
("nope".to_string(), fetch.clone()),
|
||||
(link(), fetch),
|
||||
(link(), LibraryReq::ReportDetached(Detached::default())),
|
||||
(link(), LibraryReq::ReportInserted(Detached::default())),
|
||||
];
|
||||
let fetching = Arc::new(AtomicBool::new(true));
|
||||
let t0 = Instant::now();
|
||||
let (mut d, inbox) = run(exchange::libraries(jobs.into(), fetching.clone()), t0);
|
||||
let ready = library(LibraryReply::Ready { access: Access::View });
|
||||
d.opened(t0);
|
||||
say(&mut d, &ready, t0);
|
||||
say(&mut d, &library(LibraryReply::Empty), t0);
|
||||
d.opened(t0);
|
||||
say(&mut d, &ready, t0);
|
||||
// An older server refuses the report: the check goes on.
|
||||
say(&mut d, &library(LibraryReply::Failed { reason: "no".into() }), t0);
|
||||
d.opened(t0);
|
||||
say(&mut d, &ServerMsg::Refused { reason: "couldn't be read".into() }, t0);
|
||||
assert!(!fetching.load(Ordering::SeqCst), "the next check may start");
|
||||
let events = inbox.drain();
|
||||
let replies: Vec<_> = events.iter().filter_map(|e| if let Event::Library { reply, .. } = e { Some(reply) } else { None }).collect();
|
||||
assert_eq!(replies.len(), 2, "{events:#?}");
|
||||
assert!(replies[0].is_err());
|
||||
assert!(matches!(replies[1], Ok(LibraryReply::Empty)));
|
||||
}
|
||||
|
||||
/// A fetch's answer reaches the UI as it comes, not at the end of the check: a report after it
|
||||
/// whose server never answers holds the first library back no longer than its own connection.
|
||||
#[test]
|
||||
fn a_library_check_hands_each_fetch_over_as_it_comes() {
|
||||
let fetch = LibraryReq::Fetch { have: None, usage: None };
|
||||
let jobs = vec![(link(), fetch.clone()), (link(), LibraryReq::ReportDetached(Detached::default())), (link(), fetch)];
|
||||
let fetching = Arc::new(AtomicBool::new(true));
|
||||
let t0 = Instant::now();
|
||||
let (mut d, inbox) = run(exchange::libraries(jobs.into(), fetching.clone()), t0);
|
||||
let fetched = |events: &[Event]| events.iter().filter(|e| matches!(e, Event::Library { .. })).count();
|
||||
let ready = library(LibraryReply::Ready { access: Access::View });
|
||||
d.opened(t0);
|
||||
say(&mut d, &ready, t0);
|
||||
say(&mut d, &library(LibraryReply::Empty), t0);
|
||||
assert_eq!(fetched(&inbox.drain()), 1, "the first library is in while the report's server is asked");
|
||||
// The report's connection never opens: the check gives up on it and goes on, saying nothing.
|
||||
let t1 = t0 + Duration::from_secs(5);
|
||||
d.tick(t1);
|
||||
assert_eq!(fetched(&inbox.drain()), 0);
|
||||
assert!(fetching.load(Ordering::SeqCst), "the check is still running");
|
||||
d.opened(t1);
|
||||
say(&mut d, &ready, t1);
|
||||
say(&mut d, &library(LibraryReply::Empty), t1);
|
||||
assert_eq!(fetched(&inbox.drain()), 1);
|
||||
assert!(!fetching.load(Ordering::SeqCst) && d.done());
|
||||
}
|
||||
@@ -8,8 +8,9 @@
|
||||
//! engine's `collab.*` commands drive it and the UI reads the engine's live state. Network
|
||||
//! threads wake the UI through a [`Waker`] only when something arrives; nothing polls.
|
||||
//!
|
||||
//! The browser build's [`NetLink`] joins sessions and publishes files to servers through the
|
||||
//! browser's WebSocket API (`web-sys`); hosting a session needs the desktop app. Its connection
|
||||
//! The browser build's [`NetLink`] joins sessions, publishes files to servers and asks them about
|
||||
//! team libraries and plugin directories through the browser's WebSocket API (`web-sys`); hosting
|
||||
//! a session needs the desktop app. Its connection
|
||||
//! logic (`driver.rs`, `exchange.rs`) is target-independent and tested natively.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::invite::{Endpoint, Invite, Lookup};
|
||||
use crate::join::ask;
|
||||
use crate::net::{Duplex, NetLimits, config, open};
|
||||
pub(crate) use crate::requests::REFUSED;
|
||||
use crate::requests::{code_requests, comment_request, hosting_error, link_requests, made_comment, made_links, shared};
|
||||
use crate::requests::{code_requests, comment_request, directory_error, hosting_error, link_requests, made_comment, made_links, shared};
|
||||
|
||||
type Ws = WebSocket<Duplex>;
|
||||
|
||||
@@ -165,8 +165,7 @@ pub fn plugins(server: &Endpoint, key: &str, req: PluginReq, limits: &NetLimits,
|
||||
match reply(&mut ws, limits, pick) {
|
||||
Ok(PluginReply::Ready { .. }) => {}
|
||||
// An older server can't read the request at all.
|
||||
Err(e) if e.contains("couldn't be read") => return Err(format!("{} has no plugin directory (update the server)", server.display())),
|
||||
Err(e) => return Err(e),
|
||||
Err(e) => return Err(directory_error(server, e)),
|
||||
Ok(other) => return Err(format!("the server answered {other:?} instead of opening its plugin directory")),
|
||||
}
|
||||
send(&mut ws, &ClientMsg::Plugins(req))?;
|
||||
|
||||
@@ -43,6 +43,12 @@ pub(crate) fn key_over_tls(server: &Endpoint, key: Option<&str>) -> Result<(), S
|
||||
|
||||
/// Why asking `server` about its hosting failed with `e`: a server older than open hosting can't
|
||||
/// read the question.
|
||||
/// Why opening `server`'s plugin directory failed with `e`: a server from before directories can't
|
||||
/// read the opening.
|
||||
pub(crate) fn directory_error(server: &Endpoint, e: String) -> String {
|
||||
if e.contains("couldn't be read") { format!("{} has no plugin directory (update the server)", server.display()) } else { e }
|
||||
}
|
||||
|
||||
pub(crate) fn hosting_error(server: &Endpoint, e: String) -> String {
|
||||
if e.contains("couldn't be read") {
|
||||
format!("{} takes files only with its key (it is older than this app): add ?key=… to the address", server.display())
|
||||
|
||||
@@ -17,8 +17,10 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::BTreeMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use figcraft_collab::message::{ClientMsg, Presence};
|
||||
use figcraft_collab::message::{ClientMsg, LibraryReq, Presence};
|
||||
use figcraft_engine::live::{Event, HostOptions, LiveLink, NO_SESSION, NetRequest, PublishOptions, SessionId, SessionInfo};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
@@ -163,19 +165,29 @@ fn socket() -> (u64, BrowserSocket) {
|
||||
(id, BrowserSocket { id, ws: None })
|
||||
}
|
||||
|
||||
/// The browser's [`LiveLink`]: joins sessions and publishes files to servers; hosting a session
|
||||
/// needs the desktop app.
|
||||
/// The browser's [`LiveLink`]: joins sessions, publishes files to servers and asks them about team
|
||||
/// libraries and plugin directories; hosting a session needs the desktop app.
|
||||
pub struct NetLink {
|
||||
/// Each session's number in the thread-local table.
|
||||
sessions: Sessions<u64>,
|
||||
/// Answers to requests sent in the background (outlives sessions).
|
||||
background: Inbox,
|
||||
/// A check of the team libraries is out.
|
||||
fetching: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl NetLink {
|
||||
/// `wake` is called whenever something arrives for the UI (egui's `request_repaint`).
|
||||
pub fn new(wake: Waker) -> Self {
|
||||
Self { background: Inbox::new(wake.clone()), sessions: Sessions::new(wake) }
|
||||
Self { background: Inbox::new(wake.clone()), sessions: Sessions::new(wake), fetching: Arc::default() }
|
||||
}
|
||||
|
||||
/// Run `next` on a connection of its own, its answers for the background.
|
||||
fn ask(&self, next: exchange::Next) {
|
||||
let (id, sock) = socket();
|
||||
// The exchanges name their own servers.
|
||||
let cfg = GuestConfig::new(Invite::new("", "", ""), String::new());
|
||||
run(id, Driver::asking(sock, cfg, next, self.background.clone(), Instant::now()));
|
||||
}
|
||||
|
||||
/// Session `session` runs on connection `id` now (the one it had ends).
|
||||
@@ -229,13 +241,16 @@ impl LiveLink for NetLink {
|
||||
|
||||
fn background(&mut self, job: u64, req: NetRequest) -> bool {
|
||||
let Some(next) = exchange::background(job, req) else { return false };
|
||||
let (id, sock) = socket();
|
||||
// The exchanges name their own servers.
|
||||
let cfg = GuestConfig::new(Invite::new("", "", ""), String::new());
|
||||
run(id, Driver::asking(sock, cfg, next, self.background.clone(), Instant::now()));
|
||||
self.ask(next);
|
||||
true
|
||||
}
|
||||
|
||||
fn library_background(&mut self, jobs: Vec<(String, LibraryReq)>) {
|
||||
if !jobs.is_empty() && !self.fetching.swap(true, Ordering::SeqCst) {
|
||||
self.ask(exchange::libraries(jobs.into(), self.fetching.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
fn leave(&mut self, session: SessionId) {
|
||||
if let Some(id) = self.sessions.remove(session) {
|
||||
with_driver(id, |d, now| d.leave(now));
|
||||
|
||||
@@ -431,6 +431,9 @@ pub(crate) enum Gesture {
|
||||
additive: bool,
|
||||
base: Vec<NodeId>,
|
||||
within: Option<NodeId>,
|
||||
/// A click stepping out of a selected descendant picks its frame. Wait for a real drag
|
||||
/// before replacing that selection with the marquee's contents.
|
||||
pending_click: bool,
|
||||
},
|
||||
Move {
|
||||
start: Point,
|
||||
|
||||
@@ -77,8 +77,8 @@ impl Session {
|
||||
}
|
||||
// A frame's name label picks the frame itself. The background of a top-level frame with
|
||||
// layers in it is like the canvas (a press starts a marquee inside it) unless the frame is
|
||||
// selected; an empty frame (or a widget, or a board object such as a sticky) is picked and
|
||||
// dragged.
|
||||
// selected; stepping out from a selected descendant is handled by the marquee below.
|
||||
// An empty frame (or a widget, or a board object such as a sticky) is picked and dragged.
|
||||
let board_background = |leaf: NodeId| {
|
||||
!sel.contains(&leaf)
|
||||
&& doc.node(leaf).is_some_and(|n| {
|
||||
@@ -86,11 +86,8 @@ impl Session {
|
||||
})
|
||||
};
|
||||
let label = label_at(&doc, page, &self.tool.labels, ev.p());
|
||||
let target = label.or_else(|| {
|
||||
self.hit(&doc, page, ev.p(), ev.tol() * 2.0)
|
||||
.filter(|leaf| ev.cmd || !board_background(*leaf))
|
||||
.map(|leaf| select_target(&doc, leaf, &sel, ev.cmd))
|
||||
});
|
||||
let hit = label.or_else(|| self.hit(&doc, page, ev.p(), ev.tol() * 2.0));
|
||||
let target = label.or_else(|| hit.filter(|leaf| ev.cmd || !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)));
|
||||
// A press inside the selection's box that reaches nothing above it (an unfilled shape's
|
||||
// inside, the frame or canvas behind it, or a layer stacked below the selected layer the
|
||||
// press is in) drags the selection. In a gap between selected layers, what's there is hit.
|
||||
@@ -172,10 +169,22 @@ impl Session {
|
||||
}
|
||||
None => {
|
||||
let within = self.marquee_within(ev.p())?;
|
||||
if !ev.shift {
|
||||
// Clicking the background of the frame containing the current selection steps
|
||||
// out to that frame. Keep the marquee gesture (without a Move interaction), so
|
||||
// dragging here still selects its contents and cannot leave a stale snapshot.
|
||||
let parent = hit.filter(|f| !ev.shift && !ev.cmd && within == Some(*f) && sel.iter().any(|s| doc.is_ancestor(*f, *s)));
|
||||
if let Some(f) = parent {
|
||||
self.set_selection(vec![f]);
|
||||
} else if !ev.shift {
|
||||
self.set_selection(vec![]);
|
||||
}
|
||||
self.tool.gesture = Gesture::Marquee { start: ev.p(), additive: ev.shift, base: if ev.shift { sel } else { vec![] }, within };
|
||||
self.tool.gesture = Gesture::Marquee {
|
||||
start: ev.p(),
|
||||
additive: ev.shift,
|
||||
base: if ev.shift { sel } else { vec![] },
|
||||
within,
|
||||
pending_click: parent.is_some(),
|
||||
};
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -196,9 +205,18 @@ impl Session {
|
||||
it.label = if ev.alt { "Duplicate" } else { "Move" }.into();
|
||||
}
|
||||
}
|
||||
if let Gesture::Marquee { start, pending_click, .. } = &mut g
|
||||
&& *pending_click
|
||||
{
|
||||
if within_slop(ev, *start) {
|
||||
self.tool.gesture = g;
|
||||
return Ok(());
|
||||
}
|
||||
*pending_click = false;
|
||||
}
|
||||
let res = match &g {
|
||||
Gesture::None => return self.hover(ev),
|
||||
Gesture::Marquee { start, additive, base, within } => {
|
||||
Gesture::Marquee { start, additive, base, within, .. } => {
|
||||
let r = Rect::from_points(*start, ev.p());
|
||||
self.tool.overlay.marquee = Some([r.x0, r.y0, r.x1, r.y1]);
|
||||
// Cmd/Ctrl: the nested layers it touches.
|
||||
|
||||
@@ -312,9 +312,12 @@ fn own(cmd: &str, m: &Message, who: &str, what: &str) -> crate::Result<()> {
|
||||
}
|
||||
|
||||
/// A node to pin to: a node id on `page`, `true` for the innermost frame under the point, else none.
|
||||
fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>) -> Option<NodeId> {
|
||||
fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>, within: Option<NodeId>) -> Option<NodeId> {
|
||||
match v {
|
||||
Some(Value::Bool(true)) => frame_at(doc, page, x, y),
|
||||
Some(Value::Bool(true)) => match within.filter(|w| *w != page && doc.page_of(*w) == Some(page) && contains(doc, *w, x, y)) {
|
||||
Some(w) => frame_in(doc, w, x, y, Some(w)),
|
||||
None => frame_at(doc, page, x, y),
|
||||
},
|
||||
Some(v) => id_of(v).filter(|a| *a != page && doc.page_of(*a) == Some(page)),
|
||||
None => None,
|
||||
}
|
||||
@@ -670,7 +673,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"comment.add",
|
||||
"Add comment",
|
||||
"{x, y, text, page?, author?, anchor? (node id to pin to; true = innermost frame under the point)}",
|
||||
"{x, y, text, page?, author?, anchor? (node id to pin to; true = innermost frame under the point), within? (with anchor true: search only inside this frame on the page, which is the anchor when no child holds the point)}",
|
||||
true,
|
||||
|s, p| {
|
||||
let x = req_num("comment.add", p, "x")?;
|
||||
@@ -682,7 +685,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
if !doc.pages.contains(&page) {
|
||||
return Err(bad("comment.add", format!("{page} is not a page")));
|
||||
}
|
||||
let anchor = anchor_at(doc, page, x, y, get(p, "anchor"));
|
||||
let anchor = anchor_at(doc, page, x, y, get(p, "anchor"), id(p, "within"));
|
||||
let (lx, ly) = local(doc, anchor, x, y);
|
||||
let mut c = Comment {
|
||||
id: s.doc_mut()?.new_comment_id(),
|
||||
@@ -772,7 +775,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let (x, y) = (req_num("comment.move", p, "x")?, req_num("comment.move", p, "y")?);
|
||||
let doc = s.doc()?;
|
||||
let page = doc.comment(id).map(|c| c.page).ok_or_else(|| bad("comment.move", "no comment"))?;
|
||||
let anchor = anchor_at(doc, page, x, y, Some(get(p, "anchor").unwrap_or(&Value::Bool(true))));
|
||||
let anchor = anchor_at(doc, page, x, y, Some(get(p, "anchor").unwrap_or(&Value::Bool(true))), None);
|
||||
let (lx, ly) = local(doc, anchor, x, y);
|
||||
if let Some(c) = s.doc_mut()?.comment_mut(id) {
|
||||
(c.x, c.y, c.anchor) = (lx, ly, anchor);
|
||||
@@ -974,9 +977,20 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// Innermost frame (or component/instance/section) under a page point, for anchoring.
|
||||
fn frame_at(doc: &Document, page: NodeId, x: f64, y: f64) -> Option<NodeId> {
|
||||
frame_in(doc, page, x, y, None)
|
||||
}
|
||||
|
||||
/// Whether the page point lies inside node `n`'s box.
|
||||
fn contains(doc: &Document, n: NodeId, x: f64, y: f64) -> bool {
|
||||
let Some(node) = doc.node(n) else { return false };
|
||||
let l = doc.world_transform(n).inverse() * geom::Point::new(x, y);
|
||||
l.x >= 0.0 && l.y >= 0.0 && l.x <= node.width && l.y <= node.height
|
||||
}
|
||||
|
||||
/// The innermost frame-like or section under the point, searching from `root` (with `found` as the fallback).
|
||||
fn frame_in(doc: &Document, root: NodeId, x: f64, y: f64, mut found: Option<NodeId>) -> Option<NodeId> {
|
||||
let pt = geom::Point::new(x, y);
|
||||
let mut found = None;
|
||||
let mut stack = vec![page];
|
||||
let mut stack = vec![root];
|
||||
while let Some(parent) = stack.pop() {
|
||||
let Some(n) = doc.node(parent) else { continue };
|
||||
for c in n.children.iter().rev() {
|
||||
@@ -1012,6 +1026,25 @@ mod tests {
|
||||
assert_eq!(super::parse_link("figcraft://comment/5/"), Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_add_within_anchors_to_the_presented_frame() {
|
||||
let mut s = Session::new();
|
||||
let mk = |s: &mut Session, params: serde_json::Value| crate::params::id_of(&s.execute("node.create", ¶ms).unwrap()["id"]).unwrap();
|
||||
let a = mk(&mut s, json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 200}));
|
||||
let b = mk(&mut s, json!({"type": "frame", "x": 100, "y": 0, "width": 200, "height": 200}));
|
||||
let anchor = |s: &mut Session, params: serde_json::Value| {
|
||||
let c = s.execute("comment.add", ¶ms).unwrap();
|
||||
let id = c["id"].as_u64().unwrap();
|
||||
s.doc().unwrap().comment(id).unwrap().anchor
|
||||
};
|
||||
assert_eq!(anchor(&mut s, json!({"x": 150, "y": 50, "text": "t", "anchor": true})), Some(b));
|
||||
assert_eq!(anchor(&mut s, json!({"x": 150, "y": 50, "text": "t", "anchor": true, "within": a})), Some(a));
|
||||
let c = mk(&mut s, json!({"type": "frame", "x": 120, "y": 20, "width": 50, "height": 50, "parent": a}));
|
||||
assert_eq!(anchor(&mut s, json!({"x": 130, "y": 30, "text": "t", "anchor": true, "within": a})), Some(c));
|
||||
// A point outside `within` ignores it.
|
||||
assert_eq!(anchor(&mut s, json!({"x": 250, "y": 50, "text": "t", "anchor": true, "within": a})), Some(b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_thread_lifecycle_and_anchoring() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -162,6 +162,7 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
// Text: a solid is the ink (`color`), one per fill, so the last (top) one wins.
|
||||
let top = n.fills.iter().rposition(|p| p.visible);
|
||||
for (i, p) in n.fills.iter().enumerate().filter(|(_, p)| p.visible) {
|
||||
match &p.kind {
|
||||
PaintKind::Solid { color } => {
|
||||
@@ -169,7 +170,16 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
|
||||
// A variable binds the first paint's colour.
|
||||
put("color", if i == 0 { tok(doc, n, &["fill"], c, t) } else { c });
|
||||
}
|
||||
PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)),
|
||||
PaintKind::Gradient(g) => {
|
||||
put("background", css_gradient(g, n.width, n.height, p.opacity));
|
||||
// A gradient on top fills the glyphs: clip the background to the text and clear the ink.
|
||||
// Under a later paint it must not hide that paint's colour, so it stays a plain background.
|
||||
if Some(i) == top {
|
||||
put("-webkit-background-clip", "text".into());
|
||||
put("background-clip", "text".into());
|
||||
put("color", "transparent".into());
|
||||
}
|
||||
}
|
||||
PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()),
|
||||
PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()),
|
||||
}
|
||||
|
||||
@@ -293,6 +293,9 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> {
|
||||
// An image shorthand (`url(…) center / cover`) is a whole `background`, not a bg colour.
|
||||
("background", v) if v.starts_with("url(") => one(format!("[background:{}]", arb(v).trim_matches(['[', ']']))),
|
||||
("background", v) => one(util("bg", "color", v, "color:")),
|
||||
("-webkit-background-clip", "text") => Vec::new(),
|
||||
("background-clip", "text") => kw("bg-clip-text"),
|
||||
("color", "transparent") => kw("text-transparent"),
|
||||
("color", v) => one(util("text", "color", v, "color:")),
|
||||
("border", v) => border("", v),
|
||||
("border-top", v) => border("t", v),
|
||||
|
||||
@@ -355,3 +355,35 @@ fn rem_conversion_keeps_the_original_pixels() {
|
||||
assert_eq!(f("padding: 3px;", 16.0), "padding: 0.1875rem;");
|
||||
assert_eq!(f("gap: 0.5px;", 16.0), "gap: 0.03125rem;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_gradient_fill_clips_to_the_glyphs() {
|
||||
let mut s = Session::new();
|
||||
let fills = json!([{"type": "linearGradient", "stops": ["#D98200", "#FF6B4A"]}]);
|
||||
let t = id(&ex(&mut s, "node.create", json!({"type": "text", "text": "Gradient", "props": {"fontSize": 48, "fills": fills}})));
|
||||
let c = css(&mut s, t);
|
||||
assert!(c.contains("background: linear-gradient("), "{c}");
|
||||
assert!(c.contains("-webkit-background-clip: text;"), "{c}");
|
||||
assert!(c.contains("\nbackground-clip: text;"), "{c}");
|
||||
assert!(c.contains("color: transparent;"), "{c}");
|
||||
let tw = code(&mut s, t, json!({"language": "tailwind"}));
|
||||
assert!(tw.contains("bg-clip-text") && tw.contains("text-transparent"), "{tw}");
|
||||
// A box keeps its gradient as a plain background.
|
||||
let r = rect(&mut s, 0.0, 0.0, 50.0, 50.0, None);
|
||||
let set = s.execute("node.set", &json!({"id": r, "props": {"fills": fills}}));
|
||||
assert!(set.is_ok(), "{set:?}");
|
||||
let box_css = css(&mut s, r);
|
||||
assert!(box_css.contains("background: linear-gradient("), "{box_css}");
|
||||
assert!(!box_css.contains("background-clip"), "{box_css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_gradient_under_a_solid_fill_keeps_the_solid_ink() {
|
||||
let mut s = Session::new();
|
||||
let fills = json!([{"type": "linearGradient", "stops": ["#D98200", "#FF6B4A"]}, {"type": "solid", "color": "#112233"}]);
|
||||
let t = id(&ex(&mut s, "node.create", json!({"type": "text", "text": "Gradient", "props": {"fontSize": 48, "fills": fills}})));
|
||||
let c = css(&mut s, t);
|
||||
assert!(!c.contains("color: transparent;"), "{c}");
|
||||
assert!(!c.contains("background-clip"), "{c}");
|
||||
assert!(c.contains("color: #112233;"), "{c}");
|
||||
}
|
||||
@@ -108,6 +108,42 @@ fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_device_background_after_its_nested_button_selects_the_device() {
|
||||
let mut s = Session::new();
|
||||
let device = id(&ex(&mut s, "frame.create", json!({"x": 132, "y": -148, "width": 440, "height": 956})));
|
||||
let button = id(&ex(&mut s, "frame.create", json!({"parent": device, "x": 155, "y": 30, "width": 130, "height": 34})));
|
||||
rect(&mut s, 10.0, 5.0, Some(button));
|
||||
ex(&mut s, "layout.add", json!({"ids": [button], "direction": "horizontal"}));
|
||||
ex(&mut s, "select.set", json!({"ids": [button]}));
|
||||
let before = s.doc().unwrap().clone();
|
||||
let history = s.undo_depth();
|
||||
s.pointer(&ev(PointerKind::Down, 352.0, 330.0, NONE)).unwrap();
|
||||
assert_eq!(s.selection(), vec![device], "the parent is selected on press");
|
||||
// Small pointer jitter must not turn the click into a zero-sized marquee.
|
||||
s.pointer(&ev(PointerKind::Move, 353.0, 330.0, NONE)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, 353.0, 330.0, NONE)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Hover, 353.0, 330.0, NONE)).unwrap();
|
||||
assert_eq!(s.selection(), vec![device], "the parent stays selected after release and hover");
|
||||
assert_eq!(*s.doc().unwrap(), before);
|
||||
assert_eq!(s.undo_depth(), history, "selection adds no edit history");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_a_device_background_after_its_child_still_marquees_and_closes_cleanly() {
|
||||
let mut s = Session::new();
|
||||
let k = scene(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [k.d]}));
|
||||
drag(&mut s, (390.0, 290.0), (190.0, 10.0), NONE);
|
||||
assert_eq!(s.selection(), vec![k.n], "a background drag selects the nested frame");
|
||||
assert!(s.ds().unwrap().interaction.is_none(), "a marquee leaves no move snapshot behind");
|
||||
ex(&mut s, "node.set", json!({"id": k.n, "props": {"opacity": 0.5}}));
|
||||
click(&mut s, 30.0, 130.0, NONE);
|
||||
assert_eq!(s.doc().unwrap().node(k.n).unwrap().opacity, 0.5, "the next click keeps the edit");
|
||||
ex(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc().unwrap().node(k.n).unwrap().opacity, 1.0, "the edit retains its undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_selects_by_the_documented_rules() {
|
||||
let mut s = Session::new();
|
||||
@@ -130,6 +166,9 @@ fn clicking_selects_by_the_documented_rules() {
|
||||
((520.0, 120.0), NONE, vec![], vec![k.r2], "a locked layer can't be selected on the canvas: the click goes to what is under it"),
|
||||
((520.0, 220.0), NONE, vec![k.r], vec![], "a hidden layer can't be selected on the canvas (empty canvas deselects)"),
|
||||
((390.0, 290.0), NONE, vec![k.r], vec![], "the background of a top-level frame with layers is like the canvas: a click deselects"),
|
||||
((390.0, 290.0), NONE, vec![k.c], vec![k.f], "clicking the containing frame's background steps out from its child"),
|
||||
((390.0, 290.0), NONE, vec![k.d], vec![k.f], "stepping out works from a deeper descendant too"),
|
||||
((390.0, 290.0), NONE, vec![], vec![], "without a selected descendant the background remains canvas-like"),
|
||||
((390.0, 290.0), NONE, vec![k.f], vec![k.f], "a selected top-level frame stays selected when its background is clicked"),
|
||||
((390.0, 290.0), CMD, vec![], vec![k.f], "silent: Cmd/Ctrl-click on a frame's background selects the frame (the deepest layer there)"),
|
||||
((640.0, 40.0), NONE, vec![], vec![k.empty], "an empty top-level frame is selected by a click on it"),
|
||||
|
||||
@@ -830,37 +830,53 @@ fn escape(app: &mut FigApp, ctx: &egui::Context) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The draft's composer next to its pin at `at` (screen), kept inside `bounds`; posting adds the
|
||||
/// comment (on `page` when given, else the current one) and shows its thread. The editor and the
|
||||
/// presenter both draw it here.
|
||||
///
|
||||
/// `target` is the page and the presented frame when called from the presenter: the comment then
|
||||
/// anchors within that frame. A comment that fails to post leaves the draft and its text.
|
||||
fn draft_composer(app: &mut FigApp, ctx: &egui::Context, at: Pos2, bounds: Rect, target: Option<(NodeId, NodeId)>) {
|
||||
let Some((x, y, mut text)) = app.ui.comments.draft.clone() else { return };
|
||||
let t = Tokens::get(ctx);
|
||||
let people = app.session.doc().map(|d| d.comment_people()).unwrap_or_default();
|
||||
let me = me(app);
|
||||
let mut pick = std::mem::take(&mut app.ui.comments.mention);
|
||||
let mut post = false;
|
||||
egui::Area::new(Id::unique("comment_draft")).order(egui::Order::Foreground).fixed_pos(popover_pos(at, bounds)).show(ctx, |ui| {
|
||||
popover_frame(&t).show(ui, |ui| {
|
||||
ui.set_width(POPOVER_W - 24.0);
|
||||
post = composer(ui, Id::unique("comment_draft_text"), &mut text, tr("Add a comment"), &people, &me, &mut pick);
|
||||
});
|
||||
});
|
||||
app.ui.comments.mention = pick;
|
||||
if post {
|
||||
let mut params = json!({"x": x, "y": y, "text": text.trim(), "anchor": true});
|
||||
if let (Some((page, frame)), Some(o)) = (target, params.as_object_mut()) {
|
||||
o.insert("page".into(), json!(page));
|
||||
o.insert("within".into(), json!(frame));
|
||||
}
|
||||
if let Some(r) = app.run("comment.add", params) {
|
||||
app.ui.comments.draft = None;
|
||||
if let Some(id) = r.get("id").and_then(Value::as_u64) {
|
||||
app.ui.comments.show(id);
|
||||
}
|
||||
} else if let Some(d) = &mut app.ui.comments.draft {
|
||||
d.2 = text;
|
||||
}
|
||||
} else if let Some(d) = &mut app.ui.comments.draft {
|
||||
d.2 = text;
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread popover and the draft composer, floating next to their pins on the canvas.
|
||||
pub fn popovers(app: &mut FigApp, ctx: &egui::Context) {
|
||||
if escape(app, ctx) {
|
||||
return;
|
||||
}
|
||||
let canvas = app.canvas.rect;
|
||||
if let Some((x, y, mut text)) = app.ui.comments.draft.clone() {
|
||||
let t = Tokens::get(ctx);
|
||||
let people = app.session.doc().map(|d| d.comment_people()).unwrap_or_default();
|
||||
let me = me(app);
|
||||
let mut pick = std::mem::take(&mut app.ui.comments.mention);
|
||||
let mut post = false;
|
||||
egui::Area::new(Id::unique("comment_draft")).order(egui::Order::Foreground).fixed_pos(popover_pos(app.to_screen(x, y), canvas)).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
popover_frame(&t).show(ui, |ui| {
|
||||
ui.set_width(POPOVER_W - 24.0);
|
||||
post = composer(ui, Id::unique("comment_draft_text"), &mut text, tr("Add a comment"), &people, &me, &mut pick);
|
||||
});
|
||||
},
|
||||
);
|
||||
app.ui.comments.mention = pick;
|
||||
if post {
|
||||
let r = app.run("comment.add", json!({"x": x, "y": y, "text": text.trim(), "anchor": true}));
|
||||
app.ui.comments.draft = None;
|
||||
if let Some(id) = r.and_then(|v| v.get("id").and_then(Value::as_u64)) {
|
||||
app.ui.comments.show(id);
|
||||
}
|
||||
} else if let Some(d) = &mut app.ui.comments.draft {
|
||||
d.2 = text;
|
||||
}
|
||||
if let Some((x, y, _)) = app.ui.comments.draft {
|
||||
draft_composer(app, ctx, app.to_screen(x, y), canvas, None);
|
||||
return;
|
||||
}
|
||||
let Some(open) = app.ui.comments.open else { return };
|
||||
@@ -1228,6 +1244,34 @@ pub fn presenter(app: &mut FigApp, ctx: &egui::Context, frame: NodeId, place: cr
|
||||
if let Some(id) = clicked {
|
||||
toggle(app, id);
|
||||
}
|
||||
// A click on the presented frame (not on a pin or a popover) starts a comment there: the
|
||||
// presented point back to the frame as designed.
|
||||
let frame_rect = place.rect(fb).intersect(clip);
|
||||
let click = ctx.input(|i| if i.pointer.primary_clicked() { i.pointer.interact_pos() } else { None });
|
||||
// The draft's own pin isn't interactable, so a click on it would start a new draft and lose
|
||||
// the typed text: it is left alone.
|
||||
let draft_pin = app.ui.comments.draft.as_ref().map(|(x, y, _)| pin_rect(to_screen((*x, *y))));
|
||||
if clicked.is_none()
|
||||
&& let Some(q) = click.filter(|q| frame_rect.contains(*q) && !draft_pin.is_some_and(|r| r.contains(*q)))
|
||||
&& ctx.layer_id_at(q).is_none_or(|l| l.order == egui::Order::Background)
|
||||
{
|
||||
let pt = place.page(q);
|
||||
start_draft(app, fb.x0 + (pt.x - place.page_min.0), fb.y0 + (pt.y - place.page_min.1));
|
||||
}
|
||||
if let Some((x, y, _)) = app.ui.comments.draft {
|
||||
let at = to_screen((x, y));
|
||||
let r = pin_rect(at);
|
||||
egui::Area::new(Id::unique("present_comment_draft_pin")).order(egui::Order::Foreground).fixed_pos(r.min).interactable(false).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
let (rr, _) = ui.allocate_exact_size(r.size(), Sense::hover());
|
||||
ui.painter().rect_filled(rr, BUBBLE, ACCENT);
|
||||
ui.painter().circle_filled(rr.center(), 3.0, crate::theme::ACCENT_ON);
|
||||
},
|
||||
);
|
||||
draft_composer(app, ctx, at, ctx.content_rect(), doc.page_of(frame).map(|page| (page, frame)));
|
||||
return;
|
||||
}
|
||||
match app.ui.comments.open.and_then(|o| pins.iter().find(|p| p.id == o)) {
|
||||
Some(p) => thread(app, ctx, p.id, p.at, ctx.content_rect()),
|
||||
// A thread on another frame (or none) closes.
|
||||
|
||||
@@ -338,6 +338,42 @@ struct Zones {
|
||||
tracks: Vec<[Pos2; 2]>,
|
||||
}
|
||||
|
||||
/// Screen-space grip targets. Opposite grips stay at least 20 pixels apart, moving outward from
|
||||
/// their midpoint only when needed: tiny frames and zoomed-out content must not merge them into
|
||||
/// one indistinguishable target. Bands keep their actual padding geometry.
|
||||
fn padding_handles(bands: &[(usize, Rect, f64)]) -> Vec<(usize, Rect, f64)> {
|
||||
bands
|
||||
.iter()
|
||||
.map(|&(side, band, value)| {
|
||||
let mut center = band.center();
|
||||
if let Some((_, opposite, _)) = bands.iter().find(|(s, _, _)| *s == (side + 2) % 4) {
|
||||
let (axis, other) = if side.is_multiple_of(2) { (&mut center.y, opposite.center().y) } else { (&mut center.x, opposite.center().x) };
|
||||
if (*axis - other).abs() < 20.0 {
|
||||
*axis = (*axis + other) / 2.0 + if matches!(side, 0 | 3) { -10.0 } else { 10.0 };
|
||||
}
|
||||
}
|
||||
let rect = Rect::from_center_size(center, if side.is_multiple_of(2) { vec2(20.0, 12.0) } else { vec2(12.0, 20.0) });
|
||||
(side, rect, value)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Resolve overlapping targets by distance to the visible grip, shared by hover and press.
|
||||
/// Iteration order alone can let an earlier target steal clicks on a later grip's painted bar.
|
||||
fn padding_at(handles: &[(usize, Rect, f64)], pos: Pos2) -> Option<(usize, Rect, f64)> {
|
||||
handles
|
||||
.iter()
|
||||
.filter(|(_, rect, _)| rect.contains(pos))
|
||||
.min_by(|(_, a, _), (_, b, _)| a.center().distance_sq(pos).total_cmp(&b.center().distance_sq(pos)))
|
||||
.copied()
|
||||
}
|
||||
|
||||
/// Alt links opposing sides, Alt+Shift all four. Shift alone retains the existing axis gesture.
|
||||
/// Painting and editing share this rule so the highlighted sides are exactly those that change.
|
||||
fn padding_affects(side: usize, candidate: usize, modifiers: egui::Modifiers) -> bool {
|
||||
candidate == side || (modifiers.alt && modifiers.shift) || ((modifiers.alt || modifiers.shift) && candidate == (side + 2) % 4)
|
||||
}
|
||||
|
||||
fn al_zones(app: &FigApp) -> Option<Zones> {
|
||||
let ds = app.session.ds().ok()?;
|
||||
if ds.selection.len() != 1 || ds.text_edit.is_some() || ds.vector_edit.is_some() {
|
||||
@@ -357,13 +393,17 @@ fn al_zones(app: &FigApp) -> Option<Zones> {
|
||||
app.to_screen(p.x, p.y)
|
||||
};
|
||||
let band = |x0: f64, y0: f64, x1: f64, y1: f64| Rect::from_two_pos(to(x0, y0), to(x1, y1));
|
||||
let [pt, pr, pb, pl] = al.padding;
|
||||
let [pt, pr, pb, pl] = al.padding.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 });
|
||||
let (it, ir, ib, il) = figcraft_layout::insets(n, al);
|
||||
let (fw, fh) = (n.width, n.height);
|
||||
// Padding starts at the inside edge of an included stroke, as the layout's content does.
|
||||
// The bands exclude the stroke itself so their labels and drags still edit only padding.
|
||||
let (left, top, right, bottom) = (il - pl, it - pt, fw - ir + pr, fh - ib + pb);
|
||||
let bands = vec![
|
||||
(0, band(0.0, 0.0, fw, pt.max(4.0)), pt),
|
||||
(1, band(fw - pr.max(4.0), 0.0, fw, fh), pr),
|
||||
(2, band(0.0, fh - pb.max(4.0), fw, fh), pb),
|
||||
(3, band(0.0, 0.0, pl.max(4.0), fh), pl),
|
||||
(0, band(left, top, right, top + pt.max(4.0)), pt),
|
||||
(1, band(right - pr.max(4.0), top, right, bottom), pr),
|
||||
(2, band(left, bottom - pb.max(4.0), right, bottom), pb),
|
||||
(3, band(left, top, left + pl.max(4.0), bottom), pl),
|
||||
];
|
||||
// An auto gap shows (and is dragged from) the distance the layout gives it; the drag makes it a
|
||||
// fixed gap again, as typing one does.
|
||||
@@ -376,8 +416,8 @@ fn al_zones(app: &FigApp) -> Option<Zones> {
|
||||
let mut tracks = Vec::new();
|
||||
if let Some(g) = figcraft_layout::grid_geometry(doc, id) {
|
||||
// Grid: bands between columns (column gap) and between rows (row gap), and the tracks.
|
||||
let (top, bottom) = (g.rows.first().map(|r| r.0).unwrap_or(pt), g.rows.last().map(|r| r.1).unwrap_or(fh - pb));
|
||||
let (left, right) = (g.columns.first().map(|c| c.0).unwrap_or(pl), g.columns.last().map(|c| c.1).unwrap_or(fw - pr));
|
||||
let (top, bottom) = (g.rows.first().map(|r| r.0).unwrap_or(it), g.rows.last().map(|r| r.1).unwrap_or(fh - ib));
|
||||
let (left, right) = (g.columns.first().map(|c| c.0).unwrap_or(il), g.columns.last().map(|c| c.1).unwrap_or(fw - ir));
|
||||
for pair in g.columns.windows(2) {
|
||||
if let [a, b] = pair {
|
||||
gaps.push(main(band(a.1, top, b.0, bottom), false, al.gap));
|
||||
@@ -403,7 +443,7 @@ fn al_zones(app: &FigApp) -> Option<Zones> {
|
||||
let flip = |r: figcraft_geom::Rect| if vertical { figcraft_geom::Rect::new(r.y0, r.x0, r.y1, r.x1) } else { r };
|
||||
let fband = |x0: f64, y0: f64, x1: f64, y1: f64| if vertical { band(y0, x0, y1, x1) } else { band(x0, y0, x1, y1) };
|
||||
// Main-axis length and padding, cross-axis length and padding.
|
||||
let (mw, mp0, mp1, cw, cp0, cp1) = if vertical { (fh, pt, pb, fw, pl, pr) } else { (fw, pl, pr, fh, pt, pb) };
|
||||
let (mw, mp0, mp1, cw, cp0, cp1) = if vertical { (fh, it, ib, fw, il, ir) } else { (fw, il, ir, fh, it, ib) };
|
||||
let boxes: Vec<figcraft_geom::Rect> = figcraft_layout::flow_children(doc, id)
|
||||
.into_iter()
|
||||
.filter_map(|c| doc.node(c))
|
||||
@@ -514,26 +554,38 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) {
|
||||
draw_crop(app, painter, id, &img, r);
|
||||
return;
|
||||
}
|
||||
let hover = painter.ctx().input(|i| i.pointer.hover_pos());
|
||||
let (hover, modifiers) = painter.ctx().input(|i| (i.pointer.hover_pos(), i.modifiers));
|
||||
let tool_move = app.session.tool.tool == figcraft_engine::ToolId::Move && !app.session.tool.busy();
|
||||
let dragging: Option<Drag> = painter.ctx().data(|d| d.get_temp(drag_id()));
|
||||
if !tool_move && dragging.is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(z) = al_zones(app) else { return };
|
||||
let tokens = crate::theme::Tokens::get(painter.ctx());
|
||||
let handles = padding_handles(&z.bands);
|
||||
let active_side = match &dragging {
|
||||
Some(Drag::Padding { side, .. }) => Some(*side),
|
||||
_ => None,
|
||||
_ => hover.and_then(|pos| padding_at(&handles, pos).map(|(side, _, _)| side)),
|
||||
};
|
||||
for seg in &z.tracks {
|
||||
painter.add(Shape::dashed_line(seg, Stroke::new(1.0, PINK.gamma_multiply(0.6)), 3.0, 3.0));
|
||||
}
|
||||
for (side, r, v) in &z.bands {
|
||||
let hot = hover.is_some_and(|h| r.contains(h)) || active_side == Some(*side);
|
||||
for ((side, r, v), (_, handle, _)) in z.bands.iter().zip(&handles) {
|
||||
let linked = active_side.is_some_and(|active| padding_affects(active, *side, modifiers));
|
||||
let hot = hover.is_some_and(|h| r.contains(h)) || linked;
|
||||
if hot {
|
||||
painter.rect_filled(*r, CornerRadius::ZERO, PINK.gamma_multiply(0.25));
|
||||
pink_label(painter, crate::canvas::fmt(*v), r.center());
|
||||
let offset = if side.is_multiple_of(2) { vec2(28.0, 0.0) } else { vec2(0.0, -20.0) };
|
||||
pink_label(painter, crate::canvas::fmt(*v), handle.center() + offset);
|
||||
}
|
||||
let grip = Rect::from_center_size(handle.center(), if side.is_multiple_of(2) { vec2(16.0, 4.0) } else { vec2(4.0, 16.0) });
|
||||
painter.rect_filled(grip, CornerRadius::same(2), if linked { tokens.padding_grip } else { tokens.padding_grip.gamma_multiply(0.6) });
|
||||
painter.rect_stroke(
|
||||
grip,
|
||||
CornerRadius::same(2),
|
||||
Stroke::new(if linked { 1.5 } else { 1.0 }, tokens.padding_grip_border),
|
||||
StrokeKind::Outside,
|
||||
);
|
||||
}
|
||||
let drag_key = match &dragging {
|
||||
Some(Drag::Gap { key, .. }) => Some(*key),
|
||||
@@ -552,14 +604,21 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) {
|
||||
let _ = Align2::CENTER_CENTER;
|
||||
}
|
||||
|
||||
/// Pointer handling; returns true when a handle owns the pointer this frame.
|
||||
pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
let (pressed, down, released, shift) = ctx.input(|i| {
|
||||
/// A handle may own only the cursor while ordinary canvas hover and secondary clicks continue.
|
||||
pub enum Input {
|
||||
Ignored,
|
||||
Hover(egui::CursorIcon),
|
||||
Captured,
|
||||
}
|
||||
|
||||
/// Consume active handle gestures, but report padding hover separately from captured input.
|
||||
pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> Input {
|
||||
let (pressed, down, released, modifiers) = ctx.input(|i| {
|
||||
(
|
||||
i.pointer.button_pressed(egui::PointerButton::Primary),
|
||||
i.pointer.primary_down(),
|
||||
i.pointer.button_released(egui::PointerButton::Primary),
|
||||
i.modifiers.shift,
|
||||
i.modifiers,
|
||||
)
|
||||
});
|
||||
let dragging: Option<Drag> = ctx.data(|d| d.get_temp(drag_id()));
|
||||
@@ -567,17 +626,17 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
// Escape or Undo closed the gesture under the held button: the drag is over.
|
||||
if !gesture_open(app) {
|
||||
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
|
||||
return true;
|
||||
return Input::Captured;
|
||||
}
|
||||
if down {
|
||||
apply(app, &drag, pos, shift);
|
||||
apply(app, &drag, pos, modifiers);
|
||||
ctx.set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
}
|
||||
if released || !down {
|
||||
let _ = app.session.commit_interaction();
|
||||
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
|
||||
}
|
||||
return true;
|
||||
return Input::Captured;
|
||||
}
|
||||
// Hover cursors / press to start.
|
||||
if let Some((id, fills, index, g)) = gradient_target(app) {
|
||||
@@ -594,16 +653,16 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
let _ = app.session.begin_interaction("Edit gradient");
|
||||
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gradient { id, fills, index, which }));
|
||||
}
|
||||
return true;
|
||||
return Input::Captured;
|
||||
}
|
||||
}
|
||||
// Stops: select and slide them; a click elsewhere on the line adds one there.
|
||||
let (Some(a), Some(b)) = (pts[0], pts[1]) else { return false };
|
||||
let (Some(a), Some(b)) = (pts[0], pts[1]) else { return Input::Ignored };
|
||||
let stop_hit = g.stops.iter().position(|st| (a + (b - a) * st.position - pos).length() <= 8.0);
|
||||
let t = line_param(a, b, pos);
|
||||
let on_line = t.is_some_and(|(_, d)| d <= 5.0);
|
||||
if stop_hit.is_none() && !on_line {
|
||||
return false;
|
||||
return Input::Ignored;
|
||||
}
|
||||
ctx.set_cursor_icon(if stop_hit.is_some() { egui::CursorIcon::Grab } else { egui::CursorIcon::Copy });
|
||||
if pressed {
|
||||
@@ -624,7 +683,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
ctx.data_mut(|d| d.insert_temp(crate::colorpicker::stop_id(), stop));
|
||||
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gradient { id, fills, index, which: 3 + stop }));
|
||||
}
|
||||
return true;
|
||||
return Input::Captured;
|
||||
}
|
||||
if let Some((id, index, e)) = blur_target(app, ctx) {
|
||||
let hit = blur_points(app, id, &e).and_then(|pts| pts.iter().position(|p| (*p - pos).length() <= 8.0));
|
||||
@@ -634,15 +693,15 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
let _ = app.session.begin_interaction("Edit progressive blur");
|
||||
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Blur { id, index, which }));
|
||||
}
|
||||
return true;
|
||||
return Input::Captured;
|
||||
}
|
||||
}
|
||||
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) {
|
||||
return false;
|
||||
return Input::Ignored;
|
||||
}
|
||||
let Some(c) = crop_corners(app, id, rect) else { return false };
|
||||
let Some(c) = crop_corners(app, id, rect) else { return Input::Ignored };
|
||||
let start = screen_to_unit(app, id, pos).unwrap_or((0.0, 0.0));
|
||||
let corner = c.iter().position(|p| (*p - pos).length() <= 8.0);
|
||||
let inside = start.0 >= rect.0.min(rect.2) && start.0 <= rect.0.max(rect.2) && start.1 >= rect.1.min(rect.3) && start.1 <= rect.1.max(rect.3);
|
||||
@@ -654,7 +713,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
if pressed {
|
||||
app.ui.crop = None;
|
||||
}
|
||||
return false;
|
||||
return Input::Ignored;
|
||||
}
|
||||
};
|
||||
ctx.set_cursor_icon(if which == 4 {
|
||||
@@ -668,22 +727,21 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
let _ = app.session.begin_interaction("Crop image");
|
||||
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Crop { id, fills, index, which, start, rect }));
|
||||
}
|
||||
return true;
|
||||
return Input::Captured;
|
||||
}
|
||||
if app.session.tool.tool != figcraft_engine::ToolId::Move || app.session.tool.busy() {
|
||||
return false;
|
||||
return Input::Ignored;
|
||||
}
|
||||
let Some(Zones { id, bands, gaps, .. }) = al_zones(app) else { return false };
|
||||
for (side, r, v) in bands {
|
||||
if r.contains(pos) {
|
||||
ctx.set_cursor_icon(if side % 2 == 0 { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal });
|
||||
if pressed {
|
||||
let _ = app.session.begin_interaction("Padding");
|
||||
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Padding { id, side, start: pos, value: v }));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
let Some(Zones { id, bands, gaps, .. }) = al_zones(app) else { return Input::Ignored };
|
||||
if let Some((side, _, value)) = padding_at(&padding_handles(&bands), pos) {
|
||||
let cursor = if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal };
|
||||
ctx.set_cursor_icon(cursor);
|
||||
if pressed {
|
||||
let _ = app.session.begin_interaction("Padding");
|
||||
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Padding { id, side, start: pos, value }));
|
||||
return Input::Captured;
|
||||
}
|
||||
return Input::Hover(cursor);
|
||||
}
|
||||
for g in gaps {
|
||||
if g.rect.contains(pos) {
|
||||
@@ -691,15 +749,15 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
if pressed {
|
||||
let _ = app.session.begin_interaction("Gap");
|
||||
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gap { id, start: pos, value: g.value, vertical: g.vertical, key: g.key }));
|
||||
return true;
|
||||
return Input::Captured;
|
||||
}
|
||||
return false;
|
||||
return Input::Ignored;
|
||||
}
|
||||
}
|
||||
false
|
||||
Input::Ignored
|
||||
}
|
||||
|
||||
fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, modifiers: egui::Modifiers) {
|
||||
let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0).max(1e-6);
|
||||
match drag {
|
||||
Drag::Gradient { id, fills, index, which } => {
|
||||
@@ -748,10 +806,12 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
_ => pos.x - start.x,
|
||||
}) / zoom;
|
||||
let v = (value + d).round().max(0.0);
|
||||
let key = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"].get(*side).copied().unwrap_or("paddingTop");
|
||||
// Shift drags both sides of the axis together.
|
||||
let props =
|
||||
if shift { if side % 2 == 0 { json!({"paddingVertical": v}) } else { json!({"paddingHorizontal": v}) } } else { json!({ key: v }) };
|
||||
let props: serde_json::Map<String, serde_json::Value> = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(candidate, _)| padding_affects(*side, *candidate, modifiers))
|
||||
.map(|(_, key)| ((*key).to_owned(), json!(v)))
|
||||
.collect();
|
||||
let _ = app.session.execute("node.set", &json!({"ids": [id], "props": props}));
|
||||
}
|
||||
Drag::Crop { id, fills, index, which, start, rect } => {
|
||||
@@ -767,7 +827,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
let (cx, cy) = corners.get(*which).copied().unwrap_or((x1, y1));
|
||||
let (ow, oh) = (cx - ax, cy - ay);
|
||||
let (mut nw, mut nh) = (u.0 - ax, u.1 - ay);
|
||||
if !shift {
|
||||
if !modifiers.shift {
|
||||
// Node aspect matters: the unit box is not square in pixels.
|
||||
let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return };
|
||||
let k = ((nw * n.width).abs() / (ow * n.width).abs().max(1e-9)).max((nh * n.height).abs() / (oh * n.height).abs().max(1e-9));
|
||||
@@ -806,4 +866,6 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
#[cfg(test)]
|
||||
mod character_fill_tests;
|
||||
#[cfg(test)]
|
||||
mod padding_tests;
|
||||
#[cfg(test)]
|
||||
mod region_tests;
|
||||
@@ -0,0 +1,305 @@
|
||||
//! Padding bands follow the content box, including the frame's inside stroke.
|
||||
|
||||
use egui::{Event, Rect, vec2};
|
||||
use figcraft_doc::NodeId;
|
||||
use figcraft_engine::{Session, params::id_of};
|
||||
use serde_json::json;
|
||||
|
||||
use super::{Drag, al_zones, drag_id};
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
fn scene() -> (Ui, NodeId) {
|
||||
let mut s = Session::new();
|
||||
let f = id_of(
|
||||
&s.execute(
|
||||
"frame.create",
|
||||
&json!({"x": 100, "y": 100, "width": 300, "height": 200,
|
||||
"props": {"layout": "horizontal", "gap": 10, "padding": [10, 20, 30, 40], "stroke": "#000000", "strokeWeight": 4, "strokeAlign": "inside"}
|
||||
}),
|
||||
)
|
||||
.unwrap()["id"],
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [f]})).unwrap();
|
||||
(Ui::new(s), f)
|
||||
}
|
||||
|
||||
/// The four visible grips in paint order, without relying on the hit-test geometry.
|
||||
fn painted_grips(output: &egui::FullOutput) -> Vec<Rect> {
|
||||
crate::live_tests::flat(&output.shapes)
|
||||
.iter()
|
||||
.filter_map(|shape| match shape {
|
||||
egui::Shape::Rect(r)
|
||||
if r.fill == super::PINK.gamma_multiply(0.6)
|
||||
&& ((r.rect.width() == 16.0 && r.rect.height() == 4.0) || (r.rect.width() == 4.0 && r.rect.height() == 16.0)) =>
|
||||
{
|
||||
Some(r.rect)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Even collapsed content boxes and reduced zoom leave each painted grip independently usable.
|
||||
#[test]
|
||||
fn tiny_frames_keep_every_painted_padding_grip_reachable() {
|
||||
for (width, height, zoom, stroke) in [
|
||||
(300.0, 4.0, 1.0, 0.0),
|
||||
(300.0, 6.0, 1.0, 0.0),
|
||||
(300.0, 10.0, 1.0, 0.0),
|
||||
(300.0, 20.0, 0.25, 0.0),
|
||||
(300.0, 20.0, 1.0, 8.0),
|
||||
(4.0, 200.0, 1.0, 0.0),
|
||||
(4.0, 4.0, 0.25, 0.0),
|
||||
] {
|
||||
for side in 0_usize..4 {
|
||||
let (mut u, f) = scene();
|
||||
u.app.run("node.set", json!({"ids": [f], "props": {"width": width, "height": height, "padding": 0, "strokeWeight": stroke}}));
|
||||
u.app.session.ds_mut().unwrap().view.zoom = zoom;
|
||||
let grips = painted_grips(&u.frame_output(vec![Event::PointerGone]));
|
||||
assert_eq!(grips.len(), 4);
|
||||
let center = grips[side].center();
|
||||
let output = u.frame_output(vec![Event::PointerMoved(center)]);
|
||||
assert_eq!(
|
||||
output.platform_output.cursor_icon,
|
||||
if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }
|
||||
);
|
||||
u.button(center, true);
|
||||
assert!(
|
||||
matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { side: active, .. }) if active == side),
|
||||
"{width}x{height}, zoom {zoom}, stroke {stroke}, side {side}"
|
||||
);
|
||||
let to = center + [vec2(0.0, 2.0), vec2(-2.0, 0.0), vec2(0.0, -2.0), vec2(2.0, 0.0)][side] * zoom as f32;
|
||||
u.frame(vec![Event::PointerMoved(to)]);
|
||||
u.button(to, false);
|
||||
let mut expected = [0.0; 4];
|
||||
expected[side] = 2.0;
|
||||
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, expected);
|
||||
u.app.run("edit.undo", json!({}));
|
||||
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [0.0; 4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A painted side grip wins over a neighbouring grip's enlarged, overlapping hit target.
|
||||
#[test]
|
||||
fn overlapping_padding_targets_use_the_nearest_grip_for_hover_and_press() {
|
||||
let (mut u, f) = scene();
|
||||
u.app.run("node.set", json!({"ids": [f], "props": {"width": 4, "height": 4, "padding": 0, "strokeWeight": 0}}));
|
||||
let grips = painted_grips(&u.frame_output(vec![Event::PointerGone]));
|
||||
assert_eq!(grips.len(), 4);
|
||||
// On the upper part of the right bar, also inside the top grip's larger hit target.
|
||||
let point = egui::pos2(grips[1].center().x - 1.0, grips[0].center().y + 5.0);
|
||||
assert!(grips[1].contains(point));
|
||||
let handles = super::padding_handles(&al_zones(&u.app).unwrap().bands);
|
||||
assert_eq!(handles.iter().filter(|(_, r, _)| r.contains(point)).count(), 2);
|
||||
let output = u.frame_output(vec![Event::PointerMoved(point)]);
|
||||
assert_eq!(output.platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal);
|
||||
let shapes = crate::live_tests::flat(&output.shapes);
|
||||
assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == grips[1] && r.fill == super::PINK)));
|
||||
assert!(!shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == grips[0] && r.fill == super::PINK)));
|
||||
u.button(point, true);
|
||||
assert!(matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { side: 1, .. })));
|
||||
u.button(point, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_bands_follow_uniform_and_individual_inside_strokes() {
|
||||
let (mut u, f) = scene();
|
||||
for (props, stroke) in [
|
||||
(json!({"strokeWeight": 4}), [4.0; 4]),
|
||||
(json!({"strokeWeight": 24}), [24.0; 4]),
|
||||
(json!({"strokeSides": [8, 12, 16, 24]}), [8.0, 12.0, 16.0, 24.0]),
|
||||
(json!({"strokesIncluded": false}), [0.0; 4]),
|
||||
(json!({"strokesIncluded": true, "strokeAlign": "center"}), [0.0; 4]),
|
||||
(json!({"strokeAlign": "outside"}), [0.0; 4]),
|
||||
] {
|
||||
u.app.run("node.set", json!({"ids": [f], "props": props}));
|
||||
let [t, r, b, l] = stroke;
|
||||
let expected = [
|
||||
(l, t, 300.0 - r, t + 10.0),
|
||||
(300.0 - r - 20.0, t, 300.0 - r, 200.0 - b),
|
||||
(l, 200.0 - b - 30.0, 300.0 - r, 200.0 - b),
|
||||
(l, t, l + 40.0, 200.0 - b),
|
||||
];
|
||||
let zones = al_zones(&u.app).unwrap();
|
||||
for ((side, band, value), (x0, y0, x1, y1)) in zones.bands.iter().zip(expected) {
|
||||
let expected = Rect::from_two_pos(u.app.to_screen(100.0 + x0, 100.0 + y0), u.app.to_screen(100.0 + x1, 100.0 + y1));
|
||||
assert_eq!(*band, expected, "side {side}, stroke {stroke:?}");
|
||||
assert_eq!(*value, [10.0, 20.0, 30.0, 40.0][*side]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gap_bands_span_the_content_box_inside_stroke_and_padding() {
|
||||
let (mut u, f) = scene();
|
||||
for _ in 0..2 {
|
||||
u.app.run("shape.rectangle", json!({"parent": f, "width": 40, "height": 20}));
|
||||
}
|
||||
u.app.run("select.set", json!({"ids": [f]}));
|
||||
for (mode, expected) in [("horizontal", (184.0, 114.0, 194.0, 266.0)), ("vertical", (144.0, 134.0, 376.0, 144.0))] {
|
||||
u.app.run("node.set", json!({"ids": [f], "props": {"layout": mode}}));
|
||||
let zones = al_zones(&u.app).unwrap();
|
||||
assert_eq!(zones.gaps.len(), 1);
|
||||
let (x0, y0, x1, y1) = expected;
|
||||
assert_eq!(zones.gaps[0].rect, Rect::from_two_pos(u.app.to_screen(x0, y0), u.app.to_screen(x1, y1)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_drag_starts_only_on_the_central_handle_and_undoes_in_one_step() {
|
||||
let (mut u, f) = scene();
|
||||
u.app.run("node.set", json!({"ids": [f], "props": {"strokeWeight": 24}}));
|
||||
u.frame(vec![]);
|
||||
let top = al_zones(&u.app).unwrap().bands[0].1;
|
||||
// The band away from its handle remains available to ordinary canvas tools.
|
||||
let away = top.center() + vec2(50.0, 0.0);
|
||||
u.button(away, true);
|
||||
assert!(!matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { .. })));
|
||||
u.button(away, false);
|
||||
u.app.run("select.set", json!({"ids": [f]}));
|
||||
u.frame(vec![]);
|
||||
|
||||
let center = al_zones(&u.app).unwrap().bands[0].1.center();
|
||||
let zoom = u.app.session.ds().unwrap().view.zoom as f32;
|
||||
u.button(center, true);
|
||||
assert!(matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { side: 0, .. })));
|
||||
let to = center + vec2(0.0, 6.0 * zoom);
|
||||
u.frame(vec![Event::PointerMoved(to)]);
|
||||
u.button(to, false);
|
||||
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [16.0, 20.0, 30.0, 40.0]);
|
||||
u.app.run("edit.undo", json!({}));
|
||||
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [10.0, 20.0, 30.0, 40.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_padding_grip_has_a_resize_cursor_and_links_the_requested_sides() {
|
||||
for modifiers in
|
||||
[egui::Modifiers::NONE, egui::Modifiers::ALT, egui::Modifiers::SHIFT, egui::Modifiers { alt: true, shift: true, ..Default::default() }]
|
||||
{
|
||||
for side in 0..4 {
|
||||
let (mut u, f) = scene();
|
||||
let center = al_zones(&u.app).unwrap().bands[side].1.center();
|
||||
let output = u.frame_with(vec![Event::PointerMoved(center)], modifiers);
|
||||
let cursor = if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal };
|
||||
assert_eq!(output.platform_output.cursor_icon, cursor, "padding side {side}");
|
||||
u.button(center, true);
|
||||
assert!(matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { side: active, .. }) if active == side));
|
||||
let zoom = u.app.session.ds().unwrap().view.zoom as f32;
|
||||
let delta = [vec2(0.0, 6.0), vec2(-6.0, 0.0), vec2(0.0, -6.0), vec2(6.0, 0.0)][side] * zoom;
|
||||
let to = center + delta;
|
||||
u.frame_with(vec![Event::PointerMoved(to)], modifiers);
|
||||
u.button(to, false);
|
||||
let mut expected = [10.0, 20.0, 30.0, 40.0];
|
||||
let value = expected[side] + 6.0;
|
||||
if modifiers.alt && modifiers.shift {
|
||||
expected = [value; 4];
|
||||
} else {
|
||||
expected[side] = value;
|
||||
if modifiers.alt || modifiers.shift {
|
||||
expected[(side + 2) % 4] = value;
|
||||
}
|
||||
}
|
||||
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, expected);
|
||||
u.app.run("edit.undo", json!({}));
|
||||
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [10.0, 20.0, 30.0, 40.0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modifier_keys_highlight_linked_padding_bands_before_and_during_a_drag() {
|
||||
let (mut u, _) = scene();
|
||||
let zones = al_zones(&u.app).unwrap();
|
||||
let center = zones.bands[0].1.center();
|
||||
u.frame(vec![Event::PointerMoved(center)]);
|
||||
// Pressing modifiers without moving the pointer previews the other affected sides.
|
||||
for (modifiers, active) in [
|
||||
(egui::Modifiers::NONE, [true, false, false, false]),
|
||||
(egui::Modifiers::ALT, [true, false, true, false]),
|
||||
(egui::Modifiers { alt: true, shift: true, ..Default::default() }, [true; 4]),
|
||||
(egui::Modifiers::NONE, [true, false, false, false]),
|
||||
] {
|
||||
let output = u.frame_with(vec![], modifiers);
|
||||
let shapes = crate::live_tests::flat(&output.shapes);
|
||||
for ((side, rect, _), active) in zones.bands.iter().zip(active) {
|
||||
let lit = shapes.iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.rect == *rect && r.fill == super::PINK.gamma_multiply(0.25)));
|
||||
assert_eq!(lit, active, "side {side}, modifiers {modifiers:?}");
|
||||
}
|
||||
}
|
||||
u.button(center, true);
|
||||
let modifiers = egui::Modifiers { alt: true, shift: true, ..Default::default() };
|
||||
let output = u.frame_with(vec![], modifiers);
|
||||
let zones = al_zones(&u.app).unwrap();
|
||||
let shapes = crate::live_tests::flat(&output.shapes);
|
||||
for (_, rect, _) in &zones.bands {
|
||||
assert!(shapes.iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.rect == *rect && r.fill == super::PINK.gamma_multiply(0.25))));
|
||||
}
|
||||
u.button(center, false);
|
||||
}
|
||||
|
||||
/// Hover over a grip must still update the layer under the pointer without editing the document.
|
||||
#[test]
|
||||
fn padding_grip_hover_preserves_canvas_hover_and_resize_cursor() {
|
||||
let (mut u, f) = scene();
|
||||
let other = id_of(&u.app.session.execute("shape.rectangle", &json!({"x": 500, "y": 100, "width": 40, "height": 40})).unwrap()["id"]).unwrap();
|
||||
u.app.run("select.set", json!({"ids": [f]}));
|
||||
let over_other = u.app.to_screen(520.0, 120.0);
|
||||
u.frame(vec![Event::PointerMoved(over_other)]);
|
||||
assert_eq!(u.app.session.ds().unwrap().hover, Some(other));
|
||||
let history = u.app.session.undo_depth();
|
||||
let grip = al_zones(&u.app).unwrap().bands[0].1.center();
|
||||
let output = u.frame_output(vec![Event::PointerMoved(grip)]);
|
||||
assert_eq!(u.app.session.ds().unwrap().hover, Some(f), "the previous layer must not stay hovered");
|
||||
assert_eq!(output.platform_output.cursor_icon, egui::CursorIcon::ResizeVertical);
|
||||
assert_eq!(u.app.session.undo_depth(), history);
|
||||
assert!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())).is_none());
|
||||
}
|
||||
|
||||
/// Right-click on any padding grip opens the ordinary canvas menu without starting a drag.
|
||||
#[test]
|
||||
fn padding_grips_preserve_secondary_click_context_menus() {
|
||||
for side in 0..4 {
|
||||
let (mut u, f) = scene();
|
||||
let center = al_zones(&u.app).unwrap().bands[side].1.center();
|
||||
let history = u.app.session.undo_depth();
|
||||
u.frame(vec![Event::PointerMoved(center)]);
|
||||
for pressed in [true, false] {
|
||||
u.frame(vec![Event::PointerButton { pos: center, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }]);
|
||||
}
|
||||
let (_, targets) = u.app.ui.context_menu.as_ref().expect("right-click on the grip opens the menu");
|
||||
assert!(targets.contains(&f));
|
||||
assert!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())).is_none());
|
||||
assert_eq!(u.app.session.undo_depth(), history);
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom light/dark palettes must control both grip states and their outlines.
|
||||
#[test]
|
||||
fn padding_grips_use_the_theme_fill_and_outline() {
|
||||
for mut tokens in [crate::theme::Tokens::light(), crate::theme::Tokens::dark()] {
|
||||
let (mut u, _) = scene();
|
||||
let grips = painted_grips(&u.frame_output(vec![Event::PointerGone]));
|
||||
assert_eq!(grips.len(), 4);
|
||||
tokens.padding_grip = if tokens.dark { egui::Color32::from_rgb(20, 40, 60) } else { egui::Color32::from_rgb(120, 40, 60) };
|
||||
tokens.padding_grip_border = egui::Color32::from_rgb(210, 180, 150);
|
||||
for active in [false, true] {
|
||||
let events = if active { vec![Event::PointerMoved(grips[0].center())] } else { vec![Event::PointerGone] };
|
||||
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, u.screen)), events, ..Default::default() };
|
||||
let mut output = u.ctx.clone().run_ui(raw, |ui| {
|
||||
crate::theme::apply(ui.ctx(), tokens);
|
||||
super::draw(&mut u.app, ui.painter());
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
let shapes = crate::live_tests::flat(&output.shapes);
|
||||
for (side, grip) in grips.iter().enumerate() {
|
||||
let linked = active && side == 0;
|
||||
let fill = if linked { tokens.padding_grip } else { tokens.padding_grip.gamma_multiply(0.6) };
|
||||
assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == *grip && r.fill == fill)));
|
||||
let width = if linked { 1.5 } else { 1.0 };
|
||||
assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == *grip && r.stroke.color == tokens.padding_grip_border && r.stroke.width == width)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -283,9 +283,15 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo
|
||||
if !app.canvas.dragging && resp.hovered() && crate::guides::input(app, &ctx, pos) {
|
||||
return false;
|
||||
}
|
||||
if !app.canvas.dragging && resp.hovered() && crate::handles::input(app, &ctx, pos) {
|
||||
return false;
|
||||
}
|
||||
let handle_cursor = if !app.canvas.dragging && resp.hovered() {
|
||||
match crate::handles::input(app, &ctx, pos) {
|
||||
crate::handles::Input::Captured => return false,
|
||||
crate::handles::Input::Hover(cursor) => Some(cursor),
|
||||
crate::handles::Input::Ignored => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if resp.secondary_clicked() {
|
||||
open_context_menu(app, pos, mods.command);
|
||||
return true;
|
||||
@@ -382,7 +388,13 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo
|
||||
send(app, PointerKind::Up, release_pos.unwrap_or(pos), &mods);
|
||||
}
|
||||
}
|
||||
true
|
||||
// Padding hover changes the cursor without skipping the normal hover and context-menu paths.
|
||||
if let Some(cursor) = handle_cursor {
|
||||
ctx.set_cursor_icon(cursor);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Pointer event `kind` at screen point `pos`, to the tools.
|
||||
|
||||
@@ -272,6 +272,156 @@ fn the_presenter_shows_the_frames_comments() {
|
||||
let _ = other;
|
||||
}
|
||||
|
||||
/// A presenter on a 400 x 300 frame (at page 50, 40) with a second frame, the comment mode on.
|
||||
/// Returns the harness, the frame, the other frame and the presented frame's top-left on screen.
|
||||
fn present_comment_mode() -> (Ui, figcraft_doc::NodeId, figcraft_doc::NodeId, Pos2) {
|
||||
let mut s = Session::new();
|
||||
let f = id(&s.execute("node.create", &json!({"type": "frame", "x": 50, "y": 40, "width": 400, "height": 300})).unwrap());
|
||||
let other = id(&s.execute("node.create", &json!({"type": "frame", "x": 700, "y": 0, "width": 400, "height": 300})).unwrap());
|
||||
let mut u = Ui::new(s);
|
||||
u.run("proto.present", json!({"start": f}));
|
||||
key(&mut u, Key::C, Modifiers::NONE);
|
||||
assert_eq!(u.app.inspect()["presenter"]["comments"], true);
|
||||
let screen = egui::Rect::from_min_size(pos2(0.0, 80.0), vec2(1440.0, 820.0));
|
||||
(u, f, other, screen.center() - vec2(200.0, 150.0))
|
||||
}
|
||||
|
||||
fn comment_count(u: &Ui) -> usize {
|
||||
u.app.session.doc().unwrap().comments.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_in_the_presenters_comment_mode_adds_a_comment_on_the_frame() {
|
||||
let (mut u, f, _, frame_min) = present_comment_mode();
|
||||
click(&mut u, frame_min + vec2(120.0, 90.0));
|
||||
assert!(comments(&u)["draft"].is_array(), "the click opens a draft");
|
||||
u.frame(vec![Event::Text("hello".into())]);
|
||||
key(&mut u, Key::Enter, Modifiers::NONE);
|
||||
assert_eq!(comment_count(&u), 1);
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let c = &doc.comments[0];
|
||||
assert_eq!(c.first.text, "hello");
|
||||
assert_eq!(c.anchor, Some(f));
|
||||
assert!((c.x - 120.0).abs() <= 1.0 && (c.y - 90.0).abs() <= 1.0, "frame-relative spot {},{}", c.x, c.y);
|
||||
assert_eq!(u.app.inspect()["presenter"]["comments"], true, "the mode stays on");
|
||||
assert!(u.app.ui.present.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_on_the_presenters_draft_pin_keeps_the_typed_draft() {
|
||||
let (mut u, _, _, frame_min) = present_comment_mode();
|
||||
let at = frame_min + vec2(120.0, 90.0);
|
||||
click(&mut u, at);
|
||||
u.frame(vec![Event::Text("typed".into())]);
|
||||
// The pin's body sits above and right of the point it marks.
|
||||
click(&mut u, at + vec2(6.0, -6.0));
|
||||
let draft = u.app.ui.comments.draft.clone();
|
||||
assert_eq!(draft.as_ref().map(|d| d.2.as_str()), Some("typed"), "the draft stays open with its text: {draft:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_off_the_frame_in_the_presenters_comment_mode_adds_no_draft() {
|
||||
let (mut u, _, _, frame_min) = present_comment_mode();
|
||||
click(&mut u, frame_min + vec2(-60.0, 90.0));
|
||||
assert!(comments(&u)["draft"].is_null());
|
||||
assert_eq!(comment_count(&u), 0);
|
||||
assert_eq!(u.app.inspect()["presenter"]["comments"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_closes_the_presenters_draft_then_the_mode() {
|
||||
let (mut u, _, _, frame_min) = present_comment_mode();
|
||||
click(&mut u, frame_min + vec2(120.0, 90.0));
|
||||
u.frame(vec![Event::Text("draft".into())]);
|
||||
key(&mut u, Key::Escape, Modifiers::NONE);
|
||||
assert!(comments(&u)["draft"].is_null(), "Escape closes the draft");
|
||||
assert_eq!(comment_count(&u), 0, "and adds no comment");
|
||||
assert_eq!(u.app.inspect()["presenter"]["comments"], true);
|
||||
assert!(u.app.ui.present.is_some());
|
||||
key(&mut u, Key::Escape, Modifiers::NONE);
|
||||
assert_eq!(u.app.inspect()["presenter"]["comments"], false, "Escape with no draft turns the mode off");
|
||||
assert!(u.app.ui.present.is_some(), "and keeps the presentation open");
|
||||
key(&mut u, Key::Escape, Modifiers::NONE);
|
||||
assert!(u.app.ui.present.is_none(), "with the mode off Escape still ends the presentation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_in_the_presenters_comment_mode_does_not_navigate() {
|
||||
let (mut u, f, other, frame_min) = present_comment_mode();
|
||||
u.run("proto.interaction.add", json!({"id": f, "trigger": {"type": "onClick"}, "action": {"type": "navigate", "dest": other}}));
|
||||
u.frames(2, Vec::new);
|
||||
click(&mut u, frame_min + vec2(120.0, 90.0));
|
||||
u.frames(30, Vec::new);
|
||||
assert_eq!(u.app.inspect()["presenter"]["current"], json!(f), "the click placed a comment, it didn't follow the link");
|
||||
assert!(comments(&u)["draft"].is_array());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_c_into_the_presenters_draft_keeps_the_mode_on() {
|
||||
let (mut u, _, _, frame_min) = present_comment_mode();
|
||||
click(&mut u, frame_min + vec2(120.0, 90.0));
|
||||
u.frame(vec![Event::Text("c".into())]);
|
||||
key(&mut u, Key::C, Modifiers::NONE);
|
||||
assert_eq!(u.app.inspect()["presenter"]["comments"], true);
|
||||
assert!(comments(&u)["draft"].is_array());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_posted_in_the_overlap_anchors_to_the_presented_frame() {
|
||||
let mut s = Session::new();
|
||||
let a = id(&s.execute("node.create", &json!({"type": "frame", "x": 50, "y": 40, "width": 400, "height": 300})).unwrap());
|
||||
// Stacked after `a` and overlapping its right part.
|
||||
s.execute("node.create", &json!({"type": "frame", "x": 250, "y": 40, "width": 400, "height": 300})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.run("proto.present", json!({"start": a}));
|
||||
key(&mut u, Key::C, Modifiers::NONE);
|
||||
let screen = egui::Rect::from_min_size(pos2(0.0, 80.0), vec2(1440.0, 820.0));
|
||||
let frame_min = screen.center() - vec2(200.0, 150.0);
|
||||
click(&mut u, frame_min + vec2(250.0, 90.0));
|
||||
u.frame(vec![Event::Text("overlap".into())]);
|
||||
key(&mut u, Key::Enter, Modifiers::NONE);
|
||||
assert_eq!(comment_count(&u), 1);
|
||||
let c = u.app.session.doc().unwrap().comments[0].clone();
|
||||
assert_eq!(c.anchor, Some(a), "the comment is on the presented frame, not the one stacked over it");
|
||||
assert_eq!(comments(&u)["open"], c.id, "its pin shows in the presenter");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_draft_that_fails_to_post_keeps_its_text() {
|
||||
let (mut h, _) = crate::live_tests::Harness::new();
|
||||
// A view-only link: the session refuses every edit, a comment too.
|
||||
crate::live_server_tests::joined(&mut h, figcraft_engine::live::Access::View);
|
||||
h.frames(2);
|
||||
start_draft(&mut h.app, 150.0, 150.0);
|
||||
h.frame(vec![]);
|
||||
h.frame(vec![Event::Text("hello".into())]);
|
||||
let k = |pressed| Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE };
|
||||
h.frame(vec![k(true), k(false)]);
|
||||
h.frames(2);
|
||||
assert!(h.app.session.doc().unwrap().comments.is_empty(), "the session refused the comment");
|
||||
let draft = h.app.ui.comments.draft.clone();
|
||||
assert_eq!(draft.as_ref().map(|d| d.2.as_str()), Some("hello"), "the draft and its text stay: {draft:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_press_held_into_the_presenters_comment_mode_does_not_navigate_on_release() {
|
||||
let mut s = Session::new();
|
||||
let f = id(&s.execute("node.create", &json!({"type": "frame", "x": 50, "y": 40, "width": 400, "height": 300})).unwrap());
|
||||
let other = id(&s.execute("node.create", &json!({"type": "frame", "x": 700, "y": 0, "width": 400, "height": 300})).unwrap());
|
||||
let mut u = Ui::new(s);
|
||||
u.run("proto.interaction.add", json!({"id": f, "trigger": {"type": "onClick"}, "action": {"type": "navigate", "dest": other}}));
|
||||
u.run("proto.present", json!({"start": f}));
|
||||
u.frames(2, Vec::new);
|
||||
let screen = egui::Rect::from_min_size(pos2(0.0, 80.0), vec2(1440.0, 820.0));
|
||||
let at = screen.center() - vec2(200.0, 150.0) + vec2(120.0, 90.0);
|
||||
u.button(at, true);
|
||||
key(&mut u, Key::C, Modifiers::NONE);
|
||||
assert_eq!(u.app.inspect()["presenter"]["comments"], true);
|
||||
u.button(at, false);
|
||||
u.frames(30, Vec::new);
|
||||
assert_eq!(u.app.inspect()["presenter"]["current"], json!(f), "the press began before comment mode, so its release is no click");
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Clip(Arc<Mutex<Option<String>>>);
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ fn ios_button_sets_corner_smoothing_to_60_percent() {
|
||||
#[test]
|
||||
fn corner_smoothing_icon_scrubs_with_modifiers_and_one_undo_step() {
|
||||
for (dx, modifiers, want) in
|
||||
[(16.0, Modifiers::NONE, 0.66), (8.0, Modifiers::SHIFT, 1.0), (16.0, Modifiers::ALT, 0.516), (-80.0, Modifiers::NONE, 0.0)]
|
||||
[(16.0, Modifiers::NONE, 0.58), (16.0, Modifiers::SHIFT, 1.0), (16.0, Modifiers::ALT, 0.508), (-160.0, Modifiers::NONE, 0.0)]
|
||||
{
|
||||
let (mut u, r) = scene();
|
||||
u.app.run("node.set", json!({"ids": [r], "props": {"cornerSmoothing": 0.5}}));
|
||||
@@ -117,7 +117,7 @@ fn consecutive_smoothing_drags_preserve_fractional_percentages() {
|
||||
let history = u.app.session.undo_depth().0;
|
||||
let smoothing = |u: &Ui| u.app.session.doc().unwrap().node(r).unwrap().corners.smoothing;
|
||||
for (step, (dx, modifiers, want)) in
|
||||
[(16.0, Modifiers::ALT, 0.516), (16.0, Modifiers::ALT, 0.532), (8.0, Modifiers::NONE, 0.612)].into_iter().enumerate()
|
||||
[(16.0, Modifiers::ALT, 0.508), (16.0, Modifiers::ALT, 0.516), (8.0, Modifiers::NONE, 0.556)].into_iter().enumerate()
|
||||
{
|
||||
let from = u.ctx.read_response(Id::unique("smoothing").with("lead")).unwrap().rect.center();
|
||||
u.frame_with(vec![Event::PointerMoved(from)], modifiers);
|
||||
@@ -133,7 +133,7 @@ fn consecutive_smoothing_drags_preserve_fractional_percentages() {
|
||||
assert!((smoothing(&u) - want).abs() < 1e-9, "gesture {step}: expected {want}, got {}", smoothing(&u));
|
||||
assert_eq!(u.app.session.undo_depth().0, history + step + 1);
|
||||
}
|
||||
for want in [0.532, 0.516, 0.5] {
|
||||
for want in [0.516, 0.508, 0.5] {
|
||||
u.app.session.undo().unwrap();
|
||||
assert!((smoothing(&u) - want).abs() < 1e-9, "undo restores the precise value");
|
||||
}
|
||||
|
||||
@@ -239,6 +239,17 @@ impl<'a> View<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest the window can be dragged to: wide enough that the table's header row holds the
|
||||
/// search field and a library collection's "Extend collection" button side by side.
|
||||
const MIN_SIZE: egui::Vec2 = vec2(600.0, 240.0);
|
||||
|
||||
/// The smallest and largest the window can be: at most the screen less a margin, and at least
|
||||
/// [`MIN_SIZE`] unless the screen is smaller than that (then the screen less the margin).
|
||||
fn limits(screen: Rect) -> (egui::Vec2, egui::Vec2) {
|
||||
let max = (screen.size() - vec2(16.0, 16.0)).max(vec2(1.0, 1.0));
|
||||
(MIN_SIZE.min(max), max)
|
||||
}
|
||||
|
||||
/// Show the editor while it's open (call once per frame).
|
||||
pub fn show(app: &mut FigApp, ctx: &Context) {
|
||||
let Some(mut st) = app.ui.variables.take() else { return };
|
||||
@@ -261,22 +272,30 @@ pub fn show(app: &mut FigApp, ctx: &Context) {
|
||||
st.collection = coll.map(|c| c.id.clone());
|
||||
let t = Tokens::get(ctx);
|
||||
let screen = ctx.content_rect();
|
||||
let size = vec2(880.0_f32.min(screen.width() - 80.0).max(480.0), 480.0_f32.min(screen.height() - 120.0).max(240.0));
|
||||
let (min, max) = limits(screen);
|
||||
let size = vec2(880.0_f32.min(screen.width() - 80.0), 480.0_f32.min(screen.height() - 120.0)).clamp(min, max);
|
||||
let mut open = true;
|
||||
egui::Window::new(tr("Local variables"))
|
||||
.id(Id::unique("variables_window"))
|
||||
.title_bar(false)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.fixed_size(size)
|
||||
.pivot(Align2::CENTER_CENTER)
|
||||
.default_pos(screen.center())
|
||||
.resizable(true)
|
||||
.default_size(size)
|
||||
.min_size(min)
|
||||
.max_size(max)
|
||||
// Pinned at its top-left corner, so dragging one edge leaves the opposite one in place;
|
||||
// it opens centred.
|
||||
.pivot(Align2::LEFT_TOP)
|
||||
.default_pos((screen.center() - size / 2.0).max(screen.min))
|
||||
.frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(0)))
|
||||
.show(ctx, |ui| {
|
||||
// The window's current size (its default until the user drags an edge or corner).
|
||||
let size = ui.available_size().max(min);
|
||||
ui.set_min_size(size);
|
||||
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
|
||||
header(app, ui, &mut open);
|
||||
let h = (size.y - 44.0).max(160.0);
|
||||
// The body below the 44-point header: what is left of the window (the table scrolls).
|
||||
let h = (size.y - 44.0).max(0.0);
|
||||
let top_down = egui::Layout::top_down(egui::Align::Min);
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.allocate_ui_with_layout(vec2(SIDEBAR_W, h), top_down, |ui| sidebar(app, ui, &views, &doc.variables, &mut st));
|
||||
|
||||
@@ -111,17 +111,17 @@ fn typed_text_is_a_number_arithmetic_or_an_edit_relative_to_the_value() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scrub_moves_a_step_a_point_ten_with_shift_and_a_tenth_with_alt() {
|
||||
fn a_scrub_moves_half_a_step_a_point_ten_times_that_with_shift_and_a_tenth_with_alt() {
|
||||
// (points dragged, the field's step, Shift, Alt) → how far the value moves
|
||||
let rows = [
|
||||
((25.0, 1.0, false, false), 25.0),
|
||||
((-25.0, 1.0, false, false), -25.0),
|
||||
((10.0, 1.0, true, false), 100.0),
|
||||
((20.0, 1.0, false, true), 2.0),
|
||||
((20.0, 1.0, true, true), 20.0),
|
||||
((10.0, 0.1, false, false), 1.0),
|
||||
((10.0, 0.1, true, false), 10.0),
|
||||
((10.0, 10.0, false, false), 100.0),
|
||||
((25.0, 1.0, false, false), 12.5),
|
||||
((-25.0, 1.0, false, false), -12.5),
|
||||
((10.0, 1.0, true, false), 50.0),
|
||||
((20.0, 1.0, false, true), 1.0),
|
||||
((20.0, 1.0, true, true), 10.0),
|
||||
((10.0, 0.1, false, false), 0.5),
|
||||
((10.0, 0.1, true, false), 5.0),
|
||||
((10.0, 10.0, false, false), 50.0),
|
||||
((0.0, 1.0, true, false), 0.0),
|
||||
];
|
||||
for ((dx, step, shift, alt), want) in rows {
|
||||
@@ -308,7 +308,7 @@ fn moving_up_or_down_while_scrubbing_changes_the_speed_and_says_so() {
|
||||
let (mut u, a, _) = setup();
|
||||
let toast = |u: &Ui| u.app.ui.toast.clone().map(|t| t.0).unwrap_or_default();
|
||||
// (rise in points, how far 40 points of scrub move X, the notice)
|
||||
for (rise, want, notice) in [(150.0, 80.0, "2x"), (0.0, 40.0, ""), (-150.0, 20.0, "1/2"), (-300.0, 10.0, "1/4"), (40.0, 40.0, "")] {
|
||||
for (rise, want, notice) in [(150.0, 40.0, "2x"), (0.0, 20.0, ""), (-150.0, 10.0, "1/2"), (-300.0, 5.0, "1/4"), (40.0, 20.0, "")] {
|
||||
let x0 = geom(&u, a).0;
|
||||
u.app.ui.toast = None;
|
||||
scrub_at_height(&mut u, "X", rise, 40.0);
|
||||
@@ -319,7 +319,7 @@ fn moving_up_or_down_while_scrubbing_changes_the_speed_and_says_so() {
|
||||
assert!(toast(&u).contains(notice), "rise {rise}: the notice says {}", toast(&u));
|
||||
}
|
||||
}
|
||||
// Speeds compose with the modifiers' rates: 2x with Shift is twenty steps a point.
|
||||
// Speeds compose with the modifiers' rates: 2x with Shift is ten steps a point.
|
||||
let x0 = geom(&u, a).0;
|
||||
let from = label(&mut u, "X");
|
||||
let shift = Modifiers { shift: true, ..Modifiers::NONE };
|
||||
@@ -333,7 +333,7 @@ fn moving_up_or_down_while_scrubbing_changes_the_speed_and_says_so() {
|
||||
let to = pos2(up.x + 10.0, up.y);
|
||||
u.frame_with(vec![Event::PointerMoved(to), press(false, to)], shift);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(geom(&u, a).0 - x0, 200.0, "ten points at 2x with Shift");
|
||||
assert_eq!(geom(&u, a).0 - x0, 100.0, "ten points at 2x with Shift");
|
||||
// The pointer reported gone from the window (egui's PointerGone) with the button still down
|
||||
// keeps the speed it had: no notice of 1x, and the scrub goes on at 2x once it is back.
|
||||
let x0 = geom(&u, a).0;
|
||||
@@ -356,7 +356,7 @@ fn moving_up_or_down_while_scrubbing_changes_the_speed_and_says_so() {
|
||||
let to = pos2(up.x + 30.0, up.y);
|
||||
u.frame_with(vec![Event::PointerMoved(to), press(false, to)], m);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(geom(&u, a).0 - x0, 40.0, "ten points before and ten after the pointer was gone, at 2x both");
|
||||
assert_eq!(geom(&u, a).0 - x0, 20.0, "ten points before and ten after the pointer was gone, at 2x both");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -366,11 +366,11 @@ fn scrubbing_the_label_moves_the_value_and_is_one_undo_step() {
|
||||
let alt = Modifiers { alt: true, ..Modifiers::NONE };
|
||||
// (field, points, modifiers, x after): X starts at 10.
|
||||
let rows = [
|
||||
("X", 25.0, Modifiers::NONE, 35.0),
|
||||
("X", 10.0, shift, 135.0),
|
||||
("X", 20.0, alt, 137.0),
|
||||
("X", -37.0, Modifiers::NONE, 100.0),
|
||||
("X", -8.0, shift, 20.0),
|
||||
("X", 24.0, Modifiers::NONE, 22.0),
|
||||
("X", 10.0, shift, 72.0),
|
||||
("X", 20.0, alt, 73.0),
|
||||
("X", -36.0, Modifiers::NONE, 55.0),
|
||||
("X", -8.0, shift, 15.0),
|
||||
];
|
||||
for (name, dx, m, want) in rows {
|
||||
let steps = undo_steps(&u);
|
||||
@@ -379,18 +379,18 @@ fn scrubbing_the_label_moves_the_value_and_is_one_undo_step() {
|
||||
assert_eq!(undo_steps(&u), steps + 1, "one undo step for the whole scrub");
|
||||
}
|
||||
u.app.run("edit.undo", json!({}));
|
||||
assert_eq!(geom(&u, a).0, 100.0, "undo takes back the last scrub alone");
|
||||
assert_eq!(geom(&u, a).0, 55.0, "undo takes back the last scrub alone");
|
||||
// A few points aren't a drag yet (a click on the label), then it counts from the press.
|
||||
// Alt gives tenths (the field shows them); the fraction stays under a plain scrub.
|
||||
let width = |u: &Ui| u.app.session.doc().unwrap().node(a).unwrap().width;
|
||||
scrub(&mut u, "Width", 7.0, alt);
|
||||
assert_eq!(width(&u), 40.7);
|
||||
scrub(&mut u, "Width", 8.0, alt);
|
||||
assert_eq!(width(&u), 40.4);
|
||||
scrub(&mut u, "Width", 8.0, Modifiers::NONE);
|
||||
assert_eq!(width(&u), 48.7);
|
||||
// Fractional fields: opacity moves a percent a point, rotation a degree.
|
||||
scrub(&mut u, "Opacity", -30.0, Modifiers::NONE);
|
||||
assert_eq!(width(&u), 44.4);
|
||||
// Fractional fields: opacity moves half a percent a point, rotation half a degree.
|
||||
scrub(&mut u, "Opacity", -60.0, Modifiers::NONE);
|
||||
assert_eq!(u.app.session.doc().unwrap().node(a).unwrap().opacity, 0.7);
|
||||
scrub(&mut u, "Rotation", 15.0, Modifiers::NONE);
|
||||
scrub(&mut u, "Rotation", 30.0, Modifiers::NONE);
|
||||
let rot = figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().node(a).unwrap().transform);
|
||||
assert!((rot.abs() - 15.0).abs() < 1e-6, "rotation {rot}");
|
||||
// A press on the label that doesn't move changes nothing.
|
||||
@@ -470,7 +470,7 @@ fn the_rotation_field_shows_and_sets_the_rotation_on_the_page() {
|
||||
assert_eq!(field(&mut u, "Rotation").1, "18°");
|
||||
// Scrubbing is one undo step.
|
||||
let steps = undo_steps(&u);
|
||||
scrub(&mut u, "Rotation", 15.0, Modifiers::NONE);
|
||||
scrub(&mut u, "Rotation", 30.0, Modifiers::NONE);
|
||||
assert!((page(&u, r) - 33.0).abs() < 1e-6, "{}", page(&u, r));
|
||||
assert_eq!(undo_steps(&u), steps + 1);
|
||||
// Mixed: layers in differently turned parents agree when their page angles do.
|
||||
@@ -669,7 +669,7 @@ fn scrubbing_colour_picker_fields_is_live_and_one_undo_step() {
|
||||
let steps = undo_steps(&u);
|
||||
let from = lead(&u, Id::unique(("cp_f", "r")));
|
||||
drag(&mut u, from, -20.0, Modifiers::NONE);
|
||||
assert_eq!((rgba(&u)[0], undo_steps(&u)), (r0 - 20, steps + 1), "R");
|
||||
assert_eq!((rgba(&u)[0], undo_steps(&u)), (r0 - 10, steps + 1), "R");
|
||||
// Committing adds a recent colour row and can lift the anchored picker. Settle its layout.
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
@@ -783,7 +783,7 @@ fn scrubbing_a_prototype_delay_sets_it_once_when_let_go() {
|
||||
figcraft_doc::proto::Trigger::AfterDelay { ms } => ms,
|
||||
_ => panic!("still after a delay"),
|
||||
};
|
||||
assert_eq!((ms, undo_steps(&u)), (800, steps + 1));
|
||||
assert_eq!((ms, undo_steps(&u)), (650, steps + 1));
|
||||
}
|
||||
|
||||
/// Asserts scrubbing the scale panel's width scales the layer live in one undo step.
|
||||
@@ -796,7 +796,7 @@ fn scrubbing_the_scale_panel_width_scales_live_in_one_undo_step() {
|
||||
let from = lead(&u, Id::unique("scale_w"));
|
||||
drag(&mut u, from, 20.0, Modifiers::NONE);
|
||||
let (_, _, w, h) = geom(&u, a);
|
||||
assert_eq!((w, h, undo_steps(&u)), (60.0, 45.0, steps + 1), "40×30 scaled to a width of 60");
|
||||
assert_eq!((w, h, undo_steps(&u)), (50.0, 37.5, steps + 1), "40×30 scaled to a width of 50");
|
||||
}
|
||||
|
||||
/// A 100 x 100 rectangle at the origin, selected, in a Ui with the Move tool.
|
||||
@@ -1644,10 +1644,10 @@ fn the_page_background_opacity_field_sets_the_page_colour_alpha() {
|
||||
type_into(&mut u, "Opacity", "50", Key::Enter);
|
||||
assert!(near(page_bg(&u).a, 0.5), "{:?}", page_bg(&u));
|
||||
assert_eq!(undo_steps(&u), steps + 1, "one undo step for the commit");
|
||||
// No label is drawn, so the field's leading strip scrubs it: a percent a point, live, and one
|
||||
// No label is drawn, so the field's leading strip scrubs it: half a percent a point, live, and one
|
||||
// undo step for the whole drag.
|
||||
let edge = lead(&u, Id::unique("pagebg_a"));
|
||||
drag(&mut u, edge, -25.0, Modifiers::NONE);
|
||||
drag(&mut u, edge, -50.0, Modifiers::NONE);
|
||||
assert!(near(page_bg(&u).a, 0.25), "{:?}", page_bg(&u));
|
||||
assert_eq!(undo_steps(&u), steps + 2, "one undo step for the whole scrub");
|
||||
u.app.run("edit.undo", json!({}));
|
||||
@@ -1680,7 +1680,7 @@ fn the_page_background_opacity_field_sets_the_page_colour_alpha() {
|
||||
|
||||
/// "You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option
|
||||
/// Windows: Alt" to scrub it (Adjust alignment, rotation, position, and dimensions). Alt is what
|
||||
/// makes the drag a scrub there, not the fine rate: a point moves a step, as on the label. Without
|
||||
/// makes the drag a scrub there, not the fine rate: a point moves half a step, as on the label. Without
|
||||
/// Alt a drag on the field is no click, so it neither edits nor moves anything.
|
||||
#[test]
|
||||
fn alt_held_over_a_field_scrubs_it() {
|
||||
@@ -1691,13 +1691,13 @@ fn alt_held_over_a_field_scrubs_it() {
|
||||
// a drag only once it has seen Alt; egui assigns a press by the frame before it).
|
||||
let alt = Modifiers { alt: true, ..Modifiers::NONE };
|
||||
u.frame_with(vec![Event::PointerMoved(at)], alt);
|
||||
drag(&mut u, at, 25.0, alt);
|
||||
assert_eq!(geom(&u, a).0, 35.0, "a step a point: X from 10");
|
||||
drag(&mut u, at, 24.0, alt);
|
||||
assert_eq!(geom(&u, a).0, 22.0, "half a step a point: X from 10");
|
||||
assert_eq!(undo_steps(&u), steps + 1, "one undo step for the whole scrub");
|
||||
assert_eq!(field(&mut u, "X").1, "35", "the field shows it and isn't editing");
|
||||
assert_eq!(field(&mut u, "X").1, "22", "the field shows it and isn't editing");
|
||||
let (at, _) = field(&mut u, "X");
|
||||
drag(&mut u, at, 25.0, Modifiers::NONE);
|
||||
assert_eq!(geom(&u, a).0, 35.0, "without Alt the field doesn't scrub");
|
||||
assert_eq!(geom(&u, a).0, 22.0, "without Alt the field doesn't scrub");
|
||||
assert_eq!(undo_steps(&u), steps + 1);
|
||||
// Alt let go before the button still ends the scrub with its undo step.
|
||||
let (at, _) = field(&mut u, "X");
|
||||
@@ -1710,7 +1710,7 @@ fn alt_held_over_a_field_scrubs_it() {
|
||||
let to = pos2(at.x + 20.0, at.y);
|
||||
u.frame_with(vec![Event::PointerMoved(to), press(false, Modifiers::NONE, to)], Modifiers::NONE);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(geom(&u, a).0, 55.0, "twenty more");
|
||||
assert_eq!(geom(&u, a).0, 32.0, "ten more");
|
||||
assert_eq!(undo_steps(&u), steps + 2, "committed when the button went up, without Alt");
|
||||
// Without Alt the field doesn't take the drag at all (a touch swipe over it is the panel's to
|
||||
// scroll): the press is a click of the field's, not a drag.
|
||||
@@ -1722,7 +1722,7 @@ fn alt_held_over_a_field_scrubs_it() {
|
||||
assert!(!u.ctx.is_being_dragged(field_id), "a plain press on the field isn't a drag of the field's");
|
||||
u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, Modifiers::NONE, pos2(at.x + 10.0, at.y))], Modifiers::NONE);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(geom(&u, a).0, 55.0, "nothing scrubbed");
|
||||
assert_eq!(geom(&u, a).0, 32.0, "nothing scrubbed");
|
||||
// With Alt held over it, the field does take the drag.
|
||||
let (at, _) = field(&mut u, "X");
|
||||
u.frame_with(vec![Event::PointerMoved(at)], alt);
|
||||
@@ -1731,7 +1731,7 @@ fn alt_held_over_a_field_scrubs_it() {
|
||||
assert!(u.ctx.is_being_dragged(field_id), "with Alt the drag is the field's");
|
||||
u.frame_with(vec![Event::PointerMoved(pos2(at.x + 10.0, at.y)), press(false, alt, pos2(at.x + 10.0, at.y))], alt);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(geom(&u, a).0, 65.0, "ten more");
|
||||
assert_eq!(geom(&u, a).0, 37.0, "five more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -75,13 +75,13 @@ fn centre(n: &Node) -> Pos2 {
|
||||
Pos2::new(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)
|
||||
}
|
||||
|
||||
/// The top of the search field: the text input as wide as `menu` (the panel's own fields are narrower).
|
||||
/// The top of the search field: the text input nearly as wide as `menu`, less the search box's margin and magnifier (the panel's own fields are narrower).
|
||||
fn search_top(nodes: &[Node], menu: Rect) -> f32 {
|
||||
let field = nodes
|
||||
.iter()
|
||||
.filter(|n| n.role() == Role::TextInput)
|
||||
.filter_map(|n| n.bounds())
|
||||
.find(|b| menu.contains(Pos2::new(b.x0 as f32 + 1.0, b.y0 as f32 + 1.0)) && b.x1 - b.x0 > f64::from(menu.width()) - 40.0)
|
||||
.find(|b| menu.contains(Pos2::new(b.x0 as f32 + 1.0, b.y0 as f32 + 1.0)) && b.x1 - b.x0 > f64::from(menu.width()) - 60.0)
|
||||
.expect("the menu has a search field");
|
||||
field.y0 as f32
|
||||
}
|
||||
|
||||
@@ -296,6 +296,8 @@ mod variables_rename_tests;
|
||||
#[cfg(test)]
|
||||
mod variables_select_tests;
|
||||
#[cfg(test)]
|
||||
mod variables_window_resize_tests;
|
||||
#[cfg(test)]
|
||||
mod variants_discovery_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_keys_tests;
|
||||
|
||||
@@ -503,7 +503,7 @@ mod tests {
|
||||
let red = texts.into_iter().find(|(text, _)| text == "FF0000").unwrap().1;
|
||||
let start = Pos2::new(167.0, red.y);
|
||||
p.modifiers.alt = true;
|
||||
for expected in [0.989, 0.979] {
|
||||
for expected in [0.994, 0.989] {
|
||||
p.frame(vec![
|
||||
Event::PointerMoved(start),
|
||||
Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: p.modifiers },
|
||||
@@ -521,8 +521,8 @@ mod tests {
|
||||
let opacity = p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity;
|
||||
assert!((opacity - expected).abs() < 1e-6, "fine scrub kept fractional baseline: {opacity}");
|
||||
}
|
||||
assert!(p.frame(vec![]).iter().any(|(text, _)| text == "97.9%"));
|
||||
for expected in [0.989, 0.999] {
|
||||
assert!(p.frame(vec![]).iter().any(|(text, _)| text == "98.9%"));
|
||||
for expected in [0.994, 0.999] {
|
||||
p.app.run("edit.undo", json!({}));
|
||||
let opacity = p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity;
|
||||
assert!((opacity - expected).abs() < 1e-6, "each fine scrub is one undo step: {opacity}");
|
||||
@@ -558,13 +558,13 @@ mod tests {
|
||||
Event::PointerMoved(start),
|
||||
Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() },
|
||||
]);
|
||||
for dx in [-10.0, -20.0, -30.0] {
|
||||
for dx in [-20.0, -40.0, -60.0] {
|
||||
p.frame(vec![Event::PointerMoved(start + vec2(dx, 0.0))]);
|
||||
}
|
||||
assert!(p.app.session.ds().unwrap().interaction.is_some(), "the scrub commits only on release");
|
||||
assert!(p.frame(vec![]).iter().any(|(text, _)| text == "70%"), "the live opacity stays visible while scrubbing");
|
||||
p.frame(vec![Event::PointerButton {
|
||||
pos: start - vec2(30.0, 0.0),
|
||||
pos: start - vec2(60.0, 0.0),
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: Default::default(),
|
||||
|
||||
@@ -75,6 +75,7 @@ pub(crate) fn font_picker(
|
||||
let just_opened = anchor.clicked();
|
||||
let hi_id = Id::unique("font_highlight");
|
||||
let q_id = Id::unique("font_query");
|
||||
let search_id = Id::unique("font_search");
|
||||
craft_ui::combo::Menu::new(ui, anchor)
|
||||
.height(MENU_HEIGHT)
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||||
@@ -96,9 +97,8 @@ pub(crate) fn font_picker(
|
||||
i.count_and_consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown) as i64
|
||||
- i.count_and_consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp) as i64
|
||||
});
|
||||
let search =
|
||||
ui.add(egui::TextEdit::singleline(&mut q).hint_text(tr("Search fonts")).desired_width(ui.available_width()).font(regular(11.5)));
|
||||
crate::widgets::select_all_on_focus(ui, &search, &q);
|
||||
let (field, _) = ui.allocate_exact_size(vec2(ui.available_width(), widgets::FIELD_H), egui::Sense::hover());
|
||||
let search = widgets::search_box(ui, field, search_id, &mut q, tr("Search fonts"));
|
||||
if just_opened {
|
||||
search.request_focus();
|
||||
}
|
||||
|
||||
@@ -94,12 +94,24 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Escape with no draft or thread open turns the comment mode off and keeps the presentation.
|
||||
let cu = &app.ui.comments;
|
||||
if live
|
||||
&& pres.view.comments
|
||||
&& pres.link_notice.is_none()
|
||||
&& cu.open.is_none()
|
||||
&& cu.draft.is_none()
|
||||
&& !cu.mention.active()
|
||||
&& ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
|
||||
{
|
||||
pres.view.comments = false;
|
||||
}
|
||||
if live
|
||||
&& pres.view.comments
|
||||
&& let Some((frame, place, clip)) = pres.shown
|
||||
{
|
||||
crate::comments::presenter(app, &ctx, frame, place, clip);
|
||||
} else if app.ui.comments.open.is_some() {
|
||||
} else if app.ui.comments.open.is_some() || app.ui.comments.draft.is_some() {
|
||||
app.ui.comments.close();
|
||||
}
|
||||
finish(app, &mut pres);
|
||||
|
||||
@@ -34,6 +34,19 @@ fn release_drag_scroll(p: &mut Presenter, l: &Layout, down: bool, velocity: Vec2
|
||||
}
|
||||
}
|
||||
|
||||
/// Without clicks (the comment mode), forget a press in progress and what it began: a drag-scroll and a
|
||||
/// transition following the pointer.
|
||||
fn drop_press(p: &mut Presenter, clicks: bool) {
|
||||
if clicks {
|
||||
return;
|
||||
}
|
||||
p.press = None;
|
||||
p.drag_scroll = None;
|
||||
if let Some(a) = p.anim.as_mut() {
|
||||
a.follow = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Scrolls the first of `targets` the wheel can still move, and smooths the wheel's speed over
|
||||
/// ~50 ms whatever the frame rate.
|
||||
fn wheel_scroll(p: &mut Presenter, l: &Layout, base: &Document, targets: Vec<Scroller>, wheel: Vec2, dt: f64) {
|
||||
@@ -162,13 +175,16 @@ fn fire_pads(p: &mut Presenter, doc: &Document, root: NodeId, pads: &[String], n
|
||||
/// player takes the keyboard; `pane`: it plays in the preview pane (which always fits).
|
||||
pub(super) struct InputMode {
|
||||
pub over_area: bool,
|
||||
/// Presses reach the prototype: false in the presenter's comment mode, where a click places a
|
||||
/// comment (hover and the wheel still work).
|
||||
pub clicks: bool,
|
||||
pub keys_on: bool,
|
||||
pub pane: bool,
|
||||
pub now: f64,
|
||||
}
|
||||
|
||||
pub(super) fn input(p: &mut Presenter, ctx: &egui::Context, l: &Layout, mode: InputMode) {
|
||||
let InputMode { over_area, keys_on, pane, now } = mode;
|
||||
let InputMode { over_area, clicks, keys_on, pane, now } = mode;
|
||||
let (pos, pressed, released, down, wheel, velocity, dt, keys) = ctx.input(|i| {
|
||||
let keys: Vec<(egui::Key, egui::Modifiers)> = i
|
||||
.events
|
||||
@@ -190,6 +206,9 @@ pub(super) fn input(p: &mut Presenter, ctx: &egui::Context, l: &Layout, mode: In
|
||||
)
|
||||
});
|
||||
let keys = if keys_on { keys } else { Vec::new() };
|
||||
let pressed = pressed && clicks;
|
||||
// A press already in progress when the comment mode starts is dropped, so its release is no click.
|
||||
drop_press(p, clicks);
|
||||
// Controller buttons pressed while a link notice shows are dropped, as keys are.
|
||||
let pads = std::mem::take(&mut p.pads);
|
||||
let pads = if p.link_notice.is_none() { pads } else { Vec::new() };
|
||||
|
||||
@@ -60,7 +60,18 @@ pub(super) fn player(p: &mut Presenter, ui: &mut Ui, rect: Rect, now: f64, chrom
|
||||
// The pane only takes the keyboard while the pointer is over it. While a link notice shows
|
||||
// the prototype takes neither keys nor the pointer (Escape there cancels the notice).
|
||||
let keys = chrome.keys && p.link_notice.is_none() && (!chrome.pane || over);
|
||||
input(p, &ctx, &l, InputMode { over_area: over && p.link_notice.is_none(), keys_on: keys, pane: chrome.pane, now });
|
||||
input(
|
||||
p,
|
||||
&ctx,
|
||||
&l,
|
||||
InputMode {
|
||||
over_area: over && p.link_notice.is_none(),
|
||||
clicks: !(p.view.comments && !chrome.pane),
|
||||
keys_on: keys,
|
||||
pane: chrome.pane,
|
||||
now,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
p.pads.clear();
|
||||
}
|
||||
|
||||
@@ -140,3 +140,83 @@ fn a_field_left_mid_edit_selects_all_on_the_next_click() {
|
||||
assert!(ctx.memory(|m| m.has_focus(id.with("te"))));
|
||||
assert_eq!(selection(&ctx, id.with("te")), Some((0, 6)));
|
||||
}
|
||||
|
||||
/// The vertical middle of the first painted text that contains `needle`, from one frame's shapes.
|
||||
fn text_mid_y(shapes: &[egui::epaint::ClippedShape], needle: &str) -> Option<f32> {
|
||||
fn find(s: &egui::Shape, needle: &str) -> Option<f32> {
|
||||
match s {
|
||||
egui::Shape::Text(t) if t.galley.text().contains(needle) => Some(t.pos.y + t.galley.rect.center().y),
|
||||
egui::Shape::Vec(v) => v.iter().find_map(|s| find(s, needle)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
shapes.iter().find_map(|c| find(&c.shape, needle))
|
||||
}
|
||||
|
||||
/// Runs one more quiet frame of `f` and returns its shapes.
|
||||
fn shapes_of(ctx: &egui::Context, f: &mut impl FnMut(&mut Ui)) -> Vec<egui::epaint::ClippedShape> {
|
||||
let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(FIELD));
|
||||
f(&mut child);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
out.shapes
|
||||
}
|
||||
|
||||
/// A rename in a row one line tall (the Layers panel's rows, a frame's name label): the typed text
|
||||
/// sits in the middle of the row, not hanging below it (#2318). The theme's least height for an
|
||||
/// editor is more than that row, which pushed the text down by the difference.
|
||||
#[test]
|
||||
fn a_rename_field_in_a_short_row_centres_its_text() {
|
||||
let ctx = egui::Context::default();
|
||||
let id = Id::unique("short_rename");
|
||||
let row = Rect::from_min_size(pos2(20.0, 20.0), vec2(120.0, 16.0));
|
||||
let mut f = |ui: &mut Ui| {
|
||||
widgets::rename_field(ui, id, "Frame 1", row, egui::FontId::proportional(11.0), false);
|
||||
};
|
||||
click(&ctx, pos2(60.0, 28.0), None, &mut f);
|
||||
assert!(ctx.memory(|m| m.has_focus(id.with("te"))));
|
||||
let mid = text_mid_y(&shapes_of(&ctx, &mut f), "Frame 1").expect("the text is painted");
|
||||
assert!((mid - row.center().y).abs() <= 1.0, "text centre {mid} vs row centre {}", row.center().y);
|
||||
}
|
||||
|
||||
/// The font menu's search box shows its hint (and what is typed) in the middle of the box, not
|
||||
/// along its top edge (#2318).
|
||||
#[test]
|
||||
fn the_font_search_box_centres_its_hint() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut q = String::new();
|
||||
let id = Id::unique("font_search");
|
||||
let mut mid_box = 0.0;
|
||||
let mut f = |ui: &mut Ui| {
|
||||
let (field, _) = ui.allocate_exact_size(vec2(120.0, widgets::FIELD_H), egui::Sense::hover());
|
||||
widgets::search_box(ui, field, id, &mut q, "Search fonts");
|
||||
mid_box = field.center().y;
|
||||
};
|
||||
let shapes = shapes_of(&ctx, &mut f);
|
||||
let mid = text_mid_y(&shapes, "Search fonts").expect("the hint is painted");
|
||||
assert!((mid - mid_box).abs() <= 1.0, "hint centre {mid} vs box centre {mid_box}");
|
||||
}
|
||||
|
||||
/// The font menu's search field is the shared search box: its text starts after the magnifier,
|
||||
/// not at the field's left edge as a bare editor's would (#2318).
|
||||
#[test]
|
||||
fn the_font_search_box_leaves_room_for_the_magnifier() {
|
||||
fn left(s: &egui::Shape) -> Option<f32> {
|
||||
match s {
|
||||
egui::Shape::Text(t) if t.galley.text().contains("Search fonts") => Some(t.pos.x),
|
||||
egui::Shape::Vec(v) => v.iter().find_map(left),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
let mut q = String::new();
|
||||
let id = Id::unique("font_search_icon");
|
||||
let mut f = |ui: &mut Ui| {
|
||||
let (field, _) = ui.allocate_exact_size(vec2(120.0, widgets::FIELD_H), egui::Sense::hover());
|
||||
widgets::search_box(ui, field, id, &mut q, "Search fonts");
|
||||
};
|
||||
let x = shapes_of(&ctx, &mut f).iter().find_map(|c| left(&c.shape)).expect("the hint is painted");
|
||||
assert!(x >= FIELD.min.x + 20.0, "hint starts at {x}, field at {}", FIELD.min.x);
|
||||
}
|
||||
@@ -62,7 +62,7 @@ fn spacing_fields_type_scrub_and_keep_one_undo_step() {
|
||||
u.frame(vec![]);
|
||||
let lead = u.ctx.read_response(field.with("lead")).unwrap().rect.center();
|
||||
drag(&mut u, lead, vec2(16., 0.), true);
|
||||
assert_eq!(xy(&u, ids[1]), (196., 100.));
|
||||
assert_eq!(xy(&u, ids[1]), (188., 100.));
|
||||
assert_eq!(u.app.session.undo_depth().0, history + 1);
|
||||
u.app.run("edit.undo", json!({}));
|
||||
assert_eq!(xy(&u, ids[1]), (180., 100.));
|
||||
|
||||
@@ -42,6 +42,10 @@ pub struct Tokens {
|
||||
pub success: Color32,
|
||||
pub warning: Color32,
|
||||
pub guide: Color32,
|
||||
/// Auto layout padding grips on the canvas.
|
||||
pub padding_grip: Color32,
|
||||
/// Contrasting edge around padding grips, including their dimmed state.
|
||||
pub padding_grip_border: Color32,
|
||||
pub tab_bar: Color32,
|
||||
pub tab_active: Color32,
|
||||
pub shadow: Color32,
|
||||
@@ -133,6 +137,8 @@ impl Tokens {
|
||||
success: DEV_READY,
|
||||
warning: Color32::from_rgb(0xFF, 0xCD, 0x29),
|
||||
guide: Color32::from_rgb(0xF2, 0x48, 0x22),
|
||||
padding_grip: Color32::from_rgb(0xF2, 0x48, 0x8C),
|
||||
padding_grip_border: Color32::WHITE,
|
||||
tab_bar: Color32::from_rgb(0xE8, 0xE8, 0xE8),
|
||||
tab_active: Color32::from_rgb(0xFF, 0xFF, 0xFF),
|
||||
shadow: Color32::from_black_alpha(40),
|
||||
@@ -176,6 +182,8 @@ impl Tokens {
|
||||
success: DEV_READY,
|
||||
warning: Color32::from_rgb(0xFF, 0xCD, 0x29),
|
||||
guide: Color32::from_rgb(0xF2, 0x48, 0x22),
|
||||
padding_grip: Color32::from_rgb(0xF2, 0x48, 0x8C),
|
||||
padding_grip_border: Color32::WHITE,
|
||||
tab_bar: Color32::from_rgb(0x1E, 0x1E, 0x1E),
|
||||
tab_active: Color32::from_rgb(0x2C, 0x2C, 0x2C),
|
||||
shadow: Color32::from_black_alpha(90),
|
||||
|
||||
@@ -84,18 +84,18 @@ fn typography_icon_drag_changes_each_spacing_field_in_one_undo_step() {
|
||||
let mut f = Fields::new();
|
||||
let undo = f.app.session.undo_depth().0;
|
||||
f.drag(key, 16.0, Modifiers::NONE);
|
||||
assert_eq!(f.value(key), before + 16.0, "{key}: dragging the icon must change the value");
|
||||
assert_eq!(f.value(key), before + 8.0, "{key}: dragging the icon must change the value");
|
||||
assert_eq!(f.app.session.undo_depth().0, undo + 1, "{key}: one gesture, one undo step");
|
||||
f.app.session.undo().unwrap();
|
||||
assert_eq!(f.value(key), before);
|
||||
f.app.session.redo().unwrap();
|
||||
assert_eq!(f.value(key), before + 16.0);
|
||||
assert_eq!(f.value(key), before + 8.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typography_icon_scrub_uses_shift_and_alt_rates_and_the_resize_cursor() {
|
||||
for (modifiers, delta) in [(Modifiers::SHIFT, 160.0), (Modifiers::ALT, 1.6)] {
|
||||
for (modifiers, delta) in [(Modifiers::SHIFT, 80.0), (Modifiers::ALT, 0.8)] {
|
||||
for (key, start) in [("ty_lh", 24.0), ("ty_ls", 0.0), ("ty_ps", 12.0)] {
|
||||
let mut f = Fields::new();
|
||||
let p = f.lead(key);
|
||||
@@ -114,10 +114,10 @@ fn typography_icon_scrub_preserves_units_and_clamps_only_nonnegative_fields() {
|
||||
f.drag("ty_lh", 16.0, Modifiers::NONE);
|
||||
f.drag("ty_ls", -16.0, Modifiers::NONE);
|
||||
let t = f.app.session.doc().unwrap().node(f.text).unwrap().kind.text().unwrap();
|
||||
assert_eq!(t.style.line_height, LineHeight::Percent(166.0));
|
||||
assert_eq!(t.style.letter_spacing, LetterSpacing::Pixels(-14.0));
|
||||
f.drag("ty_lh", -200.0, Modifiers::NONE);
|
||||
f.drag("ty_ps", -200.0, Modifiers::NONE);
|
||||
assert_eq!(t.style.line_height, LineHeight::Percent(158.0));
|
||||
assert_eq!(t.style.letter_spacing, LetterSpacing::Pixels(-6.0));
|
||||
f.drag("ty_lh", -320.0, Modifiers::NONE);
|
||||
f.drag("ty_ps", -320.0, Modifiers::NONE);
|
||||
assert_eq!(f.value("ty_lh"), 0.0);
|
||||
assert_eq!(f.value("ty_ps"), 0.0);
|
||||
assert!(f.app.ui.last_error.is_none(), "{:?}", f.app.ui.last_error);
|
||||
@@ -152,7 +152,7 @@ fn typography_icon_scrub_changes_only_the_selected_characters_without_ending_tex
|
||||
f.drag("ty_ls", 16.0, Modifiers::NONE);
|
||||
let t = f.app.session.doc().unwrap().node(f.text).unwrap().kind.text().unwrap();
|
||||
assert_eq!(t.style_at(0).letter_spacing, LetterSpacing::Pixels(0.0));
|
||||
assert_eq!(t.style_at(1).letter_spacing, LetterSpacing::Pixels(16.0));
|
||||
assert_eq!(t.style_at(1).letter_spacing, LetterSpacing::Pixels(8.0));
|
||||
assert_eq!(t.style_at(4).letter_spacing, LetterSpacing::Pixels(0.0));
|
||||
assert!(f.app.session.ds().unwrap().text_edit.is_some());
|
||||
assert_eq!(f.app.session.undo_depth().0, undo);
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! The Local variables window resizes from its edges and corners, height as well as width, stops at
|
||||
//! a minimum size, and keeps its size when it is closed and opened again (#2354).
|
||||
|
||||
use egui::{Event, Id, Pos2, Rect, vec2};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
use crate::live_tests::{flat, texts};
|
||||
|
||||
const COUNT: usize = 60;
|
||||
|
||||
/// The window open on a collection of many number variables.
|
||||
fn window() -> Ui {
|
||||
let mut s = Session::new();
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
|
||||
for k in 0..COUNT {
|
||||
s.execute("variable.create", &json!({"collection": "Theme", "name": format!("v{k:02}"), "type": "number", "value": 1})).unwrap();
|
||||
}
|
||||
let mut u = Ui::new(s);
|
||||
u.app.ui.variables = Some(Default::default());
|
||||
for _ in 0..10 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
u
|
||||
}
|
||||
|
||||
fn rect(u: &Ui) -> Rect {
|
||||
u.ctx.memory(|m| m.area_rect(Id::unique("variables_window"))).expect("the variables window has an area")
|
||||
}
|
||||
|
||||
/// How many variable rows are drawn inside the window (the table clips the rest).
|
||||
fn rows(u: &mut Ui) -> usize {
|
||||
let window = rect(u);
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
texts(&shapes).iter().filter(|(t, p, _)| t.len() == 3 && t.starts_with('v') && window.contains(*p)).count()
|
||||
}
|
||||
|
||||
/// Drag the bottom-right corner by `by` and let go.
|
||||
fn drag_corner(u: &mut Ui, by: egui::Vec2) {
|
||||
let from = rect(u).right_bottom();
|
||||
u.drag_to(from, from + by);
|
||||
let to: Pos2 = from + by;
|
||||
u.frame(vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }]);
|
||||
for _ in 0..5 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_variables_window_grows_when_dragged_taller() {
|
||||
let mut u = window();
|
||||
let before = rect(&u);
|
||||
let rows_before = rows(&mut u);
|
||||
drag_corner(&mut u, vec2(0.0, 200.0));
|
||||
let after = rect(&u);
|
||||
assert!((after.height() - before.height() - 200.0).abs() < 2.0, "height {} -> {}", before.height(), after.height());
|
||||
assert!((after.min.y - before.min.y).abs() < 2.0, "the top edge stays where it was: {} -> {}", before.min.y, after.min.y);
|
||||
let rows_after = rows(&mut u);
|
||||
assert!(rows_after > rows_before, "the table shows more rows: {rows_before} -> {rows_after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_a_narrow_screen_the_variables_window_fits_inside_it() {
|
||||
// Narrower than the minimum (600): the window takes the screen less its margin instead.
|
||||
let mut s = Session::new();
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.screen = vec2(550.0, 700.0);
|
||||
u.app.ui.variables = Some(Default::default());
|
||||
for _ in 0..10 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let r = rect(&u);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, u.screen);
|
||||
assert!(screen.contains_rect(r), "the window {r:?} is inside the screen {screen:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_a_short_screen_the_variables_window_fits_inside_it() {
|
||||
// Lower than the minimum (240): the body takes what is left below the header and scrolls.
|
||||
let mut s = Session::new();
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
|
||||
for k in 0..COUNT {
|
||||
s.execute("variable.create", &json!({"collection": "Theme", "name": format!("v{k:02}"), "type": "number", "value": 1})).unwrap();
|
||||
}
|
||||
let mut u = Ui::new(s);
|
||||
u.screen = vec2(800.0, 180.0);
|
||||
u.app.ui.variables = Some(Default::default());
|
||||
for _ in 0..10 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let r = rect(&u);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, u.screen);
|
||||
assert!(screen.contains_rect(r), "the window {r:?} is inside the screen {screen:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_variables_window_keeps_a_minimum_size() {
|
||||
let mut u = window();
|
||||
drag_corner(&mut u, vec2(-2000.0, -2000.0));
|
||||
let r = rect(&u);
|
||||
assert!((r.width() - 600.0).abs() < 3.0, "width {}", r.width());
|
||||
assert!((r.height() - 240.0).abs() < 3.0, "height {}", r.height());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resized_variables_window_keeps_its_size_when_reopened() {
|
||||
let mut u = window();
|
||||
drag_corner(&mut u, vec2(0.0, 150.0));
|
||||
let resized = rect(&u);
|
||||
let close = resized.right_top() + vec2(-22.0, 22.0);
|
||||
u.button(close, true);
|
||||
u.button(close, false);
|
||||
for _ in 0..5 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(u.app.ui.variables.is_none(), "the Close button closed the window");
|
||||
u.app.ui.variables = Some(Default::default());
|
||||
for _ in 0..10 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let again = rect(&u);
|
||||
assert!((again.width() - resized.width()).abs() < 1.0 && (again.height() - resized.height()).abs() < 1.0, "{resized:?} -> {again:?}");
|
||||
}
|
||||
@@ -114,10 +114,15 @@ fn key_steps(ctx: &egui::Context, suffix: &str, step: f64) -> (f64, f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a scrub of `dx` points moves a value whose field steps by `step`: 1 step a point, ten
|
||||
/// with Shift, a tenth with Alt (fine).
|
||||
/// The steps a point of scrubbing moves a field by: half, as measured in Figma (12.2 px moved X
|
||||
/// by 6, 61.2 px by 31).
|
||||
pub const SCRUB_STEPS_PER_POINT: f64 = 0.5;
|
||||
|
||||
/// How far a scrub of `dx` points moves a value whose field steps by `step`: half a step a point
|
||||
/// ([`SCRUB_STEPS_PER_POINT`]), ten times that with Shift (5 steps a point), a tenth of that with Alt (0.05 steps a point, fine).
|
||||
pub fn scrub_amount(dx: f64, step: f64, shift: bool, alt: bool) -> f64 {
|
||||
dx * step
|
||||
* SCRUB_STEPS_PER_POINT
|
||||
* match (shift, alt) {
|
||||
(true, false) => 10.0,
|
||||
(false, true) => 0.1,
|
||||
@@ -1381,7 +1386,10 @@ pub fn text_field_inline(ui: &mut Ui, id: Id, value: &str, rect: Rect, font: egu
|
||||
Some(mut text) => {
|
||||
ui.painter().rect_filled(rect.expand(2.0), CornerRadius::same(4), t.panel);
|
||||
ui.painter().rect_stroke(rect.expand(2.0), CornerRadius::same(4), Stroke::new(1.0, crate::theme::ACCENT), StrokeKind::Inside);
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect));
|
||||
// The editor is at least the theme's field height; centred on a shorter row it
|
||||
// keeps its text on the row's middle line instead of hanging below it (#2318).
|
||||
let edit = Rect::from_center_size(rect.center(), vec2(rect.width(), rect.height().max(FIELD_H)));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(edit));
|
||||
let r = crate::bidi::single_line(&mut child, te_id, &mut text, font, rect.width());
|
||||
a11y::own_focus(&r);
|
||||
keep_focus(&r, started);
|
||||
|
||||
@@ -70,10 +70,10 @@ fn a_scrubbed_field_keeps_its_value_when_the_pointer_lets_go() {
|
||||
for k in 1..=10 {
|
||||
u.frame(vec![Event::PointerMoved(from + vec2(4.0 * k as f32, 0.0))]);
|
||||
}
|
||||
assert_eq!(width(&u, a).0, 80.0, "40 points to the right while dragging");
|
||||
assert_eq!(width(&u, a).0, 60.0, "40 points to the right while dragging: half a step a point");
|
||||
u.button(from + vec2(40.0, 0.0), false);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(width(&u, a).0, 80.0, "kept after the release");
|
||||
assert_eq!(width(&u, a).0, 60.0, "kept after the release");
|
||||
assert_eq!(u.app.session.doc().unwrap().node(a).unwrap().height, 30.0);
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ pub fn try_export(doc: &Document, ids: &[NodeId], opts: &VdOptions) -> Result<Vd
|
||||
let first = ids.first().and_then(|i| doc.node(*i)).map(|n| n.name.clone()).unwrap_or_default();
|
||||
walker.nothing_drawn(&first);
|
||||
}
|
||||
let xml = xml::document(w, h, &items);
|
||||
let xml = xml::document(w, h, items);
|
||||
Ok(VdExport { xml, warnings: walker.finish() })
|
||||
}
|
||||
|
||||
|
||||
+123
-198
@@ -1,211 +1,136 @@
|
||||
//! The pretty-printed XML: elements two spaces deeper per level, one attribute per line four
|
||||
//! spaces past its element (as Android Studio formats drawables). Numbers are compact (at most
|
||||
//! three decimals, no `-0`) and always finite; text is escaped for attribute values.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
//! Maps FigCraft's projected drawable into the shared XML writer.
|
||||
//! Geometry, colour policy and compatibility decisions remain in the application.
|
||||
|
||||
use crate::model::{Fill, GradKind, Item, ItemKind};
|
||||
use craft_vectordrawable::model as wire;
|
||||
use figcraft_color::Color;
|
||||
|
||||
use crate::model::{Fill, GradKind, GroupItem, Item, ItemKind, NativeStroke, PathItem};
|
||||
|
||||
const ANDROID: &str = "http://schemas.android.com/apk/res/android";
|
||||
const AAPT: &str = "http://schemas.android.com/aapt";
|
||||
|
||||
// Shared wire primitives; app-specific drawable projection and colour policy stay here.
|
||||
#[cfg(test)]
|
||||
pub(crate) use craft_vectordrawable::write::{esc, num, path_data};
|
||||
|
||||
/// `#RRGGBB`, or `#AARRGGBB` when not opaque.
|
||||
pub(crate) fn color(c: Color) -> String {
|
||||
let [r, g, b, a] = c.sanitized().to_rgba8();
|
||||
if a == 255 { format!("#{r:02X}{g:02X}{b:02X}") } else { format!("#{a:02X}{r:02X}{g:02X}{b:02X}") }
|
||||
}
|
||||
// One document level can add a frame clip, a mask clip and a named group, plus the leaf gradient's
|
||||
// transform group. Keep every layer admitted by check_export_depth, not just 256 XML groups.
|
||||
const XML_DEPTH: usize = 3 * (figcraft_render::MAX_EXPORT_DEPTH + 1) + 2;
|
||||
const _: () = assert!(XML_DEPTH <= craft_vectordrawable::write::MAX_CONFIGURED_DEPTH);
|
||||
|
||||
struct Out {
|
||||
s: String,
|
||||
}
|
||||
|
||||
impl Out {
|
||||
/// `<tag` and its attributes, one per line; `close` ends it with `/>`, else `>`.
|
||||
fn open(&mut self, depth: usize, tag: &str, attrs: &[(&str, String)], close: bool) {
|
||||
let pad = " ".repeat(depth);
|
||||
let _ = write!(self.s, "{pad}<{tag}");
|
||||
for (i, (k, v)) in attrs.iter().enumerate() {
|
||||
if i == 0 && attrs.len() == 1 {
|
||||
let _ = write!(self.s, " {k}=\"{v}\"");
|
||||
} else {
|
||||
let _ = write!(self.s, "\n{pad} {k}=\"{v}\"");
|
||||
}
|
||||
}
|
||||
self.s.push_str(if close { " />\n" } else { ">\n" });
|
||||
}
|
||||
|
||||
fn close(&mut self, depth: usize, tag: &str) {
|
||||
let _ = writeln!(self.s, "{}</{tag}>", " ".repeat(depth));
|
||||
}
|
||||
}
|
||||
|
||||
fn uses_gradient(items: &[Item]) -> bool {
|
||||
items.iter().any(|it| match &it.kind {
|
||||
ItemKind::Path(p) => matches!(p.fill, Some(Fill::Gradient(_))),
|
||||
ItemKind::Group(g) => uses_gradient(&g.children),
|
||||
})
|
||||
}
|
||||
|
||||
/// The whole file: a `width`×`height` dp drawable with a viewport of the same size.
|
||||
pub(crate) fn document(width: f64, height: f64, items: &[Item]) -> String {
|
||||
let mut o = Out { s: String::from("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") };
|
||||
let mut attrs = vec![("xmlns:android", ANDROID.to_string())];
|
||||
if uses_gradient(items) {
|
||||
attrs.push(("xmlns:aapt", AAPT.to_string()));
|
||||
}
|
||||
attrs.extend([
|
||||
("android:width", format!("{}dp", num(width))),
|
||||
("android:height", format!("{}dp", num(height))),
|
||||
("android:viewportWidth", num(width)),
|
||||
("android:viewportHeight", num(height)),
|
||||
]);
|
||||
o.open(0, "vector", &attrs, false);
|
||||
if items.is_empty() {
|
||||
// Android refuses a <vector> without a <path> ("no path defined"): one empty, unfilled path.
|
||||
o.open(1, "path", &[("android:pathData", "M0,0".to_string())], true);
|
||||
}
|
||||
for it in items {
|
||||
item(&mut o, 1, it);
|
||||
}
|
||||
o.close(0, "vector");
|
||||
o.s
|
||||
}
|
||||
|
||||
fn item(o: &mut Out, depth: usize, it: &Item) {
|
||||
match &it.kind {
|
||||
ItemKind::Path(p) => path(o, depth, p),
|
||||
ItemKind::Group(g) => group(o, depth, g),
|
||||
}
|
||||
}
|
||||
|
||||
fn group(o: &mut Out, depth: usize, g: &GroupItem) {
|
||||
let mut attrs = Vec::new();
|
||||
if let Some(n) = &g.name {
|
||||
attrs.push(("android:name", esc(n)));
|
||||
}
|
||||
if let Some(x) = &g.xf {
|
||||
let (sx, sy) = x.scale;
|
||||
if num(x.rotation) != "0" {
|
||||
attrs.push(("android:rotation", num(x.rotation)));
|
||||
}
|
||||
if num(sx) != "1" {
|
||||
attrs.push(("android:scaleX", num(sx)));
|
||||
}
|
||||
if num(sy) != "1" {
|
||||
attrs.push(("android:scaleY", num(sy)));
|
||||
}
|
||||
if num(x.translate.0) != "0" {
|
||||
attrs.push(("android:translateX", num(x.translate.0)));
|
||||
}
|
||||
if num(x.translate.1) != "0" {
|
||||
attrs.push(("android:translateY", num(x.translate.1)));
|
||||
}
|
||||
}
|
||||
if g.children.is_empty() && g.clip.is_none() {
|
||||
o.open(depth, "group", &attrs, true);
|
||||
return;
|
||||
}
|
||||
o.open(depth, "group", &attrs, false);
|
||||
if let Some(c) = &g.clip {
|
||||
o.open(depth + 1, "clip-path", &[("android:pathData", path_data(c))], true);
|
||||
}
|
||||
for c in &g.children {
|
||||
item(o, depth + 1, c);
|
||||
}
|
||||
o.close(depth, "group");
|
||||
}
|
||||
|
||||
fn stroke_attrs(attrs: &mut Vec<(&str, String)>, s: &NativeStroke) {
|
||||
attrs.push(("android:strokeColor", color(s.color)));
|
||||
attrs.push(("android:strokeWidth", num(s.width)));
|
||||
if s.cap != "butt" {
|
||||
attrs.push(("android:strokeLineCap", s.cap.to_string()));
|
||||
}
|
||||
if s.join != "miter" {
|
||||
attrs.push(("android:strokeLineJoin", s.join.to_string()));
|
||||
} else if num(s.miter) != "4" {
|
||||
attrs.push(("android:strokeMiterLimit", num(s.miter)));
|
||||
}
|
||||
}
|
||||
|
||||
fn path(o: &mut Out, depth: usize, p: &PathItem) {
|
||||
let mut attrs = Vec::new();
|
||||
if let Some(n) = &p.name {
|
||||
attrs.push(("android:name", esc(n)));
|
||||
}
|
||||
attrs.push(("android:pathData", path_data(&p.data)));
|
||||
if let Some(Fill::Solid(c)) = &p.fill {
|
||||
attrs.push(("android:fillColor", color(*c)));
|
||||
}
|
||||
if let Some(s) = &p.stroke {
|
||||
stroke_attrs(&mut attrs, s);
|
||||
}
|
||||
if p.even_odd && p.fill.is_some() {
|
||||
attrs.push(("android:fillType", "evenOdd".to_string()));
|
||||
}
|
||||
let Some(Fill::Gradient(g)) = &p.fill else {
|
||||
o.open(depth, "path", &attrs, true);
|
||||
return;
|
||||
};
|
||||
o.open(depth, "path", &attrs, false);
|
||||
o.open(depth + 1, "aapt:attr", &[("name", "android:fillColor".to_string())], false);
|
||||
let mut ga = Vec::new();
|
||||
match g.kind {
|
||||
GradKind::Linear { start, end } => {
|
||||
ga.push(("android:type", "linear".to_string()));
|
||||
ga.push(("android:startX", num(start.0)));
|
||||
ga.push(("android:startY", num(start.1)));
|
||||
ga.push(("android:endX", num(end.0)));
|
||||
ga.push(("android:endY", num(end.1)));
|
||||
}
|
||||
GradKind::Radial { center, radius } => {
|
||||
ga.push(("android:type", "radial".to_string()));
|
||||
ga.push(("android:centerX", num(center.0)));
|
||||
ga.push(("android:centerY", num(center.1)));
|
||||
ga.push(("android:gradientRadius", num(radius)));
|
||||
}
|
||||
GradKind::Sweep { center } => {
|
||||
ga.push(("android:type", "sweep".to_string()));
|
||||
ga.push(("android:centerX", num(center.0)));
|
||||
ga.push(("android:centerY", num(center.1)));
|
||||
}
|
||||
}
|
||||
o.open(depth + 2, "gradient", &ga, false);
|
||||
for (off, c) in &g.stops {
|
||||
o.open(depth + 3, "item", &[("android:offset", num(*off)), ("android:color", color(*c))], true);
|
||||
}
|
||||
o.close(depth + 2, "gradient");
|
||||
o.close(depth + 1, "aapt:attr");
|
||||
o.close(depth, "path");
|
||||
fn wire_color(c: Color) -> wire::Color {
|
||||
// FigCraft clamps positive infinity to one (the neutral writer maps non-finite to zero).
|
||||
// Preserve the application's sanitization before passing its finite components onward.
|
||||
let c = c.sanitized();
|
||||
[c.r, c.g, c.b, c.a]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_wire_tests {
|
||||
use super::*;
|
||||
use figcraft_geom::BezPath;
|
||||
pub(crate) fn color(c: Color) -> String {
|
||||
craft_vectordrawable::write::color(wire_color(c))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_attributes_preserve_exact_xml() {
|
||||
assert_eq!(esc("<&>\"'\t\n\r\0\u{ffff}é𝄞	"), "<&>"'	 é𝄞&#9;");
|
||||
}
|
||||
fn item(it: Item) -> wire::Item {
|
||||
let kind = match it.kind {
|
||||
ItemKind::Path(p) => wire::ItemKind::Path(wire::Path {
|
||||
name: p.name,
|
||||
data: p.data,
|
||||
even_odd: p.even_odd,
|
||||
fill: p.fill.map(|f| match f {
|
||||
Fill::Solid(c) => wire::Fill::Solid(wire_color(c)),
|
||||
Fill::Gradient(g) => wire::Fill::Gradient(wire::Gradient {
|
||||
kind: match g.kind {
|
||||
GradKind::Linear { start, end } => wire::GradientKind::Linear { start, end },
|
||||
GradKind::Radial { center, radius } => wire::GradientKind::Radial { center, radius },
|
||||
GradKind::Sweep { center } => wire::GradientKind::Sweep { center },
|
||||
},
|
||||
stops: g.stops.into_iter().map(|(offset, c)| (offset, wire_color(c))).collect(),
|
||||
}),
|
||||
}),
|
||||
stroke: p.stroke.map(|s| wire::Stroke {
|
||||
color: wire_color(s.color),
|
||||
width: s.width,
|
||||
miter: s.miter,
|
||||
cap: match s.cap {
|
||||
"round" => wire::Cap::Round,
|
||||
"square" => wire::Cap::Square,
|
||||
_ => wire::Cap::Butt,
|
||||
},
|
||||
join: match s.join {
|
||||
"round" => wire::Join::Round,
|
||||
"bevel" => wire::Join::Bevel,
|
||||
_ => wire::Join::Miter,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ItemKind::Group(g) => wire::ItemKind::Group(wire::Group {
|
||||
name: g.name,
|
||||
clip: g.clip,
|
||||
transform: g.xf.map(|x| wire::GroupTransform { translate: x.translate, rotation: x.rotation, scale: x.scale }),
|
||||
children: Vec::new(),
|
||||
}),
|
||||
};
|
||||
wire::Item { kind, bbox: it.bbox }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_numbers_and_paths_preserve_android_syntax() {
|
||||
assert_eq!(num(-0.0001), "0");
|
||||
assert_eq!(num(f64::NAN), "0");
|
||||
assert_eq!(num(f64::INFINITY), "0");
|
||||
assert_eq!(num(1.23456), "1.235");
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, -0.0));
|
||||
p.line_to((1.23456, 2.0));
|
||||
p.quad_to((3.0, 4.0), (5.0, 6.0));
|
||||
p.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0));
|
||||
p.close_path();
|
||||
assert_eq!(path_data(&p), "M0,0 L1.235,2 Q3,4 5,6 C7,8 9,10 11,12 Z");
|
||||
// Explicit iterator frames keep traversal scratch proportional to depth, not sibling count.
|
||||
fn items(input: Vec<Item>) -> Vec<wire::Item> {
|
||||
let mut parents = Vec::new();
|
||||
let mut current = (input.into_iter(), Vec::new());
|
||||
loop {
|
||||
let depth = parents.len() + 1;
|
||||
if let Some(mut source) = current.0.next() {
|
||||
let children = match &mut source.kind {
|
||||
ItemKind::Group(g) => std::mem::take(&mut g.children),
|
||||
ItemKind::Path(_) => Vec::new(),
|
||||
};
|
||||
let mapped = item(source);
|
||||
if !children.is_empty() && depth < XML_DEPTH {
|
||||
let previous = std::mem::replace(&mut current, (children.into_iter(), Vec::new()));
|
||||
parents.push((previous, mapped));
|
||||
} else {
|
||||
discard_items(children);
|
||||
current.1.push(mapped);
|
||||
}
|
||||
} else {
|
||||
let Some((mut previous, mut parent)) = parents.pop() else { return current.1 };
|
||||
if let wire::ItemKind::Group(g) = &mut parent.kind {
|
||||
g.children = current.1;
|
||||
}
|
||||
previous.1.push(parent);
|
||||
current = previous;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn discard_items(items: Vec<Item>) {
|
||||
let mut frames = vec![items.into_iter()];
|
||||
while let Some(frame) = frames.last_mut() {
|
||||
if let Some(mut item) = frame.next() {
|
||||
if let ItemKind::Group(g) = &mut item.kind {
|
||||
frames.push(std::mem::take(&mut g.children).into_iter());
|
||||
}
|
||||
} else {
|
||||
frames.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn document(width: f64, height: f64, input: Vec<Item>) -> String {
|
||||
let items = items(input);
|
||||
let output = craft_vectordrawable::write::document_with_depth_limit(width, height, &items, XML_DEPTH);
|
||||
// Recursive enum destruction also consumes stack, even with an iterative writer.
|
||||
let mut frames = vec![items.into_iter()];
|
||||
while let Some(frame) = frames.last_mut() {
|
||||
if let Some(mut item) = frame.next() {
|
||||
if let wire::ItemKind::Group(g) = &mut item.kind {
|
||||
frames.push(std::mem::take(&mut g.children).into_iter());
|
||||
}
|
||||
} else {
|
||||
frames.pop();
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "xml_legacy_test.rs"]
|
||||
mod legacy;
|
||||
#[cfg(test)]
|
||||
#[path = "xml_parity_tests.rs"]
|
||||
mod parity_tests;
|
||||
@@ -0,0 +1,213 @@
|
||||
// Test-only parity oracle: FigCraft XML writer before shared cutover.
|
||||
// Original writer by Filip Strajnar (8b5441eb), with subsequent contributor fixes.
|
||||
//! The pretty-printed XML: elements two spaces deeper per level, one attribute per line four
|
||||
//! spaces past its element (as Android Studio formats drawables). Numbers are compact (at most
|
||||
//! three decimals, no `-0`) and always finite; text is escaped for attribute values.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use figcraft_color::Color;
|
||||
|
||||
use crate::model::{Fill, GradKind, GroupItem, Item, ItemKind, NativeStroke, PathItem};
|
||||
|
||||
const ANDROID: &str = "http://schemas.android.com/apk/res/android";
|
||||
const AAPT: &str = "http://schemas.android.com/aapt";
|
||||
|
||||
// Shared wire primitives; app-specific drawable projection and colour policy stay here.
|
||||
pub(crate) use craft_vectordrawable::write::{esc, num, path_data};
|
||||
|
||||
/// `#RRGGBB`, or `#AARRGGBB` when not opaque.
|
||||
pub(crate) fn color(c: Color) -> String {
|
||||
let [r, g, b, a] = c.sanitized().to_rgba8();
|
||||
if a == 255 { format!("#{r:02X}{g:02X}{b:02X}") } else { format!("#{a:02X}{r:02X}{g:02X}{b:02X}") }
|
||||
}
|
||||
|
||||
struct Out {
|
||||
s: String,
|
||||
}
|
||||
|
||||
impl Out {
|
||||
/// `<tag` and its attributes, one per line; `close` ends it with `/>`, else `>`.
|
||||
fn open(&mut self, depth: usize, tag: &str, attrs: &[(&str, String)], close: bool) {
|
||||
let pad = " ".repeat(depth);
|
||||
let _ = write!(self.s, "{pad}<{tag}");
|
||||
for (i, (k, v)) in attrs.iter().enumerate() {
|
||||
if i == 0 && attrs.len() == 1 {
|
||||
let _ = write!(self.s, " {k}=\"{v}\"");
|
||||
} else {
|
||||
let _ = write!(self.s, "\n{pad} {k}=\"{v}\"");
|
||||
}
|
||||
}
|
||||
self.s.push_str(if close { " />\n" } else { ">\n" });
|
||||
}
|
||||
|
||||
fn close(&mut self, depth: usize, tag: &str) {
|
||||
let _ = writeln!(self.s, "{}</{tag}>", " ".repeat(depth));
|
||||
}
|
||||
}
|
||||
|
||||
fn uses_gradient(items: &[Item]) -> bool {
|
||||
items.iter().any(|it| match &it.kind {
|
||||
ItemKind::Path(p) => matches!(p.fill, Some(Fill::Gradient(_))),
|
||||
ItemKind::Group(g) => uses_gradient(&g.children),
|
||||
})
|
||||
}
|
||||
|
||||
/// The whole file: a `width`×`height` dp drawable with a viewport of the same size.
|
||||
pub(crate) fn document(width: f64, height: f64, items: &[Item]) -> String {
|
||||
let mut o = Out { s: String::from("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") };
|
||||
let mut attrs = vec![("xmlns:android", ANDROID.to_string())];
|
||||
if uses_gradient(items) {
|
||||
attrs.push(("xmlns:aapt", AAPT.to_string()));
|
||||
}
|
||||
attrs.extend([
|
||||
("android:width", format!("{}dp", num(width))),
|
||||
("android:height", format!("{}dp", num(height))),
|
||||
("android:viewportWidth", num(width)),
|
||||
("android:viewportHeight", num(height)),
|
||||
]);
|
||||
o.open(0, "vector", &attrs, false);
|
||||
if items.is_empty() {
|
||||
// Android refuses a <vector> without a <path> ("no path defined"): one empty, unfilled path.
|
||||
o.open(1, "path", &[("android:pathData", "M0,0".to_string())], true);
|
||||
}
|
||||
for it in items {
|
||||
item(&mut o, 1, it);
|
||||
}
|
||||
o.close(0, "vector");
|
||||
o.s
|
||||
}
|
||||
|
||||
fn item(o: &mut Out, depth: usize, it: &Item) {
|
||||
match &it.kind {
|
||||
ItemKind::Path(p) => path(o, depth, p),
|
||||
ItemKind::Group(g) => group(o, depth, g),
|
||||
}
|
||||
}
|
||||
|
||||
fn group(o: &mut Out, depth: usize, g: &GroupItem) {
|
||||
let mut attrs = Vec::new();
|
||||
if let Some(n) = &g.name {
|
||||
attrs.push(("android:name", esc(n)));
|
||||
}
|
||||
if let Some(x) = &g.xf {
|
||||
let (sx, sy) = x.scale;
|
||||
if num(x.rotation) != "0" {
|
||||
attrs.push(("android:rotation", num(x.rotation)));
|
||||
}
|
||||
if num(sx) != "1" {
|
||||
attrs.push(("android:scaleX", num(sx)));
|
||||
}
|
||||
if num(sy) != "1" {
|
||||
attrs.push(("android:scaleY", num(sy)));
|
||||
}
|
||||
if num(x.translate.0) != "0" {
|
||||
attrs.push(("android:translateX", num(x.translate.0)));
|
||||
}
|
||||
if num(x.translate.1) != "0" {
|
||||
attrs.push(("android:translateY", num(x.translate.1)));
|
||||
}
|
||||
}
|
||||
if g.children.is_empty() && g.clip.is_none() {
|
||||
o.open(depth, "group", &attrs, true);
|
||||
return;
|
||||
}
|
||||
o.open(depth, "group", &attrs, false);
|
||||
if let Some(c) = &g.clip {
|
||||
o.open(depth + 1, "clip-path", &[("android:pathData", path_data(c))], true);
|
||||
}
|
||||
for c in &g.children {
|
||||
item(o, depth + 1, c);
|
||||
}
|
||||
o.close(depth, "group");
|
||||
}
|
||||
|
||||
fn stroke_attrs(attrs: &mut Vec<(&str, String)>, s: &NativeStroke) {
|
||||
attrs.push(("android:strokeColor", color(s.color)));
|
||||
attrs.push(("android:strokeWidth", num(s.width)));
|
||||
if s.cap != "butt" {
|
||||
attrs.push(("android:strokeLineCap", s.cap.to_string()));
|
||||
}
|
||||
if s.join != "miter" {
|
||||
attrs.push(("android:strokeLineJoin", s.join.to_string()));
|
||||
} else if num(s.miter) != "4" {
|
||||
attrs.push(("android:strokeMiterLimit", num(s.miter)));
|
||||
}
|
||||
}
|
||||
|
||||
fn path(o: &mut Out, depth: usize, p: &PathItem) {
|
||||
let mut attrs = Vec::new();
|
||||
if let Some(n) = &p.name {
|
||||
attrs.push(("android:name", esc(n)));
|
||||
}
|
||||
attrs.push(("android:pathData", path_data(&p.data)));
|
||||
if let Some(Fill::Solid(c)) = &p.fill {
|
||||
attrs.push(("android:fillColor", color(*c)));
|
||||
}
|
||||
if let Some(s) = &p.stroke {
|
||||
stroke_attrs(&mut attrs, s);
|
||||
}
|
||||
if p.even_odd && p.fill.is_some() {
|
||||
attrs.push(("android:fillType", "evenOdd".to_string()));
|
||||
}
|
||||
let Some(Fill::Gradient(g)) = &p.fill else {
|
||||
o.open(depth, "path", &attrs, true);
|
||||
return;
|
||||
};
|
||||
o.open(depth, "path", &attrs, false);
|
||||
o.open(depth + 1, "aapt:attr", &[("name", "android:fillColor".to_string())], false);
|
||||
let mut ga = Vec::new();
|
||||
match g.kind {
|
||||
GradKind::Linear { start, end } => {
|
||||
ga.push(("android:type", "linear".to_string()));
|
||||
ga.push(("android:startX", num(start.0)));
|
||||
ga.push(("android:startY", num(start.1)));
|
||||
ga.push(("android:endX", num(end.0)));
|
||||
ga.push(("android:endY", num(end.1)));
|
||||
}
|
||||
GradKind::Radial { center, radius } => {
|
||||
ga.push(("android:type", "radial".to_string()));
|
||||
ga.push(("android:centerX", num(center.0)));
|
||||
ga.push(("android:centerY", num(center.1)));
|
||||
ga.push(("android:gradientRadius", num(radius)));
|
||||
}
|
||||
GradKind::Sweep { center } => {
|
||||
ga.push(("android:type", "sweep".to_string()));
|
||||
ga.push(("android:centerX", num(center.0)));
|
||||
ga.push(("android:centerY", num(center.1)));
|
||||
}
|
||||
}
|
||||
o.open(depth + 2, "gradient", &ga, false);
|
||||
for (off, c) in &g.stops {
|
||||
o.open(depth + 3, "item", &[("android:offset", num(*off)), ("android:color", color(*c))], true);
|
||||
}
|
||||
o.close(depth + 2, "gradient");
|
||||
o.close(depth + 1, "aapt:attr");
|
||||
o.close(depth, "path");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_wire_tests {
|
||||
use super::*;
|
||||
use figcraft_geom::BezPath;
|
||||
|
||||
#[test]
|
||||
fn shared_attributes_preserve_exact_xml() {
|
||||
assert_eq!(esc("<&>\"'\t\n\r\0\u{ffff}é𝄞	"), "<&>"'	 é𝄞&#9;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_numbers_and_paths_preserve_android_syntax() {
|
||||
assert_eq!(num(-0.0001), "0");
|
||||
assert_eq!(num(f64::NAN), "0");
|
||||
assert_eq!(num(f64::INFINITY), "0");
|
||||
assert_eq!(num(1.23456), "1.235");
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, -0.0));
|
||||
p.line_to((1.23456, 2.0));
|
||||
p.quad_to((3.0, 4.0), (5.0, 6.0));
|
||||
p.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0));
|
||||
p.close_path();
|
||||
assert_eq!(path_data(&p), "M0,0 L1.235,2 Q3,4 5,6 C7,8 9,10 11,12 Z");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
use super::*;
|
||||
use crate::model::{Grad, GroupItem, GroupXf, NativeStroke, PathItem};
|
||||
use figcraft_geom::{BezPath, Rect};
|
||||
|
||||
fn path(fill: Option<Fill>, cap: &'static str, join: &'static str, c: Color) -> Item {
|
||||
let mut data = BezPath::new();
|
||||
data.move_to((0.0, -0.0));
|
||||
data.line_to((1.23456, 2.0));
|
||||
data.quad_to((3.0, 4.0), (5.0, 6.0));
|
||||
data.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0));
|
||||
data.close_path();
|
||||
Item {
|
||||
bbox: Rect::ZERO,
|
||||
kind: ItemKind::Path(PathItem {
|
||||
name: Some("<&>\"'\t\n\r\0\u{ffff}é𝄞	".into()),
|
||||
data,
|
||||
fill,
|
||||
stroke: Some(NativeStroke { color: c, width: 2.34567, cap, join, miter: 3.0 }),
|
||||
even_odd: true,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parity(w: f64, h: f64, items: &[Item]) {
|
||||
let actual = document(w, h, items.to_vec());
|
||||
assert_eq!(actual, legacy::document(w, h, items));
|
||||
let parsed = roxmltree::Document::parse(&actual).unwrap();
|
||||
assert_eq!(parsed.root_element().tag_name().name(), "vector");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_documents_preserve_exact_bytes_and_app_colour_policy() {
|
||||
parity(0.0, f64::INFINITY, &[]);
|
||||
let colours = [
|
||||
Color::BLACK,
|
||||
Color::from_rgba8(26, 43, 60, 128),
|
||||
Color { r: f32::INFINITY, g: f32::NEG_INFINITY, b: f32::NAN, a: f32::INFINITY },
|
||||
Color { r: 0.49999, g: 0.50001, b: 2.0, a: -1.0 },
|
||||
];
|
||||
for c in colours {
|
||||
let fills = [
|
||||
None,
|
||||
Some(Fill::Solid(c)),
|
||||
Some(Fill::Gradient(Grad { kind: GradKind::Linear { start: (0.0, 1.0), end: (3.0, 4.0) }, stops: vec![(0.0, c), (1.0, Color::WHITE)] })),
|
||||
Some(Fill::Gradient(Grad { kind: GradKind::Radial { center: (5.0, 6.0), radius: 7.0 }, stops: vec![(f64::NAN, c)] })),
|
||||
Some(Fill::Gradient(Grad { kind: GradKind::Sweep { center: (8.0, 9.0) }, stops: vec![] })),
|
||||
];
|
||||
for fill in fills {
|
||||
for cap in ["butt", "round", "square"] {
|
||||
for join in ["miter", "round", "bevel"] {
|
||||
let leaf = path(fill.clone(), cap, join, c);
|
||||
parity(24.12345, 18.0, std::slice::from_ref(&leaf));
|
||||
let group = Item {
|
||||
bbox: Rect::ZERO,
|
||||
kind: ItemKind::Group(GroupItem {
|
||||
name: Some("group&\"".into()),
|
||||
xf: Some(GroupXf { translate: (2.0, -3.0), rotation: 45.0, scale: (1.0, 2.0) }),
|
||||
clip: Some(BezPath::new()),
|
||||
children: vec![leaf],
|
||||
}),
|
||||
};
|
||||
parity(24.0, 18.0, &[group]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_depth_wrappers_do_not_lose_the_deepest_accepted_leaf() {
|
||||
let mut leaf = path(Some(Fill::Gradient(Grad { kind: GradKind::Sweep { center: (0.0, 0.0) }, stops: vec![] })), "butt", "miter", Color::BLACK);
|
||||
for _ in 0..XML_DEPTH - 2 {
|
||||
leaf = Item { bbox: Rect::ZERO, kind: ItemKind::Group(GroupItem { name: None, xf: None, clip: None, children: vec![leaf] }) };
|
||||
}
|
||||
let items = [leaf];
|
||||
let xml = document(1.0, 1.0, items.to_vec());
|
||||
assert_eq!(xml, legacy::document(1.0, 1.0, &items));
|
||||
assert!(xml.contains("aapt") && xml.contains("<path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_groups_and_default_attributes_match() {
|
||||
for clip in [None, Some(BezPath::new())] {
|
||||
let group = Item {
|
||||
bbox: Rect::ZERO,
|
||||
kind: ItemKind::Group(GroupItem {
|
||||
name: None,
|
||||
xf: Some(GroupXf { translate: (0.0, -0.0), rotation: -0.0001, scale: (1.0, 1.0) }),
|
||||
clip,
|
||||
children: vec![],
|
||||
}),
|
||||
};
|
||||
parity(12.0, 12.0, &[group]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_depth_fits_the_browser_sized_stack() {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(1024 * 1024)
|
||||
.spawn(|| {
|
||||
let mut leaf = path(Some(Fill::Solid(Color::BLACK)), "butt", "miter", Color::BLACK);
|
||||
for _ in 0..XML_DEPTH - 2 {
|
||||
leaf = Item { bbox: Rect::ZERO, kind: ItemKind::Group(GroupItem { name: None, xf: None, clip: None, children: vec![leaf] }) };
|
||||
}
|
||||
assert!(document(1.0, 1.0, vec![leaf]).contains("<path"));
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_siblings_nested_empty_and_clipped_groups_keep_closing_order() {
|
||||
let leaf = || path(Some(Fill::Solid(Color::BLACK)), "round", "bevel", Color::WHITE);
|
||||
let group = |name: &str, clip, children| Item {
|
||||
bbox: Rect::ZERO,
|
||||
kind: ItemKind::Group(GroupItem { name: Some(name.into()), xf: None, clip, children }),
|
||||
};
|
||||
let items = vec![
|
||||
leaf(),
|
||||
group(
|
||||
"outer",
|
||||
None,
|
||||
vec![
|
||||
group("empty", None, vec![]),
|
||||
group("clipped-empty", Some(BezPath::new()), vec![]),
|
||||
group("inner", Some(BezPath::new()), vec![leaf(), group("deeper", None, vec![leaf()]), leaf()]),
|
||||
leaf(),
|
||||
],
|
||||
),
|
||||
group("sibling", None, vec![leaf()]),
|
||||
leaf(),
|
||||
];
|
||||
parity(48.0, 32.0, &items);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_depth_input_is_discarded_without_recursive_destruction() {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(1024 * 1024)
|
||||
.spawn(|| {
|
||||
let mut leaf = path(Some(Fill::Solid(Color::BLACK)), "butt", "miter", Color::BLACK);
|
||||
for _ in 0..XML_DEPTH * 3 {
|
||||
leaf = Item { bbox: Rect::ZERO, kind: ItemKind::Group(GroupItem { name: None, xf: None, clip: None, children: vec![leaf] }) };
|
||||
}
|
||||
let output = document(1.0, 1.0, vec![leaf]);
|
||||
assert_eq!(output.matches("<group").count(), XML_DEPTH);
|
||||
assert_eq!(output.matches("</group>").count(), XML_DEPTH - 1);
|
||||
assert!(!output.contains("<path"));
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# Auto layout and constraints parity
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** patch (padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
Auto layout is the most used layout feature in Figma and the one where small differences (a
|
||||
hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%,
|
||||
@@ -27,6 +27,20 @@ outside the new frame’s layout flow and adding an unnecessary level to the lay
|
||||
the selected container makes later changes to a child’s size reflow its siblings directly.
|
||||
Selecting several groups still wraps that selection in a shared auto layout frame.
|
||||
|
||||
## Canvas padding grips
|
||||
|
||||
Padding bands begin at the inner edge of an included inside stroke. Each band's central grip
|
||||
starts a padding drag; the rest of the band still highlights on hover and remains available to
|
||||
ordinary canvas tools. The grip shows vertical resize arrows on the top and bottom, horizontal
|
||||
arrows on the sides. Alt synchronises the opposite side to the dragged value, and Alt+Shift
|
||||
synchronises all four. Shift alone retains the existing opposite-side gesture. Affected bands
|
||||
and grips highlight immediately when modifiers change, both before and during a drag. One undo
|
||||
restores every affected side. On very small frames or at reduced zoom, opposite grips move
|
||||
outward to stay at least 20 screen pixels apart; the padding bands keep their geometry.
|
||||
Overlapping hit targets select the nearest visible grip for both hover and drag. Hover keeps
|
||||
the resize cursor while updating the hovered layer, and a secondary click opens the normal
|
||||
canvas context menu. Only the primary press and active drag capture pointer input.
|
||||
|
||||
## Rules from the documentation
|
||||
|
||||
Status: **pass** (a case in the suite holds), **fixed** (the suite found a divergence, now fixed),
|
||||
@@ -52,6 +66,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver
|
||||
| Padding per side (uniform, vertical/horizontal, individual) | pass | `padding_and_stroke_rules` |
|
||||
| A frame is never smaller than its padding (plus an included inside stroke), even when Fixed, hugging or given a smaller max | **fixed** | was free to shrink below its padding |
|
||||
| Strokes included: only the frame's own **inside** stroke takes up space; center and outside strokes never do | **fixed** | every stroke alignment counted before; per-side inside weights count per side (silent on individual weights) |
|
||||
| Canvas padding and gap bands follow the included inside stroke | **fixed** | Padding bands begin at the stroke's inner edge; flow gap bands span the available content box. Only the central grip starts a padding drag; hovering the band still highlights it. Geometry and pointer interactions are covered by `canvas::handles::padding_tests`. |
|
||||
| New auto layout includes inside strokes by default | **fixed** | the default was excluded |
|
||||
| Strokes included / excluded setting in the Design panel | **added** | `strokesIncluded` existed as a prop only |
|
||||
| Gap: fixed distance; negative gaps overlap | pass | `gap_rules` |
|
||||
@@ -101,7 +116,12 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-13 | patch | M2, #2152: Padding grip fills and outlines come from dedicated theme tokens, preserving linked-state emphasis and border widths. A rendering regression checks custom light and dark palettes. |
|
||||
| 2026-11-13 | patch | M2, #2152: Padding grips preserve canvas hover and secondary-click context menus while retaining their resize cursor. Only primary presses and active handle drags capture input. Regressions reproduce both stale layer hover and blocked right-click menus. |
|
||||
| 2026-11-11 | patch | M2.1: grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) (this replaces the 2026-10-11 rule from the documentation). Layout behaviour suite: three cases flipped, three added |
|
||||
| 2026-11-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. |
|
||||
| 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. |
|
||||
| 2026-11-09 | patch | M2: Canvas padding bands follow the inner edge of included inside strokes, including per-side weights; gap bands use the same content insets. Geometry regression tests cover stroke growth, exclusion and center/outside alignment. Dimensions and padding values are unchanged. |
|
||||
| 2026-11-05 | patch | M2, #1823: Suggest auto layout is no longer Add auto layout under another name: `layout.suggest` splits a frame's layers into rows (Vertical) or else columns (Horizontal) by the gaps between their boxes, wraps each band of several layers in a new frame without fill or clipping that hugs it, and repeats inside it (16 levels, 1,000 layers per frame at most). The frame keeps its size; gap and padding come from the bands, so layers keep their boxes where the gaps are even and the bands start at the same offset; instances and layers inside them are refused; uneven gaps (smallest used), bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes come back as `warnings`. A band frame hugs only when its own split succeeds: a band whose layers overlap along both axes gets no auto layout and stays Fixed, so it cannot reflow those children. `direction` sets the top level only; one undo step; `layout.add` is unchanged. Tests in `layout_suggest_tests.rs` |
|
||||
| 2026-11-02 | patch | M2: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. The modifier was ignored before. Test: `padding_individual_tests` |
|
||||
| 2026-11-03 | patch | M2, #1825: baseline alignment of a layer without text (an icon next to a text) puts its bottom on the line's baseline, as the help center's figure shows ("the bottoms of the icon and the word home are aligned on the red line"); it kept to the top of the line. A layer reaching below the text's baseline moves the text down, and a line with no text lines the layers' bottoms up (the documentation is silent; CSS baseline alignment does the same). Tests: `alignment_rules` (three cases), engine `baseline_alignment_puts_an_icons_bottom_on_the_text_baseline`. Numbers unchanged. |
|
||||
|
||||
@@ -65,7 +65,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
| Editing a style updates its layers; detach and delete keep values; editing a styled property unlinks that style | done | an edited fill/stroke/effect/grid list or text chars unlink; applying a style replaces variables bound to what it sets; text styles on text layers only |
|
||||
| Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) |
|
||||
| Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style (a face name from a string variable, or a numeric weight from a number variable, which picks the nearest face and a variable font's `wght` axis), size, line height and letter spacing, the rest through the command; a bound line height is applied in pixels, as the reference tool does (measured 2026-11-10) |
|
||||
| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step) |
|
||||
| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 |
|
||||
| Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay |
|
||||
| Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show |
|
||||
| Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values |
|
||||
@@ -80,6 +80,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. |
|
||||
| 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-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Create component, instances, detach, reset, go to main, restore main, push changes. |
|
||||
| 2026-11-14 | patch | M3, #2353: renaming a group in the Local variables window to a path with `/` nests it, as in Figma: `Orange` renamed to `Palette/Orange` moves its variables to `Palette/Orange/100`… and the sidebar shows Orange indented under a new Palette group, where the slash used to become a hyphen (`Palette-Orange`). The typed path replaces the group's last part (a nested group stays in its parent), each part is trimmed and empty parts are dropped; a rename onto a variable name that stays is refused with nothing changed, and it is one undo step. Tests: `variables_select_tests::renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step` and the group rename tests beside it, `variables_panel::tests`. Grade unchanged. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File format parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the Line truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the 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
|
||||
@@ -57,7 +57,7 @@ export limit, not a native document nesting limit.
|
||||
| SVG | yes (outline text option, ids) | yes | alpha/luminance masks kept; noise, texture, progressive and background blur, glass embedded as images; outline text (off: `<text>` with one `<tspan>` per line, one style per layer), unique id attributes from layer names, explicit depth-limit refusal, nested frames clipped by their parent's clip (#327), simplified strokes (stroke attributes for centred strokes and for inside and outside strokes on boxes and ellipses) | — |
|
||||
| PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal; RGB is always sRGB (no color profile setting and no output intent) | CMYK output intent 2–4 |
|
||||
| WebP | — | yes (ours) | a color profile per setting as for PNG; sRGB files untagged, Display P3 files with the generated ICC profile | — |
|
||||
| Android Vector Drawable (XML) | — | yes (ours) | an `.xml` drawable resource (`file.export {format: "xml"}`, export settings, File ▸ Export…, the CLI and MCP), pretty-printed, sized in dp with the viewport in layer units, for AndroidX (VectorDrawableCompat: gradients and even-odd need API 24 without it). Shapes, booleans and text as path data with transforms baked in; solid fills and linear, radial and sweep gradients (`aapt:attr`, exact for any handles: radial and sweep in a `<group>` that maps the unit circle); centred strokes as stroke attributes where Android draws them the same (uniform scale, one cap, no dashes or variable width), other strokes as filled outlines; clipping frames and masks as `<group>` with `<clip-path>`; `android:name` from layer names with the id attribute option. What the format can't hold goes by the compatibility mode (`vdCompat`): best effort (default) applies layer opacity to each shape, rewrites even-odd fills and clip outlines as non-zero, draws diamond gradients as radial and alpha masks as outline clips, each with a warning; exact leaves out what it can't draw exactly, with a warning; ignore writes what maps without warnings: layer opacity over overlapping shapes is dropped (drawn opaque), even-odd fills keep `fillType="evenOdd"`, even-odd clip outlines clip as non-zero, diamond gradients are left out and alpha masks clip to their outline. Effects, image and pattern fills and blend modes are always left out (warned except in ignore); an export that draws nothing writes one empty path (Android refuses a drawable without a path), with a warning. Checked by parsing the XML, against FigCraft's renderer (gradients pixel by pixel), with `aapt2 compile` and `link`, and by rendering samples (linear, skewed radial and sweep gradients, a sweep with mirrored handles, even-odd booleans, centred and inside strokes, rotated text, a clipping frame, an alpha mask, a translucent group, each compatibility mode) with Android 13's (API 33) VectorDrawable on an emulator, next to FigCraft's PNG export: they match, including where the sweep starts and which way it turns, except what the compatibility mode and its warnings say (best effort: overlapping shapes in a translucent group look denser; exact and ignore leave out or draw opaque what they list). Not checked on API 21–23 (VectorDrawableCompat) | — |
|
||||
| Android Vector Drawable (XML) | — | yes (ours) | an `.xml` drawable resource serialized by `craft-vectordrawable` through an app-model adapter (`file.export {format: "xml"}`, export settings, File ▸ Export…, the CLI and MCP), pretty-printed, sized in dp with the viewport in layer units, for AndroidX (VectorDrawableCompat: gradients and even-odd need API 24 without it). Shapes, booleans and text as path data with transforms baked in; solid fills and linear, radial and sweep gradients (`aapt:attr`, exact for any handles: radial and sweep in a `<group>` that maps the unit circle); centred strokes as stroke attributes where Android draws them the same (uniform scale, one cap, no dashes or variable width), other strokes as filled outlines; clipping frames and masks as `<group>` with `<clip-path>`; `android:name` from layer names with the id attribute option. What the format can't hold goes by the compatibility mode (`vdCompat`): best effort (default) applies layer opacity to each shape, rewrites even-odd fills and clip outlines as non-zero, draws diamond gradients as radial and alpha masks as outline clips, each with a warning; exact leaves out what it can't draw exactly, with a warning; ignore writes what maps without warnings: layer opacity over overlapping shapes is dropped (drawn opaque), even-odd fills keep `fillType="evenOdd"`, even-odd clip outlines clip as non-zero, diamond gradients are left out and alpha masks clip to their outline. Effects, image and pattern fills and blend modes are always left out (warned except in ignore); an export that draws nothing writes one empty path (Android refuses a drawable without a path), with a warning. Checked by parsing the XML, against FigCraft's renderer (gradients pixel by pixel), with `aapt2 compile` and `link`, and by rendering samples (linear, skewed radial and sweep gradients, a sweep with mirrored handles, even-odd booleans, centred and inside strokes, rotated text, a clipping frame, an alpha mask, a translucent group, each compatibility mode) with Android 13's (API 33) VectorDrawable on an emulator, next to FigCraft's PNG export: they match, including where the sweep starts and which way it turns, except what the compatibility mode and its warnings say (best effort: overlapping shapes in a translucent group look denser; exact and ignore leave out or draw opaque what they list). Not checked on API 21–23 (VectorDrawableCompat) | — |
|
||||
| Copy as CSS / SVG / PNG / text / link | yes | yes | Copy as PNG: the whole selection at 2x | — |
|
||||
| Dev Mode code (CSS, iOS SwiftUI, Android Compose) | yes | yes, plus HTML, React, Vue, Leptos, ArkUI and Flutter | see [dev-mode-parity](dev-mode-parity.md) | — |
|
||||
| `.fig` ("Save local copy") | yes | **experimental** | the whole file, also as a copy from File ▸ Save as… (the document keeps its `.figcraft` path and unsaved state); see [Export to `.fig`](#export-to-fig-experimental). Round trips through our own importer; written files checked by opening them in other software: layers, fills, gradients, strokes, shadows, vectors, components and text draw as in FigCraft; resized and scaled instances keep their size and lay their layers out for it, variables with their modes and colour bindings resolve there (a frame set to another mode shows that mode's colours, also inside instances), colour, text, effect and grid styles are listed, and variable-width strokes that are the same on both sides of the path draw with their width | 5–15 (non-colour bindings as bindings, checks of effects, images and prototypes, and against real files) |
|
||||
@@ -196,6 +196,7 @@ scales and empty-style clears; they have not been checked in other software.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
|
||||
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. |
|
||||
| 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software |
|
||||
| 2026-11-12 | minor | M6, #2323: the `.fig` export writes text on a path as the format's own layer kind (`TEXT_PATH`): the first part of its path as a vector network of one open or closed chain with the segment the text starts on marked, the start as that segment's own parameter (`textPathStart.tValue`, found by inverse arc length) and the side as `forward`. Vertical alignment is written as top, which is how text on a path draws. The importer already read all of it; a closed path comes back starting at the marked segment, the same curve and start point. Text with more than one line and paths the format can't hold stay plain text, the parts of a path after the first are left out, and text on a path in an instance but not in its main component (or the other way round) is written as the main has it, each with its own warning. The field numbers come from the schema of a synthetic file saved from Figma's web app. Checked through the importer only, not in other software |
|
||||
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
# Where FigCraft falls short of Figma
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (deLine truncated
|
||||
|
||||
Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from
|
||||
doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The
|
||||
@@ -272,7 +272,8 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
Lines and SVG (plugin API 6, 2026-10-31): a widget layer can be a `line` or an `svg`, whose
|
||||
picture comes in as locked layers, scaled to fit a size.
|
||||
- **Missing:** a public catalogue and Community files, publisher accounts and signatures, ratings
|
||||
and install counts, background update checks, the directory in the browser build; widgets have no
|
||||
and install counts, background update checks, keeping plugins installed in the browser past the
|
||||
page (the directory works there since 2026-10-31); widgets have no
|
||||
timers. Figma's own plugins are JavaScript against
|
||||
Figma's plugin API and don't run.
|
||||
- **Impact:** teams that depend on specific Figma plugins (icons, content, accessibility checks)
|
||||
@@ -617,6 +618,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. |
|
||||
| 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` |
|
||||
| 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` |
|
||||
| 2026-11-17 | minor | Gap 7: the desktop refines a zoom's preview only once the zoom has paused, as the browser does, so a full render that can't be stopped no longer holds up the next steps of a held zoom. Numbers unchanged. Test: `zoom_preview_tests::the_render_thread_refines_a_zoom_only_once_it_pauses` |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Hardware and platform parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (unused; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; under Wayland a minimised window answers control and MCP requests in about half a second instead of timing out after 60 s (#1906); images copied in other apps paste in the browser (#492); text reads only the fallback fonts it draws with; `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); a batch keeps one undo snapshot, not one per step (#1099); one depth cap bounds a whole render, pattern sources included, and render threads get 8 MiB stacks (#1082); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); macOS: the Quit menu and ⌘Q ask about unsaved changes (#857); egui/eframe 0.37 dependency migration; hidden-window screenshot deadlines; zoom previews; hidden windows answer control requests; macOS file opening, the Windows start-up message, Linux packaging; copy and paste in the browser; Windows QA pass; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; pen pressure for the Pencil and brushes on Windows and from browser styluses; macOS: quitting ends the process once everything is kept, avoiding the Touch Bar teardown crash (#781); Linux and BSD clipboard: images under Wayland, reads time out; minimised windows under Wayland; window controls on Wayland without server decorations; canvas textures on device pixels) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; unused; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; under Wayland a minimised window answers control and MCP requests in about half a second instead of timing out after 60 s (#1906); images copied in other apps paste in the browser (#492); text reads only the fallback fonts it draws with; `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); a batch keeps one undo snapshot, not one per step (#1099); one depth cap bounds a whole render, pattern sources included, and render threads get 8 MiB stacks (#1082); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); macOS: the Quit menu and ⌘Q ask about unsaved changes (#857); egui/eframe 0.37 dependency migration; hidden-window screenshot deadlines; zoom previews; hidden windows answer control requests; macOS file opening, the Windows start-up message, Linux packaging; copy and paste in the browser; Windows QA pass; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; pen pressure for the Pencil and brushes on Windows and from browser styluses; macOS: quitting ends the process once everything is kept, avoiding the Touch Bar teardown crash (#781); Linux and BSD clipboard: images under Wayland, reads time out; minimised windows under Wayland; window controls on Wayland without server decorations; canvas textures on device pixels) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
How FigCraft uses hardware and which platforms it runs on, against Figma. Figma's desktop app is
|
||||
Electron with a GPU helper process; its canvas renders on the GPU (WebGL, with WebGPU rolling out
|
||||
@@ -50,6 +50,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
|
||||
| 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. |
|
||||
| 2026-11-10 | patch | M10, #1343 (also #1422, #2233): Windows: the window no longer draws below a hidden caption. FigCraft draws its own title bar on Windows and opens undecorated windows, but winit 0.30 still gives them `WS_CAPTION` and `WS_BORDER`; on some systems the desktop compositor reserves that caption, so the content was drawn about 30 px low (a black band above it) while clicks kept the client coordinates and landed above what was drawn. A per-frame step (`apps/figcraft/src/window_frame.rs`, safe `winsafe` calls, Windows only) clears `WS_CAPTION` and `WS_BORDER` from every FigCraft window, the main one and the others, keeping the sizing border and window buttons so edge resizing and snap work, and writes only when a style changed (winit puts them back on maximize and restore). The same fix as DesignCraft #2139 and PhotoCraft #2401; the maximize-to-work-area trim from DesignCraft is left for a later change. Not run on a Windows machine that shows the offset: the style math and the per-frame hook are tested, the window itself needs a live check. Tests: `window_frame_tests`. Numbers unchanged |
|
||||
| 2026-11-06 | patch | M8, #1906: under Wayland (seen on GNOME and KDE Plasma) a minimised FigCraft window still reports itself visible and the compositor stops asking it to draw, so every control or attached-MCP request waited for a frame and timed out after 60 s ("it was not applied"), though eframe kept running the app's logic. `control::background` now treats a window that drew no frame for `NOT_DRAWING_AFTER` (0.2 s) while a request waited for it as hidden: state-only requests are answered from the logic passes (0.54 s each, measured on GNOME Wayland; they took 13.7 s or timed out before), the wait starts again when the window draws, and screenshots and `ui.input` still wait for a frame. Test: `idle_tests::a_window_that_stopped_drawing_answers_from_its_logic_passes` |
|
||||
|
||||
+5
-4
@@ -214,9 +214,10 @@ whole bundle before keeping it, refuses a version that isn't newer than the one
|
||||
the new version at once. `plugin.directory.unpublish` (or the operator's `figcraft-server plugins
|
||||
remove`) takes a version, or the whole plugin, down; installed copies keep working.
|
||||
|
||||
**In the browser** the directory isn't available yet: the browser build's network link has no
|
||||
plugin directory requests (`plugin.directory.*` says so). Import plugins with `plugin.import
|
||||
{manifest, wasm}` there.
|
||||
**In the browser** Manage plugins browses a directory and installs from it as the desktop app
|
||||
does, but there is no folder to keep a plugin in, so it lasts as long as the page. Scripts through
|
||||
`window.figcraft` can't reach a directory (commands there don't wait for the server, and
|
||||
`plugin.directory.*` says so): import plugins with `plugin.import {manifest, wasm}` there.
|
||||
|
||||
## The manifest: `figcraft-plugin.json`
|
||||
|
||||
@@ -548,7 +549,7 @@ import what you need from `figcraft`.
|
||||
- Distribution: directories live on your own `figcraft-server`; there is no public catalogue,
|
||||
no publisher accounts or signatures (the server's key is the publisher), no ratings, reviews or
|
||||
install counts, and updates are found when you browse, not in the background. The browser build
|
||||
can't use a directory yet.
|
||||
keeps what it installs only as long as the page.
|
||||
- Plugins written for other apps (JavaScript plugins) don't run.
|
||||
- Widgets: clicks, field edits and menu items are their only events (no hover or timers), a field
|
||||
is plain text (no placeholder, length or single-line setting), and their layers are frames, text, rectangles, ellipses and images only (no
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Prototyping parity
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (a connection dragged from a variant, or a layer in it, onto a sibling variant makes Change to, On click, Instant, with the sibling outlined (#2158); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (in the presenter's comment mode (C) a click on the presented frame starts a comment there and the mode stays on for the next one, Escape closes the draft and then the mode, measured in Figma's web app 2026-11-10 (#2209); a connection dragged from a variant, or a layer in it, onto a sibling variant makes Change to, On click, Instant, with the sibling outlined (#2158); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
**Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except
|
||||
media control, every transition and easing exist; key/gamepad triggers take controller buttons,
|
||||
@@ -93,7 +93,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr
|
||||
| Interactive components: instances play their variant's interactions, overridden per trigger | done | |
|
||||
| Drag-driven animations that follow the pointer, in their direction | done | |
|
||||
| Presenter: device frames and colours, rotation, custom sizes, fit/fill/100%, responsive frames | done | device bodies drawn in code. Presenting opens a tab for the page, named "file - page", which keeps its screen and history while you go back to the design, with a thumbnail of the current frame, previous / next, device presets and scale choices; the frame is laid out again for the device's screen on the prototype's copy (constraints and auto layout; the file is untouched); on phones and tablets overflowing content drags while the device stays put: a top-level frame bigger than the screen always scrolls (as in Figma, with no overflow setting), content past the frame's own edges as its overflow setting allows ("No scrolling" clips it); closing the window asks about unsaved changes above the presentation (#537). Devices not compared with Figma's |
|
||||
| Hotspot hints, inspect panel in the presenter, comments in the presenter | done | |
|
||||
| Hotspot hints, inspect panel in the presenter, comments in the presenter | done | in comment mode (C) a click on the presented frame starts a comment there (a click off the frame does nothing, and the prototype's own click interactions don't fire) and the mode stays on for the next comment; Escape closes the draft, then the mode (the presentation stays open), as measured in Figma's web app 2026-11-10 (#2209). No comments sidebar in the presenter |
|
||||
| Hide UI in the presenter (Options menu, Cmd/Ctrl+\) | done | the bar above the prototype and the navigation bar under it go away and the prototype takes their room; a toast names the key that brings them back; `proto.presentOptions {hideUi}`, kept for later presentations (#1820) |
|
||||
| Preview pane following edits live | done | |
|
||||
| Edit interactions on several layers at once | done | |
|
||||
@@ -110,6 +110,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr
|
||||
|---|---|---|
|
||||
| 2026-11-14 | patch | M5, #2352: a chain of variant changes on After delay plays to the end (A to B to C to D); before, the step a variant had fired stayed marked as fired when the instance changed variant, so the chain stopped after one step, and now each step's delay counts from when its variant appears (`crates/ui-egui/src/present/afterdelay_chain_tests.rs`). Numbers unchanged |
|
||||
| 2026-11-09 | patch | M7, #2158: a connection dragged from a variant (or a layer in it) onto a sibling variant of its set did nothing, because the drop looked only for top-level frames and a variant's top-level frame is its set. It now creates Change to the sibling (On click, Instant, as measured in Figma's web app) and outlines the sibling while dragging; the set's background and the variant itself still add nothing, and a frame outside the set still gets Navigate to |
|
||||
| 2026-11-10 | patch | M7, #2209: the presenter's comment mode showed the frame's pins but nothing started a comment. Measured in Figma's web app: with the mode on (C or the bar's comment button) a click on the presented frame drops a pin at the click and opens an "Add a comment" composer beside it; Enter posts, the pin stays at the same frame-relative spot and the mode stays on; a click on the background does nothing; Escape closes a composer, and with none open turns the mode off; the comment shows on the frame in the editor. Now the same: the click starts the draft at the point mapped back through the presenter's placement, the editor's composer is shared, the post carries the frame's page, the player ignores the pointer while the mode is on (no click interactions or hotspots fire), and Escape closes the draft, then the mode. Tests: `comments_tests::a_click_in_the_presenters_comment_mode_adds_a_comment_on_the_frame` and four more. |
|
||||
| 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` |
|
||||
| 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. |
|
||||
| 2026-10-30 | minor | Opening a link in place: Open link has "Open in new tab", on by default; off, the web build's own tab goes to the link after the notice (or at once with it skipped); the desktop app has no tab of its own and opens the browser either way. Saved in files only when off (`openInNewTab`) and read from REST files. |
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
# FigCraft roadmap: milestones and what's next
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer'sLine truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (the browser build uses team libraries and plugin directories on a server; zoomed-out images draw from small copies that stay decoded, so a page of photos zooms out without decoding them again; mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' Line truncated
|
||||
|
||||
Forward-looking plan. Where FigCraft stands today: [`ROADMAP.md`](../ROADMAP.md) and
|
||||
[`target-app-parity.md`](target-app-parity.md); the full ranked list: [`gaps.md`](gaps.md). Hours
|
||||
@@ -76,6 +76,7 @@ blockers.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
|
||||
| 2026-11-10 | minor | Zoomed-out images: the canvas's copies of an image shown smaller than its pixels now also come at 256, 512, 1024 and 2048 px, the smallest that holds what the screen shows, and images of 4096 px or less get them too (they were drawn from the image itself at any size). On a page of 237 photos, about 4.6 GB decoded against the 512 MB cache, every zoomed-out render decoded them again: 3.4 s a frame at 1% before, 0.9 s the first time and 4 ms after; peak memory 3.9 → 2.3 GB. Exports, and images shown at their own size or larger, still draw from the image itself. |
|
||||
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
|
||||
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged |
|
||||
|
||||
+4
-1
@@ -268,7 +268,10 @@ send their requests on a thread of their own, show that they're on their way (wi
|
||||
finish when the answer arrives, acting on the file they started in. Scripts, the CLI and the MCP
|
||||
server run the same commands and wait for the answer.
|
||||
|
||||
The browser build can't use team libraries yet (it has no library support of its own).
|
||||
The browser build uses team libraries through the same panel: adding one by its link, its styles
|
||||
and components, publishing a file that is on the server, Show usage and the reports a file sends.
|
||||
A browser can't keep a library file, and scripts through `window.figcraft` can't reach a server
|
||||
(commands there don't wait for it), so those stay with the desktop app, the CLI and MCP.
|
||||
|
||||
## Plugin directory
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# FigCraft parity with Figma
|
||||
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS)
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS)
|
||||
|
||||
The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md)
|
||||
summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is
|
||||
@@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 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-15 | minor | M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured |
|
||||
| 2026-11-10 | minor | M4, #2222: a boolean group's corner radius rounds every sharp corner of its result (row 4). Numbers unchanged |
|
||||
| 2026-11-08 | minor | M8: measured in Figma on 2026-11-08, vector edit mode's Point section: X and Y show the value the selected points share, or Mixed when they differ, and a typed value sets every selected point's own coordinate in the layer being edited, points of other edited layers left as they are (it moved the group's top-left before); a relative edit (`+10`, `*2`, `/2`) typed into a Mixed field applies to each point's own value (`vector.edit.position` takes a number or `{add}`, `{mul}`, `{div}` per axis); the W and H row and other edited layers' points are unchanged. |
|
||||
|
||||
+2
-1
@@ -76,7 +76,7 @@ interaction feel only partly compared: the interactions measured so far, case by
|
||||
| Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing |
|
||||
| Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) |
|
||||
| Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; the pixel grid shows from 400% (`view_behaviour_tests`) |
|
||||
| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: a step a point (1 px; 1% of opacity, 1° of rotation), ten with Shift, a tenth with Alt, each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; rates not compared with Figma's; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837) |
|
||||
| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: half a step a point (0.5 px; 0.5% of opacity, 0.5° of rotation), as measured in Figma on 2026-11-08 (a 12.2 px drag moved X by 6, a 61.2 px drag by 31; rotation by 6° and opacity by 5% for 12.2 px), ten times that with Shift (5 steps a point) and a tenth of that with Alt (0.05 steps a point; neither measured), each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; the Shift and Alt rates and the speed by height are not compared with Figma's, and the rotation scrub's direction is not confirmed; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837) |
|
||||
| Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation |
|
||||
| Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection |
|
||||
| Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session |
|
||||
@@ -208,6 +208,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 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-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed |
|
||||
| 2026-11-17 | patch | M8: each page keeps its view in a session: going back to a page (the Pages list, `page.select`, Previous/Next page) shows it where it was left instead of fitting it again; a new page is still fitted, and going to the page shown moves nothing (`page_view_tests`) |
|
||||
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): UI3 layout, Light and dark themes, Rotate just outside a corner, Selection colors, Keyboard box selection, Boolean groups, Text: point, auto height, fixed, Text: wrap style, Bound as documented, Pan/zoom. |
|
||||
| 2026-11-12 | patch | M8: a double-click on a layer's icon in the Layers panel selects the layer and zooms the canvas to it (`view.zoomSelection`) and starts no rename, as measured in Figma's web app on 2026-11-12; a double-click on the name or elsewhere on the row still renames; the icon's hit area is the rect the row paints the icon in (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`), Rename row |
|
||||
|
||||
Reference in new issue
Block a user