mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # docs/ui-parity.md
This commit is contained in:
commit
31f38737a4
140 files changed
+12143
-460
No files matched your search
@@ -368,6 +368,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|---|---|---|
|
||||
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
|
||||
| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged |
|
||||
| 2026-11-19 | minor | M8: Code Connect for agents. A link can name its source file, what variant values are called in code (Primary becomes `primary` in the snippet) and notes, in the Inspect tab, `codeConnect.set` and `figcraft.connect.json`. `codeConnect.list` and the MCP tool `component_mappings` say which code component each design component is, and whether its source file exists; `sync_mappings` imports and exports a repository's file. `codeConnect.export {path}` keeps the file's other keys and the links of components the design doesn't have, so several designs can share one file. Numbers unchanged |
|
||||
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
|
||||
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
|
||||
| 2026-11-18 | minor | M8: asset handoff. `file.exportAssets` and the MCP tool `export_assets` write a design's images and vectors into a folder: images as the file's original bytes, never re-encoded, vectors as SVG, layers with export settings by those settings, each saying which it is. Files are named by their content, so an asset has one file and exporting again writes nothing; what a layer does to an image that isn't in its bytes is listed. Numbers unchanged |
|
||||
|
||||
+48
-22
@@ -344,6 +344,14 @@ fn main() -> eframe::Result {
|
||||
let mut session = Session::empty();
|
||||
// Live sessions: the network threads wake the window when something arrives.
|
||||
session.live.install(Box::new(figcraft_collab_net::NetLink::new(Arc::new(wake(&ctx_slot)))));
|
||||
// The preferences first: a file named on the command line opens where it was left and goes to
|
||||
// the top of the recent files, and they hold the online files a recovered document may be one of.
|
||||
let recovery = recovery::Shared::default();
|
||||
let svc = services::Desktop::load(recovery.clone());
|
||||
svc.follow_system_dark(wake(&ctx_slot));
|
||||
if let Some(prefs) = svc.prefs.clone() {
|
||||
session.prefs = prefs;
|
||||
}
|
||||
// A file that won't open is said in the window too: it may have been double-clicked.
|
||||
let mut failed_open = None;
|
||||
for f in &args.files {
|
||||
@@ -353,16 +361,9 @@ fn main() -> eframe::Result {
|
||||
failed_open = Some(format!("{name}: {e}"));
|
||||
}
|
||||
}
|
||||
let opened: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
|
||||
let mut opened: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
|
||||
// Documents a crashed or killed run left unsaved come back; this run keeps its own copies.
|
||||
let recovery_root = services::config_dir().map(|d| d.join("Recovery"));
|
||||
// The preferences first: they hold the online files a recovered document may be one of.
|
||||
let recovery = recovery::Shared::default();
|
||||
let svc = services::Desktop::load(recovery.clone());
|
||||
svc.follow_system_dark(wake(&ctx_slot));
|
||||
if let Some(prefs) = svc.prefs.clone() {
|
||||
session.prefs = prefs;
|
||||
}
|
||||
let recovered = recovery_root.as_deref().map(|r| recovery::recover_all(r, &mut session)).unwrap_or_default();
|
||||
let mut copies = recovery_root.as_deref().and_then(recovery::Recovery::start);
|
||||
// Copies of online files stay until their files arrive from their servers.
|
||||
@@ -380,7 +381,20 @@ fn main() -> eframe::Result {
|
||||
session.invite_links_startup();
|
||||
}
|
||||
let first_run = svc.prefs.is_none() && args.join.is_none();
|
||||
if session.docs.is_empty() && opens_new_file(first_run, session.prefs.start_on_home, port.is_some()) {
|
||||
if reopens_files(first_run, session.prefs.start_on_home) {
|
||||
let before: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
|
||||
for (path, e) in session.reopen_files() {
|
||||
log::error!("{path}: {e}");
|
||||
let name = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned());
|
||||
failed_open = Some(format!("{name}: {e}"));
|
||||
}
|
||||
// A file named on the command line stays in front.
|
||||
if let Some(i) = opened.last().and_then(|uid| session.docs.iter().position(|d| d.uid == *uid)) {
|
||||
session.active = i;
|
||||
}
|
||||
opened.extend(session.docs.iter().map(|d| d.uid).filter(|u| !before.contains(u)));
|
||||
}
|
||||
if session.docs.is_empty() && opens_new_file(first_run, port.is_some()) {
|
||||
let _ = session.execute("file.new", &json!({}));
|
||||
}
|
||||
// The interface language from the first frame on, and for the message when the window can't
|
||||
@@ -395,7 +409,8 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
fig.automation_roots = roots;
|
||||
fig.ui.home = false;
|
||||
// Files named on the command line are the user's too: their missing fonts are listed.
|
||||
// Files named on the command line or reopened are the user's too: their missing fonts are
|
||||
// listed.
|
||||
fig.ui.font_checks = opened;
|
||||
fig.note_recovered(recovered.copies);
|
||||
if let Some(message) = failed_open {
|
||||
@@ -516,12 +531,17 @@ fn main() -> eframe::Result {
|
||||
graphics.finish(result, frames, port.is_some())
|
||||
}
|
||||
|
||||
/// With nothing to open, whether the window starts in a new file rather than on the home screen.
|
||||
/// A first run (no settings kept yet) shows the home screen's tips and templates, and later runs
|
||||
/// start in a new file unless the preference asks for Home, which `--control` overrides: its
|
||||
/// callers expect a document to act on.
|
||||
fn opens_new_file(first_run: bool, start_on_home: bool, control: bool) -> bool {
|
||||
!first_run && (!start_on_home || control)
|
||||
/// Whether the files open when the app last quit open again: not on a first run (no settings kept
|
||||
/// yet), nor when the preference asks for the Home screen.
|
||||
fn reopens_files(first_run: bool, start_on_home: bool) -> bool {
|
||||
!first_run && !start_on_home
|
||||
}
|
||||
|
||||
/// With nothing open, whether the window starts in a new file rather than on the home screen: only
|
||||
/// with a control port open (`--control`), whose callers expect a document to act on. A first run
|
||||
/// shows the home screen's tips and templates whatever the port.
|
||||
fn opens_new_file(first_run: bool, control: bool) -> bool {
|
||||
!first_run && control
|
||||
}
|
||||
|
||||
/// The title bar FigCraft starts with, decided by the shared craft-window crate so every Craft app
|
||||
@@ -617,14 +637,20 @@ mod title_bar_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod start_tests {
|
||||
use super::opens_new_file;
|
||||
use super::{opens_new_file, reopens_files};
|
||||
|
||||
#[test]
|
||||
fn the_home_preference_starts_on_home_except_for_control_callers() {
|
||||
assert!(opens_new_file(false, false, false), "a new file by default");
|
||||
assert!(!opens_new_file(false, true, false), "Home when the preference asks");
|
||||
assert!(opens_new_file(false, true, true), "--control still starts with a document");
|
||||
assert!(!opens_new_file(true, false, false), "a first run shows the home screen");
|
||||
fn the_last_files_reopen_unless_the_home_preference_asks_or_on_a_first_run() {
|
||||
assert!(reopens_files(false, false), "by default");
|
||||
assert!(!reopens_files(false, true), "Home when the preference asks");
|
||||
assert!(!reopens_files(true, false), "a first run has nothing to reopen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_nothing_open_only_control_callers_start_in_a_new_file() {
|
||||
assert!(!opens_new_file(false, false), "the home screen, not an empty file");
|
||||
assert!(opens_new_file(false, true), "--control starts with a document");
|
||||
assert!(!opens_new_file(true, true), "a first run shows the home screen");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -357,9 +357,12 @@ fn open_directory(file: &std::fs::File) -> Result<(), String> {
|
||||
const STATE: &str = "state.json";
|
||||
|
||||
/// Everything quitting keeps, all done when it returns (macOS then ends the process): the
|
||||
/// preferences in `dir`, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit))
|
||||
/// preferences in `dir` with the files open now, which the next start reopens, and where each was
|
||||
/// left, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit))
|
||||
/// and the live sessions' ends (one this app hosts tells everyone and stops; a joined one leaves).
|
||||
pub fn shutdown(app: &mut FigApp, dir: Option<&Path>, recovery: Option<crate::recovery::Recovery>) {
|
||||
app.session.remember_open_files();
|
||||
app.session.remember_views();
|
||||
if let Some(dir) = dir {
|
||||
write_prefs(dir, &app.session.prefs);
|
||||
}
|
||||
@@ -535,6 +538,12 @@ impl Services for Desktop {
|
||||
Some((w, h, img.bytes.into_owned()))
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
fn clipboard_image_file(&mut self) -> Option<PathBuf> {
|
||||
let files = self.clipboard.as_mut()?.get().file_list().ok()?;
|
||||
let [path] = files.as_slice() else { return None };
|
||||
image::ImageFormat::from_path(path).ok()?.reading_enabled().then(|| path.clone())
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
fn clipboard_get_png(&mut self) -> Option<Vec<u8>> {
|
||||
let board = objc2_app_kit::NSPasteboard::generalPasteboard();
|
||||
let png = board.dataForType(&objc2_foundation::NSString::from_str(MACOS_PASTEBOARD_PNG))?;
|
||||
|
||||
@@ -84,6 +84,16 @@ impl Host {
|
||||
if cfg.view_token.as_deref().is_some_and(|v| same_secret(v, &cfg.token)) {
|
||||
return Err(io::Error::other("the view-only secret is the same as the edit secret"));
|
||||
}
|
||||
// The file's review settings stay inside the limits this build keeps: clients apply every
|
||||
// arriving value against them, so a file past them (written by an older or looser build)
|
||||
// would break everyone who joins. The host trims them first (`design.configure`).
|
||||
let over = cfg.doc.design_review.over_limits();
|
||||
if !over.is_empty() {
|
||||
let list = over.iter().map(|(what, have, max)| format!("{have} {what} (this build keeps at most {max})")).collect::<Vec<_>>().join(", ");
|
||||
return Err(io::Error::other(format!(
|
||||
"this file can't be shared: its design review settings hold {list}; trim them with design.configure (or reset the settings), then share again"
|
||||
)));
|
||||
}
|
||||
let listener = match TcpListener::bind(cfg.addr) {
|
||||
Ok(l) => l,
|
||||
Err(e) if e.kind() == io::ErrorKind::AddrInUse && cfg.any_port_if_taken => TcpListener::bind(SocketAddr::new(cfg.addr.ip(), 0))?,
|
||||
|
||||
@@ -10,6 +10,9 @@ use super::{
|
||||
/// How long a closing connection waits for the peer to hang up.
|
||||
const LINGER: Duration = Duration::from_secs(2);
|
||||
|
||||
/// How long the non-blocking accept loop sleeps when no connection is queued.
|
||||
const ACCEPT_POLL: Duration = Duration::from_millis(20);
|
||||
|
||||
/// Signals (cursor chat, spotlight) a client may send per second on average, and in a burst;
|
||||
/// beyond that they are dropped.
|
||||
pub const SIGNAL_RATE: f64 = 20.0;
|
||||
@@ -91,12 +94,14 @@ pub(super) struct Shared {
|
||||
|
||||
pub(super) fn accept(listener: &TcpListener, hub: &Sender<HubIn>, stop: &AtomicBool, open: &Arc<AtomicUsize>, limits: NetLimits, shared: Shared) {
|
||||
let mut next = 0u64;
|
||||
for stream in listener.incoming() {
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
let stream = match stream {
|
||||
Ok(s) => s,
|
||||
while !stop.load(Ordering::SeqCst) {
|
||||
let stream = match listener.accept() {
|
||||
Ok((s, _)) => s,
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
|
||||
std::thread::sleep(ACCEPT_POLL);
|
||||
continue;
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => {
|
||||
// Out of sockets or similar: don't spin.
|
||||
log::warn!("live session: accept failed: {e}");
|
||||
@@ -104,6 +109,15 @@ pub(super) fn accept(listener: &TcpListener, hub: &Sender<HubIn>, stop: &AtomicB
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
// Accepted sockets inherit O_NONBLOCK from the listener on BSD/macOS; `serve` uses
|
||||
// blocking reads and writes with explicit timeouts.
|
||||
if let Err(e) = stream.set_nonblocking(false) {
|
||||
log::warn!("live session: can't set accepted socket blocking: {e}");
|
||||
continue;
|
||||
}
|
||||
if open.load(Ordering::Relaxed) >= limits.max_connections {
|
||||
log::info!("live session: too many connections; refusing one");
|
||||
continue;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::backend::Backend;
|
||||
use super::conn::{Shared, accept};
|
||||
use super::limits::{PerAddress, loopback};
|
||||
use super::limits::PerAddress;
|
||||
use super::queue::{Blocks, HubIn, InFlight};
|
||||
use super::{
|
||||
Arc, AtomicBool, AtomicUsize, ClientMsg, Duration, HashMap, Hub, Inbox, Instant, JoinHandle, MAX_NAME, NetLimits, Ordering, Presence, Readers,
|
||||
Room, Sender, Server, SocketAddr, TcpListener, TcpStream, channel, io,
|
||||
Room, Sender, Server, SocketAddr, TcpListener, channel, io,
|
||||
};
|
||||
|
||||
/// The person hosting an app session: in the file's session without a socket.
|
||||
@@ -48,6 +48,7 @@ impl Hosting {
|
||||
|
||||
pub(crate) fn start<B: Backend>(listener: TcpListener, backend: B, limits: NetLimits, local: Option<Local>) -> io::Result<Hosting> {
|
||||
let addr = listener.local_addr()?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let in_flight = InFlight(Arc::default());
|
||||
let mut hub = Hub {
|
||||
backend,
|
||||
@@ -169,15 +170,8 @@ impl Hosting {
|
||||
if let Some(t) = self.hub_thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
// The accept loop checks the flag after each connection: wake it with one.
|
||||
let wake = if self.addr.ip().is_unspecified() { SocketAddr::new(loopback(self.addr), self.addr.port()) } else { self.addr };
|
||||
let woke = TcpStream::connect_timeout(&wake, Duration::from_secs(1)).is_ok();
|
||||
if let Some(t) = self.accept_thread.take() {
|
||||
if woke {
|
||||
let _ = t.join();
|
||||
} else {
|
||||
log::warn!("live session: couldn't wake the accept loop; it ends with the next connection");
|
||||
}
|
||||
let _ = t.join();
|
||||
}
|
||||
// Readers end once their writers have closed the sockets.
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
@@ -202,3 +196,53 @@ impl Drop for Open {
|
||||
self.0.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::hub::{Admission, Closing};
|
||||
|
||||
struct Noop;
|
||||
|
||||
impl Backend for Noop {
|
||||
fn admit(&mut self, _file: &str, _token: &str) -> Result<Admission, String> {
|
||||
Err("no".into())
|
||||
}
|
||||
|
||||
fn open(&mut self, _file: &str) -> Result<Server, String> {
|
||||
Err("no".into())
|
||||
}
|
||||
|
||||
fn closing(&self) -> Closing {
|
||||
Closing::Ended
|
||||
}
|
||||
}
|
||||
|
||||
/// Stopping a wildcard (`0.0.0.0`) host must return even when another listener already holds
|
||||
/// `127.0.0.1` on the same port (allowed on BSD/macOS under `SO_REUSEADDR`), and must not
|
||||
/// connect to that loopback listener.
|
||||
#[test]
|
||||
fn stopping_a_wildcard_host_returns_when_loopback_shares_the_port() {
|
||||
let shadow = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = shadow.local_addr().unwrap().port();
|
||||
let (wildcard, shadowed) = match TcpListener::bind(("0.0.0.0", port)) {
|
||||
Ok(l) => (l, true),
|
||||
Err(_) if !cfg!(any(target_os = "freebsd", target_os = "macos")) => (TcpListener::bind("0.0.0.0:0").unwrap(), false),
|
||||
Err(e) => panic!("expected BSD dual-bind on 0.0.0.0:{port} alongside 127.0.0.1:{port}: {e}"),
|
||||
};
|
||||
let mut hosting = Hosting::serve(wildcard, Noop, NetLimits::default()).unwrap();
|
||||
let (tx, rx) = channel();
|
||||
std::thread::spawn(move || {
|
||||
hosting.stop();
|
||||
let _ = tx.send(());
|
||||
});
|
||||
assert!(rx.recv_timeout(Duration::from_secs(3)).is_ok(), "Hosting::stop() hung with a loopback listener on port {port}");
|
||||
if shadowed {
|
||||
shadow.set_nonblocking(true).unwrap();
|
||||
assert!(
|
||||
shadow.accept().is_err_and(|e| e.kind() == io::ErrorKind::WouldBlock),
|
||||
"Hosting::stop() must not poke another listener on 127.0.0.1:{port}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{Access, Arc, HashMap, IpAddr, Ipv6Addr, Mutex, PoisonError, SocketAddr};
|
||||
use super::{Access, Arc, HashMap, IpAddr, Ipv6Addr, Mutex, PoisonError};
|
||||
|
||||
/// What a link lets a hello do.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -21,11 +21,6 @@ pub fn ip_key(ip: IpAddr) -> IpAddr {
|
||||
}
|
||||
}
|
||||
|
||||
/// The loopback address of `addr`'s family.
|
||||
pub(super) fn loopback(addr: SocketAddr) -> std::net::IpAddr {
|
||||
if addr.is_ipv6() { std::net::Ipv6Addr::LOCALHOST.into() } else { std::net::Ipv4Addr::LOCALHOST.into() }
|
||||
}
|
||||
|
||||
/// A block of addresses: its first address and its prefix length (2001:db8:: as a /64 and as a
|
||||
/// /48 are different blocks).
|
||||
pub type Block = (IpAddr, u8);
|
||||
|
||||
@@ -290,6 +290,39 @@ fn a_view_token_lets_people_look_and_not_edit() {
|
||||
host.stop();
|
||||
}
|
||||
|
||||
/// A file whose review settings are past this build's limits is not hosted: joining clients
|
||||
/// would refuse the value when it reaches them. The error names the lists and the way out.
|
||||
#[test]
|
||||
fn a_file_with_review_settings_past_the_limits_is_not_shared() {
|
||||
use figcraft_doc::{DesignReview, MAX_DISABLED, MAX_RADII};
|
||||
|
||||
let probe = Probe::new();
|
||||
let mut doc = Document::new("Shared file");
|
||||
doc.repair();
|
||||
doc.design_review = DesignReview {
|
||||
radii: (0..MAX_RADII + 1).map(|i| i as f64).collect(),
|
||||
disabled: (0..MAX_DISABLED + 1).map(|i| format!("rule.{i}")).collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let cfg = HostConfig {
|
||||
addr: SocketAddr::from(([127, 0, 0, 1], 0)),
|
||||
any_port_if_taken: false,
|
||||
file: FILE.into(),
|
||||
token: TOKEN.into(),
|
||||
view_token: None,
|
||||
doc,
|
||||
name: "Hana".into(),
|
||||
limits: fast_limits(),
|
||||
core: Limits::default(),
|
||||
};
|
||||
let e = Host::start(cfg, probe.inbox.clone()).err().expect("settings past the limits are refused");
|
||||
let text = e.to_string();
|
||||
assert!(text.contains("can't be shared"), "{text}");
|
||||
assert!(text.contains(&format!("{} corner radii (this build keeps at most {MAX_RADII})", MAX_RADII + 1)), "{text}");
|
||||
assert!(text.contains(&format!("{} disabled rules", MAX_DISABLED + 1)), "{text}");
|
||||
assert!(text.contains("design.configure"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreachable_hosts_fail_at_once() {
|
||||
// A port nothing listens on.
|
||||
|
||||
@@ -230,6 +230,11 @@ pub enum DocProp {
|
||||
Vote,
|
||||
/// Ended votes' results kept in the file, oldest first (whole).
|
||||
VoteHistory,
|
||||
/// The file's design review settings (`design.configure`).
|
||||
///
|
||||
/// Kept last: the wire encodes a variant's position, so adding one before it would shift the
|
||||
/// existing properties.
|
||||
DesignReview,
|
||||
}
|
||||
|
||||
/// A document-level entry, by id.
|
||||
@@ -331,6 +336,19 @@ impl Change {
|
||||
Change::Create { .. } | Change::Set { .. } | Change::Delete { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this writes the file's design review settings: a batch carrying one can't be read
|
||||
/// by a peer that doesn't announce [`crate::message::DESIGN_REVIEW`], so the server keeps it
|
||||
/// out of what it sends them ([`Self::without_design_review`]).
|
||||
pub(crate) fn is_design_review(&self) -> bool {
|
||||
matches!(self, Change::SetDoc { prop: DocProp::DesignReview, .. })
|
||||
}
|
||||
|
||||
/// `changes` without the review-setting edits: what an older peer reads of a batch (its other
|
||||
/// edits, order kept), or of a catch-up delta or snapshot.
|
||||
pub(crate) fn without_design_review(changes: Vec<Self>) -> Vec<Self> {
|
||||
changes.into_iter().filter(|c| !c.is_design_review()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{Comment, DevSnapshot, Document, ImageData, Message, Node, NodeId, NodeKind, Style, StyleKind};
|
||||
use figcraft_doc::{Comment, DesignPreset, DevSnapshot, Document, ImageData, MAX_DISABLED, Message, Node, NodeId, NodeKind, Style, StyleKind};
|
||||
|
||||
use crate::change::{Change, DocProp, Entry, Json, Prop};
|
||||
use crate::replica::{Mode, Replica};
|
||||
@@ -48,6 +48,65 @@ fn property_edits_send_only_what_changed() {
|
||||
assert!(round_trip(&a, a.document()).is_empty(), "nothing changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn design_review_settings_round_trip_and_reach_a_snapshot() {
|
||||
let (a, _, _, _) = setup();
|
||||
let mut b = a.document().clone();
|
||||
b.design_review.preset = DesignPreset::Strict;
|
||||
b.design_review.grid = 8.0;
|
||||
let changes = round_trip(&a, &b);
|
||||
assert!(changes.contains(&Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }));
|
||||
let snapshot = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
|
||||
assert!(snapshot.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "a snapshot carries the review settings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() {
|
||||
let (a, _, _, _) = setup();
|
||||
// An edit peer trying to hand the file tens of thousands of radii is refused at apply.
|
||||
let mut b = a.document().clone();
|
||||
b.design_review.preset = DesignPreset::Strict;
|
||||
b.design_review.grid = 8.0;
|
||||
b.design_review.radii = (0..40).map(|i| i as f64).collect();
|
||||
b.design_review.brand = vec![Color::from_rgb8_const(1, 2, 3); 40];
|
||||
b.design_review.disabled = vec!["radius.off-scale".into()];
|
||||
let mut r = a.clone();
|
||||
let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() };
|
||||
let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string();
|
||||
assert!(err.contains("pass the 32 limit `design.configure` keeps"), "{err}");
|
||||
// A snapshot holding settings over the limits (an old file's) opens clamped to what fits:
|
||||
// the preset, grid and disabled rules exactly as saved, the lists to the limit.
|
||||
let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
|
||||
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap();
|
||||
assert!(clamped, "the settings needed clamping, and the caller is told");
|
||||
assert_eq!(left_out, 0, "nothing needed leaving out");
|
||||
let cfg = &r2.document().design_review;
|
||||
assert_eq!(cfg.preset, DesignPreset::Strict, "the preset survives");
|
||||
assert_eq!(cfg.grid, 8.0, "the grid survives");
|
||||
assert_eq!(cfg.disabled, vec!["radius.off-scale".to_string()], "the disabled rules survive");
|
||||
assert_eq!(cfg.radii, (0..32).map(|i| i as f64).collect::<Vec<_>>(), "the radii keep their first 32");
|
||||
assert_eq!(cfg.brand, vec![Color::from_rgb8_const(1, 2, 3); 32], "the brand colours keep their first 32");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them() {
|
||||
let (a, _, _, _) = setup();
|
||||
let mut b = a.document().clone();
|
||||
b.design_review.disabled = (0..200).map(|i| format!("rule.{i}")).collect();
|
||||
let mut r = a.clone();
|
||||
let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() };
|
||||
let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string();
|
||||
assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}");
|
||||
// A snapshot with a longer list opens with the ones that fit, not without the settings.
|
||||
let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
|
||||
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap();
|
||||
assert!(clamped);
|
||||
assert_eq!(left_out, 0, "nothing needed leaving out");
|
||||
let cfg = &r2.document().design_review;
|
||||
assert_eq!(cfg.disabled.len(), MAX_DISABLED, "the list keeps its first {MAX_DISABLED}");
|
||||
assert_eq!(cfg.disabled.first().map(String::as_str), Some("rule.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creations_moves_reorders_and_deletions_round_trip() {
|
||||
let (a, page, frame, kids) = setup();
|
||||
|
||||
@@ -353,6 +353,7 @@ doc_scalars! {
|
||||
Timer => timer,
|
||||
Vote => vote,
|
||||
VoteHistory => vote_history,
|
||||
DesignReview => design_review,
|
||||
}
|
||||
|
||||
/// Keyed maps (no order): changed and added entries are put, missing ones removed.
|
||||
@@ -402,12 +403,48 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result<bool, Error>
|
||||
apply_indexed(doc, change, &mut Index::default())
|
||||
}
|
||||
|
||||
/// Clamp the review settings a snapshot carries to the limits this build keeps, in place, and say
|
||||
/// whether it changed them: an older or looser snapshot may hold longer radii, brand or disabled
|
||||
/// lists, and the file opens with what fits — the preset, grid and the rest of each list exactly
|
||||
/// as saved. An ordinary edit is refused instead (`apply_indexed`), and a peer that can't read the
|
||||
/// settings at all gets them left out of what the server sends
|
||||
/// (`Change::without_design_review`).
|
||||
pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec<Change>) -> bool {
|
||||
let mut clamped_any = false;
|
||||
for c in changes {
|
||||
if let Change::SetDoc { prop: DocProp::DesignReview, value } = c
|
||||
&& let Ok(config) = value.read::<figcraft_doc::DesignReview>("design review")
|
||||
&& !config.over_limits().is_empty()
|
||||
{
|
||||
let mut clamped = config;
|
||||
clamped.radii.truncate(figcraft_doc::MAX_RADII);
|
||||
clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS);
|
||||
clamped.disabled.truncate(figcraft_doc::MAX_DISABLED);
|
||||
if let Ok(v) = Json::of(&clamped) {
|
||||
*value = v;
|
||||
clamped_any = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
clamped_any
|
||||
}
|
||||
|
||||
/// Apply a document-level change, with the keyed lists' positions kept in `index` between the
|
||||
/// changes of one batch. Returns whether it can change which pages are listed (the library store
|
||||
/// page is never listed).
|
||||
pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Index) -> Result<bool, Error> {
|
||||
match change {
|
||||
Change::SetDoc { prop, value } => {
|
||||
// A peer's review settings stay inside the limits `design.configure` enforces, so an
|
||||
// edit cannot smuggle in tens of thousands of radii, accents or rule ids for every
|
||||
// check to scan. An oversized value arrives only in an old snapshot, and the snapshot
|
||||
// path clamps it (`clamp_snapshot_design_review`).
|
||||
if *prop == DocProp::DesignReview {
|
||||
let config: figcraft_doc::DesignReview = value.read("design review")?;
|
||||
if let Some((what, have, max)) = config.over_limits().first() {
|
||||
return Err(Error::Invalid(format!("design review: {have} {what} pass the {max} limit `design.configure` keeps")));
|
||||
}
|
||||
}
|
||||
if set_scalar(doc, *prop, value)? {
|
||||
return Ok(*prop == DocProp::Libraries);
|
||||
}
|
||||
|
||||
@@ -34,9 +34,15 @@ pub const COMMENTS: &str = "comments";
|
||||
/// read it).
|
||||
pub const PACKED: &str = "packed";
|
||||
|
||||
/// The word a client puts in its [`Hello::client_version`] when it reads
|
||||
/// [`DocProp::DesignReview`](crate::DocProp::DesignReview): a server keeps review-setting changes
|
||||
/// out of the batches, catch-up deltas and snapshots it sends to clients that don't say so
|
||||
/// (older ones couldn't decode the variant at all).
|
||||
pub const DESIGN_REVIEW: &str = "design-review";
|
||||
|
||||
/// The `client_version` this build announces: its version, then what it reads beyond the protocol.
|
||||
pub fn client_version() -> String {
|
||||
format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED}", env!("CARGO_PKG_VERSION"))
|
||||
format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW}", env!("CARGO_PKG_VERSION"))
|
||||
}
|
||||
|
||||
/// Whether `client_version` announces `word`.
|
||||
@@ -64,6 +70,11 @@ pub fn reads_packed(client_version: &str) -> bool {
|
||||
announces(client_version, PACKED)
|
||||
}
|
||||
|
||||
/// A [`Hello::client_version`] that announces [`DESIGN_REVIEW`].
|
||||
pub fn reads_design_review(client_version: &str) -> bool {
|
||||
announces(client_version, DESIGN_REVIEW)
|
||||
}
|
||||
|
||||
/// Join a file's session.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Hello {
|
||||
|
||||
@@ -291,6 +291,91 @@ fn random_drops_and_reconnects_converge() {
|
||||
assert!(snapshots > 0, "no reconnect needed a snapshot");
|
||||
}
|
||||
|
||||
/// A session saved by a build with larger review limits restores with them clamped. Its saved
|
||||
/// batches still hold the value past the limits, so a resuming client catches up with the
|
||||
/// snapshot: replaying the log would hand it a change this build refuses.
|
||||
#[test]
|
||||
fn a_restored_session_with_clamped_settings_catches_up_by_snapshot() {
|
||||
use crate::change::{Change, DocProp, Json};
|
||||
use figcraft_doc::{DesignReview, MAX_RADII};
|
||||
|
||||
let mut s = Server::new(base(), "tok", Limits::default());
|
||||
let mut a = join(&mut s);
|
||||
// `b` joined but misses the review batch: it resumes from the log, which is where the old
|
||||
// build's over-limit value still sits.
|
||||
let mut b = join(&mut s);
|
||||
let m = edit(&mut a, |d| d.design_review.grid = 8.0).unwrap();
|
||||
let out = s.receive(a.id(), m);
|
||||
deliver(&mut a, &out);
|
||||
b.disconnect();
|
||||
let mut state = s.state().unwrap();
|
||||
assert_eq!(state.log.len(), 1, "the review batch is in the log");
|
||||
|
||||
// An older build wrote more radii than this one keeps, in the snapshot and in the batch.
|
||||
let wide = DesignReview { grid: 8.0, radii: (0..MAX_RADII + 8).map(|i| i as f64).collect(), ..Default::default() };
|
||||
let value = Json::of(&wide).unwrap();
|
||||
for c in state.snapshot.iter_mut().chain(state.log.iter_mut().flat_map(|a| a.changes.iter_mut())) {
|
||||
if let Change::SetDoc { prop: DocProp::DesignReview, value: v } = c {
|
||||
*v = value.clone();
|
||||
}
|
||||
}
|
||||
|
||||
let mut restored = Server::restore(state, "tok", Limits::default()).unwrap();
|
||||
assert_eq!(restored.document().design_review.radii.len(), MAX_RADII, "the snapshot keeps what fits");
|
||||
let ClientMsg::Hello(h) = b.reconnect(hello()) else { panic!() };
|
||||
let (id, out) = restored.join(h).unwrap();
|
||||
assert_eq!(id, b.id(), "a reconnecting client keeps its id");
|
||||
assert!(
|
||||
matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })),
|
||||
"a clamped session hands out the snapshot, not a batch past the limits: {out:?}"
|
||||
);
|
||||
deliver(&mut b, &out);
|
||||
assert_eq!(b.seq(), restored.seq());
|
||||
assert_eq!(b.document().design_review.radii.len(), MAX_RADII, "the client takes what the session has");
|
||||
// The client that already had the batch catches up with the same snapshot, so both sides
|
||||
// agree on the clamped value.
|
||||
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
|
||||
let (_, out) = restored.join(h).unwrap();
|
||||
deliver(&mut a, &out);
|
||||
assert_eq!(a.document(), b.document());
|
||||
}
|
||||
|
||||
/// The same fixture inside the limits keeps resuming from the log: the snapshot catch-up above is
|
||||
/// for settings this build had to change, not for review settings as such.
|
||||
#[test]
|
||||
fn a_restored_session_within_the_limits_resumes_from_the_log() {
|
||||
use crate::change::{Change, DocProp, Json};
|
||||
use figcraft_doc::DesignReview;
|
||||
|
||||
let mut s = Server::new(base(), "tok", Limits::default());
|
||||
let mut a = join(&mut s);
|
||||
let mut b = join(&mut s);
|
||||
let m = edit(&mut a, |d| d.design_review.grid = 8.0).unwrap();
|
||||
let out = s.receive(a.id(), m);
|
||||
deliver(&mut a, &out);
|
||||
b.disconnect();
|
||||
let mut state = s.state().unwrap();
|
||||
let narrow = DesignReview { grid: 8.0, radii: (0..20).map(|i| i as f64).collect(), ..Default::default() };
|
||||
let value = Json::of(&narrow).unwrap();
|
||||
for c in state.snapshot.iter_mut().chain(state.log.iter_mut().flat_map(|a| a.changes.iter_mut())) {
|
||||
if let Change::SetDoc { prop: DocProp::DesignReview, value: v } = c {
|
||||
*v = value.clone();
|
||||
}
|
||||
}
|
||||
|
||||
let mut restored = Server::restore(state, "tok", Limits::default()).unwrap();
|
||||
assert_eq!(restored.document().design_review.radii.len(), 20, "the snapshot needs no clamping");
|
||||
let ClientMsg::Hello(h) = b.reconnect(hello()) else { panic!() };
|
||||
let (_, out) = restored.join(h).unwrap();
|
||||
assert!(
|
||||
matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Delta(_), .. })),
|
||||
"a session that needed no clamping resumes from its log: {out:?}"
|
||||
);
|
||||
deliver(&mut b, &out);
|
||||
assert_eq!(b.seq(), restored.seq());
|
||||
assert_eq!(b.document().design_review.radii.len(), 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_needs_the_issued_secret() {
|
||||
let mut s = Server::new(base(), "tok", Limits { max_peers: 2, ..Limits::default() });
|
||||
|
||||
@@ -72,19 +72,24 @@ impl Replica {
|
||||
|
||||
/// Rebuild a replica from a [`snapshot`](Self::snapshot).
|
||||
pub fn from_snapshot(changes: &[Change]) -> Result<Replica, Error> {
|
||||
Self::from_snapshot_leaving_out(changes).map(|(r, _)| r)
|
||||
Self::from_snapshot_leaving_out(changes).map(|(r, _, _)| r)
|
||||
}
|
||||
|
||||
/// [`from_snapshot`](Self::from_snapshot), and how many image entries it left out: a
|
||||
/// snapshot saved before the image checks may hold one they refuse, and opens without it.
|
||||
pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize), Error> {
|
||||
/// Review settings past the current limits are clamped to them, not dropped (see
|
||||
/// [`docprops::clamp_snapshot_design_review`]); the last value says whether that happened,
|
||||
/// because a session whose settings had to be clamped can no longer replay its saved batches
|
||||
/// for clients that resume (they hold the value past the limits).
|
||||
pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize, bool), Error> {
|
||||
let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() };
|
||||
let mut changes = changes.to_vec();
|
||||
let clamped = docprops::clamp_snapshot_design_review(&mut changes);
|
||||
let left_out = r.apply_kept(&mut changes, Change::is_image)?;
|
||||
if r.doc.pages.is_empty() {
|
||||
return Err(Error::Invalid("a snapshot needs a page".into()));
|
||||
}
|
||||
Ok((r, left_out))
|
||||
Ok((r, left_out, clamped))
|
||||
}
|
||||
|
||||
/// Apply `changes` strictly. When they don't apply together — history written under older
|
||||
|
||||
@@ -8,7 +8,8 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::change::{Change, Entry, Family, Prop, Target};
|
||||
use crate::message::{
|
||||
Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_signals,
|
||||
Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_design_review,
|
||||
reads_signals,
|
||||
};
|
||||
use crate::replica::{Mode, Replica, create_change};
|
||||
use crate::{Error, Limits, docprops, same_secret};
|
||||
@@ -86,6 +87,10 @@ pub struct Server {
|
||||
journal: Option<Vec<Journal>>,
|
||||
/// The connected clients that read signals (cursor chat, spotlight).
|
||||
signals: BTreeSet<u32>,
|
||||
/// The connected clients that read the design review settings (`DocProp::DesignReview`): a
|
||||
/// peer that doesn't announce them can't decode the variant, so the server keeps review
|
||||
/// edits out of everything it sends them.
|
||||
design_review: BTreeSet<u32>,
|
||||
/// Who spotlights now (a newcomer is told).
|
||||
spotlight: Option<u32>,
|
||||
/// Saved history this server restored or replayed left image entries out (or may give a
|
||||
@@ -146,6 +151,7 @@ impl Server {
|
||||
limited: BTreeMap::new(),
|
||||
journal: None,
|
||||
signals: BTreeSet::new(),
|
||||
design_review: BTreeSet::new(),
|
||||
spotlight: None,
|
||||
resync: false,
|
||||
}
|
||||
@@ -169,7 +175,7 @@ impl Server {
|
||||
/// reconnect with their ids). A log that doesn't lead up to the sequence number is dropped
|
||||
/// (clients then catch up with a snapshot).
|
||||
pub fn restore(state: SessionState, token: impl Into<String>, limits: Limits) -> Result<Server, Error> {
|
||||
let (replica, left_out) = Replica::from_snapshot_leaving_out(&state.snapshot)?;
|
||||
let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(&state.snapshot)?;
|
||||
let mut server = Server::new(replica.document().clone(), token, limits);
|
||||
server.state = replica;
|
||||
server.session = state.session;
|
||||
@@ -189,9 +195,11 @@ impl Server {
|
||||
// History saved before the image checks may hold image entries they refuse. The snapshot
|
||||
// opens without them, and a saved log putting images may give a resuming client other
|
||||
// bytes under a key it holds, which this state can't check: either way resuming clients
|
||||
// catch up with the snapshot.
|
||||
// catch up with the snapshot. The same holds for review settings this build had to clamp:
|
||||
// a saved batch still carries the value past the limits, and a resuming client would
|
||||
// refuse it, so the clamped snapshot is what everyone catches up with.
|
||||
let puts_images = state.log.iter().flat_map(|a| &a.changes).any(Change::is_image);
|
||||
server.resync = left_out > 0 || puts_images;
|
||||
server.resync = left_out > 0 || puts_images || review_clamped;
|
||||
if contiguous && state.log.last().is_none_or(|a| a.seq == state.seq) {
|
||||
for a in state.log {
|
||||
server.remember(a);
|
||||
@@ -333,12 +341,16 @@ impl Server {
|
||||
}
|
||||
// The log holds every batch after `floor`.
|
||||
let floor = self.log.front().map_or(self.seq, |a| a.seq.saturating_sub(1));
|
||||
let reads_design_review = reads_design_review(&hello.client_version);
|
||||
let catch_up = match resume {
|
||||
Some(r) if !self.resync && r.seq <= self.seq && r.seq >= floor => {
|
||||
CatchUp::Delta(self.log.iter().filter(|a| a.seq > r.seq).cloned().collect())
|
||||
}
|
||||
_ => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?),
|
||||
};
|
||||
// A peer that doesn't read the review settings can't decode them: its catch-up carries
|
||||
// everything else.
|
||||
let catch_up = filter_catch_up(catch_up, reads_design_review);
|
||||
let (id, secret) = match resume {
|
||||
Some(r) => (r.client_id, *self.secrets.entry(r.client_id).or_insert(r.secret)),
|
||||
None => {
|
||||
@@ -374,9 +386,20 @@ impl Server {
|
||||
} else {
|
||||
self.signals.remove(&id);
|
||||
}
|
||||
if reads_design_review {
|
||||
self.design_review.insert(id);
|
||||
} else {
|
||||
self.design_review.remove(&id);
|
||||
}
|
||||
Ok((id, outs))
|
||||
}
|
||||
|
||||
/// Whether every connected peer reads the design review settings: then a batch goes out as
|
||||
/// one message, the common case.
|
||||
fn everyone_reads_design_review(&self) -> bool {
|
||||
self.peers.keys().all(|id| self.design_review.contains(id))
|
||||
}
|
||||
|
||||
/// Whether `r` may take its client id back: it carries the secret that id was given with, or
|
||||
/// (after a restart, which forgets secrets) a secret for an id nobody is connected as.
|
||||
fn may_resume(&self, r: &Resume) -> bool {
|
||||
@@ -393,6 +416,7 @@ impl Server {
|
||||
self.acked.remove(&id);
|
||||
self.limited.remove(&id);
|
||||
self.signals.remove(&id);
|
||||
self.design_review.remove(&id);
|
||||
if self.spotlight == Some(id) {
|
||||
self.spotlight = None;
|
||||
}
|
||||
@@ -430,7 +454,7 @@ impl Server {
|
||||
let acc = Accepted { seq: self.seq, author: from, batch_id, changes };
|
||||
self.remember(acc.clone());
|
||||
self.note(Journal::Accepted(acc.clone()));
|
||||
vec![Outgoing::All(ServerMsg::Changes(acc))]
|
||||
self.relay_changes(acc)
|
||||
}
|
||||
Err(e) => {
|
||||
self.note(Journal::Refused { client: from, batch_id });
|
||||
@@ -482,6 +506,31 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send an accepted batch to every connected peer. A peer that doesn't read the review
|
||||
/// settings can't decode them, so it gets the same batch (its seq, batch id and the peer's
|
||||
/// own accounting included) with those edits left out and everything else in order.
|
||||
fn relay_changes(&self, acc: Accepted) -> Vec<Outgoing> {
|
||||
if !acc.changes.iter().any(Change::is_design_review) || self.everyone_reads_design_review() {
|
||||
return vec![Outgoing::All(ServerMsg::Changes(acc))];
|
||||
}
|
||||
// Every peer hears the batch, even one with nothing left for it: the batch still carries
|
||||
// the next sequence number, and a peer that skipped it would reject its next ordinary
|
||||
// batch as out of order.
|
||||
self.peers
|
||||
.keys()
|
||||
.copied()
|
||||
.map(|id| {
|
||||
if self.design_review.contains(&id) || id == acc.author {
|
||||
Outgoing::To(id, ServerMsg::Changes(acc.clone()))
|
||||
} else {
|
||||
let mut filtered = acc.clone();
|
||||
filtered.changes = Change::without_design_review(filtered.changes);
|
||||
Outgoing::To(id, ServerMsg::Changes(filtered))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Client `from` is called `name` from now on (cleaned): everyone, itself too, hears it as its
|
||||
/// `PeerJoined`, and newcomers' welcomes list it so.
|
||||
fn rename(&mut self, from: u32, name: String) -> Vec<Outgoing> {
|
||||
@@ -704,3 +753,23 @@ pub fn weight(changes: &[Change]) -> usize {
|
||||
})
|
||||
.fold(0, usize::saturating_add)
|
||||
}
|
||||
|
||||
/// A catch-up a peer that doesn't read the design review settings can decode: the review-setting
|
||||
/// edits are left out of a delta and out of a snapshot, everything else as it was.
|
||||
fn filter_catch_up(cu: CatchUp, reads_design_review: bool) -> CatchUp {
|
||||
if reads_design_review {
|
||||
return cu;
|
||||
}
|
||||
match cu {
|
||||
CatchUp::Delta(list) => CatchUp::Delta(
|
||||
list.into_iter()
|
||||
.map(|mut a| {
|
||||
a.changes = Change::without_design_review(a.changes);
|
||||
a
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
CatchUp::Snapshot(changes) => CatchUp::Snapshot(Change::without_design_review(changes)),
|
||||
packed => packed,
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
use figcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use crate::change::{Change, Entry, Json, Prop};
|
||||
use crate::message::{ClientMsg, Hello, PROTOCOL, Presence, ServerMsg};
|
||||
use crate::change::{Change, DocProp, Entry, Json, Prop};
|
||||
use crate::message::{CatchUp, ClientMsg, Hello, PROTOCOL, Presence, ServerMsg, client_version, reads_design_review};
|
||||
use crate::replica::Mode;
|
||||
use crate::{Client, Limits, NoRecompute, Outgoing, Server};
|
||||
|
||||
@@ -39,6 +39,22 @@ fn for_client(out: &[Outgoing], to: u32) -> Vec<ServerMsg> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A hello whose `client_version` says exactly `version` (what an older or newer build announces).
|
||||
fn hello_of(version: &str) -> Hello {
|
||||
Hello { client_version: version.to_string(), ..hello("tok") }
|
||||
}
|
||||
|
||||
/// The changes an `Accepted` relay or catch-up carries, or none.
|
||||
fn accepted_changes(msgs: &[ServerMsg]) -> Vec<&Change> {
|
||||
msgs.iter()
|
||||
.filter_map(|m| match m {
|
||||
ServerMsg::Changes(a) => Some(a.changes.iter().collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn edit(c: &mut Client, f: impl FnOnce(&mut Document)) -> ClientMsg {
|
||||
let mut d = c.document().clone();
|
||||
f(&mut d);
|
||||
@@ -364,3 +380,177 @@ fn junk_batches_never_panic_and_never_corrupt_the_document() {
|
||||
assert!(s.document().validate().is_empty(), "{:?}", s.document().validate());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_version_announces_the_design_review() {
|
||||
assert!(reads_design_review(&client_version()));
|
||||
assert!(!reads_design_review("0.18.0 signals hosting comments packed"));
|
||||
}
|
||||
|
||||
/// A capable editor, a peer built before the review existed, and a mixed batch: the old peer
|
||||
/// hears the same batch without the review-setting edit, the new peer hears it whole.
|
||||
#[test]
|
||||
fn a_review_edit_reaches_only_the_peers_that_read_it() {
|
||||
let (d, _, _) = doc();
|
||||
let mut s = Server::new(d, "tok", Limits::default());
|
||||
let capable = join(&mut s);
|
||||
let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap();
|
||||
let old = {
|
||||
let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") };
|
||||
Client::join(welcome).unwrap()
|
||||
};
|
||||
assert_eq!(old.id(), old_id);
|
||||
|
||||
// One batch: rename the document (everyone) and set the review grid (capable peers only).
|
||||
let batch = vec![
|
||||
Change::SetDoc { prop: DocProp::Name, value: Json::of("Renamed").unwrap() },
|
||||
Change::SetDoc { prop: DocProp::DesignReview, value: Json(serde_json::json!({"preset": "strict", "grid": 8.0})) },
|
||||
];
|
||||
let out = s.receive(capable.id(), ClientMsg::Changes { base_seq: s.seq(), batch_id: 1, changes: batch });
|
||||
let for_old = for_client(&out, old.id());
|
||||
assert!(accepted_changes(&for_old).iter().all(|c| !c.is_design_review()), "the old peer's copy carries no review edit: {:?}", for_old);
|
||||
assert!(
|
||||
accepted_changes(&for_old).iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })),
|
||||
"the old peer still hears the rename: {:?}",
|
||||
for_old
|
||||
);
|
||||
let for_new = for_client(&out, capable.id());
|
||||
assert_eq!(accepted_changes(&for_new).len(), 2, "the capable peer hears both: {for_new:?}");
|
||||
|
||||
// A capable newcomer's catch-up (a fresh join, so a snapshot) carries the settings.
|
||||
let (_, out) = s.join(hello("tok")).unwrap();
|
||||
let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) =
|
||||
out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. })))
|
||||
else {
|
||||
panic!("no welcome");
|
||||
};
|
||||
let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") };
|
||||
assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "{changes:?}");
|
||||
|
||||
// An old newcomer's catch-up carries none, and still has the rename.
|
||||
let (_, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap();
|
||||
let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) =
|
||||
out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. })))
|
||||
else {
|
||||
panic!("no welcome");
|
||||
};
|
||||
let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") };
|
||||
assert!(changes.iter().all(|c| !c.is_design_review()), "{changes:?}");
|
||||
assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), "{changes:?}");
|
||||
}
|
||||
|
||||
/// A review-only batch advances the server sequence for every peer. An older peer must still be
|
||||
/// sent the accepted batch, empty as it is, or it falls a sequence behind and refuses what
|
||||
/// follows.
|
||||
#[test]
|
||||
fn a_review_only_batch_keeps_an_older_peer_in_step() {
|
||||
let (d, _, frame) = doc();
|
||||
let mut s = Server::new(d, "tok", Limits::default());
|
||||
let mut capable = join(&mut s);
|
||||
let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap();
|
||||
let mut old = {
|
||||
let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") };
|
||||
Client::join(welcome).unwrap()
|
||||
};
|
||||
assert_eq!(old.id(), old_id);
|
||||
|
||||
// Only the review settings change, so this batch has nothing for the older peer.
|
||||
let msg = edit(&mut capable, |d| d.design_review.grid = 8.0);
|
||||
let ClientMsg::Changes { changes, .. } = &msg else { panic!("not a batch") };
|
||||
assert!(!changes.is_empty() && changes.iter().all(Change::is_design_review), "review only: {changes:?}");
|
||||
let out = s.receive(capable.id(), msg);
|
||||
assert_eq!(s.seq(), 1);
|
||||
let to_old = for_client(&out, old.id());
|
||||
let empty = to_old.iter().any(|m| matches!(m, ServerMsg::Changes(a) if a.changes.is_empty()));
|
||||
assert!(empty, "the older peer is told the batch happened: {to_old:?}");
|
||||
for m in for_client(&out, capable.id()) {
|
||||
capable.receive(m, &NoRecompute).unwrap();
|
||||
}
|
||||
for m in to_old {
|
||||
old.receive(m, &NoRecompute).unwrap();
|
||||
}
|
||||
assert_eq!(old.seq(), s.seq());
|
||||
|
||||
// The next ordinary edit still lands for it.
|
||||
let msg = edit(&mut capable, |d| {
|
||||
d.create(frame, NodeKind::Rectangle, "After", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
});
|
||||
let out = s.receive(capable.id(), msg);
|
||||
for m in for_client(&out, capable.id()) {
|
||||
capable.receive(m, &NoRecompute).unwrap();
|
||||
}
|
||||
for m in for_client(&out, old.id()) {
|
||||
old.receive(m, &NoRecompute).unwrap();
|
||||
}
|
||||
assert_eq!(old.seq(), s.seq());
|
||||
assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(1), "the new node is there");
|
||||
}
|
||||
|
||||
/// The same batch through the other catch-up path: a peer that was away comes back with a delta,
|
||||
/// and the review-only batch is there as an accepted batch with nothing in it for it, so its
|
||||
/// sequence carries on and the edits after it apply.
|
||||
#[test]
|
||||
fn a_review_only_batch_is_an_empty_delta_for_a_peer_that_was_away() {
|
||||
let (d, _, frame) = doc();
|
||||
let mut s = Server::new(d, "tok", Limits::default());
|
||||
let mut capable = join(&mut s);
|
||||
let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap();
|
||||
let mut old = {
|
||||
let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") };
|
||||
Client::join(welcome).unwrap()
|
||||
};
|
||||
assert_eq!(old.id(), old_id);
|
||||
|
||||
// One ordinary edit, so the peer's resume point sits before the review-only batch.
|
||||
let msg = edit(&mut capable, |d| {
|
||||
d.create(frame, NodeKind::Rectangle, "Before", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
});
|
||||
let out = s.receive(capable.id(), msg);
|
||||
for m in for_client(&out, capable.id()) {
|
||||
capable.receive(m, &NoRecompute).unwrap();
|
||||
}
|
||||
for m in for_client(&out, old.id()) {
|
||||
old.receive(m, &NoRecompute).unwrap();
|
||||
}
|
||||
assert_eq!(old.seq(), 1);
|
||||
|
||||
// It drops; only the review settings change while it is away.
|
||||
old.disconnect();
|
||||
let msg = edit(&mut capable, |d| d.design_review.grid = 8.0);
|
||||
let out = s.receive(capable.id(), msg);
|
||||
for m in for_client(&out, capable.id()) {
|
||||
capable.receive(m, &NoRecompute).unwrap();
|
||||
}
|
||||
assert_eq!(s.seq(), 2);
|
||||
|
||||
// It comes back: the delta holds the batch, empty, and its sequence carries on.
|
||||
let ClientMsg::Hello(h) = old.reconnect(hello_of("0.18.0 signals hosting comments packed")) else {
|
||||
panic!("not a hello");
|
||||
};
|
||||
let (id, out) = s.join(h).unwrap();
|
||||
assert_eq!(id, old.id());
|
||||
let welcome = out
|
||||
.into_iter()
|
||||
.find_map(|o| match o {
|
||||
Outgoing::To(to, w @ ServerMsg::Welcome { .. }) if to == id => Some(w),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("no welcome"));
|
||||
assert!(
|
||||
matches!(&welcome, ServerMsg::Welcome { catch_up: CatchUp::Delta(list), .. } if list.len() == 1 && list[0].changes.is_empty()),
|
||||
"{welcome:?}"
|
||||
);
|
||||
old.receive(welcome, &NoRecompute).unwrap();
|
||||
assert_eq!(old.seq(), s.seq());
|
||||
|
||||
// And the next ordinary edit still applies.
|
||||
let msg = edit(&mut capable, |d| {
|
||||
d.create(frame, NodeKind::Rectangle, "After", 0.0, 20.0, 10.0, 10.0).unwrap();
|
||||
});
|
||||
let out = s.receive(capable.id(), msg);
|
||||
for m in for_client(&out, old.id()) {
|
||||
old.receive(m, &NoRecompute).unwrap();
|
||||
}
|
||||
assert_eq!(old.seq(), s.seq());
|
||||
assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(2), "both nodes are there");
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! The design system a file's review follows: how strict it is, the spacing grid, the radii it
|
||||
//! accepts and the brand accents it knows (`design.configure`).
|
||||
//!
|
||||
//! Kept in the document, so a file carries its settings for everyone who opens it, and the audit,
|
||||
//! the fixer and CI all read the same values.
|
||||
|
||||
use figcraft_color::Color;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How strict `design.audit` is.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum DesignPreset {
|
||||
/// The rules that catch the usual AI-generated tells.
|
||||
#[default]
|
||||
Recommended,
|
||||
/// Recommended plus the judgment calls (too many accent colours, frames without auto layout).
|
||||
Strict,
|
||||
/// Only the findings that keep a design usable: contrast, the type floor, gradient text and
|
||||
/// clipped text.
|
||||
Accessibility,
|
||||
}
|
||||
|
||||
impl DesignPreset {
|
||||
pub const ALL: [Self; 3] = [Self::Recommended, Self::Strict, Self::Accessibility];
|
||||
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Recommended => "recommended",
|
||||
Self::Strict => "strict",
|
||||
Self::Accessibility => "accessibility",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(s: &str) -> Option<Self> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"recommended" | "default" => Some(Self::Recommended),
|
||||
"strict" => Some(Self::Strict),
|
||||
"accessibility" | "a11y" => Some(Self::Accessibility),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest and largest spacing grid a file may set.
|
||||
pub const GRID_MIN: f64 = 1.0;
|
||||
pub const GRID_MAX: f64 = 64.0;
|
||||
|
||||
/// Most radii and brand colours a file keeps.
|
||||
pub const MAX_RADII: usize = 32;
|
||||
pub const MAX_BRAND_COLORS: usize = 32;
|
||||
|
||||
/// Most rules a file turns off. The rule catalog is smaller than this: the cap keeps a hand-edited
|
||||
/// or older file from carrying thousands of ids every review would read.
|
||||
pub const MAX_DISABLED: usize = 64;
|
||||
|
||||
/// A file's design review settings. The default is the recommended preset on a 4px grid with the
|
||||
/// 4px radius scale and no brand palette.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DesignReview {
|
||||
pub preset: DesignPreset,
|
||||
/// The spacing and radius grid in pixels (`0`: 4). A value outside [`GRID_MIN`]..=[`GRID_MAX`]
|
||||
/// reads as the default.
|
||||
pub grid: f64,
|
||||
/// The corner radii the design uses, in pixels. Empty: any multiple of the grid from the grid
|
||||
/// up, or a pill.
|
||||
pub radii: Vec<f64>,
|
||||
/// The brand's accent colours: they don't count as stray accents (`color.accents`).
|
||||
pub brand: Vec<Color>,
|
||||
/// Rule ids this file turns off.
|
||||
pub disabled: Vec<String>,
|
||||
}
|
||||
|
||||
impl DesignReview {
|
||||
/// Whether the settings are the default ones (nothing to save).
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
|
||||
/// The grid in pixels, with invalid values read as 4.
|
||||
pub fn grid(&self) -> f64 {
|
||||
if self.grid.is_finite() && (GRID_MIN..=GRID_MAX).contains(&self.grid) { self.grid } else { 4.0 }
|
||||
}
|
||||
|
||||
/// The lists that hold more than this build keeps, as `(what, how many, the cap)`. Sharing a
|
||||
/// file with any of these is refused (`collab.share`), an arriving edit is refused
|
||||
/// (`figcraft_collab`), and a saved snapshot opens with what fits instead.
|
||||
pub fn over_limits(&self) -> Vec<(&'static str, usize, usize)> {
|
||||
[
|
||||
("corner radii", self.radii.len(), MAX_RADII),
|
||||
("brand colours", self.brand.len(), MAX_BRAND_COLORS),
|
||||
("disabled rules", self.disabled.len(), MAX_DISABLED),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(_, have, max)| have > max)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn presets_round_trip_by_id() {
|
||||
for p in DesignPreset::ALL {
|
||||
assert_eq!(DesignPreset::from_id(p.id()), Some(p));
|
||||
}
|
||||
assert_eq!(DesignPreset::from_id("a11y"), Some(DesignPreset::Accessibility));
|
||||
assert_eq!(DesignPreset::from_id("loud"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_file_does_not_serialize_the_settings_and_junk_grid_reads_as_four() {
|
||||
let doc = crate::Document::new("Untitled");
|
||||
let json = serde_json::to_value(&doc).unwrap();
|
||||
assert!(json.get("designReview").is_none(), "{json}");
|
||||
let mut settings = DesignReview::default();
|
||||
assert!(settings.is_default());
|
||||
settings.grid = -3.0;
|
||||
assert_eq!(settings.grid(), 4.0);
|
||||
settings.grid = f64::NAN;
|
||||
assert_eq!(settings.grid(), 4.0);
|
||||
settings.grid = 8.0;
|
||||
assert_eq!(settings.grid(), 8.0);
|
||||
assert!(!settings.is_default());
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ mod board_mindmap;
|
||||
mod board_route;
|
||||
pub mod colors;
|
||||
pub mod comments;
|
||||
pub mod design_review;
|
||||
pub mod facilitation;
|
||||
pub mod geometry;
|
||||
pub mod handoff;
|
||||
@@ -34,6 +35,7 @@ pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES,
|
||||
pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points};
|
||||
pub use colors::*;
|
||||
pub use comments::*;
|
||||
pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_DISABLED, MAX_RADII};
|
||||
pub use facilitation::*;
|
||||
pub use figcraft_color as color;
|
||||
pub use figcraft_geom as geom;
|
||||
@@ -233,6 +235,9 @@ pub struct Document {
|
||||
/// Image adjustment presets saved in this file.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub image_presets: Vec<ImagePreset>,
|
||||
/// The design system and rules this file's review follows (`design.configure`).
|
||||
#[serde(default, skip_serializing_if = "DesignReview::is_default")]
|
||||
pub design_review: DesignReview,
|
||||
/// Annotation categories (`None`: [`AnnotationCategory::defaults`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub annotation_categories: Option<Vec<AnnotationCategory>>,
|
||||
@@ -289,6 +294,7 @@ impl Document {
|
||||
published: None,
|
||||
color_profile: ColorProfile::Srgb,
|
||||
image_presets: Vec::new(),
|
||||
design_review: DesignReview::default(),
|
||||
annotation_categories: None,
|
||||
dev_snapshots: BTreeMap::new(),
|
||||
timer: None,
|
||||
|
||||
@@ -250,6 +250,15 @@ pub struct CodeLink {
|
||||
pub name: String,
|
||||
/// The snippet with `{property}` and `{property ? "a" : "b"}` placeholders.
|
||||
pub template: String,
|
||||
/// Where the code component lives, relative to the code repository.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub source: String,
|
||||
/// What a property's design values are called in code: property → design value → code value.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub values: BTreeMap<String, BTreeMap<String, String>>,
|
||||
/// Notes for whoever uses the component.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub notes: String,
|
||||
}
|
||||
|
||||
/// A dev resource: a link for developers attached to a layer. The URL is data only: it is shown
|
||||
|
||||
@@ -338,6 +338,8 @@ pub fn prop_default_value(d: &PropDef) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod nested_binding_tests;
|
||||
#[cfg(test)]
|
||||
mod rebase_source_tests;
|
||||
|
||||
|
||||
@@ -35,6 +35,38 @@ pub(super) fn bindings_of<'a>(n: &'a Node, g: &'a str) -> impl Iterator<Item = (
|
||||
n.bound.iter().filter(move |(k, _)| binding_group(k) == Some(g))
|
||||
}
|
||||
|
||||
/// Whether `n` binds group `g` to other variables than `src` does. Keys are compared by what they
|
||||
/// bind, so `fill` and `fills/0/color` are the same binding.
|
||||
pub(super) fn bound_differently(n: &Node, src: &Node, g: &str) -> bool {
|
||||
let canonical = |m: &Node| -> std::collections::BTreeSet<(String, String)> {
|
||||
bindings_of(m, g)
|
||||
.map(|(k, v)| {
|
||||
let key = crate::cmd::lists::list_binding(k).map_or_else(|| k.clone(), |(l, i, f)| format!("{}/{i}/{f}", l.prefix()));
|
||||
(key, v.clone())
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
canonical(n) != canonical(src)
|
||||
}
|
||||
|
||||
/// The property groups whose variable bindings differ between layer `n` and its main layer `src`:
|
||||
/// overrides even where both resolve to the same value.
|
||||
pub(super) fn rebound_groups(n: &Node, src: &Node) -> Vec<&'static str> {
|
||||
let mut compared = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for k in n.bound.keys().chain(src.bound.keys()) {
|
||||
let Some(g) = binding_group(k) else { continue };
|
||||
if compared.contains(&g) {
|
||||
continue;
|
||||
}
|
||||
compared.push(g);
|
||||
if bound_differently(n, src, g) {
|
||||
out.push(g);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Property groups that differ between two versions of a node.
|
||||
pub fn diff_groups(a: &Node, b: &Node) -> Vec<&'static str> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
use serde_json::json;
|
||||
|
||||
use super::rebase_instance;
|
||||
use super::tests::{button, copy_of, ex, fill, idv, node};
|
||||
use crate::{NodeId, Session};
|
||||
|
||||
fn bound_shape_in_button() -> (Session, NodeId, NodeId, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
let (_, shape, button, nested) = button(&mut s);
|
||||
ex(&mut s, "variable.createCollection", json!({"name": "T"}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "T", "name": "ink", "type": "color", "value": "#111111"}));
|
||||
let inner = copy_of(&s, nested, shape);
|
||||
ex(&mut s, "variable.bind", json!({"ids": [inner.0], "field": "fill", "variable": "ink"}));
|
||||
assert!(node(&s, inner).overrides.contains("fills"));
|
||||
(s, shape, button, nested, inner)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relinking_an_instance_keeps_a_binding_its_main_lacks_as_an_override() {
|
||||
let (mut s, shape, button, nested, inner) = bound_shape_in_button();
|
||||
let doc = s.ds_mut().unwrap().doc_mut();
|
||||
doc.get_mut(inner).unwrap().overrides.clear();
|
||||
rebase_instance(doc, nested);
|
||||
assert!(node(&s, inner).overrides.contains("fills"), "the same colour from a variable the main doesn't bind");
|
||||
ex(&mut s, "node.set", json!({"id": shape, "props": {"fill": "#FF0000"}}));
|
||||
assert_eq!(fill(&s, inner), "111111", "an edit of the icon's main leaves the bound colour");
|
||||
let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400})));
|
||||
let copy = copy_of(&s, placed, inner);
|
||||
assert_eq!(node(&s, copy).bound.values().collect::<Vec<_>>(), [&node(&s, inner).bound["fill"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hiding_and_showing_a_bound_fill_keeps_its_override() {
|
||||
let (mut s, _, _, _, inner) = bound_shape_in_button();
|
||||
ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": false}));
|
||||
ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": true}));
|
||||
let n = node(&s, inner);
|
||||
assert!(n.bound.contains_key("fill"));
|
||||
assert!(n.overrides.contains("fills"), "the binding still differs from the main's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_level_instance_s_own_resizing_binding_is_not_an_override() {
|
||||
let mut s = Session::new();
|
||||
let (_, _, button, _) = button(&mut s);
|
||||
let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400})));
|
||||
let doc = s.ds_mut().unwrap().doc_mut();
|
||||
doc.get_mut(placed).unwrap().bound.insert("minWidth".into(), "VariableID:1:1".into());
|
||||
rebase_instance(doc, placed);
|
||||
assert!(!node(&s, placed).overrides.contains("resizing"), "a top-level instance's resizing is its own");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::diff::{binding_group, bindings_of, diff_groups, follow_boolean_defaults, geometry_derived, variable_groups};
|
||||
use super::diff::{binding_group, bound_differently, diff_groups, follow_boolean_defaults, geometry_derived, rebound_groups, variable_groups};
|
||||
use super::guard::{own_slot_content, relink_copy};
|
||||
use super::instances::{copy_group, field_group, sync_instance};
|
||||
use super::sync::insert_linked;
|
||||
@@ -179,12 +179,17 @@ fn override_groups(doc: &Document, before: &Document, id: NodeId, n: &Node, b: &
|
||||
// Binding another variable (or none) where the main binds one is an override.
|
||||
for (k, _) in b.bound.iter().chain(n.bound.iter()) {
|
||||
let Some(g) = binding_group(k) else { continue };
|
||||
let rebound = b.bound.get(k) != n.bound.get(k) && !bindings_of(n, g).eq(bindings_of(src, g));
|
||||
let rebound = b.bound.get(k) != n.bound.get(k) && bound_differently(n, src, g);
|
||||
if rebound && !groups.contains(&g) {
|
||||
groups.push(g);
|
||||
}
|
||||
}
|
||||
cleared = raw.iter().filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && n.overrides.contains(**g)).copied().collect();
|
||||
let rebound = rebound_groups(n, src);
|
||||
cleared = raw
|
||||
.iter()
|
||||
.filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && !rebound.contains(g) && n.overrides.contains(**g))
|
||||
.copied()
|
||||
.collect();
|
||||
if top_root {
|
||||
cleared.retain(|g| !matches!(*g, "component" | "props"));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::diff::{diff_groups, variable_groups};
|
||||
use super::diff::{diff_groups, rebound_groups, variable_groups};
|
||||
use super::instances::{field_group, path_map};
|
||||
use super::{BTreeMap, BTreeSet, Document, MAX_DEPTH, Node, NodeId, NodeKind, default_instance_name, holds_content};
|
||||
|
||||
@@ -216,6 +216,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa
|
||||
let mut bound: Vec<&str> = m.prop_refs.keys().map(|f| field_group(f)).collect();
|
||||
bound.extend(variable_groups(n, m));
|
||||
overrides.extend(value_groups(m, n).into_iter().filter(|g| !bound.contains(&g.as_str())));
|
||||
overrides.extend(rebound_groups(n, m).into_iter().map(str::to_string));
|
||||
if matches!((&m.kind, &n.kind), (NodeKind::Instance { component: a, .. }, NodeKind::Instance { component: b, .. }) if a != b) {
|
||||
overrides.insert("component".into());
|
||||
}
|
||||
@@ -233,6 +234,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa
|
||||
let mut groups: Vec<String> = value_groups(m, n)
|
||||
.into_iter()
|
||||
.filter(|g| !matches!(g.as_str(), "name" | "exports" | "interactions") && !from_variables.contains(&g.as_str()))
|
||||
.chain(rebound_groups(n, m).into_iter().map(str::to_string))
|
||||
.filter(|g| placed_source.is_some() || !matches!(g.as_str(), "resizing" | "modes"))
|
||||
.collect();
|
||||
let named = if placed_source.is_some() { n.name != m.name } else { n.name != default_instance_name(doc, component) };
|
||||
|
||||
@@ -115,9 +115,65 @@ fn match_layers(
|
||||
}
|
||||
m.map.insert(*s, nid);
|
||||
}
|
||||
match_text_by_name(doc, inst, component, src, old, &mut m);
|
||||
m
|
||||
}
|
||||
|
||||
/// Main text layers nothing matched take the unmatched old text layer of the same name, when
|
||||
/// exactly one of each has it: text typed into an instance stays when it switches to a variant that
|
||||
/// nests the same text layer in other frames (its name path differs). Only layers outside nested
|
||||
/// instances, which rebuild from their own mains. Names are counted over all those text layers,
|
||||
/// matched ones too, so a name two layers share on either side never pairs by elimination.
|
||||
fn match_text_by_name(
|
||||
doc: &Document,
|
||||
inst: NodeId,
|
||||
component: NodeId,
|
||||
src: &[NodeId],
|
||||
old: &BTreeMap<NodeId, std::sync::Arc<Node>>,
|
||||
m: &mut Matched,
|
||||
) {
|
||||
fn unique<K: Ord>(pairs: impl Iterator<Item = (K, NodeId)>) -> BTreeMap<K, NodeId> {
|
||||
let mut seen: BTreeMap<K, Option<NodeId>> = BTreeMap::new();
|
||||
for (k, id) in pairs {
|
||||
seen.entry(k).and_modify(|e| *e = None).or_insert(Some(id));
|
||||
}
|
||||
seen.into_iter().filter_map(|(k, id)| Some((k, id?))).collect()
|
||||
}
|
||||
let text = |n: &Node| matches!(n.kind, NodeKind::Text(_));
|
||||
let mut mains =
|
||||
unique(src.iter().filter_map(|s| doc.node(*s)).filter(|s| text(s) && outside_nested(doc, s.id, component)).map(|s| (s.name.clone(), s.id)));
|
||||
mains.retain(|_, s| m.fresh.contains(s));
|
||||
if mains.is_empty() {
|
||||
return;
|
||||
}
|
||||
let olds = unique(
|
||||
old.iter()
|
||||
.filter(|(id, o)| text(o) && outside_nested(doc, **id, inst))
|
||||
.map(|(id, o)| (o.source.and_then(|s| doc.node(s)).map_or(&o.name, |s| &s.name).clone(), *id)),
|
||||
);
|
||||
for (name, s) in mains {
|
||||
if let Some(o) = olds.get(&name).filter(|o| !m.used.contains(*o)) {
|
||||
m.used.insert(*o);
|
||||
m.map.insert(s, *o);
|
||||
m.fresh.retain(|f| *f != s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether layer `id` is below `root` with no instance between them.
|
||||
fn outside_nested(doc: &Document, id: NodeId, root: NodeId) -> bool {
|
||||
let mut cur = doc.node(id).and_then(|n| n.parent);
|
||||
for _ in 0..=1_000_000 {
|
||||
match cur.and_then(|c| doc.node(c)) {
|
||||
Some(n) if n.id == root => return true,
|
||||
Some(n) if matches!(n.kind, NodeKind::Instance { .. }) => return false,
|
||||
Some(n) => cur = n.parent,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A rebuild's copies of the main's layers, pre-order (parents first).
|
||||
struct Copies {
|
||||
nodes: Vec<Node>,
|
||||
|
||||
@@ -282,6 +282,50 @@ fn variant_switch_keeps_compatible_overrides() {
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_text_stays_across_variants_that_nest_it_differently() {
|
||||
let mut s = Session::new();
|
||||
// Each variant's Label layers, by the frames holding them.
|
||||
let shapes: [(&str, &[&[&str]]); 4] =
|
||||
[("Kind=Plain", &[&["text"]]), ("Kind=Boxed", &[&["div", "text"]]), ("Kind=Twice", &[&["a"], &["b"]]), ("Kind=Moved", &[&["a"], &["c"]])];
|
||||
let mut labels = Vec::new();
|
||||
let mut variants = Vec::new();
|
||||
for (k, (name, paths)) in shapes.into_iter().enumerate() {
|
||||
let v = idv(&ex(&mut s, "frame.create", json!({"x": k as f64 * 300.0, "y": 0, "width": 200, "height": 60, "name": name})));
|
||||
for frames in paths {
|
||||
let mut parent = v;
|
||||
for f in *frames {
|
||||
parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "parent": parent, "name": f})));
|
||||
}
|
||||
labels.push(idv(&ex(&mut s, "text.create", json!({"text": "I agree", "x": 0, "y": 0, "parent": parent, "props": {"name": "Label"}}))));
|
||||
}
|
||||
variants.push(idv(&ex(&mut s, "component.create", json!({"ids": [v]}))));
|
||||
}
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
|
||||
let i = idv(&ex(&mut s, "instance.create", json!({"component": variants[0], "x": 0, "y": 300})));
|
||||
let typed = copy_of(&s, i, labels[0]);
|
||||
ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"}));
|
||||
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Boxed"}}));
|
||||
healthy(&s);
|
||||
assert_eq!(chars(&s, copy_of(&s, i, labels[1])), "Architect", "one frame deeper, same name");
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Plain"}}));
|
||||
assert_eq!(chars(&s, copy_of(&s, i, labels[0])), "Architect", "and back");
|
||||
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Twice"}}));
|
||||
healthy(&s);
|
||||
let texts: Vec<String> = labels[2..4].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect();
|
||||
assert_eq!(texts, ["I agree", "I agree"], "two layers of that name: neither is the one typed into");
|
||||
|
||||
// `a › Label` matches by path; the leftover `b › Label` and `c › Label` still share a name with it.
|
||||
let typed = copy_of(&s, i, labels[3]);
|
||||
ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"}));
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Moved"}}));
|
||||
healthy(&s);
|
||||
let texts: Vec<String> = labels[4..].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect();
|
||||
assert_eq!(texts, ["I agree", "I agree"], "a name two layers share doesn't pair what path matching left over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detach_keeps_the_look() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -1422,25 +1422,7 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
|
||||
remote.extend(merge_components(doc, src, &BTreeMap::new(), Some(&foreign))?);
|
||||
}
|
||||
// Components `src` publishes: from its library.
|
||||
if let Some(lib) = src.published.as_ref().filter(|l| own.as_deref() != Some(l.manifest.id.as_str())) {
|
||||
let keys: Vec<NodeId> =
|
||||
roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect();
|
||||
if !keys.is_empty() {
|
||||
remote.extend(import(doc, lib, &keys, false)?);
|
||||
let m = &lib.manifest;
|
||||
if doc.libraries.link(&m.id).is_none()
|
||||
&& let Some(path) = src_path
|
||||
{
|
||||
doc.libraries_mut().enabled.push(LibraryLink {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
path: path.to_string(),
|
||||
version: m.version,
|
||||
relative: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
remote.extend(from_published(doc, src, src_path, &roots)?);
|
||||
// Point the pasted layers at those mains; what stays behind gets ids of its own.
|
||||
let mut behind: BTreeMap<NodeId, NodeId> = BTreeMap::new();
|
||||
let mut follow = |doc: &mut Document, id: NodeId| -> NodeId {
|
||||
@@ -1479,6 +1461,45 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `doc`'s copies of the components among `roots` (assets of `src`) that `src` publishes as a
|
||||
/// library (`src`'s ids → `doc`'s), taken from that library, which gets enabled in `doc` when `src`
|
||||
/// is saved at `src_path`. Empty when `src` publishes no library, or publishes `doc`'s own.
|
||||
fn from_published(doc: &mut Document, src: &Document, src_path: Option<&str>, roots: &[NodeId]) -> Result<BTreeMap<NodeId, NodeId>> {
|
||||
let own = doc.published.as_ref().map(|p| p.manifest.id.as_str());
|
||||
let Some(lib) = src.published.as_ref().filter(|l| own != Some(l.manifest.id.as_str())) else { return Ok(BTreeMap::new()) };
|
||||
let keys: Vec<NodeId> =
|
||||
roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect();
|
||||
if keys.is_empty() {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let remote = import(doc, lib, &keys, false)?;
|
||||
let m = &lib.manifest;
|
||||
if doc.libraries.link(&m.id).is_none()
|
||||
&& let Some(path) = src_path
|
||||
{
|
||||
doc.libraries_mut().enabled.push(LibraryLink {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
path: path.to_string(),
|
||||
version: m.version,
|
||||
relative: String::new(),
|
||||
});
|
||||
}
|
||||
Ok(remote)
|
||||
}
|
||||
|
||||
/// The main in `doc` that pasting main component `main`, copied from another document `src`,
|
||||
/// makes an instance of: `doc`'s copy of it from the library `src` publishes, as
|
||||
/// [`adopt_pasted`] uses for instances. `None` when `src` doesn't offer it, so the paste copies
|
||||
/// the main itself: also when the library holds it only because an offered component uses it.
|
||||
pub fn published_main(doc: &mut Document, src: &Document, src_path: Option<&str>, main: NodeId) -> Result<Option<NodeId>> {
|
||||
let Some(root) = asset_root(src, main) else { return Ok(None) };
|
||||
if !src.published.as_ref().and_then(|l| l.manifest.component(root)).is_some_and(|a| a.published) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(from_published(doc, src, src_path, &[root])?.get(&main).copied())
|
||||
}
|
||||
|
||||
/// Refuse edits of library copies, except by library commands (and imports of other files,
|
||||
/// which bring their copies along).
|
||||
pub fn check_read_only(cmd: &str, before: &Document, after: &Document) -> std::result::Result<(), String> {
|
||||
|
||||
@@ -695,3 +695,72 @@ fn library_links_follow_a_moved_folder() {
|
||||
link_found(&mut s, &lid);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A main component copied from a library file and pasted into another file is an instance of it
|
||||
/// from that library, which gets enabled, as pasting an instance of it is; a variant is an instance
|
||||
/// of that variant. A component the library doesn't offer pastes as a copy of itself, also one the
|
||||
/// library holds because an offered component uses it.
|
||||
#[test]
|
||||
fn a_main_pasted_from_its_library_file_is_an_instance_of_it() {
|
||||
let d = dir("paste-main");
|
||||
let lib_path = path_str(&d.join("kit.figcraft"));
|
||||
let mut s = Session::new();
|
||||
let k = kit(&mut s);
|
||||
let sizes: Vec<NodeId> = ["Size=S", "Size=L"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(n, name)| {
|
||||
idv(&ex(
|
||||
&mut s,
|
||||
"node.create",
|
||||
json!({"type": "component", "name": name, "x": 600.0 + n as f64 * 100.0, "y": 0, "width": 40, "height": 20}),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": sizes.clone()}));
|
||||
let spare = idv(&ex(&mut s, "frame.create", json!({"x": 300, "y": 300, "width": 10, "height": 10, "name": "_Spare"})));
|
||||
let spare = idv(&ex(&mut s, "component.create", json!({"ids": [spare]})));
|
||||
let icon = idv(&ex(&mut s, "frame.create", json!({"x": 400, "y": 300, "width": 10, "height": 10, "name": "_Icon"})));
|
||||
let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon]})));
|
||||
let badge = idv(&ex(&mut s, "frame.create", json!({"x": 500, "y": 300, "width": 30, "height": 30, "name": "Badge"})));
|
||||
ex(&mut s, "instance.create", json!({"component": icon, "x": 5, "y": 5, "parent": badge}));
|
||||
ex(&mut s, "component.create", json!({"ids": [badge]}));
|
||||
let lid = publish_to(&mut s, &lib_path);
|
||||
assert!(s.doc().unwrap().published.as_ref().unwrap().manifest.component(icon).is_some_and(|a| !a.published));
|
||||
let at = s.doc().unwrap().world_bounds(k.button).unwrap();
|
||||
ex(&mut s, "file.new", json!({"name": "Design"}));
|
||||
let paste = |s: &mut Session, main: NodeId| -> NodeId {
|
||||
ex(s, "doc.switch", json!({"index": 0}));
|
||||
ex(s, "edit.copy", json!({"ids": [main]}));
|
||||
ex(s, "doc.switch", json!({"index": 1}));
|
||||
id_of(&ex(s, "edit.paste", json!({}))["ids"][0]).unwrap()
|
||||
};
|
||||
let main_of = |s: &Session, id: NodeId| match node(s, id).kind {
|
||||
NodeKind::Instance { component, .. } => component,
|
||||
k => panic!("not an instance: {k:?}"),
|
||||
};
|
||||
let button = paste(&mut s, k.button);
|
||||
let doc = s.doc().unwrap();
|
||||
assert_eq!(library_source(doc, main_of(&s, button)), Some((lid.as_str(), k.button)));
|
||||
assert_eq!(doc.libraries.enabled.iter().map(|l| l.path.as_str()).collect::<Vec<_>>(), [lib_path.as_str()]);
|
||||
assert_eq!(doc.world_bounds(button), Some(at), "where the main was");
|
||||
let label = node(&s, button).children[0];
|
||||
assert_eq!(chars(&s, label), "OK");
|
||||
healthy(&s);
|
||||
let copies = s.doc().unwrap().libraries.components.len();
|
||||
let again = paste(&mut s, k.button);
|
||||
assert_eq!(main_of(&s, again), main_of(&s, button), "the same library copy");
|
||||
assert_eq!(s.doc().unwrap().libraries.components.len(), copies);
|
||||
let large = paste(&mut s, sizes[1]);
|
||||
assert_eq!(library_source(s.doc().unwrap(), main_of(&s, large)), Some((lid.as_str(), sizes[1])));
|
||||
let card = paste(&mut s, k.card);
|
||||
assert_eq!(library_source(s.doc().unwrap(), main_of(&s, card)), Some((lid.as_str(), k.card)));
|
||||
let copy = paste(&mut s, spare);
|
||||
assert!(matches!(node(&s, copy).kind, NodeKind::Component { .. }), "not offered by the library: a copy");
|
||||
assert!(!s.doc().unwrap().is_remote(copy));
|
||||
let icon_copy = paste(&mut s, icon);
|
||||
assert!(matches!(node(&s, icon_copy).kind, NodeKind::Component { .. }), "only used by an offered component: a copy");
|
||||
assert!(!s.doc().unwrap().is_remote(icon_copy));
|
||||
healthy(&s);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
@@ -44,6 +44,7 @@ pub const NODE_KEYS: &[&str] = &[
|
||||
"fontFamily",
|
||||
"fontSize",
|
||||
"fontStyle",
|
||||
"fontWeight",
|
||||
"fontVariations",
|
||||
"gridCell",
|
||||
"grids",
|
||||
@@ -435,6 +436,7 @@ fn text_props(t: &TextData, o: &mut serde_json::Map<String, Value>, options: &In
|
||||
});
|
||||
insert_prop(o, options, "fontFamily", || json!(t.style.font_family));
|
||||
insert_prop(o, options, "fontStyle", || json!(t.style.font_style));
|
||||
insert_prop(o, options, "fontWeight", || json!(t.style.weight()));
|
||||
insert_prop(o, options, "fontSize", || json!(t.style.font_size));
|
||||
if !t.style.variations.is_empty() {
|
||||
insert_prop(o, options, "fontVariations", || json!(t.style.variations));
|
||||
|
||||
@@ -4,13 +4,32 @@
|
||||
//! guide lines (with spacing labels) for the canvas to draw in red. Vector points also snap to
|
||||
//! other points (see `vectoredit::snap`); landing on one shows a marker (a zero-length guide).
|
||||
|
||||
use figcraft_doc::{BoardItem, Document, NodeId};
|
||||
use figcraft_doc::{BoardItem, Document, Node, NodeId, NodeKind};
|
||||
use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::guides;
|
||||
use crate::tools::UNMEASURED_SNAP_PX;
|
||||
|
||||
/// Whether `n` lands on whole pixels when dragged whatever Snap to pixel grid says: frames,
|
||||
/// sections, components, component sets and instances. Figma's help: they "always snap to the
|
||||
/// pixel grid, even if Snap to pixel grid is disabled". Other layers follow the setting.
|
||||
pub fn always_on_pixels(n: &Node) -> bool {
|
||||
n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. })
|
||||
}
|
||||
|
||||
/// Put `id`'s position in its parent on whole pixels when its axes are its parent's: returns
|
||||
/// whether it moved. A layer turned off its parent's axes keeps its position.
|
||||
pub fn settle_on_pixels(doc: &mut Document, id: NodeId) -> crate::Result<bool> {
|
||||
let n = doc.get_mut(id)?;
|
||||
let [a, b, c, d, e, f] = n.transform.as_coeffs();
|
||||
if !guides::axis_aligned(n.transform) || (e.round() == e && f.round() == f) {
|
||||
return Ok(false);
|
||||
}
|
||||
n.transform = Affine::new([a, b, c, d, e.round(), f.round()]);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A guide line to draw: from (x0, y0) to (x1, y1) in page coordinates, with an optional label
|
||||
/// (a distance) at its middle; `dashed` marks a measurement's extension line.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
|
||||
@@ -402,6 +402,94 @@ pub fn list_indent(s: &mut Session, out: bool) -> Result<bool> {
|
||||
Ok(text_of(s, id)? != before)
|
||||
}
|
||||
|
||||
/// Whether Tab in text layer `id` moves between text layers: not in a board object's text (a
|
||||
/// sticky's note, a table cell, a code block) or a widget's field, where it types as before.
|
||||
fn tabs_between_texts(doc: &Document, id: NodeId) -> bool {
|
||||
!in_board_object(doc, id) && crate::widgets::field_of(doc, id).is_none()
|
||||
}
|
||||
|
||||
fn in_board_object(doc: &Document, id: NodeId) -> bool {
|
||||
std::iter::once(id).chain(doc.ancestors(id)).any(|a| doc.node(a).is_some_and(|n| n.board.is_some()))
|
||||
}
|
||||
|
||||
/// Tab (Shift+Tab: `back`) while editing text layer `from`: editing it ends as Escape ends it, and
|
||||
/// the next (previous) text layer in reading order is edited with all of its text selected. At the
|
||||
/// last (first) one nothing happens.
|
||||
fn tab_to_next_text(s: &mut Session, from: NodeId, back: bool) -> Result<()> {
|
||||
let order = reading_order(s.doc()?, tab_stops(s.doc()?, from));
|
||||
let Some(at) = order.iter().position(|t| *t == from) else { return Ok(()) };
|
||||
let next = if back { at.checked_sub(1).and_then(|i| order.get(i)) } else { order.get(at + 1) };
|
||||
let Some(&next) = next else { return Ok(()) };
|
||||
end(s)?;
|
||||
begin(s, next, None, false)
|
||||
}
|
||||
|
||||
/// The text layers Tab moves between from text layer `from`: those in the top-level layer holding
|
||||
/// it (the frame or group on the page or in a section), at any depth and inside instances, that are
|
||||
/// visible and unlocked with every layer around them and not in a board object; for a text on the
|
||||
/// page or in a section itself, the text layers beside it there. `from` is always one of them.
|
||||
fn tab_stops(doc: &Document, from: NodeId) -> Vec<NodeId> {
|
||||
let is_section = |id: &NodeId| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }));
|
||||
let chain: Vec<NodeId> = std::iter::once(from).chain(doc.ancestors(from)).collect();
|
||||
let Some(page_at) = chain.iter().position(|c| doc.node(*c).is_some_and(|n| n.is_page())) else { return vec![from] };
|
||||
let top = chain.get(..page_at).and_then(|below| below.iter().rev().copied().find(|c| !is_section(c)));
|
||||
let stop = |n: &figcraft_doc::Node| n.visible && !n.locked && n.board.is_none();
|
||||
let mut out = Vec::new();
|
||||
match top {
|
||||
Some(top) if top != from => {
|
||||
let mut stack = vec![top];
|
||||
let mut seen = 0usize;
|
||||
while let Some(id) = stack.pop() {
|
||||
seen += 1;
|
||||
if seen > 1_000_000 {
|
||||
break;
|
||||
}
|
||||
let Some(n) = doc.node(id).filter(|n| stop(n)) else { continue };
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
out.push(id);
|
||||
}
|
||||
stack.extend(n.children.iter().copied());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let beside = doc.node(from).and_then(|n| n.parent).and_then(|p| doc.node(p)).map(|p| p.children.clone()).unwrap_or_default();
|
||||
out.extend(beside.into_iter().filter(|c| doc.node(*c).is_some_and(|n| stop(n) && matches!(n.kind, NodeKind::Text(_)))));
|
||||
}
|
||||
}
|
||||
if !out.contains(&from) {
|
||||
out.push(from);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `ids` in reading order by their boxes on the page: rows top to bottom, each row left to right.
|
||||
/// Rows are made from the top down: a layer joins the row of the topmost layer before it when the
|
||||
/// two overlap vertically by more than nothing and by at least half the height of the shorter one,
|
||||
/// else it starts the next row. Layers without bounds are left out.
|
||||
fn reading_order(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let mut boxes: Vec<(NodeId, figcraft_geom::Rect)> = ids.into_iter().filter_map(|i| Some((i, doc.world_bounds(i)?))).collect();
|
||||
boxes.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0).then(a.1.x0.total_cmp(&b.1.x0)));
|
||||
let mut rows: Vec<Vec<(NodeId, figcraft_geom::Rect)>> = Vec::new();
|
||||
for (id, b) in boxes {
|
||||
let joins = |row: &Vec<(NodeId, figcraft_geom::Rect)>| {
|
||||
row.first().is_some_and(|(_, a)| {
|
||||
let overlap = a.y1.min(b.y1) - a.y0.max(b.y0);
|
||||
overlap > 0.0 && overlap >= 0.5 * a.height().min(b.height())
|
||||
})
|
||||
};
|
||||
match rows.last_mut() {
|
||||
Some(row) if joins(row) => row.push((id, b)),
|
||||
_ => rows.push(vec![(id, b)]),
|
||||
}
|
||||
}
|
||||
rows.into_iter()
|
||||
.flat_map(|mut row| {
|
||||
row.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.1.y0.total_cmp(&b.1.y0)));
|
||||
row.into_iter().map(|(id, _)| id)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The kind of word char `i` belongs to: 0 for spaces and punctuation, else its script, so a word
|
||||
/// ends where the script changes (Han, hiragana, katakana and Hangul runs are words of their own in
|
||||
/// text without spaces). Combining marks and voicing marks belong to the char before them.
|
||||
@@ -460,7 +548,9 @@ fn word_right(chars: &[char], mut i: usize) -> usize {
|
||||
i
|
||||
}
|
||||
|
||||
/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Escape, SelectAll.
|
||||
/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Tab, Escape, SelectAll.
|
||||
/// Tab and Shift+Tab outside a list, a code block, a board object and a widget's field edit the
|
||||
/// next or previous text layer ([`tab_to_next_text`]).
|
||||
/// `word` moves or deletes by word, `line` to the line's ends (Up/Down, Home/End: the text's ends);
|
||||
/// [`crate::keymap::text_motion`] gives them for the platform's keys. `ArrowLeft` etc. also work.
|
||||
pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> Result<()> {
|
||||
@@ -485,6 +575,7 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R
|
||||
match key {
|
||||
"Escape" => return end(s),
|
||||
"Enter" => return insert(s, "\n"),
|
||||
"Tab" if !word && !line && tabs_between_texts(s.doc()?, te.id) => return tab_to_next_text(s, te.id, shift),
|
||||
"Tab" => return insert(s, "\t"),
|
||||
"Backspace" | "Delete" => {
|
||||
return edit(s, |t, te| {
|
||||
|
||||
@@ -249,7 +249,11 @@ impl Session {
|
||||
let raw = d;
|
||||
let snap_on = self.ds().map(|ds| ds.view.snap_objects).unwrap_or(true) && !ev.cmd && !ev.ctrl;
|
||||
let mut guides = Vec::new();
|
||||
if self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
|
||||
let boards = {
|
||||
let doc = self.doc()?;
|
||||
ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels))
|
||||
};
|
||||
if boards || self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
|
||||
// Keep the box's origin on whole pixels (a rotated parent frame's, inside one);
|
||||
// snapping to layers comes after, so it wins on the axes it snaps.
|
||||
d = targets.round_move(d);
|
||||
@@ -259,6 +263,11 @@ impl Session {
|
||||
d += c;
|
||||
guides = g2;
|
||||
}
|
||||
if boards {
|
||||
// Frames, sections and components stay on whole pixels even where a layer
|
||||
// they snap to doesn't.
|
||||
d = targets.round_move(d);
|
||||
}
|
||||
let ids = ids.clone();
|
||||
let dup = *duplicate;
|
||||
let page = self.page()?;
|
||||
@@ -343,6 +352,9 @@ impl Session {
|
||||
doc.reparent(*m, page, None)?;
|
||||
}
|
||||
move_world(doc, *m, d.x, d.y)?;
|
||||
if doc.node(*m).is_some_and(crate::snap::always_on_pixels) {
|
||||
shifted &= !crate::snap::settle_on_pixels(doc, *m)?;
|
||||
}
|
||||
}
|
||||
drop_target = (flow && target != page).then_some(target);
|
||||
Ok(())
|
||||
@@ -521,7 +533,13 @@ impl Session {
|
||||
// The pixel grid: an upright box's dragged sides land on whole pixels (the Scale tool
|
||||
// scales by the factor as dragged). Snapping to layers comes after, so it wins on the axes
|
||||
// it snaps.
|
||||
if !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
|
||||
// Frames, sections and components land on whole pixels whatever the setting, also where a
|
||||
// layer they snap to doesn't.
|
||||
let boards = {
|
||||
let doc = self.doc()?;
|
||||
!scale_tool && crate::guides::axis_aligned(frame) && ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels))
|
||||
};
|
||||
if boards || !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
|
||||
p = Point::new(p.x.round(), p.y.round());
|
||||
}
|
||||
if let Some(t) = &targets {
|
||||
@@ -530,6 +548,9 @@ impl Session {
|
||||
p.y += dy;
|
||||
guides = g;
|
||||
}
|
||||
if boards {
|
||||
p = Point::new(p.x.round(), p.y.round());
|
||||
}
|
||||
let q = frame.inverse() * p;
|
||||
let is_line = r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| matches!(n.kind, NodeKind::Line))).unwrap_or(false);
|
||||
if scale_tool {
|
||||
@@ -557,9 +578,16 @@ impl Session {
|
||||
self.tool.overlay.guides = guides;
|
||||
return Ok(());
|
||||
}
|
||||
// Constrain proportions (Shift, or the node's lock).
|
||||
let keep = ev.shift || r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false);
|
||||
let (x0, y0, x1, y1) = resized_box(r.handle, q, w0, h0, keep, ev.alt);
|
||||
let image_box = ids.first().filter(|_| ev.cmd && r.single).and_then(|i| self.image_box(*i));
|
||||
// Constrain proportions (Shift, or the node's lock; cropping an image ignores the lock).
|
||||
let locked =
|
||||
r.single && image_box.is_none() && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false);
|
||||
let keep = ev.shift || locked;
|
||||
let resized = resized_box(r.handle, q, w0, h0, keep, ev.alt);
|
||||
let (x0, y0, x1, y1) = match image_box {
|
||||
Some(image) => within_the_image(resized, image, (w0, h0), keep),
|
||||
None => resized,
|
||||
};
|
||||
let (flip_x, flip_y) = (x1 < x0, y1 < y0);
|
||||
let (nx0, ny0) = (x0.min(x1), y0.min(y1));
|
||||
let (nw, nh) = ((x1 - x0).abs(), (y1 - y0).abs());
|
||||
@@ -571,46 +599,30 @@ impl Session {
|
||||
let keeps = |doc: &Document, id: NodeId| {
|
||||
doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }) || (ev.cmd && single && n.kind.is_frame_like()))
|
||||
};
|
||||
let dragged_box = |world: Affine, (ox, oy): (f64, f64)| {
|
||||
let mut t = world * Affine::translate((ox, oy));
|
||||
if flip_x {
|
||||
t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]);
|
||||
}
|
||||
if flip_y {
|
||||
t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]);
|
||||
}
|
||||
t
|
||||
};
|
||||
self.preview(|doc, _| {
|
||||
if single {
|
||||
let Some((id, world, _, _)) = nodes.first() else { return Ok(()) };
|
||||
let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() };
|
||||
let mut t = *world * Affine::translate((nx0, ny0));
|
||||
if flip_x {
|
||||
t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]);
|
||||
}
|
||||
if flip_y {
|
||||
t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]);
|
||||
}
|
||||
let t = dragged_box(*world, (nx0, ny0));
|
||||
// Text reflow and auto layout can recompute this box after the preview (a size bound
|
||||
// to a variable lets go of it: the resize is an explicit edit).
|
||||
// to a variable lets go of it: the resize is an explicit edit). A text keeps its
|
||||
// fills; any other layer's image is cropped again for the box layout leaves
|
||||
// (`crop_to_the_laid_out_box`).
|
||||
let n = doc.get(*id)?;
|
||||
let crop_images = ev.cmd
|
||||
&& !matches!(n.kind, NodeKind::Text(_))
|
||||
&& !std::iter::once(*id).chain(doc.ancestors(*id)).any(|a| doc.node(a).is_some_and(|n| n.layout.is_some()));
|
||||
if crop_images {
|
||||
// Crop the layer's image fills without moving their pixels on the page.
|
||||
// Work from the interaction snapshot, just like the geometry on every move.
|
||||
let (w, h) = (n.width.max(1e-6), n.height.max(1e-6));
|
||||
let to_old =
|
||||
Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * t * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01));
|
||||
let mut fills = n.fills.clone();
|
||||
for paint in &mut fills {
|
||||
let PaintKind::Image(img) = &mut paint.kind else { continue };
|
||||
// A repeating image cannot be represented by a single Crop placement.
|
||||
if img.scale_mode == ImageScaleMode::Tile {
|
||||
continue;
|
||||
}
|
||||
let Some(data) = doc.images.get(&img.image) else { continue };
|
||||
let (iw, ih) = (f64::from(data.width), f64::from(data.height));
|
||||
// A degenerate (zero-scale) layer has no inverse: its image keeps its placement.
|
||||
let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_old).as_coeffs();
|
||||
if !crop.iter().all(|c| c.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
img.crop = Some(crop);
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
}
|
||||
// Crop the layer's image fills without moving their pixels on the page.
|
||||
// Work from the interaction snapshot, just like the geometry on every move.
|
||||
if ev.cmd && !matches!(n.kind, NodeKind::Text(_)) {
|
||||
let fills = cropped_image_fills(doc, n, *world, t, (nw, nh));
|
||||
doc.get_mut(*id)?.fills = fills;
|
||||
}
|
||||
doc.set_world_transform(*id, t)?;
|
||||
@@ -650,16 +662,81 @@ impl Session {
|
||||
let lin = (mirror * local).with_translation(Vec2::ZERO);
|
||||
let origin = Point::new(x0 + center.x * sx, y0 + center.y * sy) - lin * Point::new(w2 / 2.0, h2 / 2.0);
|
||||
let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() };
|
||||
doc.set_world_transform(*id, frame * lin.with_translation(origin))?;
|
||||
let (t, w2, h2) = if boards {
|
||||
on_whole_pixels(doc, *id, frame * lin.with_translation(origin), w2, h2)
|
||||
} else {
|
||||
(frame * lin.with_translation(origin), w2, h2)
|
||||
};
|
||||
doc.set_world_transform(*id, t)?;
|
||||
crate::cmd::props::resize_node(doc, *id, w2, h2)?;
|
||||
if boards {
|
||||
crate::snap::settle_on_pixels(doc, *id)?;
|
||||
}
|
||||
crate::cmd::props::restore_worlds(doc, &kept)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if single
|
||||
&& ev.cmd
|
||||
&& let Some((id, world, _, _)) = nodes.first()
|
||||
{
|
||||
let laid_out_box = |(fw, fh): (f64, f64)| {
|
||||
let origin = match image_box {
|
||||
Some((ix0, iy0, ix1, iy1)) => {
|
||||
(slid_onto_the_image(nx0, fw, flip_x, (ix0, ix1), w0), slid_onto_the_image(ny0, fh, flip_y, (iy0, iy1), h0))
|
||||
}
|
||||
None => (nx0, ny0),
|
||||
};
|
||||
dragged_box(*world, origin)
|
||||
};
|
||||
self.crop_to_the_laid_out_box(*id, *world, laid_out_box, (nw, nh))?;
|
||||
}
|
||||
self.tool.overlay.guides = guides;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The box `(x0, y0, x1, y1)` of the first visible, untiled image fill of `id` in the layer's
|
||||
/// own axes, as it was when the gesture began; `None` for a text or a layer without one.
|
||||
fn image_box(&self, id: NodeId) -> Option<(f64, f64, f64, f64)> {
|
||||
let snapshot = self.ds().ok()?.interaction.as_ref()?.doc.clone();
|
||||
let n = snapshot.node(id)?;
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
return None;
|
||||
}
|
||||
n.fills.iter().filter(|p| p.visible).find_map(|p| match &p.kind {
|
||||
PaintKind::Image(img) if img.scale_mode != ImageScaleMode::Tile => {
|
||||
let data = snapshot.images.get(&img.image)?;
|
||||
let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
|
||||
let (x0, y0, x1, y1) = figcraft_doc::color::ImagePaint::crop_rect(crop);
|
||||
Some((x0 * n.width, y0 * n.height, x1 * n.width, y1 * n.height))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// After the preview's layout: when the layer didn't keep the dragged size `(nw, nh)` (a
|
||||
/// minimum size, a Hug frame), crop its image fills again from the snapshot for the size it
|
||||
/// has, the box placed by `laid_out_box` (given that size) in the layer's starting axes.
|
||||
fn crop_to_the_laid_out_box(
|
||||
&mut self,
|
||||
id: NodeId,
|
||||
world: Affine,
|
||||
laid_out_box: impl Fn((f64, f64)) -> Affine,
|
||||
(nw, nh): (f64, f64),
|
||||
) -> Result<()> {
|
||||
let ds = self.ds_mut()?;
|
||||
let Some(snapshot) = ds.interaction.as_ref().map(|it| it.doc.clone()) else { return Ok(()) };
|
||||
let Some(before) = snapshot.node(id).filter(|n| !matches!(n.kind, NodeKind::Text(_))) else { return Ok(()) };
|
||||
let Some((fw, fh)) = ds.doc.node(id).map(|n| (n.width, n.height)) else { return Ok(()) };
|
||||
if (fw - nw.max(0.01)).abs() < 1e-9 && (fh - nh.max(0.01)).abs() < 1e-9 {
|
||||
return Ok(());
|
||||
}
|
||||
let fills = cropped_image_fills(&snapshot, before, world, laid_out_box((fw, fh)), (fw, fh));
|
||||
std::sync::Arc::make_mut(&mut ds.doc).get_mut(id)?.fills = fills;
|
||||
ds.revision += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scale tool handle drag (`q`: the snapped pointer in the handle box's axes): everything
|
||||
/// scales by one factor about the anchor point (Alt: the centre), strokes, effects, radii and
|
||||
/// text included, children by the same factor whatever their constraints.
|
||||
@@ -697,6 +774,25 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// `world` and the size `w` x `h` a layer of a resized selection takes, moved so its box in its
|
||||
/// parent has its edges on whole pixels, each on the nearest one and the box at least a pixel
|
||||
/// wide: a frame resized with others lands on whole pixels as one resized alone does. A layer
|
||||
/// turned or scaled in its parent keeps them.
|
||||
fn on_whole_pixels(doc: &Document, id: NodeId, world: Affine, w: f64, h: f64) -> (Affine, f64, f64) {
|
||||
let pw = doc.node(id).and_then(|n| n.parent).map_or(Affine::IDENTITY, |p| doc.world_transform(p));
|
||||
let local = pw.inverse() * world;
|
||||
let [a, b, c, d, e, f] = local.as_coeffs();
|
||||
if !crate::guides::axis_aligned(local) || (a.abs() - 1.0).abs() > 1e-9 || (d.abs() - 1.0).abs() > 1e-9 {
|
||||
return (world, w, h);
|
||||
}
|
||||
let edges = |at: f64, flip: bool, len: f64| if flip { (at - len, at) } else { (at, at + len) };
|
||||
let ((x0, x1), (y0, y1)) = (edges(e, a < 0.0, w), edges(f, d < 0.0, h));
|
||||
let (x0, y0) = (x0.round(), y0.round());
|
||||
let (w, h) = ((x1.round() - x0).max(1.0), (y1.round() - y0).max(1.0));
|
||||
let (e, f) = (if a < 0.0 { x0 + w } else { x0 }, if d < 0.0 { y0 + h } else { y0 });
|
||||
(pw * Affine::new([a, b, c, d, e, f]), w, h)
|
||||
}
|
||||
|
||||
/// Moving `moving` by the same offset moves nothing else and changes nothing about them but where
|
||||
/// they are: none is inside another (it would move twice) or placed by its parent's auto layout
|
||||
/// (the layout would put it back, or close the gap it leaves).
|
||||
@@ -714,3 +810,78 @@ fn only_shifted(doc: &Document, moving: &[NodeId]) -> bool {
|
||||
!in_flow && !nested
|
||||
})
|
||||
}
|
||||
|
||||
/// `before`'s fills (from the snapshot `doc`) with each image cropped to the box `dragged` (the
|
||||
/// layer's new transform, `nw` × `nh`), its pixels left where they were on the page (`world`:
|
||||
/// the layer's transform before the drag).
|
||||
fn cropped_image_fills(
|
||||
doc: &Document,
|
||||
before: &figcraft_doc::Node,
|
||||
world: Affine,
|
||||
dragged: Affine,
|
||||
(nw, nh): (f64, f64),
|
||||
) -> Vec<figcraft_doc::color::Paint> {
|
||||
let (w, h) = (before.width.max(1e-6), before.height.max(1e-6));
|
||||
let to_before = Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * dragged * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01));
|
||||
let mut fills = before.fills.clone();
|
||||
for paint in &mut fills {
|
||||
let PaintKind::Image(img) = &mut paint.kind else { continue };
|
||||
// A repeating image cannot be represented by a single Crop placement.
|
||||
if img.scale_mode == ImageScaleMode::Tile {
|
||||
continue;
|
||||
}
|
||||
let Some(data) = doc.images.get(&img.image) else { continue };
|
||||
let (iw, ih) = (f64::from(data.width), f64::from(data.height));
|
||||
// A degenerate (zero-scale) layer has no inverse: its image keeps its placement.
|
||||
let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_before).as_coeffs();
|
||||
if !crop.iter().all(|c| c.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
img.crop = Some(crop);
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
}
|
||||
fills
|
||||
}
|
||||
|
||||
/// The extent `lo..hi` an image of extent `image` lets a crop reach on one axis of a layer that
|
||||
/// started `len` long: the image's, or the layer's where that reaches further (a Fit image is
|
||||
/// smaller than its layer).
|
||||
fn crop_reach(image: (f64, f64), len: f64) -> (f64, f64) {
|
||||
(image.0.min(image.1).min(0.0), image.0.max(image.1).max(len))
|
||||
}
|
||||
|
||||
/// The dragged box `(x0, y0, x1, y1)` drawn back towards the starting box `(0, 0, w0, h0)` until
|
||||
/// its sides stop at the image's box `image` (see [`crop_reach`]). Both ends of an axis go back by
|
||||
/// the same fraction, so an Alt resize stays centred, and with `keep` (Shift) both axes do, so the
|
||||
/// ratio holds. A flipped axis stays as dragged.
|
||||
fn within_the_image((x0, y0, x1, y1): (f64, f64, f64, f64), image: (f64, f64, f64, f64), (w0, h0): (f64, f64), keep: bool) -> (f64, f64, f64, f64) {
|
||||
let fraction = |a: f64, b: f64, image: (f64, f64), len: f64| {
|
||||
if b < a {
|
||||
return 1.0;
|
||||
}
|
||||
let (lo, hi) = crop_reach(image, len);
|
||||
let mut t: f64 = 1.0;
|
||||
if a < lo {
|
||||
t = t.min(lo / a);
|
||||
}
|
||||
if b > hi {
|
||||
t = t.min((hi - len) / (b - len));
|
||||
}
|
||||
if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }
|
||||
};
|
||||
let (tx, ty) = (fraction(x0, x1, (image.0, image.2), w0), fraction(y0, y1, (image.1, image.3), h0));
|
||||
let (tx, ty) = if keep { (tx.min(ty), tx.min(ty)) } else { (tx, ty) };
|
||||
(x0 * tx, y0 * ty, w0 + (x1 - w0) * tx, h0 + (y1 - h0) * ty)
|
||||
}
|
||||
|
||||
/// Where a crop box `len` long, placed at `start` on one axis, starts once it is slid back onto
|
||||
/// the image (see [`crop_reach`]): layout can make a layer longer than it was dragged (a minimum
|
||||
/// size), and the crop then moves along the image rather than past its edge. A flipped axis, or
|
||||
/// a box longer than the reach, stays where it is.
|
||||
fn slid_onto_the_image(start: f64, len: f64, flipped: bool, image: (f64, f64), len0: f64) -> f64 {
|
||||
let (lo, hi) = crop_reach(image, len0);
|
||||
if flipped || len.is_nan() || len > hi - lo {
|
||||
return start;
|
||||
}
|
||||
start.max(lo).min(hi - len)
|
||||
}
|
||||
@@ -30,7 +30,10 @@ impl Session {
|
||||
let tool = self.tool.tool;
|
||||
let mut p = ev.p();
|
||||
let mut guides = Vec::new();
|
||||
let pixel = self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
|
||||
// Frames and sections land on whole pixels whatever the setting, also where a layer they
|
||||
// snap to doesn't (see `snap::always_on_pixels`).
|
||||
let board = matches!(tool, ToolId::Frame | ToolId::Section);
|
||||
let pixel = board || self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
|
||||
// The pixel grid first: snapping to layers comes after, so it wins on the axes it snaps.
|
||||
if pixel {
|
||||
p = Point::new(p.x.round(), p.y.round());
|
||||
@@ -41,6 +44,9 @@ impl Session {
|
||||
p.y += dy;
|
||||
guides = g;
|
||||
}
|
||||
if board {
|
||||
p = Point::new(p.x.round(), p.y.round());
|
||||
}
|
||||
let mut created = id;
|
||||
let page = self.page()?;
|
||||
// Edit ▸ Set default properties: what new shapes take (not frames, sections, slices, lines
|
||||
@@ -100,6 +106,9 @@ impl Session {
|
||||
n.transform = pw.inverse() * Affine::translate((r.x0, r.y0));
|
||||
}
|
||||
doc.insert(n, parent, None)?;
|
||||
if board {
|
||||
crate::snap::settle_on_pixels(doc, nid)?;
|
||||
}
|
||||
if let Some(d) = &defaults {
|
||||
// Best effort: a default the shape can't take leaves it as drawn.
|
||||
let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", doc, nid, d);
|
||||
@@ -156,6 +165,11 @@ impl Session {
|
||||
}
|
||||
// A layer can't go into itself; it stays where it is.
|
||||
let _ = d.reparent(*m, target, None);
|
||||
// Frames, sections and components land on whole pixels of the frame
|
||||
// they are dropped into too.
|
||||
if d.node(*m).is_some_and(crate::snap::always_on_pixels) {
|
||||
crate::snap::settle_on_pixels(d, *m)?;
|
||||
}
|
||||
}
|
||||
crate::normalize(ds.doc_mut(), &before);
|
||||
}
|
||||
|
||||
@@ -109,6 +109,7 @@ fn registry() -> &'static Registry {
|
||||
list.extend(crate::dev_resources::specs());
|
||||
list.extend(crate::dev_measurements::specs());
|
||||
list.extend(crate::distance::specs());
|
||||
list.extend(crate::design::specs());
|
||||
list.extend(crate::collab::specs());
|
||||
list.extend(crate::branches::specs());
|
||||
list.extend(crate::plugins::specs());
|
||||
|
||||
@@ -24,6 +24,7 @@ use instance::{detach, make_slot, push_changes, remove_slot, reset_instance, res
|
||||
pub(crate) use instance::{swap_at, swap_instance};
|
||||
use props::{add_prop, bind_prop, delete_prop, edit_prop, set_props};
|
||||
pub(crate) use props::{apply_prop_bindings, check_prop_binding, describe_props};
|
||||
pub(crate) use variants::fit_set;
|
||||
use variants::{add_variant, combine, create_set};
|
||||
pub use variants::{can_add_variant, can_combine_variants, can_create_set};
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ pub(super) fn create_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Grow a component set so it wraps its variants with 20 px of padding (right and bottom).
|
||||
pub(super) fn fit_set(doc: &mut Document, set: NodeId) {
|
||||
pub(crate) fn fit_set(doc: &mut Document, set: NodeId) {
|
||||
let Some(kids) = doc.node(set).map(|n| n.children.clone()) else { return };
|
||||
let (mut w, mut h) = (0.0f64, 0.0f64);
|
||||
for c in kids {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Creating nodes.
|
||||
|
||||
use figcraft_color::{ImageFilters, ImageScaleMode, Paint};
|
||||
use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, TextAutoResize, TextData, VectorNetwork};
|
||||
use figcraft_doc::{Document, Node, NodeId, NodeKind, Sizing, StrokeCap, TextAutoResize, TextData, VectorNetwork};
|
||||
use figcraft_geom::Point;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"text.create",
|
||||
"Text",
|
||||
"{text | characters, x, y, parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontFamily, …), select? (default true)}",
|
||||
"{text | characters, x?, y? (ignored inside an auto layout parent unless props.absolute is true, which keeps the transform they set), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}",
|
||||
true,
|
||||
|s, p| { create_kind(s, p, "text") }
|
||||
),
|
||||
@@ -275,7 +275,9 @@ pub fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = s.doc()?;
|
||||
let pn = doc.get(parent)?;
|
||||
if !pn.kind.is_container() {
|
||||
return Err(bad(cmd, format!("{parent} can't contain layers")));
|
||||
let name = pn.name.trim();
|
||||
let what = if name.is_empty() { pn.kind.type_name().to_string() } else { format!("{} \"{}\"", pn.kind.type_name(), name) };
|
||||
return Err(bad(cmd, format!("{parent} ({what}) can't contain layers")));
|
||||
}
|
||||
if base == "Section" && !doc.takes_sections(parent) {
|
||||
return Err(bad(cmd, "sections go on the page or in other sections"));
|
||||
@@ -371,6 +373,24 @@ pub fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
doc.insert(node, parent, index)?;
|
||||
if let Some(Value::Object(props)) = get(p, "props") {
|
||||
super::props::apply(cmd, doc, nid, props)?;
|
||||
// An auto layout frame hugs the axes the caller left unset — the incumbent's default, and
|
||||
// the difference between a card and a 100pt-tall box that silently clips its rows.
|
||||
// Explicit width/height and explicit sizing keep their fixed/fill behaviour.
|
||||
if doc.node(nid).is_some_and(|n| n.layout.is_some()) {
|
||||
let asked = |axis: &str, keys: &[&str]| {
|
||||
let long = if axis == "h" { "width" } else { "height" };
|
||||
let short = if axis == "h" { "w" } else { "h" };
|
||||
num(p, long).is_some() || props.contains_key(long) || props.contains_key(short) || keys.iter().any(|k| props.contains_key(*k))
|
||||
};
|
||||
if let Some(n) = doc.node_mut(nid) {
|
||||
if !asked("h", &["sizingH", "layoutSizingHorizontal"]) {
|
||||
n.child_layout.sizing_h = Sizing::Hug;
|
||||
}
|
||||
if !asked("v", &["sizingV", "layoutSizingVertical"]) {
|
||||
n.child_layout.sizing_v = Sizing::Hug;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if boolean(p, "select").unwrap_or(true) {
|
||||
ds.selection = vec![nid];
|
||||
|
||||
@@ -358,7 +358,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move layer into",
|
||||
"{ids?, parent, index? (final position among parent's children, bottom first; default top)}",
|
||||
true,
|
||||
reparent
|
||||
|s, p| reparent(s, p, "node.reparent", false)
|
||||
),
|
||||
spec!(
|
||||
"layers.reparent",
|
||||
"Move layer into",
|
||||
"{ids (in the destination's stored child order), parent, index? (final position among parent's children, bottom first; default top)}",
|
||||
true,
|
||||
|s, p| reparent(s, p, "layers.reparent", true)
|
||||
),
|
||||
spec!("node.reorder", "Reorder layer", "{id, index}", true, |s, p| {
|
||||
let i = req_id("node.reorder", p, "id")?;
|
||||
|
||||
@@ -127,6 +127,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A design-app paste replaces the copied layers, not the copied rows: a `fill.copy` before it
|
||||
// still pastes afterwards.
|
||||
let props = s.clipboard.props.take();
|
||||
let props_source_doc = s.clipboard.props_source_doc;
|
||||
let paint = s.clipboard.paint.take();
|
||||
let stroke = s.clipboard.stroke.take();
|
||||
let paint_images = std::mem::take(&mut s.clipboard.paint_images);
|
||||
@@ -138,6 +139,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
nodes,
|
||||
images,
|
||||
props,
|
||||
props_source_doc,
|
||||
paint,
|
||||
stroke,
|
||||
paint_images,
|
||||
@@ -219,8 +221,18 @@ pub(super) fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
delete(s, &json!({"ids": layers}))
|
||||
}
|
||||
|
||||
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords).
|
||||
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords). A
|
||||
/// copied main is pasted as an instance of it; in another file, as an instance of it from the
|
||||
/// library the source file publishes, and as a copy of it when that library doesn't offer it.
|
||||
pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Result<Vec<NodeId>> {
|
||||
paste_layers(s, parent, at, false)
|
||||
}
|
||||
|
||||
/// [`paste_into`]. With `as_variants`, copied variants pasted into `parent`, their own set, are
|
||||
/// deep copies (new variants, as Duplicate makes) and the set grows to hold them. Only a plain
|
||||
/// paste with that set, or a layer in it, selected asks for this; every other paste of a copied
|
||||
/// main, into another set too, still makes an instance.
|
||||
fn paste_layers(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>, as_variants: bool) -> Result<Vec<NodeId>> {
|
||||
let clip = s.clipboard.clone();
|
||||
if clip.nodes.is_empty() {
|
||||
return Err(EngineError::Disabled("edit.paste".into(), "the clipboard is empty".into()));
|
||||
@@ -238,15 +250,20 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
|
||||
(Some((x, y)), Some(b)) => Affine::translate((x - b.x0, y - b.y0)),
|
||||
_ => Affine::IDENTITY,
|
||||
};
|
||||
let into_set = as_variants && copy_local && copied_variants_set(doc, &clip.nodes) == Some(parent);
|
||||
let mut out = Vec::new();
|
||||
let mut all = BTreeMap::new();
|
||||
for (root, nodes) in &clip.nodes {
|
||||
if copy_local
|
||||
&& clip.copied_components.contains(root)
|
||||
&& let Some(n) = nodes.first().filter(|n| matches!(n.kind, NodeKind::Component { .. }))
|
||||
&& doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))
|
||||
{
|
||||
let instance = crate::components::create_instance(doc, *root, parent, 0.0, 0.0)?;
|
||||
let copied_main = nodes.first().filter(|n| clip.copied_components.contains(root) && matches!(n.kind, NodeKind::Component { .. }));
|
||||
let main = match (copied_main, foreign) {
|
||||
(Some(_), _) if copy_local => {
|
||||
(!into_set && doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))).then_some(*root)
|
||||
}
|
||||
(Some(_), Some(src)) => crate::library::published_main(doc, src, clip.source_path.as_deref(), *root)?,
|
||||
_ => None,
|
||||
};
|
||||
if let (Some(main), Some(n)) = (main, copied_main) {
|
||||
let instance = crate::components::create_instance(doc, main, parent, 0.0, 0.0)?;
|
||||
doc.get_mut(instance)?.transform = doc.world_transform(parent).inverse() * shift * n.transform;
|
||||
keep_a_cropped_images_proportions(doc, instance, parent);
|
||||
out.push(instance);
|
||||
@@ -267,6 +284,9 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
|
||||
out.push(pasted);
|
||||
all.extend(map);
|
||||
}
|
||||
if into_set {
|
||||
crate::cmd::component::fit_set(doc, parent);
|
||||
}
|
||||
// Board connectors pasted with what they join join the pasted copies.
|
||||
let originals: Vec<(NodeId, figcraft_doc::BoardItem)> =
|
||||
clip.nodes.iter().flat_map(|(_, nodes)| nodes).filter_map(|n| Some((*all.get(&n.id)?, n.board.clone()?))).collect();
|
||||
@@ -307,7 +327,16 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = s.selection();
|
||||
let doc = s.doc()?;
|
||||
let copy_local = s.ds()?.uid == s.clipboard.source_doc;
|
||||
let target = id(p, "parent").or_else(|| {
|
||||
let variants_set = copied_variants_set(doc, &s.clipboard.nodes)
|
||||
.filter(|set| copy_local && id(p, "parent").is_none() && !sel.is_empty() && sel.iter().all(|i| doc.is_ancestor(*set, *i)));
|
||||
// Where the copied variants are now, not where they were copied: the set may have moved since.
|
||||
let below_the_variants = variants_set.and_then(|set| {
|
||||
let copied: Vec<NodeId> = s.clipboard.nodes.iter().map(|(root, _)| *root).collect();
|
||||
let left = doc.bounds_of(&copied)?.x0;
|
||||
let bottom = doc.node(set)?.children.iter().filter_map(|c| doc.world_bounds(*c)).map(|r| r.y1).reduce(f64::max)?;
|
||||
Some((left, bottom + 20.0))
|
||||
});
|
||||
let target = id(p, "parent").or(variants_set).or_else(|| {
|
||||
sel.first()
|
||||
.copied()
|
||||
.filter(|i| {
|
||||
@@ -322,6 +351,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let parent = target.unwrap_or(page);
|
||||
let at = match (num(p, "x"), num(p, "y")) {
|
||||
(Some(x), Some(y)) => Some((x, y)),
|
||||
_ if below_the_variants.is_some() => below_the_variants,
|
||||
_ => {
|
||||
let b = s.clipboard.bounds;
|
||||
match (target, b) {
|
||||
@@ -344,7 +374,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let ids = paste_into(s, parent, at)?;
|
||||
let ids = paste_layers(s, parent, at, variants_set.is_some())?;
|
||||
if let Some(sel) = sibling_of {
|
||||
let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1);
|
||||
move_above(s, &ids, parent, above)?;
|
||||
@@ -381,14 +411,27 @@ fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option<usi
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The set the copied layers are variants of: every copied root is a main component in `doc` whose
|
||||
/// parent is that one component set. `None` for anything else.
|
||||
fn copied_variants_set(doc: &Document, copied: &[(NodeId, Vec<Node>)]) -> Option<NodeId> {
|
||||
let mut sets = copied.iter().map(|(root, _)| {
|
||||
let n = doc.node(*root).filter(|n| matches!(n.kind, NodeKind::Component { .. }))?;
|
||||
n.parent.filter(|set| doc.node(*set).is_some_and(|p| matches!(p.kind, NodeKind::ComponentSet { .. })))
|
||||
});
|
||||
let first = sets.next()??;
|
||||
sets.all(|set| set == Some(first)).then_some(first)
|
||||
}
|
||||
|
||||
/// Paste over selection (Shift+Cmd/Ctrl+V): the copies go into the parent of the selected layer
|
||||
/// [`last_seen`] picks, just above it, at the place it gives.
|
||||
pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let sel = s.selection();
|
||||
let page = s.page()?;
|
||||
let doc = s.doc()?;
|
||||
let (parent, at, above) = match sel.first() {
|
||||
Some(i) => {
|
||||
let parent = doc.node(*i).and_then(|n| n.parent).unwrap_or(page);
|
||||
(parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)), doc.index_in_parent(*i).map(|ix| ix + 1))
|
||||
let (parent, at, above) = match last_seen(doc, &sel) {
|
||||
Some((i, at)) => {
|
||||
let parent = doc.node(i).and_then(|n| n.parent).unwrap_or(page);
|
||||
(parent, at, doc.index_in_parent(i).map(|ix| ix + 1))
|
||||
}
|
||||
None => (page, None, None),
|
||||
};
|
||||
@@ -398,6 +441,38 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({"ids": ids}))
|
||||
}
|
||||
|
||||
/// The selected layer Paste over selection pastes after, and where the copies' top-left goes.
|
||||
///
|
||||
/// One layer: that layer, at its position. Several in one auto layout frame's flow (none absolutely
|
||||
/// positioned): the last of them in the flow, which the layout follows. Several elsewhere: the lowest (then rightmost), with the copies
|
||||
/// below it, as far below as it is from the selected layers above it. A selection with nothing above
|
||||
/// its lowest layer is a row: the copies go right of the rightmost, as far as it is from its
|
||||
/// neighbour on the left. Layers that overlap every way get the copies right under the lowest.
|
||||
fn last_seen(doc: &Document, sel: &[NodeId]) -> Option<(NodeId, Option<(f64, f64)>)> {
|
||||
let first = *sel.first()?;
|
||||
let top_left = |i: NodeId| doc.world_bounds(i).map(|b| (b.x0, b.y0));
|
||||
if sel.len() == 1 {
|
||||
return Some((first, top_left(first)));
|
||||
}
|
||||
let parent = doc.node(first).and_then(|n| n.parent);
|
||||
let one_flow = parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some())
|
||||
&& sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.parent == parent && !n.child_layout.absolute));
|
||||
if one_flow {
|
||||
let last = sel.iter().copied().max_by_key(|i| doc.index_in_parent(*i))?;
|
||||
return Some((last, top_left(last)));
|
||||
}
|
||||
let boxes: Vec<(NodeId, figcraft_geom::Rect)> = sel.iter().filter_map(|i| Some((*i, doc.world_bounds(*i)?))).collect();
|
||||
let (lowest, low) = *boxes.iter().max_by(|(_, a), (_, b)| a.y1.total_cmp(&b.y1).then(a.x1.total_cmp(&b.x1)))?;
|
||||
if let Some(above) = boxes.iter().filter(|(_, o)| o.y1 <= low.y0).map(|(_, o)| o.y1).max_by(f64::total_cmp) {
|
||||
return Some((lowest, Some((low.x0, low.y1 + (low.y0 - above)))));
|
||||
}
|
||||
let (rightmost, right) = *boxes.iter().max_by(|(_, a), (_, b)| a.x1.total_cmp(&b.x1).then(a.y1.total_cmp(&b.y1)))?;
|
||||
match boxes.iter().filter(|(_, o)| o.x1 <= right.x0).map(|(_, o)| o.x1).max_by(f64::total_cmp) {
|
||||
Some(left) => Some((rightmost, Some((right.x1 + (right.x0 - left), right.y0)))),
|
||||
None => Some((lowest, Some((low.x0, low.y1)))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn paste_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = req_targets("edit.pasteReplace", s, p)?;
|
||||
let mut out = Vec::new();
|
||||
@@ -438,7 +513,19 @@ pub(super) fn copy_props_of(doc: &Document, id: NodeId) -> Value {
|
||||
v["cornerRadius"] = json!(n.corners.radii);
|
||||
v["cornerSmoothing"] = json!(n.corners.smoothing);
|
||||
}
|
||||
// A frame's layout grids go with its look, as its fills do.
|
||||
if n.kind.is_frame_like() {
|
||||
v["grids"] = json!(n.grids);
|
||||
v["gridStyle"] = json!(n.styles.grid);
|
||||
}
|
||||
// The links behind the values: the styles and the variables they come from, so the pasted
|
||||
// layer follows them as the copied one does.
|
||||
v["fillStyle"] = json!(n.styles.fill);
|
||||
v["strokeStyle"] = json!(n.styles.stroke);
|
||||
v["effectStyle"] = json!(n.styles.effect);
|
||||
v["boundVariables"] = Value::Object(n.bound.iter().filter(|(f, _)| copied_binding(f)).map(|(f, v)| (f.clone(), json!(v))).collect());
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
v["textStyle"] = json!(n.styles.text);
|
||||
v["fontFamily"] = json!(t.style.font_family);
|
||||
v["fontStyle"] = json!(t.style.font_style);
|
||||
v["fontSize"] = json!(t.style.font_size);
|
||||
@@ -453,26 +540,110 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.copyProperties", "select one layer"))?;
|
||||
let v = copy_props_of(s.doc()?, id);
|
||||
s.clipboard.props = Some(v.clone());
|
||||
s.clipboard.props_source_doc = s.ds()?.uid;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Copied properties `props` without their style and variable links, for a paste into another
|
||||
/// file: the copied ids name the source file's styles and variables, and the same ids here can
|
||||
/// name unrelated ones. The values paste unlinked, and the layer's own links on them go.
|
||||
fn without_links(mut props: Value) -> Value {
|
||||
if let Some(m) = props.as_object_mut() {
|
||||
for (k, v) in m.iter_mut() {
|
||||
if k.ends_with("Style") && !k.starts_with("font") {
|
||||
*v = Value::Null;
|
||||
} else if k == "boundVariables" {
|
||||
*v = json!({});
|
||||
}
|
||||
}
|
||||
}
|
||||
props
|
||||
}
|
||||
|
||||
/// Give layer `id` the properties [`copy_props_of`] copied (`props`), those it can take: the text
|
||||
/// properties only to text, the corners only to a layer with corners.
|
||||
pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, props: &Value) -> Result<()> {
|
||||
let mut m = props.as_object().cloned().unwrap_or_default();
|
||||
let is_text = matches!(doc.get(id)?.kind, NodeKind::Text(_));
|
||||
if !is_text {
|
||||
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
|
||||
let n = doc.get(id)?;
|
||||
let (is_text, corners, frame) = (matches!(n.kind, NodeKind::Text(_)), n.kind.has_corner_radius(), n.kind.is_frame_like());
|
||||
let takes = |k: &str| {
|
||||
let text = k.starts_with("font") || k.starts_with("paragraph") || matches!(k, "lineHeight" | "letterSpacing" | "textStyle");
|
||||
let corner = k == "cornerSmoothing" || k.ends_with("Radius");
|
||||
let grid = k == "gridStyle" || k == "grids" || k.starts_with("layoutGrids/");
|
||||
(is_text || !text) && (corners || !corner) && (frame || !grid)
|
||||
};
|
||||
m.retain(|k, _| takes(k));
|
||||
// A style or variable the file doesn't have (deleted since the copy) isn't here to link to: the
|
||||
// values it gave are pasted without a link, so the layer's own link goes too.
|
||||
let here = |v: &Value| v.as_str().is_none_or(|sid| doc.style(sid).is_some());
|
||||
for (k, v) in m.iter_mut() {
|
||||
if k.ends_with("Style") && !k.starts_with("font") && !here(v) {
|
||||
*v = Value::Null;
|
||||
}
|
||||
}
|
||||
if !doc.get(id)?.kind.has_corner_radius() {
|
||||
m.remove("cornerRadius");
|
||||
m.remove("cornerSmoothing");
|
||||
if let Some(Value::Object(copied)) = m.get_mut("boundVariables") {
|
||||
copied.retain(|_, v| v.as_str().is_some_and(|vid| doc.variables.get_by_id(vid).is_some()));
|
||||
}
|
||||
// The layer's own bindings on what is pasted give way to the copied layer's: kept, a binding
|
||||
// would hold the old value over the pasted one. A binding on what the copy doesn't carry (a
|
||||
// text layer's font size, pasted from a frame) stays.
|
||||
if let Some(Value::Object(copied)) = m.get("boundVariables") {
|
||||
let mut bound: serde_json::Map<String, Value> =
|
||||
n.bound.keys().filter(|f| copied_binding(f) && m.contains_key(pasted_key(f))).map(|f| (f.clone(), Value::Null)).collect();
|
||||
bound.extend(copied.iter().filter(|(f, _)| takes(f)).map(|(f, v)| (f.clone(), v.clone())));
|
||||
m.insert("boundVariables".into(), Value::Object(bound));
|
||||
}
|
||||
crate::cmd::props::apply(cmd, doc, id, &m)
|
||||
}
|
||||
|
||||
/// The key of the properties [`copy_props_of`] copies that sets what a variable bound to `field`
|
||||
/// sets: a corner's radius is `cornerRadius`, a side's stroke weight `strokeWeight`, the font
|
||||
/// weight `fontStyle`, a layout grid's field `grids` and a paint's or effect's field its list.
|
||||
fn pasted_key(field: &str) -> &str {
|
||||
match field {
|
||||
"topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "cornerRadius",
|
||||
f if crate::cmd::props::STROKE_SIDES.contains(&f) => "strokeWeight",
|
||||
"fontWeight" => "fontStyle",
|
||||
f => match f.split_once('/') {
|
||||
Some(("layoutGrids", _)) => "grids",
|
||||
Some((list, _)) => list,
|
||||
None => f,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a variable bound to `field` goes with the properties [`copy_props_of`] copies: not a
|
||||
/// size, auto layout spacing, visibility or text content.
|
||||
fn copied_binding(field: &str) -> bool {
|
||||
!matches!(
|
||||
field,
|
||||
"width"
|
||||
| "height"
|
||||
| "minWidth"
|
||||
| "maxWidth"
|
||||
| "minHeight"
|
||||
| "maxHeight"
|
||||
| "gap"
|
||||
| "columnGap"
|
||||
| "rowGap"
|
||||
| "crossGap"
|
||||
| "padding"
|
||||
| "paddingHorizontal"
|
||||
| "paddingVertical"
|
||||
| "paddingTop"
|
||||
| "paddingRight"
|
||||
| "paddingBottom"
|
||||
| "paddingLeft"
|
||||
| "visible"
|
||||
| "characters"
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn paste_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
|
||||
let mut props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
|
||||
if s.ds()?.uid != s.clipboard.props_source_doc {
|
||||
props = without_links(props);
|
||||
}
|
||||
let ids = req_targets("edit.pasteProperties", s, p)?;
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
|
||||
@@ -268,12 +268,13 @@ pub(super) fn stroke_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = req_targets("node.reparent", s, p)?;
|
||||
let parent = req_id("node.reparent", p, "parent")?;
|
||||
let index = opt_index("node.reparent", p, "index")?;
|
||||
pub(super) fn reparent(s: &mut Session, p: &Value, cmd: &str, keep_order: bool) -> Result<Value> {
|
||||
let ids = req_targets(cmd, s, p)?;
|
||||
let parent = req_id(cmd, p, "parent")?;
|
||||
let index = opt_index(cmd, p, "index")?;
|
||||
let doc = s.doc_mut()?;
|
||||
let ids = z_sorted(doc, &roots(doc, &ids));
|
||||
let roots = roots(doc, &ids);
|
||||
let ids = if keep_order { roots } else { z_sorted(doc, &roots) };
|
||||
// `index` is where the first moved layer ends up among the parent's children (bottom first),
|
||||
// counted after the move, the way `node.reorder` counts it. The layers land together, keeping
|
||||
// their order, under the sibling that stays put and ends up just after them (none: on top).
|
||||
@@ -445,20 +446,58 @@ fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Re
|
||||
}
|
||||
};
|
||||
if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills && to_regions) {
|
||||
let (nw, nh) = s.doc().ok().and_then(|d| d.node(id)).map_or((100.0, 100.0), |n| (n.width, n.height));
|
||||
let image_dims = s.doc().ok().and_then(|d| match &new_paint {
|
||||
Some(figcraft_color::Paint { kind: figcraft_color::PaintKind::Image(img), .. })
|
||||
if img.scale_mode == figcraft_color::ImageScaleMode::Crop =>
|
||||
{
|
||||
d.images.get(&img.image).map(|data| (f64::from(data.width), f64::from(data.height)))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
edit_region_fills(s.doc_mut()?, id, ®ions, |list| {
|
||||
if list.is_empty() {
|
||||
list.push(figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE));
|
||||
}
|
||||
let at = idx.unwrap_or(list.len().saturating_sub(1));
|
||||
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
|
||||
let old = slot.clone();
|
||||
edit_slot(slot);
|
||||
if let Some((iw, ih)) = image_dims
|
||||
&& let figcraft_color::PaintKind::Image(img) = &mut slot.kind
|
||||
&& img.scale_mode == figcraft_color::ImageScaleMode::Crop
|
||||
{
|
||||
match &old.kind {
|
||||
figcraft_color::PaintKind::Image(old_img) if old_img.image == img.image => {
|
||||
if old_img.rotation != img.rotation {
|
||||
img.crop = None;
|
||||
img.crop = Some(img.placement_crop(iw, ih, nw, nh));
|
||||
} else if img.crop.is_none() {
|
||||
img.crop = Some(old_img.placement_crop(iw, ih, nw, nh));
|
||||
} else if regions.len() > 1 && old_img.scale_mode == figcraft_color::ImageScaleMode::Crop {
|
||||
img.crop = old_img.crop;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if img.crop.is_none() {
|
||||
img.crop = Some(img.placement_crop(iw, ih, nw, nh));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
let image_dims = s.doc().ok().and_then(|d| match &new_paint {
|
||||
Some(figcraft_color::Paint { kind: figcraft_color::PaintKind::Image(img), .. }) if img.scale_mode == figcraft_color::ImageScaleMode::Crop => {
|
||||
d.images.get(&img.image).map(|data| (f64::from(data.width), f64::from(data.height)))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
let n = doc.get_mut(i)?;
|
||||
for i in &ids {
|
||||
let n = doc.get_mut(*i)?;
|
||||
if fills {
|
||||
crate::cmd::lists::take_character_fills(n);
|
||||
}
|
||||
@@ -470,6 +509,28 @@ fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Re
|
||||
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
|
||||
let old = slot.clone();
|
||||
edit_slot(slot);
|
||||
if let Some((iw, ih)) = image_dims
|
||||
&& let figcraft_color::PaintKind::Image(img) = &mut slot.kind
|
||||
&& img.scale_mode == figcraft_color::ImageScaleMode::Crop
|
||||
{
|
||||
match &old.kind {
|
||||
figcraft_color::PaintKind::Image(old_img) if old_img.image == img.image => {
|
||||
if old_img.rotation != img.rotation {
|
||||
img.crop = None;
|
||||
img.crop = Some(img.placement_crop(iw, ih, n.width, n.height));
|
||||
} else if img.crop.is_none() {
|
||||
img.crop = Some(old_img.placement_crop(iw, ih, n.width, n.height));
|
||||
} else if ids.len() > 1 && old_img.scale_mode == figcraft_color::ImageScaleMode::Crop {
|
||||
img.crop = old_img.crop;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if img.crop.is_none() {
|
||||
img.crop = Some(img.placement_crop(iw, ih, n.width, n.height));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::cmd::lists::rebind_edited_paint(n, fills, at, &old);
|
||||
if fills {
|
||||
n.styles.fill = None;
|
||||
|
||||
@@ -462,6 +462,7 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let uid = ds.uid;
|
||||
let active_uid = s.docs.get(s.active).map(|d| d.uid);
|
||||
s.remember_view(i);
|
||||
s.remove_tabs(|d| d.uid == uid);
|
||||
// Removing a tab before the active one shifts its index; keep the same document selected.
|
||||
s.active = active_uid.and_then(|a| s.docs.iter().position(|d| d.uid == a)).unwrap_or(i.min(s.docs.len().saturating_sub(1)));
|
||||
|
||||
@@ -107,6 +107,7 @@ pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ds.on_disk = on_disk.filter(|_| native);
|
||||
s.docs.push(ds);
|
||||
s.active = s.docs.len() - 1;
|
||||
s.restore_view();
|
||||
let mut out = json!({"index": s.active, "summary": summary});
|
||||
out[if warnings { "warnings" } else { "repairs" }] = json!(loaded.issues);
|
||||
Ok(out)
|
||||
|
||||
@@ -173,7 +173,8 @@ fn wants_data(p: &Value) -> bool {
|
||||
|
||||
/// Save the file of the active tab (the main file for a branch tab, with its branches), or export
|
||||
/// the active document as an experimental `.fig` copy without changing its native save state.
|
||||
/// Without a path the file comes back as base64 `data` for the caller to deliver (#969).
|
||||
/// Without a path the file comes back as base64 `data` for the caller to deliver (#969). Saved
|
||||
/// to another file, the document takes that file's name, as its tab does.
|
||||
fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
|
||||
if let Some(path) = path.as_deref().filter(|p| ext(p) == "fig") {
|
||||
return export_fig(s, &json!({"path": path}));
|
||||
@@ -185,9 +186,7 @@ fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
|
||||
refuse_dropping_images(ds, path)?;
|
||||
}
|
||||
let mut snapshot = FileSnapshot::of(ds);
|
||||
let follows_path = ds.path.as_deref().map_or(ds.doc.name == "Untitled", |old| ds.doc.name == file_stem(old));
|
||||
if let Some(path) = path.as_deref()
|
||||
&& follows_path
|
||||
&& ds.path.as_deref() != Some(path)
|
||||
{
|
||||
Arc::make_mut(&mut snapshot.doc).name = file_stem(path);
|
||||
|
||||
@@ -234,6 +234,9 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Like any paint edit, the layer leaves its paint style.
|
||||
n.styles.fill = None;
|
||||
}
|
||||
if s.ds()?.vector_edit.is_some() {
|
||||
crate::vectoredit::end(s)?;
|
||||
}
|
||||
s.request_ui(cmd, json!({"id": id, "index": index}));
|
||||
Ok(json!({"id": id, "index": index}))
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, paddi
|
||||
mainAlign (min|center|max, or the auto gaps spaceBetween|spaceAround|spaceEvenly), crossAlign (min|center|max|baseline: first text baselines, horizontal layouts), contentAlign (wrapped lines: auto = packed where crossAlign says | spaceBetween), wrap (rows of a horizontal layout, columns of a vertical one), strokesIncluded (the frame's inside stroke takes up space), reverseZ (canvas stacking: true = first on top), \
|
||||
columnGap / rowGap (aliases of gap / crossGap), gridColumns, gridRows, columnTracks / rowTracks ([120 | \"1fr\" | \"auto\" | {sizing, value}]), \
|
||||
gridColumn / gridRow (0-based cell anchor, null = auto), gridColumnSpan, gridRowSpan, gridAlignH / gridAlignV (a grid child's alignment in its cell: min|center|max, auto/null = the frame's), sizingH / sizingV (fixed|hug|fill), \
|
||||
absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, \
|
||||
absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, fontWeight (a number: 400 Regular, 600 Semi Bold — the nearest face the family has), \
|
||||
fontSize, lineHeight (auto|px|\"150%\"), letterSpacing (px|\"2%\"), textAlign (left|center|right|justified), textAlignVertical, textAutoResize \
|
||||
(widthAndHeight|height|none|truncate), textDecoration, textDecorationStyle (solid|dotted|wavy), textDecorationThickness / textDecorationOffset \
|
||||
(auto|px|\"10%\" of the font size; the offset runs from the baseline down to an underline's top edge), textDecorationSkipInk (underlines break around descenders), \
|
||||
|
||||
@@ -642,7 +642,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"text.edit.key",
|
||||
"Text key",
|
||||
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent",
|
||||
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent; elsewhere Tab and Shift+Tab edit the next or previous text layer of the frame in reading order (rows top to bottom, each left to right), all of it selected, and do nothing at the last and the first (in a board object or a widget's field Tab types a tab)",
|
||||
true,
|
||||
|s, p| {
|
||||
let k = req_string("text.edit.key", p, "key")?;
|
||||
|
||||
@@ -298,3 +298,207 @@ fn many_entries_for_one_component_each_link() {
|
||||
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover, "x": 0, "y": 500})));
|
||||
assert_eq!(code(&mut s, i, "react"), "<Button />\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_names_its_source_and_translates_variant_values() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, hover) = button(&mut s);
|
||||
ex(
|
||||
&mut s,
|
||||
"codeConnect.set",
|
||||
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button state={State} />",
|
||||
"source": "src/ui/button.tsx", "values": {"State": {"Hover": "hovered"}}, "notes": "Primary action"}),
|
||||
);
|
||||
let instance = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
|
||||
assert!(code(&mut s, instance, "react").contains(r#"state="hovered""#), "{}", code(&mut s, instance, "react"));
|
||||
// A value without a mapping keeps the design's name.
|
||||
let plain = idv(&ex(&mut s, "instance.create", json!({"component": set})));
|
||||
assert!(code(&mut s, plain, "react").contains(r#"state="Default""#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_outside_the_repository_is_refused() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let c = card(&mut s);
|
||||
for source in ["../up.tsx", "/etc/passwd", "a\\b.tsx", "a/../../b.tsx"] {
|
||||
let e = s.execute("codeConnect.set", &json!({"id": c, "source": source})).unwrap_err();
|
||||
assert!(e.to_string().contains("source"), "{source}: {e}");
|
||||
}
|
||||
assert!(s.execute("codeConnect.set", &json!({"id": c, "values": 3})).is_err());
|
||||
assert!(s.execute("codeConnect.set", &json!({"id": c, "source": "src/card.tsx"})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_fields_survive_a_trip_through_the_file() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(
|
||||
&mut s,
|
||||
"codeConnect.set",
|
||||
json!({"id": set, "name": "Button", "template": "<Button />", "source": "src/b.tsx", "values": {"State": {"Hover": "h"}}, "notes": "n"}),
|
||||
);
|
||||
let text = ex(&mut s, "codeConnect.export", json!({}))["text"].as_str().unwrap().to_string();
|
||||
let mut other = Session::new();
|
||||
ex(&mut other, "file.new", json!({}));
|
||||
let (set2, _) = button(&mut other);
|
||||
assert_eq!(ex(&mut other, "codeConnect.import", json!({"json": text}))["linked"], 1);
|
||||
let link = &other.doc().unwrap().node(set2).unwrap().code_links[0];
|
||||
assert_eq!((link.source.as_str(), link.notes.as_str()), ("src/b.tsx", "n"));
|
||||
assert_eq!(link.values["State"]["Hover"], "h");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_from_before_stays_as_it_was() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
|
||||
let v = ex(&mut s, "codeConnect.export", json!({}));
|
||||
let parsed: Value = serde_json::from_str(v["text"].as_str().unwrap()).unwrap();
|
||||
let keys: Vec<&String> = parsed["links"][0].as_object().unwrap().keys().collect();
|
||||
assert_eq!(keys, ["component", "importPath", "language", "name", "template"], "no new keys unless they're used");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_answers_what_an_agent_asks() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-connect-list-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join("src")).unwrap();
|
||||
std::fs::write(dir.join("src/button.tsx"), "").unwrap();
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, hover) = button(&mut s);
|
||||
let c = card(&mut s);
|
||||
ex(
|
||||
&mut s,
|
||||
"codeConnect.set",
|
||||
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button />", "source": "src/button.tsx"}),
|
||||
);
|
||||
let v = ex(&mut s, "codeConnect.list", json!({"root": dir}));
|
||||
assert_eq!((v["mapped"].as_u64(), v["unmapped"].as_u64()), (Some(1), Some(1)));
|
||||
let b = v["components"].as_array().unwrap().iter().find(|e| e["id"] == json!(set)).unwrap();
|
||||
assert_eq!(b["links"][0]["import"], r#"import { Button } from "@/ui/button";"#);
|
||||
assert_eq!(b["links"][0]["sourceFound"], true);
|
||||
assert!(b["links"][0]["snippet"].as_str().unwrap().contains("<Button"));
|
||||
assert!(b["properties"].as_array().unwrap().iter().any(|p| p["type"] == "variant"));
|
||||
let only = ex(&mut s, "codeConnect.list", json!({"unmapped": true}));
|
||||
assert_eq!(only["components"][0]["id"], json!(c));
|
||||
// A layer leads to the component it uses, a frame to those it holds.
|
||||
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
|
||||
assert_eq!(ex(&mut s, "codeConnect.list", json!({"ids": [i]}))["components"][0]["id"], json!(set));
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "source": "src/gone.tsx"}));
|
||||
assert_eq!(ex(&mut s, "codeConnect.list", json!({"root": dir, "ids": [set]}))["components"][0]["links"][0]["sourceFound"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exporting_keeps_what_other_designs_put_in_the_file() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-connect-others-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("figcraft.connect.json");
|
||||
std::fs::write(&path, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Other","language":"react","name":"Other","template":"<Other />"},{"component":"Button","language":"react","name":"Old","template":"<Old />"}]}"#).unwrap();
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
|
||||
ex(&mut s, "codeConnect.export", json!({"path": path}));
|
||||
let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
let names: Vec<&str> = v["links"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Button", "Other"], "this design's link wins, the other design's stays");
|
||||
assert_eq!(v["project"]["name"], "shop", "keys the command doesn't own stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_refuses_a_malformed_target_rather_than_reading_the_selection() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [set]}));
|
||||
for p in [json!({"id": "not-an-id"}), json!({"ids": [set, "nope"]}), json!({"ids": "1"}), json!({"ids": [999_999]})] {
|
||||
assert!(s.execute("codeConnect.list", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A set called `name` with a variant `prop=value` for each of `values`. Returns (set, variants).
|
||||
fn set_of(s: &mut Session, name: &str, prop: &str, values: &[&str]) -> (NodeId, Vec<NodeId>) {
|
||||
let variants: Vec<NodeId> = values
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, v)| {
|
||||
let f = idv(&ex(s, "frame.create", json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 40, "name": format!("{prop}={v}")})));
|
||||
idv(&ex(s, "component.create", json!({"ids": [f]})))
|
||||
})
|
||||
.collect();
|
||||
let set = idv(&ex(s, "component.combineVariants", json!({"ids": variants.clone()})));
|
||||
ex(s, "node.set", json!({"id": set, "props": {"name": name}}));
|
||||
(set, variants)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_condition_reads_the_designs_value_not_its_name_in_code() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, variants) = set_of(&mut s, "Toggle", "State", &["On", "Off"]);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Toggle", "template": "{State ? \"enabled\" : \"disabled\"} {State}"}));
|
||||
let off = idv(&ex(&mut s, "instance.create", json!({"component": variants[1]})));
|
||||
assert!(code(&mut s, off, "react").starts_with("disabled"), "{}", code(&mut s, off, "react"));
|
||||
// `inactive` reads as true, but the condition is about the design's Off.
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Off": "inactive"}}}));
|
||||
let out = code(&mut s, off, "react");
|
||||
assert!(out.starts_with("disabled") && out.contains("inactive"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mapping_keyed_by_a_name_it_cant_use_is_reported() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, hover) = button(&mut s);
|
||||
let r = ex(
|
||||
&mut s,
|
||||
"codeConnect.set",
|
||||
json!({"id": set, "name": "Button", "template": "<Button state={State} />", "values": {"state": {"Hover": "hovered"}}}),
|
||||
);
|
||||
assert!(r.to_string().contains("\"state\""), "the lowercase key does nothing, so it's named: {r}");
|
||||
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
|
||||
assert!(code(&mut s, i, "react").contains(r#"state="Hover""#));
|
||||
let r = ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Hover": "hovered"}}}));
|
||||
assert!(!r.to_string().contains("\"State\""), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_with_malformed_values_keeps_the_link_there() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />", "values": {"State": {"Hover": "h"}}}));
|
||||
let links = json!([{"component": "Button", "language": "react", "name": "Other", "template": "<Other />", "values": {"State": {"Hover": 7}}}]);
|
||||
let r = ex(&mut s, "codeConnect.import", json!({"json": {"version": 1, "links": links}}));
|
||||
assert_eq!(r["linked"], 0, "{r}");
|
||||
assert!(r["warnings"][0].as_str().unwrap().contains("values"), "{r}");
|
||||
let link = &s.doc().unwrap().node(set).unwrap().code_links[0];
|
||||
assert_eq!((link.name.as_str(), link.values["State"]["Hover"].as_str()), ("Button", "h"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exporting_over_a_file_it_cant_read_is_refused() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-connect-unread-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
|
||||
let big = vec![b' '; 4 * 1024 * 1024 + 1];
|
||||
for (name, bytes) in [("broken.json", b"{\"links\": [".to_vec()), ("list.json", b"[]".to_vec()), ("big.json", big)] {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
assert!(s.execute("codeConnect.export", &json!({"path": path})).is_err(), "{name}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "{name} is left as it was");
|
||||
}
|
||||
// A file that isn't there yet is written.
|
||||
let new = dir.join("figcraft.connect.json");
|
||||
let _ = std::fs::remove_file(&new);
|
||||
ex(&mut s, "codeConnect.export", json!({"path": new}));
|
||||
assert!(new.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -115,6 +115,7 @@ fn copying_a_variant_pastes_an_instance_but_copying_its_set_keeps_the_components
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [hover]}));
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
ex(&mut s, "select.set", json!({"ids": []}));
|
||||
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
|
||||
assert_eq!(component_of(&s, pasted), hover);
|
||||
assert_eq!(node(&s, pasted).name, node(&s, set).name);
|
||||
@@ -241,6 +242,108 @@ fn alt_dragging_a_main_component_copies_an_instance() {
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_a_variant_with_its_set_selected_adds_a_variant_below_the_others() {
|
||||
let mut s = Session::new();
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
let bounds = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
|
||||
let named = |s: &Session, i: NodeId, name: &str| kids(s, i).into_iter().find(|c| node(s, *c).name == name).unwrap();
|
||||
ex(&mut s, "select.set", json!({"ids": [hover]}));
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let bottom = kids(&s, set).iter().map(|k| bounds(&s, *k).y1).fold(f64::MIN, f64::max);
|
||||
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
|
||||
assert!(matches!(node(&s, pasted).kind, NodeKind::Component { .. }));
|
||||
assert_eq!(node(&s, pasted).parent, Some(set));
|
||||
assert_eq!(kids(&s, set).len(), 3);
|
||||
assert_eq!(chars(&s, named(&s, pasted, "Label")), "Hover");
|
||||
let (b, h) = (bounds(&s, pasted), bounds(&s, hover));
|
||||
assert_eq!((b.x0, b.y0), (h.x0, bottom + 20.0));
|
||||
assert!(bounds(&s, set).y1 >= b.y1, "the set grows to hold it");
|
||||
|
||||
let label = named(&s, hover, "Label");
|
||||
ex(&mut s, "select.set", json!({"ids": [label]}));
|
||||
let second = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
|
||||
assert_eq!(node(&s, second).parent, Some(set), "a layer inside a variant selected");
|
||||
assert_eq!(bounds(&s, second).y0, b.y1 + 20.0);
|
||||
ex(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(kids(&s, set).len(), 3);
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variant_pasted_into_its_set_after_the_set_moved_lands_under_the_variant() {
|
||||
let mut s = Session::new();
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
let bounds = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
|
||||
ex(&mut s, "select.set", json!({"ids": [hover]}));
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let x = bounds(&s, set).x0;
|
||||
ex(&mut s, "node.set", json!({"id": set, "props": {"x": x + 1000.0}}));
|
||||
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
|
||||
let (b, h, sb) = (bounds(&s, pasted), bounds(&s, hover), bounds(&s, set));
|
||||
assert_eq!(b.x0, h.x0, "under the copied variant where it is now, not where it was copied");
|
||||
assert!(sb.x0 <= b.x0 && sb.x1 >= b.x1 && sb.y1 >= b.y1, "inside the set");
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
/// Copy `main`, select `selected` and run `command` with `params`; the first pasted layer.
|
||||
fn copy_then(s: &mut Session, main: NodeId, selected: &[NodeId], command: &str, params: Value) -> NodeId {
|
||||
ex(s, "select.set", json!({"ids": [main]}));
|
||||
ex(s, "edit.copy", json!({}));
|
||||
ex(s, "select.set", json!({"ids": selected}));
|
||||
crate::params::id_of(&ex(s, command, params)["ids"][0]).unwrap()
|
||||
}
|
||||
|
||||
// Only a plain paste with the copied variants' own set, or a layer in it, selected makes new
|
||||
// variants. Every other paste of a copied main into a set makes an instance of it there, as
|
||||
// before: the tests below.
|
||||
|
||||
#[test]
|
||||
fn a_variant_pasted_with_another_set_selected_is_an_instance() {
|
||||
let mut s = Session::new();
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
let (other, ..) = button_set(&mut s);
|
||||
ex(&mut s, "node.set", json!({"id": other, "props": {"y": 300}}));
|
||||
let pasted = copy_then(&mut s, hover, &[other], "edit.paste", json!({}));
|
||||
assert_eq!(component_of(&s, pasted), hover);
|
||||
assert_eq!(node(&s, pasted).parent, Some(other));
|
||||
assert_eq!((kids(&s, set).len(), kids(&s, other).len()), (2, 3));
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_main_that_is_no_variant_pasted_with_a_set_selected_is_an_instance() {
|
||||
let mut s = Session::new();
|
||||
let (set, ..) = button_set(&mut s);
|
||||
let k = kit(&mut s);
|
||||
let pasted = copy_then(&mut s, k.card, &[set], "edit.paste", json!({}));
|
||||
assert_eq!(component_of(&s, pasted), k.card);
|
||||
assert_eq!(node(&s, pasted).parent, Some(set));
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variant_pasted_with_its_own_set_as_an_explicit_parent_is_an_instance() {
|
||||
let mut s = Session::new();
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
let pasted = copy_then(&mut s, hover, &[hover], "edit.paste", json!({"parent": set}));
|
||||
assert_eq!(component_of(&s, pasted), hover);
|
||||
assert_eq!(node(&s, pasted).parent, Some(set));
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_over_or_replacing_a_variant_makes_an_instance_of_the_copied_variant() {
|
||||
for command in ["edit.pasteOver", "edit.pasteReplace"] {
|
||||
let mut s = Session::new();
|
||||
let (set, default, hover) = button_set(&mut s);
|
||||
let pasted = copy_then(&mut s, hover, &[default], command, json!({}));
|
||||
assert_eq!(component_of(&s, pasted), hover, "{command} on a variant of the copied variant's set");
|
||||
assert_eq!(node(&s, pasted).parent, Some(set), "{command}");
|
||||
healthy(&s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_a_variant_adds_a_variant_to_its_set() {
|
||||
let mut s = Session::new();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,334 @@
|
||||
//! `design.fix`: repair the findings `design.audit` marks fixable, as one undo step.
|
||||
//!
|
||||
//! Every repair is the safe, unambiguous one the audit already suggested: spacing snapped to the
|
||||
//! 4px grid, radii to the scale, heavy headings to Semi Bold, italic and negative tracking removed,
|
||||
//! glows taken out, shadow colours neutralised and strong borders thinned. Content rules (copy,
|
||||
//! naming) and gradients are left alone: those need a decision, not arithmetic.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use figcraft_color::{Color, PaintKind};
|
||||
use figcraft_doc::{DesignPreset, Document, EffectKind, LayoutMode, LetterSpacing, Node, NodeId, NodeKind, TextData, TextStyle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color};
|
||||
|
||||
/// Fix what `roots` made fixable among `filter`'s rules. With `exact_ids`, only findings on those
|
||||
/// layers are repaired, not findings on their descendants. The walk stops at `max_nodes` nodes.
|
||||
pub(crate) fn run(
|
||||
doc: &mut Document,
|
||||
roots: &[NodeId],
|
||||
anchor: Option<NodeId>,
|
||||
anchor_path: &str,
|
||||
scope: &str,
|
||||
preset: Option<DesignPreset>,
|
||||
filter: Option<&BTreeSet<String>>,
|
||||
exact_ids: Option<&[NodeId]>,
|
||||
max_nodes: usize,
|
||||
dry_run: bool,
|
||||
) -> Value {
|
||||
let settings = Settings::new(doc, preset);
|
||||
let before = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes);
|
||||
// A truncated walk would repair only the visited prefix and stay silent about the rest: the
|
||||
// caller would leave with a "fixed" file that never was whole. Say so instead of guessing.
|
||||
if before.truncated {
|
||||
return json!({
|
||||
"scope": scope,
|
||||
"dryRun": dry_run,
|
||||
"changed": 0,
|
||||
"skipped": 0,
|
||||
"truncated": true,
|
||||
"byRule": {},
|
||||
"before": tally(&before, &settings),
|
||||
"after": tally(&before, &settings),
|
||||
});
|
||||
}
|
||||
let targets: Vec<(NodeId, &'static str)> = before
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|f| f.fixable && settings.enabled(f.rule))
|
||||
.filter(|f| filter.is_none_or(|set| set.contains(f.rule)))
|
||||
.filter(|f| exact_ids.is_none_or(|ids| ids.contains(&f.node)))
|
||||
.map(|f| (f.node, f.rule))
|
||||
.collect();
|
||||
let mut by_rule: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
let mut changed = 0usize;
|
||||
let mut skipped = 0usize;
|
||||
if dry_run {
|
||||
changed = targets.len();
|
||||
for (_, rule) in &targets {
|
||||
*by_rule.entry(*rule).or_default() += 1;
|
||||
}
|
||||
} else {
|
||||
for (id, rule) in &targets {
|
||||
match apply(doc, *id, rule, &settings) {
|
||||
Some(true) => {
|
||||
changed += 1;
|
||||
*by_rule.entry(*rule).or_default() += 1;
|
||||
}
|
||||
_ => skipped += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
let after = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes);
|
||||
json!({
|
||||
"scope": scope,
|
||||
"dryRun": dry_run,
|
||||
"changed": changed,
|
||||
"skipped": skipped,
|
||||
"truncated": false,
|
||||
"byRule": by_rule,
|
||||
"before": tally(&before, &settings),
|
||||
"after": tally(&after, &settings),
|
||||
})
|
||||
}
|
||||
|
||||
fn tally(report: &Report, settings: &Settings) -> Value {
|
||||
let shown: Vec<&super::audit::Finding> = report.findings.iter().filter(|f| settings.enabled(f.rule)).collect();
|
||||
let mut counts = [0usize; 3];
|
||||
for f in &shown {
|
||||
counts[f.severity.index()] += 1;
|
||||
}
|
||||
let score = (100.0 - shown.iter().map(|f| f.severity.penalty()).sum::<f64>()).clamp(0.0, 100.0).round();
|
||||
json!({
|
||||
"score": score,
|
||||
"counts": {"high": counts[2], "medium": counts[1], "low": counts[0]},
|
||||
"nodes": report.nodes,
|
||||
"findings": shown.len(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Apply one finding's repair. `None` when the layer is gone or the repair does not apply to it;
|
||||
/// `Some(false)` when it applied to nothing (a no-op the caller counts as skipped).
|
||||
fn apply(doc: &mut Document, id: NodeId, rule: &str, settings: &Settings) -> Option<bool> {
|
||||
if rule == "color.contrast" {
|
||||
return apply_contrast(doc, id);
|
||||
}
|
||||
let n = doc.node_mut(id)?;
|
||||
match rule {
|
||||
"spacing.off-grid" => apply_spacing(n, settings),
|
||||
"radius.off-scale" => {
|
||||
if ["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) {
|
||||
return Some(false);
|
||||
}
|
||||
apply_radius(n, settings)
|
||||
}
|
||||
"type.weight" | "type.italic" | "type.negative-tracking" => {
|
||||
if text_styled(n) || ["fontSize", "fontStyle", "fontWeight", "letterSpacing"].iter().any(|k| n.bound.contains_key(*k)) {
|
||||
return Some(false);
|
||||
}
|
||||
match rule {
|
||||
"type.weight" => apply_text(n, cap_weight),
|
||||
"type.italic" => apply_text(n, unitalic),
|
||||
_ => apply_text(n, zero_tracking),
|
||||
}
|
||||
}
|
||||
"color.glow" | "color.colored-shadow" => {
|
||||
if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) {
|
||||
return Some(false);
|
||||
}
|
||||
if rule == "color.glow" { apply_glow(n) } else { apply_neutral_shadows(n) }
|
||||
}
|
||||
"color.border-opacity" => {
|
||||
if n.styles.stroke.is_some() || n.bound.keys().any(|k| k.starts_with("strokes/")) {
|
||||
return Some(false);
|
||||
}
|
||||
apply_border(n)
|
||||
}
|
||||
_ => Some(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// A text layer whose type comes from a text style (the whole layer or one run).
|
||||
fn text_styled(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => n.styles.text.is_some() || t.style.style_id.is_some() || t.runs.iter().any(|r| r.style.style_id.is_some()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Darken (or lighten, on a dark backdrop) the text colour until it reaches the WCAG ratio. The
|
||||
/// hue is kept as far as the blend allows; when even black or white cannot reach the ratio, the
|
||||
/// text is left as it is and counted as skipped.
|
||||
fn apply_contrast(doc: &mut Document, id: NodeId) -> Option<bool> {
|
||||
let n = doc.node(id)?;
|
||||
let NodeKind::Text(t) = &n.kind else { return Some(false) };
|
||||
if n.styles.fill.is_some() || n.bound.keys().any(|k| k.starts_with("fills/")) {
|
||||
return Some(false);
|
||||
}
|
||||
let fg = text_color(n, t)?;
|
||||
let bg = backdrop(doc, n)?;
|
||||
let size = t.style.font_size;
|
||||
let large = size >= 24.0 || (size >= 18.0 && t.style.weight() >= 700);
|
||||
let need = if large { 3.0 } else { 4.5 };
|
||||
if fg.contrast(bg) >= need {
|
||||
return Some(false);
|
||||
}
|
||||
let fixed = accessible(fg, bg, need);
|
||||
if fixed.contrast(bg) < need {
|
||||
return Some(false);
|
||||
}
|
||||
let n = doc.node_mut(id)?;
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Some(false) };
|
||||
let paints = match &mut t.style.fills {
|
||||
Some(fills) => fills,
|
||||
None => &mut n.fills,
|
||||
};
|
||||
let paint = paints.iter_mut().rev().find(|p| p.visible && matches!(&p.kind, PaintKind::Solid { .. }))?;
|
||||
paint.opacity = 1.0;
|
||||
if let PaintKind::Solid { color } = &mut paint.kind {
|
||||
*color = fixed.with_alpha(fg.a);
|
||||
Some(true)
|
||||
} else {
|
||||
Some(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// The closest shade of `fg` towards black (light backdrop) or white (dark backdrop) that meets
|
||||
/// `need` against `bg`, by bisection.
|
||||
fn accessible(fg: Color, bg: Color, need: f32) -> Color {
|
||||
let target = if bg.luminance() > 0.5 { Color::BLACK } else { Color::WHITE };
|
||||
let (mut lo, mut hi) = (0.0f32, 1.0f32);
|
||||
let mut best = target;
|
||||
for _ in 0..24 {
|
||||
let t = (lo + hi) / 2.0;
|
||||
let c = Color::new(fg.r + (target.r - fg.r) * t, fg.g + (target.g - fg.g) * t, fg.b + (target.b - fg.b) * t, 1.0);
|
||||
if c.contrast(bg) >= need {
|
||||
best = c;
|
||||
hi = t;
|
||||
} else {
|
||||
lo = t;
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
fn apply_spacing(n: &mut Node, settings: &Settings) -> Option<bool> {
|
||||
// Any spacing binding owns the whole layout value: fixing one field next to a token would
|
||||
// leave a mixed layout and is not what the audit promised.
|
||||
if [
|
||||
"gap",
|
||||
"columnGap",
|
||||
"rowGap",
|
||||
"crossGap",
|
||||
"padding",
|
||||
"paddingHorizontal",
|
||||
"paddingVertical",
|
||||
"paddingTop",
|
||||
"paddingRight",
|
||||
"paddingBottom",
|
||||
"paddingLeft",
|
||||
]
|
||||
.iter()
|
||||
.any(|k| n.bound.contains_key(*k))
|
||||
{
|
||||
return Some(false);
|
||||
}
|
||||
let al = n.layout.as_mut()?;
|
||||
let mut changed = false;
|
||||
if al.mode != LayoutMode::Grid {
|
||||
let gap = settings.snap(al.gap);
|
||||
if (gap - al.gap).abs() > 1e-6 {
|
||||
al.gap = gap;
|
||||
changed = true;
|
||||
}
|
||||
if al.wrap {
|
||||
let cross = settings.snap(al.cross_gap);
|
||||
if (cross - al.cross_gap).abs() > 1e-6 {
|
||||
al.cross_gap = cross;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for side in &mut al.padding {
|
||||
let value = settings.snap(*side);
|
||||
if (value - *side).abs() > 1e-6 {
|
||||
*side = value;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
|
||||
fn apply_radius(n: &mut Node, settings: &Settings) -> Option<bool> {
|
||||
let (w, h) = (n.width, n.height);
|
||||
let pill = w.min(h);
|
||||
let mut changed = false;
|
||||
for r in &mut n.corners.radii {
|
||||
if *r > 0.01 && !settings.radius_ok(*r, w, h) {
|
||||
*r = if pill > 0.0 && (*r - pill / 2.0).abs() <= 1.0 { pill / 2.0 } else { settings.snap_radius(*r) };
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
|
||||
/// Run `f` over a text layer's base style and its runs; true when any style changed.
|
||||
fn apply_text(n: &mut Node, f: fn(&mut TextStyle) -> bool) -> Option<bool> {
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Some(false) };
|
||||
let TextData { style, runs, .. } = t;
|
||||
let mut changed = f(style);
|
||||
for run in runs {
|
||||
changed |= f(&mut run.style);
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
|
||||
fn cap_weight(s: &mut TextStyle) -> bool {
|
||||
if s.font_size >= 20.0 && s.weight() > 600 {
|
||||
s.set_font_style("Semi Bold");
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn unitalic(s: &mut TextStyle) -> bool {
|
||||
if !s.italic() {
|
||||
return false;
|
||||
}
|
||||
let words: Vec<&str> = s.font_style.split_whitespace().filter(|w| !w.eq_ignore_ascii_case("italic")).collect();
|
||||
let name = if words.is_empty() { "Regular".to_string() } else { words.join(" ") };
|
||||
s.set_font_style(name);
|
||||
true
|
||||
}
|
||||
|
||||
fn zero_tracking(s: &mut TextStyle) -> bool {
|
||||
let px = s.letter_spacing.resolve(s.font_size);
|
||||
if s.font_size > 0.0 && s.font_size < 24.0 && px.is_finite() && px < -0.01 {
|
||||
s.letter_spacing = LetterSpacing::Percent(0.0);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_glow(n: &mut Node) -> Option<bool> {
|
||||
let before = n.effects.len();
|
||||
n.effects.retain(|e| !is_glow(e));
|
||||
Some(n.effects.len() != before)
|
||||
}
|
||||
|
||||
fn apply_neutral_shadows(n: &mut Node) -> Option<bool> {
|
||||
let mut changed = false;
|
||||
for e in &mut n.effects {
|
||||
if let EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) = &mut e.kind
|
||||
&& is_colored_shadow(s)
|
||||
{
|
||||
s.color = Color::new(0.0, 0.0, 0.0, s.color.a);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
|
||||
fn apply_border(n: &mut Node) -> Option<bool> {
|
||||
let mut changed = false;
|
||||
for p in &mut n.strokes {
|
||||
if p.visible && p.opacity > 0.08 {
|
||||
p.opacity = 0.08;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
//! Design review: deterministic checks for the usual AI-generated interface tells.
|
||||
//!
|
||||
//! `design.audit` reads a selection, a page or the whole document and reports what a designer
|
||||
//! would fix first — spacing off the 4px grid, radii outside the scale, too many type sizes,
|
||||
//! gradient text, glows, low-contrast text, emoji labels. It changes nothing. `design.fix` (the
|
||||
//! planned follow-up) repairs the findings marked `fixable`.
|
||||
//!
|
||||
//! The rules are our own reading of the public "unslop" checklist (CC BY 4.0, heydamir/unslop):
|
||||
//! only the ideas, no text or assets from it.
|
||||
|
||||
mod audit;
|
||||
mod fix;
|
||||
mod rules;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use figcraft_doc::{CollectionId, DesignPreset, DesignReview, Document, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII, ModeId, NodeId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::CommandSpec;
|
||||
use crate::params;
|
||||
use crate::{EngineError, Result, Session, bad, spec};
|
||||
use rules::{RULES, Severity, presets_of, rule};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
spec!(
|
||||
"design.audit",
|
||||
"Check design",
|
||||
"{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them), limit?: 1000-1000000 (nodes before the report says truncated; default 50000)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, limit, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated, unchecked: [{rule, reason, layers?}]} reads the design and reports the AI-slop tells; changes nothing (unchecked names the rules the run could not check: truncated, or a measure cap)",
|
||||
false,
|
||||
audit_cmd
|
||||
),
|
||||
spec!(
|
||||
"design.fix",
|
||||
"Fix design",
|
||||
"{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), limit?: 1000-1000000 (nodes the walk looks at; default 50000), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone",
|
||||
true,
|
||||
fix_cmd
|
||||
),
|
||||
spec!(
|
||||
"design.assert",
|
||||
"Assert design",
|
||||
"{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000), allowSkipped?: bool (default false; passes a gate naming a rule the file disables or its preset excludes — never a truncated audit or a measure cap)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit could not check a rule it asked for (truncated at the node limit it ran with, past a measure cap, or skipped by the file's settings: what it did not reach is unchecked, so narrow the scope, filter the rules or raise `limit`); read-only, for CI",
|
||||
false,
|
||||
assert_cmd
|
||||
),
|
||||
spec!(
|
||||
"design.configure",
|
||||
"Configure design review",
|
||||
"{preset?: recommended|strict|accessibility, grid?: 1-64 (px, default 4), radii?: [px] (empty: the grid scale and a pill), brand?: [colour] (accent colours the file owns), disabled?: [rule ids] (rules off in this file), reset?: bool} → {preset, grid, radii, brand, disabled} changes the file's design review settings in one undo step; audit, fix and assert use them from then on",
|
||||
true,
|
||||
configure_cmd
|
||||
),
|
||||
spec!(
|
||||
"design.rules",
|
||||
"List design rules",
|
||||
"{} → {rules: [{id, severity, fixable, description, presets}], presets: [{id, description}]}",
|
||||
false,
|
||||
|_, _| Ok(json!({
|
||||
"rules": RULES.iter().map(|r| json!({
|
||||
"id": r.id,
|
||||
"severity": r.severity.id(),
|
||||
"fixable": r.fixable,
|
||||
"description": r.description,
|
||||
"presets": presets_of(r.id),
|
||||
})).collect::<Vec<_>>(),
|
||||
"presets": DesignPreset::ALL.iter().map(|p| json!({
|
||||
"id": p.id(),
|
||||
"description": preset_description(*p),
|
||||
})).collect::<Vec<_>>(),
|
||||
}))
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn audit_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (label, roots, anchor, path) = scope_of(s, "design.audit", p)?;
|
||||
let min = severity_arg("design.audit", p)?;
|
||||
let filter = filter_arg("design.audit", p)?;
|
||||
let preset = preset_arg("design.audit", p)?;
|
||||
let modes = modes_arg("design.audit", p, s.doc()?)?;
|
||||
let limit = limit_arg("design.audit", p)?;
|
||||
Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes, limit))
|
||||
}
|
||||
|
||||
fn fix_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (label, roots, anchor, path) = scope_of(s, "design.fix", p)?;
|
||||
let filter = filter_arg("design.fix", p)?;
|
||||
let preset = preset_arg("design.fix", p)?;
|
||||
let exact = params::boolean(p, "exact").unwrap_or(false);
|
||||
let exact_ids = if exact { ids_arg("design.fix", p)? } else { None };
|
||||
let limit = limit_arg("design.fix", p)?;
|
||||
let dry = params::boolean(p, "dryRun").unwrap_or(false);
|
||||
// A dry run or a fix that changes nothing must not mark the file unsaved or add an undo step:
|
||||
// work on a copy and put it back only when it differs.
|
||||
let mut doc = s.doc()?.clone();
|
||||
let result = fix::run(&mut doc, &roots, anchor, &path, &label, preset, filter.as_ref(), exact_ids.as_deref(), limit, dry);
|
||||
if !dry && s.doc()? != &doc {
|
||||
*s.doc_mut()? = doc;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// `design.assert`: a read-only gate for CI. Returns the score when the design passes; an error
|
||||
/// that names the counts when it does not.
|
||||
fn assert_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (label, roots, anchor, path) = scope_of(s, "design.assert", p)?;
|
||||
let filter = filter_arg("design.assert", p)?;
|
||||
let fail_on = severity_named("design.assert", p, "failOn", Severity::High)?;
|
||||
let preset = preset_arg("design.assert", p)?;
|
||||
let modes = modes_arg("design.assert", p, s.doc()?)?;
|
||||
let min_score = match params::get(p, "minScore") {
|
||||
None => 0.0,
|
||||
Some(v) => match params::f64_of(v) {
|
||||
Some(v) if (0.0..=100.0).contains(&v) => v,
|
||||
_ => return Err(bad("design.assert", "`minScore` must be a number between 0 and 100")),
|
||||
},
|
||||
};
|
||||
// The score covers the whole review (as the window shows it); only findings at or above
|
||||
// `failOn` fail the gate.
|
||||
let limit = limit_arg("design.assert", p)?;
|
||||
let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes, limit);
|
||||
let failing: Vec<&Value> = report["findings"]
|
||||
.as_array()
|
||||
.map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect())
|
||||
.unwrap_or_default();
|
||||
let score = report["score"].as_f64().unwrap_or(0.0);
|
||||
// A truncated audit checked only the first nodes of the scope: what it did not reach is
|
||||
// unchecked, so it can never prove a design passes (a white-on-white label past the cap
|
||||
// would sail through as score 100).
|
||||
if report["truncated"].as_bool() == Some(true) {
|
||||
let nodes = report["nodes"].as_u64().unwrap_or(0);
|
||||
return Err(EngineError::Other(format!(
|
||||
"design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or raise `limit`, then assert again"
|
||||
)));
|
||||
}
|
||||
// A gate naming a rule the file disabled or its preset leaves out is asking for a check the
|
||||
// run does not do: refused, unless the caller passes `allowSkipped` to accept exactly that —
|
||||
// it does not waive a truncated audit or a measure cap, which stay unchecked evidence.
|
||||
let allow_skipped = params::boolean(p, "allowSkipped").unwrap_or(false);
|
||||
let skipped: Vec<&str> = report["unchecked"]
|
||||
.as_array()
|
||||
.map(|v| {
|
||||
v.iter()
|
||||
.filter(|e| matches!(e["reason"].as_str(), Some("disabled") | Some("preset")))
|
||||
.filter_map(|e| e["rule"].as_str())
|
||||
.filter(|rule| filter.as_ref().is_none_or(|set| set.contains(*rule)))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if !skipped.is_empty() && !allow_skipped {
|
||||
return Err(EngineError::Other(format!(
|
||||
"design review failed: the file's settings skip {} (disabled by the file, or not in the preset it checks with), so a gate naming it checked nothing for it; check the file's design.configure, gate with a preset that includes it, or pass allowSkipped to accept the skip",
|
||||
skipped.join(", ")
|
||||
)));
|
||||
}
|
||||
// What the audit reported as unchecked, restricted to the rules this gate asked for. The
|
||||
// audit names each rule it could not check (`limit` truncation is handled above with its own
|
||||
// advice), so a cap added there fails this gate without a list here to keep in step.
|
||||
let unchecked: Vec<&str> = report["unchecked"]
|
||||
.as_array()
|
||||
.map(|v| {
|
||||
v.iter()
|
||||
.filter(|e| e["reason"].as_str() == Some("measure-cap"))
|
||||
.filter_map(|e| e["rule"].as_str())
|
||||
.filter(|rule| filter.as_ref().is_none_or(|set| set.contains(*rule)))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if !unchecked.is_empty() {
|
||||
return Err(EngineError::Other(format!(
|
||||
"design review failed: the audit did not measure all of {} on this scope (past the per-run measure cap), so what it skipped is unchecked; audit a smaller scope, then assert again",
|
||||
unchecked.join(", ")
|
||||
)));
|
||||
}
|
||||
if !failing.is_empty() || score < min_score {
|
||||
let mut by_rule: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
|
||||
for f in &failing {
|
||||
if let Some(rule) = f["rule"].as_str() {
|
||||
*by_rule.entry(rule).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let rules: Vec<String> = by_rule.iter().take(4).map(|(rule, count)| format!("{rule} ×{count}")).collect();
|
||||
let detail = if rules.is_empty() { String::new() } else { format!(" ({})", rules.join(", ")) };
|
||||
return Err(EngineError::Other(format!(
|
||||
"design review failed: score {score:.0}, {} finding(s) at {} or above{detail}",
|
||||
failing.len(),
|
||||
fail_on.id()
|
||||
)));
|
||||
}
|
||||
Ok(json!({"ok": true, "score": score, "counts": report["counts"]}))
|
||||
}
|
||||
|
||||
fn severity_named(cmd: &str, p: &Value, key: &str, default: Severity) -> Result<Severity> {
|
||||
match params::string(p, key).map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) {
|
||||
None => Ok(default),
|
||||
Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`{key}` must be low, medium or high, not `{s}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `limit` parameter: how many nodes one audit walk may look at before the report says
|
||||
/// `truncated`. Default 50,000; a CI gate over a huge file may raise it, never past the hard cap.
|
||||
fn limit_arg(cmd: &str, p: &Value) -> Result<usize> {
|
||||
let Some(v) = params::get(p, "limit") else { return Ok(audit::MAX_NODES) };
|
||||
let Some(n) = params::f64_of(v) else { return Err(bad(cmd, "`limit` must be a whole number of nodes between 1,000 and 1,000,000")) };
|
||||
if !n.is_finite() || n.fract() != 0.0 || !(1_000.0..=(audit::MAX_LIMIT as f64)).contains(&n) {
|
||||
return Err(bad(cmd, "`limit` must be a whole number of nodes between 1,000 and 1,000,000"));
|
||||
}
|
||||
Ok(n as usize)
|
||||
}
|
||||
|
||||
fn preset_arg(cmd: &str, p: &Value) -> Result<Option<DesignPreset>> {
|
||||
match params::string(p, "preset").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) {
|
||||
None => Ok(None),
|
||||
Some(s) => {
|
||||
DesignPreset::from_id(&s).map(Some).ok_or_else(|| bad(cmd, format!("`preset` must be recommended, strict or accessibility, not `{s}`")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn preset_description(preset: DesignPreset) -> &'static str {
|
||||
match preset {
|
||||
DesignPreset::Recommended => "The usual AI-generated tells",
|
||||
DesignPreset::Strict => "Recommended plus accent colours and frames without auto layout",
|
||||
DesignPreset::Accessibility => "Contrast, the type floor, gradient text and clipped text only",
|
||||
}
|
||||
}
|
||||
|
||||
/// The variable modes a run resolves colours in: `{collection: mode}`, by id or by name.
|
||||
fn modes_arg(cmd: &str, p: &Value, doc: &Document) -> Result<BTreeMap<CollectionId, ModeId>> {
|
||||
let Some(v) = params::get(p, "modes") else { return Ok(BTreeMap::new()) };
|
||||
let Value::Object(map) = v else { return Err(bad(cmd, "`modes` must be an object of collection → mode")) };
|
||||
if map.len() > 64 {
|
||||
return Err(bad(cmd, "at most 64 collections in `modes`"));
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
for (collection_key, mode_value) in map {
|
||||
let Some(mode_key) = mode_value.as_str().map(str::trim).filter(|s| !s.is_empty()) else {
|
||||
return Err(bad(cmd, "`modes` values must be mode ids or names"));
|
||||
};
|
||||
let Some(collection) = doc.variables.collection(collection_key.trim()) else {
|
||||
return Err(bad(cmd, format!("unknown collection `{collection_key}`")));
|
||||
};
|
||||
let Some(mode) = collection.find_mode(mode_key) else {
|
||||
return Err(bad(cmd, format!("unknown mode `{mode_key}` in `{}`", collection.name)));
|
||||
};
|
||||
out.insert(collection.id.clone(), mode.id.clone());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `design.configure`: change the file's design system and rules in one undo step.
|
||||
fn configure_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut config = if params::boolean(p, "reset").unwrap_or(false) { DesignReview::default() } else { s.doc()?.design_review.clone() };
|
||||
if let Some(preset) = preset_arg("design.configure", p)? {
|
||||
config.preset = preset;
|
||||
}
|
||||
if let Some(v) = params::get(p, "grid") {
|
||||
let grid = params::f64_of(v)
|
||||
.filter(|g| g.is_finite() && (GRID_MIN..=GRID_MAX).contains(g))
|
||||
.ok_or_else(|| bad("design.configure", format!("`grid` must be a number from {GRID_MIN} to {GRID_MAX}")))?;
|
||||
config.grid = grid;
|
||||
}
|
||||
if let Some(v) = params::get(p, "radii") {
|
||||
let Value::Array(items) = v else { return Err(bad("design.configure", "`radii` must be an array of numbers")) };
|
||||
if items.len() > MAX_RADII {
|
||||
return Err(bad("design.configure", format!("at most {MAX_RADII} radii")));
|
||||
}
|
||||
let mut radii = Vec::new();
|
||||
for item in items {
|
||||
let r = params::f64_of(item)
|
||||
.filter(|r| r.is_finite() && (0.0..=999.0).contains(r))
|
||||
.ok_or_else(|| bad("design.configure", "each radius must be a number from 0 to 999"))?;
|
||||
radii.push((r * 100.0).round() / 100.0);
|
||||
}
|
||||
radii.sort_by(f64::total_cmp);
|
||||
radii.dedup_by(|a, b| (*a - *b).abs() <= 1e-6);
|
||||
config.radii = radii;
|
||||
}
|
||||
if let Some(v) = params::get(p, "brand") {
|
||||
let Value::Array(items) = v else { return Err(bad("design.configure", "`brand` must be an array of colours")) };
|
||||
if items.len() > MAX_BRAND_COLORS {
|
||||
return Err(bad("design.configure", format!("at most {MAX_BRAND_COLORS} brand colours")));
|
||||
}
|
||||
let mut brand = Vec::new();
|
||||
for item in items {
|
||||
let color = params::color_of(item).ok_or_else(|| bad("design.configure", "each brand colour must be a colour"))?;
|
||||
if color.a > 0.05 {
|
||||
brand.push(color);
|
||||
}
|
||||
}
|
||||
config.brand = brand;
|
||||
}
|
||||
if let Some(v) = params::get(p, "disabled") {
|
||||
let Value::Array(items) = v else { return Err(bad("design.configure", "`disabled` must be an array of rule ids")) };
|
||||
let mut ids = BTreeSet::new();
|
||||
for item in items {
|
||||
let Some(id) = item.as_str().map(str::trim) else {
|
||||
return Err(bad("design.configure", "`disabled` must be an array of rule ids"));
|
||||
};
|
||||
if rule(id).is_none() {
|
||||
return Err(bad("design.configure", format!("unknown rule `{id}` (run design.rules for the list)")));
|
||||
}
|
||||
ids.insert(id.to_string());
|
||||
}
|
||||
config.disabled = ids.into_iter().collect();
|
||||
}
|
||||
if s.doc()?.design_review == config {
|
||||
return Ok(settings_json(&config));
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
doc.design_review = config;
|
||||
Ok(settings_json(&doc.design_review))
|
||||
}
|
||||
|
||||
fn settings_json(config: &DesignReview) -> Value {
|
||||
let brand: Vec<String> = config
|
||||
.brand
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let rgba = c.to_rgba8();
|
||||
format!("#{:02X}{:02X}{:02X}", rgba[0], rgba[1], rgba[2])
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"preset": config.preset.id(),
|
||||
"grid": config.grid(),
|
||||
"radii": config.radii,
|
||||
"brand": brand,
|
||||
"disabled": config.disabled,
|
||||
})
|
||||
}
|
||||
|
||||
/// The layers a command works on, its scope label, the layer aggregate findings point at and that
|
||||
/// layer's path.
|
||||
/// The `ids` parameter, parsed without collapsing ancestors: `exact` needs the layers the caller
|
||||
/// listed, while the walk uses their top-most roots.
|
||||
fn ids_arg(cmd: &str, p: &Value) -> Result<Option<Vec<NodeId>>> {
|
||||
let Some(v) = params::get(p, "ids") else { return Ok(None) };
|
||||
let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) };
|
||||
let mut ids = Vec::new();
|
||||
for item in items {
|
||||
let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) };
|
||||
ids.push(id);
|
||||
}
|
||||
Ok(Some(ids))
|
||||
}
|
||||
|
||||
fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec<NodeId>, Option<NodeId>, String)> {
|
||||
let doc = s.doc()?;
|
||||
// `ids` names the layers directly (the review window fixes only the findings the user kept).
|
||||
// An empty or unknown id checks nothing, which a CI gate must not mistake for a pass.
|
||||
if let Some(ids) = ids_arg(cmd, p)? {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "`ids` is empty: name at least one layer to audit, or drop `ids` for the selection, page or document"));
|
||||
}
|
||||
let missing: Vec<String> = ids.iter().filter(|id| doc.node(**id).is_none()).map(|id| id.to_string()).collect();
|
||||
if !missing.is_empty() {
|
||||
return Err(bad(cmd, format!("`ids` names layers that do not exist: {}", missing.join(", "))));
|
||||
}
|
||||
let roots = top_most(doc, &ids);
|
||||
let anchor = roots.first().copied();
|
||||
let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default();
|
||||
return Ok(("selection".into(), roots, anchor, path));
|
||||
}
|
||||
let scope = scope_arg(cmd, p)?;
|
||||
let selection = s.selection();
|
||||
let page = s.page()?;
|
||||
// An explicitly empty selection checks nothing either; only the implicit default falls back
|
||||
// to the page. A CI gate must not read an unchecked scope as a pass.
|
||||
if scope.as_deref() == Some("selection") && selection.is_empty() {
|
||||
return Err(bad(cmd, "nothing is selected: name `ids`, pick a scope of page or document, or select the layers to audit"));
|
||||
}
|
||||
let (roots, label, anchor, path) = match scope.as_deref() {
|
||||
None if selection.is_empty() => (vec![page], "page", Some(page), node_label(doc, page)),
|
||||
None => selection_scope(doc, &selection),
|
||||
Some("selection") => selection_scope(doc, &selection),
|
||||
Some("page") => (vec![page], "page", Some(page), node_label(doc, page)),
|
||||
Some("document") => {
|
||||
let roots = doc.pages.clone();
|
||||
let anchor = roots.first().copied();
|
||||
let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default();
|
||||
(roots, "document", anchor, path)
|
||||
}
|
||||
Some(other) => return Err(bad(cmd, format!("`scope` must be selection, page or document, not `{other}`"))),
|
||||
};
|
||||
Ok((label.to_string(), roots, anchor, path))
|
||||
}
|
||||
|
||||
fn selection_scope(doc: &Document, selection: &[NodeId]) -> (Vec<NodeId>, &'static str, Option<NodeId>, String) {
|
||||
let roots = top_most(doc, selection);
|
||||
let anchor = roots.first().copied();
|
||||
let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default();
|
||||
(roots, "selection", anchor, path)
|
||||
}
|
||||
|
||||
fn scope_arg(cmd: &str, p: &Value) -> Result<Option<String>> {
|
||||
let Some(v) = params::get(p, "scope") else { return Ok(None) };
|
||||
let Value::String(s) = v else { return Err(bad(cmd, "`scope` must be a string")) };
|
||||
let s = s.trim().to_ascii_lowercase();
|
||||
if s.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if matches!(s.as_str(), "selection" | "page" | "document") {
|
||||
Ok(Some(s))
|
||||
} else {
|
||||
Err(bad(cmd, format!("`scope` must be selection, page or document, not `{s}`")))
|
||||
}
|
||||
}
|
||||
|
||||
fn severity_arg(cmd: &str, p: &Value) -> Result<Severity> {
|
||||
match params::string(p, "minSeverity").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) {
|
||||
None => Ok(Severity::Low),
|
||||
Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`minSeverity` must be low, medium or high, not `{s}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_arg(cmd: &str, p: &Value) -> Result<Option<BTreeSet<String>>> {
|
||||
let Some(v) = params::get(p, "rules") else { return Ok(None) };
|
||||
let Value::Array(items) = v else { return Err(bad(cmd, "`rules` must be an array of rule ids")) };
|
||||
// A filter that names nothing checks nothing: a gate would pass over a review that never
|
||||
// ran, the same way a truncated audit would.
|
||||
if items.is_empty() {
|
||||
return Err(bad(
|
||||
cmd,
|
||||
"`rules` names no rule, so nothing would be checked; list at least one (design.rules has them) or leave `rules` out to check them all",
|
||||
));
|
||||
}
|
||||
let mut set = BTreeSet::new();
|
||||
for item in items {
|
||||
let Some(s) = item.as_str() else { return Err(bad(cmd, "`rules` must be an array of rule ids")) };
|
||||
let id = s.trim();
|
||||
if rule(id).is_none() {
|
||||
return Err(bad(cmd, format!("unknown rule `{id}` (run design.rules for the list)")));
|
||||
}
|
||||
set.insert(id.to_string());
|
||||
}
|
||||
Ok(Some(set))
|
||||
}
|
||||
|
||||
/// Selected layers without the ones whose ancestor is selected too: their subtrees would be
|
||||
/// audited twice.
|
||||
fn top_most(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out: Vec<NodeId> = Vec::new();
|
||||
for id in ids {
|
||||
if out.contains(id) {
|
||||
continue;
|
||||
}
|
||||
let mut parent = doc.node(*id).and_then(|n| n.parent);
|
||||
let mut depth = 0;
|
||||
let mut nested = false;
|
||||
while let Some(pid) = parent {
|
||||
if depth > 256 {
|
||||
break;
|
||||
}
|
||||
if ids.contains(&pid) {
|
||||
nested = true;
|
||||
break;
|
||||
}
|
||||
parent = doc.node(pid).and_then(|n| n.parent);
|
||||
depth += 1;
|
||||
}
|
||||
if !nested {
|
||||
out.push(*id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn node_label(doc: &Document, id: NodeId) -> String {
|
||||
doc.node(id).map(|n| n.name.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Layer {}", id.0))
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The rules `design.audit` checks, with the severity and fixability the report carries.
|
||||
|
||||
use figcraft_doc::DesignPreset;
|
||||
|
||||
/// How much a finding matters: `High` first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) enum Severity {
|
||||
Low,
|
||||
Medium,
|
||||
High,
|
||||
}
|
||||
|
||||
impl Severity {
|
||||
pub(crate) fn id(self) -> &'static str {
|
||||
match self {
|
||||
Severity::Low => "low",
|
||||
Severity::Medium => "medium",
|
||||
Severity::High => "high",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_id(s: &str) -> Option<Self> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"low" => Some(Severity::Low),
|
||||
"medium" | "med" => Some(Severity::Medium),
|
||||
"high" => Some(Severity::High),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `0` for low, `1` for medium, `2` for high.
|
||||
pub(crate) fn index(self) -> usize {
|
||||
match self {
|
||||
Severity::Low => 0,
|
||||
Severity::Medium => 1,
|
||||
Severity::High => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// The points a finding of this severity takes off the score.
|
||||
pub(crate) fn penalty(self) -> f64 {
|
||||
match self {
|
||||
Severity::Low => 0.5,
|
||||
Severity::Medium => 2.0,
|
||||
Severity::High => 5.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One check: what it looks for, how much it matters and whether `design.fix` can repair it.
|
||||
pub(crate) struct Rule {
|
||||
pub id: &'static str,
|
||||
pub severity: Severity,
|
||||
/// The planned fixer can change this without guessing (see `docs/design-review.md`).
|
||||
pub fixable: bool,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
pub(crate) const RULES: &[Rule] = &[
|
||||
Rule { id: "spacing.off-grid", severity: Severity::Medium, fixable: true, description: "Auto layout gap or padding is not on the 4px grid" },
|
||||
Rule { id: "radius.off-scale", severity: Severity::Low, fixable: true, description: "A corner radius is not on the 4px scale or a pill" },
|
||||
Rule { id: "type.sizes", severity: Severity::Medium, fixable: false, description: "More than five font sizes in one scope" },
|
||||
Rule { id: "type.families", severity: Severity::Medium, fixable: false, description: "More than two font families in one scope" },
|
||||
Rule { id: "type.weight", severity: Severity::Low, fixable: true, description: "A heading uses a weight above 600" },
|
||||
Rule { id: "type.italic", severity: Severity::Low, fixable: true, description: "Interface text is italic" },
|
||||
Rule { id: "type.too-small", severity: Severity::Medium, fixable: false, description: "Body text is smaller than 11px" },
|
||||
Rule { id: "type.negative-tracking", severity: Severity::Low, fixable: true, description: "Small text has negative letter spacing" },
|
||||
Rule { id: "color.gradient", severity: Severity::Medium, fixable: false, description: "A shape is filled or stroked with a gradient" },
|
||||
Rule { id: "color.gradient-text", severity: Severity::High, fixable: false, description: "Text is painted with a gradient" },
|
||||
Rule {
|
||||
id: "color.glow",
|
||||
severity: Severity::Medium,
|
||||
fixable: true,
|
||||
description: "A shadow has no offset and a large blur, so it reads as a glow",
|
||||
},
|
||||
Rule { id: "color.colored-shadow", severity: Severity::Low, fixable: true, description: "A shadow has a visible hue instead of a neutral" },
|
||||
Rule { id: "color.border-opacity", severity: Severity::Low, fixable: true, description: "A border is more opaque than a hairline" },
|
||||
Rule { id: "color.contrast", severity: Severity::High, fixable: true, description: "Text contrast is below 4.5:1 (3:1 for large text)" },
|
||||
Rule { id: "color.accents", severity: Severity::Medium, fixable: false, description: "More than two accent colours in one scope (Strict)" },
|
||||
Rule { id: "token.hardcoded-color", severity: Severity::Low, fixable: false, description: "A colour matches a variable but is not bound to it" },
|
||||
Rule {
|
||||
id: "token.hardcoded-number",
|
||||
severity: Severity::Low,
|
||||
fixable: false,
|
||||
description: "A spacing, radius, size or opacity value matches a variable but is not bound",
|
||||
},
|
||||
Rule { id: "icon.emoji", severity: Severity::Low, fixable: false, description: "Text or a layer name contains an emoji" },
|
||||
Rule { id: "copy.exclamation", severity: Severity::Low, fixable: false, description: "Interface copy uses an exclamation mark" },
|
||||
Rule { id: "copy.trailing-period", severity: Severity::Low, fixable: false, description: "A short label ends with a period" },
|
||||
Rule { id: "copy.hype", severity: Severity::Low, fixable: false, description: "Copy uses hype words such as \"AI-powered\"" },
|
||||
Rule { id: "naming.auto", severity: Severity::Low, fixable: false, description: "A layer still has its default auto name (Frame 12)" },
|
||||
Rule { id: "detail.shadow-count", severity: Severity::Low, fixable: false, description: "Shadows and blurs sit on too many layers" },
|
||||
Rule {
|
||||
id: "layout.no-auto-layout",
|
||||
severity: Severity::Low,
|
||||
fixable: false,
|
||||
description: "A frame or component with several children has no auto layout (Strict)",
|
||||
},
|
||||
Rule {
|
||||
id: "layout.text-overflow",
|
||||
severity: Severity::High,
|
||||
fixable: false,
|
||||
description: "A fixed-width text box is shorter than the text it holds, so it clips or overlaps",
|
||||
},
|
||||
Rule {
|
||||
id: "layout.clipped",
|
||||
severity: Severity::High,
|
||||
fixable: false,
|
||||
description: "A fixed-size auto layout frame clips children that overflow it, so they are invisible",
|
||||
},
|
||||
];
|
||||
|
||||
pub(crate) fn rule(id: &str) -> Option<&'static Rule> {
|
||||
RULES.iter().find(|r| r.id == id)
|
||||
}
|
||||
|
||||
/// Whether `preset` checks `id`. Recommended and Strict check every rule except the Strict-only
|
||||
/// ones; Accessibility checks only the findings that keep a design usable.
|
||||
pub(crate) fn enabled(id: &str, preset: DesignPreset) -> bool {
|
||||
match preset {
|
||||
DesignPreset::Recommended => !matches!(id, "color.accents" | "layout.no-auto-layout"),
|
||||
DesignPreset::Strict => true,
|
||||
DesignPreset::Accessibility => {
|
||||
matches!(id, "color.contrast" | "color.gradient-text" | "type.too-small" | "layout.text-overflow" | "layout.clipped")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The presets that check `id`, for `design.rules`.
|
||||
pub(crate) fn presets_of(id: &str) -> Vec<&'static str> {
|
||||
DesignPreset::ALL.iter().copied().filter(|p| enabled(id, *p)).map(DesignPreset::id).collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -407,3 +407,29 @@ fn a_join_stopped_at_its_budget_says_so() {
|
||||
let (some, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 3);
|
||||
assert_eq!((some.len(), complete), (3, false), "{some:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_links_keep_their_value_names_and_carry_source_and_notes() {
|
||||
let mut s = session();
|
||||
let variants: Vec<_> = ["small", "extra_large"]
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let f = node(&mut s, json!({"type": "frame", "name": format!("Size={v}"), "width": 80, "height": 32}));
|
||||
id(&s.execute("component.create", &json!({"ids": [f]})).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let set = id(&s.execute("component.combineVariants", &json!({"ids": variants})).unwrap());
|
||||
s.execute(
|
||||
"codeConnect.set",
|
||||
&json!({"id": set, "name": "Button", "template": "<Button size={Size} />", "source": "src/button.tsx",
|
||||
"notes": "Use for main actions", "values": {"Size": {"extra_large": "xl"}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let instance = id(&s.execute("instance.create", &json!({"component": variants[1]})).unwrap());
|
||||
let v = context(&mut s, json!({"ids": [instance]}));
|
||||
let link = &v["components"][set.to_string()]["codeLinks"][0];
|
||||
assert_eq!(link["values"]["Size"]["extra_large"], "xl", "a design value keeps its name: {link}");
|
||||
let code = &only(&v)["code"][0];
|
||||
assert_eq!((code["source"].as_str(), code["notes"].as_str()), (Some("src/button.tsx"), Some("Use for main actions")), "{code}");
|
||||
assert!(code["code"].as_str().unwrap().contains("xl"), "{code}");
|
||||
}
|
||||
@@ -26,6 +26,11 @@ pub const MAX_TEMPLATE: usize = 4_000;
|
||||
pub const MAX_NAME: usize = 100;
|
||||
/// Longest import path (chars).
|
||||
pub const MAX_IMPORT: usize = 300;
|
||||
/// Longest source path, and notes (chars).
|
||||
pub const MAX_SOURCE: usize = 300;
|
||||
pub const MAX_NOTES: usize = 2_000;
|
||||
/// Most properties with mapped values on a link, and values on each.
|
||||
const MAX_MAPPED: usize = 100;
|
||||
/// Most links a connect file holds.
|
||||
pub const MAX_FILE_LINKS: usize = 5_000;
|
||||
/// Largest connect file read (bytes).
|
||||
@@ -377,6 +382,8 @@ fn html_text(s: &str) -> String {
|
||||
|
||||
/// `link`'s template with `values` (one per parameter of `c`), every line prefixed by `pad`.
|
||||
pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)], link: &CodeLink, lang: CodeLang, pad: &str) -> String {
|
||||
// A value is written as code calls it; a condition reads the design's own value.
|
||||
let coded = &in_code(values, link);
|
||||
let mut out = String::new();
|
||||
// A quoted attribute stays open across substitutions: `title="{a} {b}"` must treat both
|
||||
// placeholders as attribute values, not text after the first one.
|
||||
@@ -391,7 +398,7 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
|
||||
vue_attr = None;
|
||||
}
|
||||
}
|
||||
Piece::Value { name, inner } => match find(c, values, name) {
|
||||
Piece::Value { name, inner } => match find(c, coded, name) {
|
||||
Some((p, v)) => {
|
||||
let e = expr(doc, c, p, v, lang);
|
||||
// JSX and `view!`: a plain string reads best as an attribute value, anything
|
||||
@@ -454,6 +461,12 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
|
||||
out.lines().map(|l| if l.is_empty() { "\n".to_string() } else { format!("{pad}{l}\n") }).collect()
|
||||
}
|
||||
|
||||
/// `values` with each design value the link names turned into what code calls it.
|
||||
fn in_code(values: &[(String, Value)], link: &CodeLink) -> Vec<(String, Value)> {
|
||||
let code = |prop: &str, v: &Value| link.values.get(prop)?.get(v.as_str()?).cloned();
|
||||
values.iter().map(|(prop, v)| (prop.clone(), code(prop, v).map_or_else(|| v.clone(), Value::String))).collect()
|
||||
}
|
||||
|
||||
/// A starting template: the code component called with every property (but slots) passed.
|
||||
fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
|
||||
let params: Vec<&str> = c.params.iter().filter(|p| p.kind != ParamKind::Slot).map(|p| p.ident.as_str()).collect();
|
||||
@@ -469,6 +482,15 @@ fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `source` can't name a file in a code repository: it goes down from the repository's root.
|
||||
fn check_source(source: &str) -> std::result::Result<(), String> {
|
||||
let plain = source.chars().count() <= MAX_SOURCE
|
||||
&& !source.contains('\\')
|
||||
&& !source.chars().any(char::is_control)
|
||||
&& std::path::Path::new(source).components().all(|c| matches!(c, std::path::Component::Normal(_) | std::path::Component::CurDir));
|
||||
if plain { Ok(()) } else { Err(format!("source: a path inside the code repository, up to {MAX_SOURCE} characters")) }
|
||||
}
|
||||
|
||||
/// Checks a link: its name, import path and template. Returns the placeholder names that aren't
|
||||
/// properties of `c` (kept as written).
|
||||
pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Result<Vec<String>, String> {
|
||||
@@ -500,6 +522,14 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
|
||||
_ => format!("importPath: a module or package name (letters, digits, _ and .), up to {MAX_IMPORT} characters"),
|
||||
});
|
||||
}
|
||||
check_source(&link.source)?;
|
||||
if link.notes.chars().count() > MAX_NOTES {
|
||||
return Err(format!("notes: up to {MAX_NOTES} characters"));
|
||||
}
|
||||
let long = |s: &String| s.chars().count() > MAX_NAME;
|
||||
if link.values.len() > MAX_MAPPED || link.values.values().any(|m| m.len() > MAX_MAPPED || m.iter().any(|(k, v)| long(k) || long(v))) {
|
||||
return Err(format!("values: at most {MAX_MAPPED} properties of {MAX_MAPPED} values, each up to {MAX_NAME} characters"));
|
||||
}
|
||||
let t = &link.template;
|
||||
if t.trim().is_empty() || t.chars().count() > MAX_TEMPLATE || t.chars().any(|ch| ch.is_control() && !"\n\t\r".contains(ch)) {
|
||||
return Err(format!("template: the snippet, up to {MAX_TEMPLATE} characters"));
|
||||
@@ -515,6 +545,12 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
|
||||
unknown.push(name.to_string());
|
||||
}
|
||||
}
|
||||
// `in_code` reads a mapping by property name, so a key that is only a parameter name does nothing.
|
||||
for prop in link.values.keys() {
|
||||
if !c.params.iter().any(|p| p.prop == *prop) && !unknown.iter().any(|u| u == prop) {
|
||||
unknown.push(prop.clone());
|
||||
}
|
||||
}
|
||||
Ok(unknown)
|
||||
}
|
||||
|
||||
@@ -557,12 +593,103 @@ fn store(doc: &mut Document, owner: NodeId, link: CodeLink) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The variant properties of component or set `owner`, with their values.
|
||||
pub fn variants(doc: &Document, owner: NodeId) -> Vec<(String, Vec<String>)> {
|
||||
main_of(doc, owner)
|
||||
.and_then(|m| describe(doc, m))
|
||||
.map(|c| c.params.iter().filter_map(|p| if let ParamKind::Variant(v) = &p.kind { Some((p.prop.clone(), v.clone())) } else { None }).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A link as the connect file holds it.
|
||||
fn link_json(component: &str, l: &CodeLink) -> Value {
|
||||
let mut v = link_fields(l);
|
||||
v["component"] = json!(component);
|
||||
v
|
||||
}
|
||||
|
||||
/// A link's own fields, as the connect file and `inspect.designContext` give them: its keys are
|
||||
/// the file's, and a mapping's property names and values stay as written.
|
||||
pub(crate) fn link_fields(l: &CodeLink) -> Value {
|
||||
let mut v = json!({"language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template});
|
||||
if !l.source.is_empty() {
|
||||
v["source"] = json!(l.source);
|
||||
}
|
||||
if !l.values.is_empty() {
|
||||
v["values"] = json!(l.values);
|
||||
}
|
||||
if !l.notes.is_empty() {
|
||||
v["notes"] = json!(l.notes);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The components and sets `ids` are, use or hold (every one in the file without `ids`).
|
||||
fn listed(doc: &Document, ids: Option<&[NodeId]>) -> Vec<NodeId> {
|
||||
let mut out: Vec<NodeId> = match ids {
|
||||
None => doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.id).collect(),
|
||||
Some(ids) => ids.iter().flat_map(|i| doc.subtree(*i)).filter_map(|i| owner(doc, i)).collect(),
|
||||
};
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// What an agent needs to use a component: its code link for each language, or that it has none.
|
||||
fn entry(doc: &Document, id: NodeId, root: Option<&str>) -> Option<Value> {
|
||||
let n = doc.node(id)?;
|
||||
let links: Vec<Value> = n
|
||||
.code_links
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let lang = CodeLang::from_id(&l.language);
|
||||
let mut v = link_fields(l);
|
||||
v["import"] = json!(lang.map(|k| import_line(l, k)));
|
||||
v["snippet"] = json!(lang.and_then(|k| connected_code(doc, id, k, l)));
|
||||
if let Some(root) = root.filter(|_| !l.source.is_empty()) {
|
||||
v["sourceFound"] = json!(crate::file_access::exists(std::path::Path::new(root).join(&l.source)));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Some(json!({
|
||||
"id": id,
|
||||
"name": n.name,
|
||||
"type": n.kind.type_name(),
|
||||
"mapped": !links.is_empty(),
|
||||
"properties": crate::cmd::component::describe_props(doc, id)["properties"],
|
||||
"links": links,
|
||||
}))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "codeConnect.list";
|
||||
let doc = s.doc()?;
|
||||
// Anything named must be layers; nothing named lists every component in the file.
|
||||
let named = get(p, "ids").is_some() || get(p, "id").is_some();
|
||||
let ids = if named { Some(crate::params::req_targets(cmd, s, p)?) } else { None };
|
||||
let root = text(cmd, p, "root")?;
|
||||
let unmapped = crate::params::boolean(p, "unmapped").unwrap_or(false);
|
||||
let all: Vec<Value> = listed(doc, ids.as_deref()).into_iter().filter_map(|id| entry(doc, id, root.as_deref())).collect();
|
||||
let count = |m: bool| all.iter().filter(|e| e["mapped"] == m).count();
|
||||
let (mapped, missing) = (count(true), count(false));
|
||||
let components: Vec<Value> = all.into_iter().filter(|e| !unmapped || e["mapped"] == false).collect();
|
||||
Ok(json!({"components": components, "mapped": mapped, "unmapped": missing}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
spec!(
|
||||
"codeConnect.list",
|
||||
"List code connections",
|
||||
"{ids? | id? (the components those layers are, use or hold; default every component in the file), unmapped? (only those without a link), root? (the code repository: says if each link's source is there)} → {components: [{id, name, type, mapped, properties, links: [{language, importPath, import, name, template, snippet, source?, sourceFound?, values?, notes?}]}], mapped, unmapped}",
|
||||
false,
|
||||
list
|
||||
),
|
||||
spec!(
|
||||
"codeConnect.set",
|
||||
"Connect to code",
|
||||
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property)} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
|
||||
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property), source? (the file, relative to the code repository), values? ({property: {design value: code value}}), notes?} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
|
||||
true,
|
||||
|s, p| {
|
||||
let cmd = "codeConnect.set";
|
||||
@@ -578,7 +705,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
None => old.template,
|
||||
};
|
||||
let import_path = text(cmd, p, "importPath")?.map_or(old.import_path, |i| i.trim().to_string());
|
||||
let link = CodeLink { language: lang.id().into(), import_path, name, template };
|
||||
let source = text(cmd, p, "source")?.map_or(old.source, |v| v.trim().to_string());
|
||||
let notes = text(cmd, p, "notes")?.unwrap_or(old.notes);
|
||||
let values = match get(p, "values") {
|
||||
None => old.values,
|
||||
Some(v) => serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "values: {property: {design value: code value}}"))?,
|
||||
};
|
||||
let link = CodeLink { language: lang.id().into(), import_path, name, template, source, values, notes };
|
||||
let unknown = check(&c, &link, lang).map_err(|e| bad(cmd, e))?;
|
||||
let code = connected_code(doc, id, lang, &link);
|
||||
store(s.doc_mut()?, owner, link)?;
|
||||
@@ -610,27 +743,34 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"codeConnect.export",
|
||||
"Export code connections",
|
||||
"{path? (write it there, e.g. figcraft.connect.json in the code repository)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template}]}, sorted → {text, links} or {path, links}",
|
||||
"{path? (write it there, e.g. figcraft.connect.json in the code repository; other top-level keys of a file already there stay, and so do the links of components this file doesn't have; a file there it can't read is left alone and the export refused)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template, source?, values?, notes?}]}, sorted → {text, links} or {path, links}",
|
||||
false,
|
||||
|s, p| {
|
||||
let cmd = "codeConnect.export";
|
||||
let path = text(cmd, p, "path")?;
|
||||
let doc = s.doc()?;
|
||||
let mut links: Vec<Value> = doc
|
||||
.nodes()
|
||||
.filter(|n| owner(doc, n.id) == Some(n.id))
|
||||
.flat_map(|n| {
|
||||
n.code_links.iter().map(|l| {
|
||||
json!({"component": n.name, "language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut links: Vec<Value> =
|
||||
doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).flat_map(|n| n.code_links.iter().map(|l| link_json(&n.name, l))).collect();
|
||||
let key =
|
||||
|v: &Value| (v["component"].as_str().unwrap_or_default().to_string(), v["language"].as_str().unwrap_or_default().to_string());
|
||||
links.sort_by_key(key);
|
||||
let count = links.len();
|
||||
let text =
|
||||
serde_json::to_string_pretty(&json!({"version": VERSION, "links": links})).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
|
||||
// The file also holds the project's settings and the links of other designs: only
|
||||
// the links of this file's components are this command's.
|
||||
let old = match path.as_deref() {
|
||||
Some(path) => kept_keys(cmd, path)?,
|
||||
None => serde_json::Map::new(),
|
||||
};
|
||||
let here: Vec<&str> = doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.name.as_str()).collect();
|
||||
let others = old.get("links").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
links.extend(others.iter().filter(|l| !l.get("component").and_then(Value::as_str).is_some_and(|c| here.contains(&c))).cloned());
|
||||
links.sort_by_key(key);
|
||||
let mut file = json!({"version": VERSION, "links": links});
|
||||
if let Some(fields) = file.as_object_mut() {
|
||||
for (k, v) in old {
|
||||
fields.entry(k).or_insert(v);
|
||||
}
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
|
||||
match path {
|
||||
Some(path) => {
|
||||
crate::cmd::file::write(&path, text.as_bytes())?;
|
||||
@@ -650,6 +790,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The top-level keys of the connect file at `path`, none when there is no file. A file that
|
||||
/// can't be read as one is an error: writing over it would lose what it holds.
|
||||
fn kept_keys(cmd: &str, path: &str) -> Result<serde_json::Map<String, Value>> {
|
||||
if !crate::file_access::exists(path) {
|
||||
return Ok(serde_json::Map::new());
|
||||
}
|
||||
match serde_json::from_slice(&crate::cmd::file::read_capped(path, MAX_FILE)?) {
|
||||
Ok(Value::Object(fields)) => Ok(fields),
|
||||
_ => Err(bad(cmd, format!("{path} isn't a connect file it can read, so it was left as it is"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "codeConnect.import";
|
||||
let parse_json = |b: &[u8]| serde_json::from_slice::<Value>(b).map_err(|e| bad(cmd, format!("not JSON: {e}")));
|
||||
@@ -688,11 +840,24 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
));
|
||||
continue;
|
||||
};
|
||||
let values = match e.get("values") {
|
||||
None | Some(Value::Null) => Default::default(),
|
||||
Some(v) => match serde_json::from_value(v.clone()) {
|
||||
Ok(values) => values,
|
||||
Err(_) => {
|
||||
warnings.push(format!("link {}: values: {{property: {{design value: code value}}}}, all strings", i + 1));
|
||||
continue;
|
||||
}
|
||||
},
|
||||
};
|
||||
let link = CodeLink {
|
||||
language: lang.id().into(),
|
||||
import_path: field("importPath").unwrap_or_default().to_string(),
|
||||
name: name.into(),
|
||||
template: template.into(),
|
||||
source: field("source").unwrap_or_default().to_string(),
|
||||
values,
|
||||
notes: field("notes").unwrap_or_default().to_string(),
|
||||
};
|
||||
let matches = owners.get(component).cloned().unwrap_or_default();
|
||||
if matches.is_empty() {
|
||||
|
||||
@@ -384,6 +384,10 @@ fn stroke_color(n: &Node) -> Option<Color> {
|
||||
/// The CSS borders a solid stroke makes: one `border`, or with individual stroke sides a border
|
||||
/// on each side that has a weight.
|
||||
fn css_borders(doc: &Document, n: &Node, t: &mut Tokens) -> Vec<(String, String)> {
|
||||
// A vector's stroke belongs to its path, not to a rectangle around its bounding box.
|
||||
if matches!(n.kind, NodeKind::Vector { .. }) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(c) = stroke_color(n) else { return Vec::new() };
|
||||
let Some(sides) = n.stroke.sides else {
|
||||
let weight = tok(doc, n, &["strokeWeight"], format!("{}px", num(n.stroke.weight)), t);
|
||||
@@ -573,6 +577,126 @@ mod tests {
|
||||
assert!(!css.contains("gradient"), "{css}");
|
||||
}
|
||||
|
||||
fn embedded_svgs(code: &str) -> Vec<String> {
|
||||
use base64::Engine as _;
|
||||
code.split("data:image/svg+xml;base64,")
|
||||
.skip(1)
|
||||
.map(|rest| {
|
||||
let b64 = rest.split('"').next().unwrap();
|
||||
String::from_utf8(base64::engine::general_purpose::STANDARD.decode(b64).unwrap()).unwrap()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_code_uses_its_svg_asset_not_a_box_border() {
|
||||
let mut s = Session::new();
|
||||
let icon =
|
||||
id_of(&s.execute("frame.create", &json!({"name": "icon", "width": 24, "height": 24, "props": {"fill": "none"}})).unwrap()["id"]).unwrap();
|
||||
let check = id_of(&s.execute("vector.create", &json!({"path": "M4 12 L10 18 L20 6", "parent": icon, "name": "check", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 2}})).unwrap()["id"]).unwrap();
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().fills = vec![Paint::solid(Color::WHITE)];
|
||||
let doc = s.doc().unwrap();
|
||||
let html = code_for(doc, icon, CodeLang::Html);
|
||||
assert!(html.contains("<div class=\"check\">"), "node wrapper: {html}");
|
||||
assert!(html.contains("<img class=\"check-asset\" src=\"data:image/svg+xml;base64,"), "{html}");
|
||||
assert!(html.contains("alt=\"check\""), "{html}");
|
||||
assert!(!html.contains("border: 2px solid"), "{html}");
|
||||
assert!(!html.contains("background:"), "the vector's fill belongs to its SVG, not its box: {html}");
|
||||
let opaque = embedded_svgs(&html);
|
||||
assert_eq!(opaque.len(), 1, "{html}");
|
||||
assert!(opaque[0].contains("<path") && opaque[0].contains("#1F3A68"), "{:?}", opaque[0]);
|
||||
for lang in [CodeLang::React, CodeLang::Vue, CodeLang::Leptos, CodeLang::Tailwind] {
|
||||
let code = code_for(doc, icon, lang);
|
||||
assert!(code.contains("<img") && code.contains("src=\"data:image/svg+xml;base64,"), "{}: {code}", lang.id());
|
||||
assert!(!code.contains("border: 2px solid") && !code.contains("border-[2px]"), "{}: {code}", lang.id());
|
||||
}
|
||||
let css = code_for(doc, icon, CodeLang::Css);
|
||||
assert!(!css.contains("border: 2px solid"), "{css}");
|
||||
let swift = code_for(doc, icon, CodeLang::SwiftUi);
|
||||
assert!(swift.contains("Image(\"check\")"), "{swift}");
|
||||
assert!(!swift.contains(".overlay(RoundedRectangle"), "{swift}");
|
||||
let ark = code_for(doc, icon, CodeLang::ArkUi);
|
||||
assert!(!ark.contains(".border({"), "{ark}");
|
||||
|
||||
// CSS owns the node's rotation and opacity, so the embedded asset must not bake them in.
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().opacity = 0.5;
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().transform = figcraft_geom::Affine::rotate(30f64.to_radians());
|
||||
let transformed = code_for(s.doc().unwrap(), icon, CodeLang::Html);
|
||||
assert!(transformed.contains("opacity: 0.5;"), "{transformed}");
|
||||
assert!(transformed.contains("transform: rotate("), "{transformed}");
|
||||
assert_eq!(embedded_svgs(&transformed), opaque, "the asset stays node-local and opaque: {transformed}");
|
||||
|
||||
let rectangle =
|
||||
id_of(&s.execute("shape.rectangle", &json!({"parent": icon, "props": {"stroke": "#1F3A68", "strokeWeight": 2}})).unwrap()["id"]).unwrap();
|
||||
assert!(code_for(s.doc().unwrap(), rectangle, CodeLang::Css).contains("border: 2px solid"), "box strokes remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_assets_are_self_contained_and_leptos_literals_escape() {
|
||||
let mut s = Session::new();
|
||||
let icon = id_of(&s.execute("frame.create", &json!({"name": "Icons", "width": 24, "height": 24})).unwrap()["id"]).unwrap();
|
||||
for name in ["Check Icon", "Check Icon", r"icon\q", "check#dark"] {
|
||||
s.execute("vector.create", &json!({"path": "M4 12 L10 18 L20 6", "parent": icon, "name": name, "props": {"fill": "none"}})).unwrap();
|
||||
}
|
||||
let html = code_for(s.doc().unwrap(), icon, CodeLang::Html);
|
||||
assert_eq!(embedded_svgs(&html).len(), 4, "nested vectors need no separate filesystem export: {html}");
|
||||
assert!(!html.contains("src=\"check#dark.svg\""), "{html}");
|
||||
let leptos = code_for(s.doc().unwrap(), icon, CodeLang::Leptos);
|
||||
assert!(leptos.contains("alt=\"icon\\\\q\""), "{leptos}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_asset_keeps_stroke_overflow_inside_a_node_sized_wrapper() {
|
||||
let mut s = Session::new();
|
||||
let badge = id_of(
|
||||
&s.execute(
|
||||
"vector.create",
|
||||
&json!({"path": "M0 0 H24 V24 H0 Z", "name": "badge", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 2}}),
|
||||
)
|
||||
.unwrap()["id"],
|
||||
)
|
||||
.unwrap();
|
||||
s.doc_mut().unwrap().get_mut(badge).unwrap().stroke.miter_limit = 1.0;
|
||||
let html = code_for(s.doc().unwrap(), badge, CodeLang::Html);
|
||||
assert!(html.contains("<div class=\"badge\">"), "node-sized wrapper: {html}");
|
||||
assert!(html.contains("<img class=\"badge-asset\""), "inner asset: {html}");
|
||||
assert!(html.contains("overflow: visible;"), "stroke is not clipped: {html}");
|
||||
assert!(html.contains("left: -2px;") && html.contains("top: -2px;"), "asset offset: {html}");
|
||||
assert!(html.contains("width: 28px;") && html.contains("height: 28px;"), "asset keeps its bounds: {html}");
|
||||
assert!(html.contains("max-width: none;"), "the wrapper cannot shrink the asset: {html}");
|
||||
let svg = embedded_svgs(&html);
|
||||
assert_eq!(svg.len(), 1, "{html}");
|
||||
assert!(svg[0].contains("width=\"28\" height=\"28\""), "{}", svg[0]);
|
||||
let tailwind = code_for(s.doc().unwrap(), badge, CodeLang::Tailwind);
|
||||
assert!(tailwind.contains("overflow-visible") && tailwind.contains("max-w-none"), "{tailwind}");
|
||||
assert!(tailwind.contains("w-7") && tailwind.contains("h-7"), "28px on the spacing scale: {tailwind}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_markup_does_not_duplicate_svg_effects() {
|
||||
let mut s = Session::new();
|
||||
let vector = id_of(
|
||||
&s.execute("vector.create", &json!({"path": "M0 0 H24 V24 H0 Z", "name": "effect icon", "props": {"fill": "#FFFFFF"}})).unwrap()["id"],
|
||||
)
|
||||
.unwrap();
|
||||
s.doc_mut().unwrap().get_mut(vector).unwrap().effects = vec![
|
||||
figcraft_doc::Effect { kind: EffectKind::LayerBlur(figcraft_doc::Blur::uniform(8.0)), visible: true },
|
||||
figcraft_doc::Effect { kind: EffectKind::DropShadow(Shadow { radius: 4.0, offset: (3.0, 4.0), ..Default::default() }), visible: true },
|
||||
];
|
||||
let html = code_for(s.doc().unwrap(), vector, CodeLang::Html);
|
||||
assert!(!html.contains("filter: blur(") && !html.contains("box-shadow:"), "the SVG owns these effects: {html}");
|
||||
let svg = embedded_svgs(&html);
|
||||
assert_eq!(svg.len(), 1, "{html}");
|
||||
assert!(svg[0].contains("feGaussianBlur") && svg[0].contains("feOffset"), "{}", svg[0]);
|
||||
let standalone = code_for(s.doc().unwrap(), vector, CodeLang::Css);
|
||||
assert!(standalone.contains("filter: blur(4px)") && standalone.contains("box-shadow:"), "standalone CSS is unchanged: {standalone}");
|
||||
|
||||
let rectangle = id_of(&s.execute("shape.rectangle", &json!({"name": "ordinary", "width": 24, "height": 24})).unwrap()["id"]).unwrap();
|
||||
s.doc_mut().unwrap().get_mut(rectangle).unwrap().effects = s.doc().unwrap().node(vector).unwrap().effects.clone();
|
||||
let ordinary = code_for(s.doc().unwrap(), rectangle, CodeLang::Html);
|
||||
assert!(ordinary.contains("filter: blur(4px)") && ordinary.contains("box-shadow:"), "ordinary shapes keep CSS effects: {ordinary}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swiftui_and_compose_for_an_auto_layout_card() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -216,7 +216,7 @@ fn arkui_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
|
||||
}
|
||||
}
|
||||
// Ellipses take their stroke as a shape attribute (above).
|
||||
if !matches!(n.kind, NodeKind::Ellipse { .. })
|
||||
if !matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Vector { .. })
|
||||
&& let Some(c) = stroke_color(n)
|
||||
{
|
||||
mods.push(format!(".border({{ width: {}, color: {} }})", num(n.stroke.weight), ark_color(c)));
|
||||
|
||||
@@ -126,6 +126,16 @@ pub(super) fn css(doc: &Document, id: NodeId) -> String {
|
||||
/// The CSS declarations for `n`'s own look and size, one per line; `hug` leaves out the width
|
||||
/// and/or height (they follow the content). Bound variables become `var(--name, value)`.
|
||||
pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool)) -> String {
|
||||
css_decls_impl(doc, n, t, hug, false)
|
||||
}
|
||||
|
||||
/// The declarations around an embedded vector image: its SVG owns shadows and layer blur, so
|
||||
/// only the markup wrapper omits those. Standalone CSS and ordinary shapes keep them.
|
||||
pub(crate) fn css_decls_for_markup(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool)) -> String {
|
||||
css_decls_impl(doc, n, t, hug, true)
|
||||
}
|
||||
|
||||
fn css_decls_impl(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool), vector_svg: bool) -> String {
|
||||
let px = |v: f64| format!("{}px", num(v));
|
||||
let mut out = String::new();
|
||||
let mut put = |key: &str, value: String| out.push_str(&format!("{key}: {value};\n"));
|
||||
@@ -188,7 +198,12 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
|
||||
// One `background` with every visible fill as a layer, top first (a document's fills run
|
||||
// bottom to top, as the renderer paints them). CSS allows a plain colour only as the last
|
||||
// layer, so a solid above another fill becomes a one-colour gradient.
|
||||
let visible: Vec<(usize, &figcraft_color::Paint)> = n.fills.iter().enumerate().filter(|(_, p)| p.visible).collect();
|
||||
let visible: Vec<(usize, &figcraft_color::Paint)> = if matches!(n.kind, NodeKind::Vector { .. }) {
|
||||
// The SVG carries the path's fills; an image's box must not get a rectangular one.
|
||||
Vec::new()
|
||||
} else {
|
||||
n.fills.iter().enumerate().filter(|(_, p)| p.visible).collect()
|
||||
};
|
||||
let layers: Vec<String> = visible
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -217,7 +232,7 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
|
||||
for (key, value) in css_borders(doc, n, t) {
|
||||
put(&key, value);
|
||||
}
|
||||
effect_decls(n, &mut put);
|
||||
effect_decls(n, &mut put, vector_svg && matches!(n.kind, NodeKind::Vector { .. }));
|
||||
if let NodeKind::Text(tx) = &n.kind {
|
||||
text_decls(doc, n, tx, t, &mut put);
|
||||
}
|
||||
@@ -274,12 +289,14 @@ fn layout_decls(doc: &Document, n: &Node, l: &figcraft_doc::AutoLayout, t: &mut
|
||||
}
|
||||
}
|
||||
|
||||
/// Shadows and blurs of `n`.
|
||||
fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String)) {
|
||||
/// Shadows and blurs of `n`. `svg_owned` leaves shadows and layer blur to the embedded SVG;
|
||||
/// backdrop filters stay in CSS because the self-contained asset has no outer page behind it.
|
||||
fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String), svg_owned: bool) {
|
||||
let shadows: Vec<String> = n
|
||||
.effects
|
||||
.iter()
|
||||
.filter(|e| e.visible)
|
||||
.filter(|e| !(svg_owned && matches!(e.kind, EffectKind::DropShadow(_) | EffectKind::InnerShadow(_))))
|
||||
.filter_map(|e| match &e.kind {
|
||||
EffectKind::DropShadow(s) => {
|
||||
Some(format!("{}px {}px {}px {}px {}", num(s.offset.0), num(s.offset.1), num(s.radius), num(s.spread), s.color.to_css()))
|
||||
@@ -296,7 +313,7 @@ fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String)) {
|
||||
for e in n.effects.iter().filter(|e| e.visible) {
|
||||
match e.kind {
|
||||
// CSS blurs are uniform: a progressive blur has no CSS equivalent and is left out.
|
||||
EffectKind::LayerBlur(ref b) if !b.is_progressive() => put("filter", format!("blur({}px)", num(b.radius / 2.0))),
|
||||
EffectKind::LayerBlur(ref b) if !svg_owned && !b.is_progressive() => put("filter", format!("blur({}px)", num(b.radius / 2.0))),
|
||||
EffectKind::BackgroundBlur(ref b) if !b.is_progressive() => put("backdrop-filter", format!("blur({}px)", num(b.radius / 2.0))),
|
||||
// CSS has no refraction: the frost is the nearest.
|
||||
EffectKind::Glass(ref g) => put("backdrop-filter", format!("blur({}px)", num(g.sanitized().frost / 2.0))),
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::css::{Tokens, css_decls};
|
||||
use base64::Engine as _;
|
||||
|
||||
use super::css::{Tokens, css_decls_for_markup};
|
||||
use super::{CodeLang, Ctx, Document, LayoutMode, Node, NodeId, NodeKind, Param, Sizing, indent, num, with_v_if};
|
||||
|
||||
// ------------------------------------------------------------------ HTML and React markup
|
||||
@@ -85,6 +87,24 @@ fn html_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('\n', "<br>")
|
||||
}
|
||||
|
||||
/// A layer name in a quoted markup attribute, with line breaks flattened.
|
||||
fn attr_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace(['\n', '\r'], " ")
|
||||
}
|
||||
|
||||
/// A vector as a self-contained SVG asset and its local painted bounds. CSS owns the node's
|
||||
/// placement and opacity, so the embedded geometry is node-local and fully opaque. No filesystem
|
||||
/// export or URL escaping is needed, and nested vectors work exactly like top-level ones.
|
||||
fn vector_data_uri(doc: &mut Document, n: &Node) -> Option<(String, figcraft_geom::Rect)> {
|
||||
let node = doc.get_mut(n.id).ok()?;
|
||||
node.parent = None;
|
||||
node.transform = figcraft_geom::Affine::IDENTITY;
|
||||
node.opacity = 1.0;
|
||||
let bounds = figcraft_render::export_bounds(doc, n.id)?;
|
||||
let svg = figcraft_svg::export_svg(doc, &[n.id], &Default::default())?;
|
||||
Some((format!("data:image/svg+xml;base64,{}", base64::engine::general_purpose::STANDARD.encode(svg)), bounds))
|
||||
}
|
||||
|
||||
/// Text as JSX children: HTML escapes, braces as expressions, line breaks as `<br />`.
|
||||
fn jsx_text(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
@@ -147,6 +167,8 @@ pub(crate) struct Markup<'c, 'a> {
|
||||
/// With `fluid`, other layers at least this share of the root's width are fluid too (a
|
||||
/// divider, a banner image); smaller ones (icons) keep their size. Default: none.
|
||||
pub fluid_leaves: f64,
|
||||
/// Lazily cloned once for node-local SVG assets, not once per vector.
|
||||
asset_doc: Option<Document>,
|
||||
}
|
||||
|
||||
/// How `n` sits in its parent: in the flex flow, or placed at its position.
|
||||
@@ -175,6 +197,18 @@ fn placement_decls(n: &Node, parent: Option<&Node>, root: bool, in_flow: bool) -
|
||||
decls
|
||||
}
|
||||
|
||||
/// Extra declarations around an embedded vector image. The inner SVG can be larger than the
|
||||
/// node box, so the wrapper must establish positioning in flex flow and leave overflow visible.
|
||||
fn vector_wrapper_decls(n: &Node, in_flow: bool, own: &mut String) {
|
||||
if !matches!(n.kind, NodeKind::Vector { .. }) {
|
||||
return;
|
||||
}
|
||||
own.push_str("overflow: visible;\n");
|
||||
if in_flow {
|
||||
own.push_str("position: relative;\n");
|
||||
}
|
||||
}
|
||||
|
||||
impl<'c, 'a> Markup<'c, 'a> {
|
||||
pub fn new(ctx: &'c Ctx<'a>, lang: CodeLang) -> Self {
|
||||
Markup {
|
||||
@@ -192,6 +226,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
inline: false,
|
||||
fluid: false,
|
||||
fluid_leaves: f64::INFINITY,
|
||||
asset_doc: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,6 +325,30 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A node-sized wrapper and its inner SVG image. The inner rule uses the exported bounds,
|
||||
/// so strokes and effects keep their size and can overflow the wrapper without clipping.
|
||||
fn vector_element(&mut self, n: &Node, depth: usize, path: &str, class: &str, attr: &str, pad: &str, attrs: &str) {
|
||||
let root_doc = self.ctx.doc;
|
||||
let asset = vector_data_uri(self.asset_doc.get_or_insert_with(|| root_doc.clone()), n);
|
||||
let bounds = asset.as_ref().map(|(_, b)| *b).unwrap_or_else(|| n.local_rect());
|
||||
let asset_class = class_name(&format!("{class} asset"), "asset", &mut self.used);
|
||||
let asset_decls = format!(
|
||||
"display: block;\nposition: absolute;\nleft: {}px;\ntop: {}px;\nwidth: {}px;\nheight: {}px;\nmax-width: none;\n",
|
||||
num(bounds.x0),
|
||||
num(bounds.y0),
|
||||
num(bounds.width()),
|
||||
num(bounds.height())
|
||||
);
|
||||
self.rule(&format!("{path}/$svg"), &asset_class, asset_decls);
|
||||
// Leptos attributes are Rust string literals; the other targets use HTML escaping.
|
||||
let lang = self.lang;
|
||||
let quote = |value: &str| if lang == CodeLang::Leptos { format!("{value:?}") } else { format!("\"{}\"", attr_escape(value)) };
|
||||
let src = asset.map(|(uri, _)| format!(" src={}", quote(&uri))).unwrap_or_default();
|
||||
let alt = quote(&n.name);
|
||||
let inner = self.pad(depth + 1);
|
||||
self.markup.push_str(&format!("{pad}<div {attr}=\"{class}\"{attrs}>\n{inner}<img {attr}=\"{asset_class}\"{src} alt={alt} />\n{pad}</div>\n"));
|
||||
}
|
||||
|
||||
fn element(&mut self, n: &Node, parent: Option<&Node>, depth: usize, path: &str) {
|
||||
let doc = self.ctx.doc;
|
||||
let root = n.id == self.ctx.root;
|
||||
@@ -319,7 +378,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
}
|
||||
let hugs = n.layout.is_some() || matches!(n.kind, NodeKind::Text(_));
|
||||
let hug = (hugs && n.child_layout.sizing_h == Sizing::Hug, hugs && n.child_layout.sizing_v == Sizing::Hug);
|
||||
let mut own = css_decls(doc, n, &mut self.tokens, hug);
|
||||
let mut own = css_decls_for_markup(doc, n, &mut self.tokens, hug);
|
||||
let page = self.ctx.doc.node(self.ctx.root).map_or(f64::INFINITY, |r| r.width);
|
||||
if self.fluid && (n.layout.is_some() || matches!(n.kind, NodeKind::Text(_)) || (!root && n.width >= page * self.fluid_leaves)) {
|
||||
// Full width, or sized by the flex row (`flex: 1`): no cap needed.
|
||||
@@ -328,6 +387,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
if n.layout.is_none() && !n.children.is_empty() && !root && in_flow {
|
||||
own.push_str("position: relative;\n");
|
||||
}
|
||||
vector_wrapper_decls(n, in_flow, &mut own);
|
||||
decls.push_str(&own);
|
||||
self.rule(path, &class, decls);
|
||||
// The root's variant attributes, and a Vue `v-if` guard, ride on the open tag.
|
||||
@@ -339,6 +399,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
}
|
||||
let open = |tag: &str| format!("{pad}<{tag} {attr}=\"{class}\"{attrs}>");
|
||||
match &n.kind {
|
||||
NodeKind::Vector { .. } => self.vector_element(n, depth, path, &class, attr, &pad, &attrs),
|
||||
NodeKind::Text(t) => {
|
||||
let body = self.text_body(n, t);
|
||||
self.markup.push_str(&format!("{}{body}</p>\n", open("p")));
|
||||
|
||||
@@ -192,7 +192,9 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
|
||||
mods.push(format!(".frame(width: {w}, height: {h})"));
|
||||
}
|
||||
}
|
||||
if let Some(c) = stroke_color(n) {
|
||||
if !matches!(n.kind, NodeKind::Vector { .. })
|
||||
&& let Some(c) = stroke_color(n)
|
||||
{
|
||||
mods.push(format!(
|
||||
".overlay(RoundedRectangle(cornerRadius: {corner}).stroke({}, lineWidth: {}))",
|
||||
bound(&["stroke"], swift_color(c)),
|
||||
|
||||
@@ -178,7 +178,14 @@ fn code(doc: &Document, id: NodeId) -> Vec<Value> {
|
||||
.filter_map(|l| {
|
||||
let lang = CodeLang::from_id(&l.language)?;
|
||||
let snippet = code_connect::connected_code(doc, id, lang, l)?;
|
||||
Some(json!({"language": l.language, "importPath": l.import_path, "name": l.name, "code": snippet}))
|
||||
// The snippet already holds the template and the values it maps.
|
||||
let mut v = code_connect::link_fields(l);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.remove("template");
|
||||
o.remove("values");
|
||||
}
|
||||
v["code"] = json!(snippet);
|
||||
Some(v)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -355,7 +362,7 @@ fn components_json(doc: &Document, ids: &BTreeSet<NodeId>) -> Value {
|
||||
v["description"] = json!(description);
|
||||
}
|
||||
if !n.code_links.is_empty() {
|
||||
v["codeLinks"] = camel(serde_json::to_value(&n.code_links).unwrap_or(Value::Null));
|
||||
v["codeLinks"] = json!(n.code_links.iter().map(code_connect::link_fields).collect::<Vec<_>>());
|
||||
}
|
||||
out.insert(id.to_string(), v);
|
||||
}
|
||||
|
||||
@@ -274,8 +274,10 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> {
|
||||
("width", "100%") => kw("w-full"),
|
||||
("width", v) => one(spacing("w", v)),
|
||||
("height", v) => one(spacing("h", v)),
|
||||
("max-width", "none") => kw("max-w-none"),
|
||||
("max-width", v) => one(format!("max-w-{}", arb(v))),
|
||||
("min-height", v) => one(format!("min-h-{}", arb(v))),
|
||||
("overflow", "visible") => kw("overflow-visible"),
|
||||
("margin-inline", "auto") => kw("mx-auto"),
|
||||
("gap", v) => one(spacing("gap", v)),
|
||||
("padding", v) => padding(v),
|
||||
|
||||
@@ -119,6 +119,9 @@ pub struct DocState {
|
||||
/// Where each page's view was left in this session (its centre and zoom; see
|
||||
/// [`Self::open_page`]; not saved).
|
||||
page_views: BTreeMap<NodeId, (f64, f64, f64)>,
|
||||
/// The canvas fits the page's content when it first gets its size. Off when the view was
|
||||
/// restored from where the file was left ([`Session::restore_view`]).
|
||||
pub fit_when_sized: bool,
|
||||
}
|
||||
|
||||
/// A version shown on the canvas in place of the document: read-only until it's restored or the
|
||||
@@ -184,6 +187,7 @@ impl DocState {
|
||||
images_left_in_file: None,
|
||||
on_disk: None,
|
||||
page_views: BTreeMap::new(),
|
||||
fit_when_sized: true,
|
||||
};
|
||||
st.zoom_to_fit();
|
||||
st
|
||||
@@ -332,6 +336,29 @@ impl DocState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each page's view as left: the one shown now at its current view, the others shown in this
|
||||
/// session at theirs.
|
||||
pub(crate) fn page_views(&self) -> impl Iterator<Item = (NodeId, (f64, f64, f64))> + '_ {
|
||||
let shown = (self.page, (self.view.cx, self.view.cy, self.view.zoom));
|
||||
self.page_views.iter().filter(|(p, _)| **p != self.page).map(|(p, v)| (*p, *v)).chain(std::iter::once(shown))
|
||||
}
|
||||
|
||||
/// Take `views` as where their pages were left, and show `page` (or the page shown now) at
|
||||
/// its view. With one, the canvas keeps it instead of fitting the page when it gets its size.
|
||||
pub(crate) fn show_views(&mut self, page: Option<NodeId>, views: impl IntoIterator<Item = (NodeId, (f64, f64, f64))>) {
|
||||
self.page_views.extend(views);
|
||||
if let Some(page) = page {
|
||||
self.page = page;
|
||||
}
|
||||
match self.page_views.get(&self.page) {
|
||||
Some(&(cx, cy, zoom)) => {
|
||||
(self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom);
|
||||
self.fit_when_sized = false;
|
||||
}
|
||||
None => self.zoom_to_fit(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn zoom_to_fit(&mut self) {
|
||||
match self.doc.page_content_bounds(self.page) {
|
||||
Some(b) => self.view.fit(b, 1.0),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Files open again where they were left: when a file's tab closes or the app quits, the page it
|
||||
//! showed and each page's view (its centre and zoom) are kept for that file, and opening it again
|
||||
//! shows them, as Figma opens a file where you were. They live in the preferences, not in the
|
||||
//! file, so looking around never changes a file.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{NodeId, Session, ViewState};
|
||||
|
||||
/// How many files' views are kept, the most recently left first.
|
||||
pub const MAX_FILE_VIEWS: usize = 100;
|
||||
|
||||
/// Where a file was left.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FileView {
|
||||
pub path: String,
|
||||
/// The page shown.
|
||||
pub page: NodeId,
|
||||
/// The view of each page shown while it was open.
|
||||
pub pages: Vec<PageView>,
|
||||
}
|
||||
|
||||
/// A page's view: the page point at the canvas's centre, and the zoom.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PageView {
|
||||
pub page: NodeId,
|
||||
pub cx: f64,
|
||||
pub cy: f64,
|
||||
pub zoom: f64,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Keep where tab `i`'s file is left. A tab without a file of its own (a new or imported file,
|
||||
/// a branch) keeps nothing.
|
||||
pub(crate) fn remember_view(&mut self, i: usize) {
|
||||
let Some(ds) = self.docs.get(i).filter(|d| d.branch_of.is_none()) else { return };
|
||||
let Some(path) = ds.path.clone() else { return };
|
||||
let pages = ds.page_views().map(|(page, (cx, cy, zoom))| PageView { page, cx, cy, zoom }).collect();
|
||||
let view = FileView { path, page: ds.page, pages };
|
||||
let views = &mut self.prefs.file_views;
|
||||
views.retain(|v| v.path != view.path);
|
||||
views.insert(0, view);
|
||||
views.truncate(MAX_FILE_VIEWS);
|
||||
self.prefs_unsaved = true;
|
||||
}
|
||||
|
||||
/// [`remember_view`](Self::remember_view) for every open tab, before the app quits.
|
||||
pub fn remember_views(&mut self) {
|
||||
for i in 0..self.docs.len() {
|
||||
self.remember_view(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show the active tab's file where it was left, if it was: its page, if the file still has
|
||||
/// it as a page that isn't a divider, at its view, and each other page at its view when it is
|
||||
/// shown. A view that isn't a finite centre with a zoom the canvas takes is left out.
|
||||
pub(crate) fn restore_view(&mut self) {
|
||||
let Ok(ds) = self.ds() else { return };
|
||||
let Some(kept) = ds.path.as_deref().and_then(|p| self.prefs.file_views.iter().find(|v| v.path == p)).cloned() else { return };
|
||||
let Ok(ds) = self.ds_mut() else { return };
|
||||
let doc = ds.doc.clone();
|
||||
let views = kept
|
||||
.pages
|
||||
.iter()
|
||||
.filter(|v| doc.pages.contains(&v.page) && [v.cx, v.cy, v.zoom].iter().all(|x| x.is_finite()))
|
||||
.filter(|v| (ViewState::MIN_ZOOM..=ViewState::MAX_ZOOM).contains(&v.zoom))
|
||||
.map(|v| (v.page, (v.cx, v.cy, v.zoom)));
|
||||
let page = Some(kept.page).filter(|p| doc.pages.contains(p) && !doc.is_divider(*p));
|
||||
ds.show_views(page, views);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Files open again where they were left.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A test's folder, removed when the test ends, a failing one too.
|
||||
struct Dir(std::path::PathBuf);
|
||||
|
||||
impl std::ops::Deref for Dir {
|
||||
type Target = std::path::Path;
|
||||
fn deref(&self) -> &std::path::Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn dir(name: &str) -> Dir {
|
||||
let d = std::env::temp_dir().join(format!("figcraft-file-views-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
Dir(d)
|
||||
}
|
||||
|
||||
/// A saved file at `path` with two pages, each holding a rectangle, the first page shown.
|
||||
fn two_pages(s: &mut Session, path: &str) -> (NodeId, NodeId) {
|
||||
ex(s, "file.new", json!({}));
|
||||
ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 100}));
|
||||
ex(s, "page.add", json!({"name": "Second"}));
|
||||
let pages = s.doc().unwrap().pages.clone();
|
||||
ex(s, "page.select", json!({"id": pages[1].0}));
|
||||
ex(s, "shape.rectangle", json!({"x": 2000, "y": 2000, "width": 50, "height": 50}));
|
||||
ex(s, "page.select", json!({"id": pages[0].0}));
|
||||
ex(s, "file.saveAs", json!({"path": path}));
|
||||
(pages[0], pages[1])
|
||||
}
|
||||
|
||||
fn view(s: &Session) -> (NodeId, f64, f64, f64) {
|
||||
let ds = s.ds().unwrap();
|
||||
(ds.page, ds.view.cx, ds.view.cy, ds.view.zoom)
|
||||
}
|
||||
|
||||
fn look(s: &mut Session, cx: f64, cy: f64, zoom: f64) {
|
||||
let v = &mut s.ds_mut().unwrap().view;
|
||||
(v.cx, v.cy, v.zoom) = (cx, cy, zoom);
|
||||
}
|
||||
|
||||
/// Closed and opened again, a file shows the page it showed, at its view, and its other page at
|
||||
/// the view that page was left at; looking around leaves the file unchanged.
|
||||
#[test]
|
||||
fn a_file_opens_again_where_it_was_left() {
|
||||
let d = dir("left");
|
||||
let path = d.join("two.figcraft").to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
let (first, second) = two_pages(&mut s, &path);
|
||||
let saved = std::fs::read(&path).unwrap();
|
||||
look(&mut s, 40.0, 60.0, 2.5);
|
||||
ex(&mut s, "page.select", json!({"id": second.0}));
|
||||
look(&mut s, 2010.0, 2020.0, 0.5);
|
||||
assert!(!s.ds().unwrap().is_dirty(), "looking around is no change to the file");
|
||||
ex(&mut s, "file.close", json!({}));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), saved, "nothing written to the file");
|
||||
assert!(s.prefs_unsaved, "kept in the preferences");
|
||||
ex(&mut s, "file.open", json!({"path": path}));
|
||||
assert_eq!(view(&s), (second, 2010.0, 2020.0, 0.5));
|
||||
assert!(!s.ds().unwrap().fit_when_sized, "the canvas keeps the view instead of fitting");
|
||||
ex(&mut s, "page.select", json!({"id": first.0}));
|
||||
assert_eq!(view(&s), (first, 40.0, 60.0, 2.5));
|
||||
// Through the preferences file, as the next start reads them.
|
||||
let prefs: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
|
||||
let mut next = Session::new();
|
||||
next.prefs = prefs;
|
||||
ex(&mut next, "file.open", json!({"path": path}));
|
||||
assert_eq!(view(&next), (second, 2010.0, 2020.0, 0.5));
|
||||
}
|
||||
|
||||
/// Quitting keeps every open file's view; a file never saved keeps none.
|
||||
#[test]
|
||||
fn quitting_keeps_each_open_files_view() {
|
||||
let d = dir("quit");
|
||||
let (a, b) = (d.join("a.figcraft").to_string_lossy().into_owned(), d.join("b.figcraft").to_string_lossy().into_owned());
|
||||
let mut s = Session::new();
|
||||
let (a_page, _) = two_pages(&mut s, &a);
|
||||
look(&mut s, 1.0, 2.0, 3.0);
|
||||
let (b_page, _) = two_pages(&mut s, &b);
|
||||
look(&mut s, 4.0, 5.0, 0.25);
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
s.remember_views();
|
||||
let kept: Vec<&str> = s.prefs.file_views.iter().map(|v| v.path.as_str()).collect();
|
||||
assert_eq!(kept.len(), 2, "{kept:?}");
|
||||
let mut next = Session::new();
|
||||
next.prefs = s.prefs.clone();
|
||||
ex(&mut next, "file.open", json!({"path": a}));
|
||||
assert_eq!(view(&next), (a_page, 1.0, 2.0, 3.0));
|
||||
ex(&mut next, "file.open", json!({"path": b}));
|
||||
assert_eq!(view(&next), (b_page, 4.0, 5.0, 0.25));
|
||||
}
|
||||
|
||||
/// A kept page the file no longer has, or a view the canvas can't show, is left out: the file
|
||||
/// opens fitted as before.
|
||||
#[test]
|
||||
fn a_view_that_no_longer_fits_the_file_is_left_out() {
|
||||
let d = dir("stale");
|
||||
let path = d.join("one.figcraft").to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
let (first, _) = two_pages(&mut s, &path);
|
||||
ex(&mut s, "file.close", json!({}));
|
||||
s.prefs.file_views[0].page = NodeId(999_999);
|
||||
s.prefs.file_views[0].pages = vec![PageView { page: first, cx: f64::NAN, cy: 0.0, zoom: 1.0 }];
|
||||
ex(&mut s, "file.open", json!({"path": path}));
|
||||
let ds = s.ds().unwrap();
|
||||
assert_eq!(ds.page, first);
|
||||
assert!(ds.fit_when_sized, "fitted as a file never left");
|
||||
assert!(ds.view.cx.is_finite());
|
||||
}
|
||||
|
||||
/// The views kept are bounded, the most recently left first.
|
||||
#[test]
|
||||
fn the_most_recently_left_files_are_kept() {
|
||||
let mut s = Session::new();
|
||||
for k in 0..MAX_FILE_VIEWS + 5 {
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
s.ds_mut().unwrap().path = Some(format!("/nowhere/{k}.figcraft"));
|
||||
ex(&mut s, "file.close", json!({"force": true}));
|
||||
}
|
||||
assert_eq!(s.prefs.file_views.len(), MAX_FILE_VIEWS);
|
||||
assert_eq!(s.prefs.file_views[0].path, format!("/nowhere/{}.figcraft", MAX_FILE_VIEWS + 4));
|
||||
}
|
||||
@@ -116,6 +116,7 @@ fn empty_options_keep_the_main_tree_and_document_output() {
|
||||
"fontFamily": "Synthetic",
|
||||
"fontSize": 18.0,
|
||||
"fontStyle": "Bold",
|
||||
"fontWeight": 700,
|
||||
"height": 24.0,
|
||||
"id": 3,
|
||||
"letterSpacing": "1",
|
||||
|
||||
@@ -368,6 +368,7 @@ pub static GESTURES: &[(Group, &str, &str, &str)] = &[
|
||||
(Selection, "Pick select: next or previous layer", "⇥ / ⇧⇥", "Tab / Shift+Tab"),
|
||||
(Selection, "Pick select: into a layer, out to its parent", "↵ / ⇧↵", "Enter / Shift+Enter"),
|
||||
(Selection, "Pick select: select the picked layer", "Space", "Space"),
|
||||
(Text, "While editing text: next or previous text layer", "⇥ / ⇧⇥", "Tab / Shift+Tab"),
|
||||
(Edit, "Duplicate by dragging", "⌥ drag", "Alt+drag"),
|
||||
(Transform, "Nudge (Shift: big nudge)", "← ↑ → ↓", "← ↑ → ↓"),
|
||||
(Transform, "Resize by the nudge amount", "⌘ arrows", "Ctrl+arrows"),
|
||||
|
||||
@@ -16,6 +16,7 @@ mod canvas;
|
||||
pub mod catalog;
|
||||
pub mod cmd;
|
||||
mod content;
|
||||
mod design;
|
||||
mod dev;
|
||||
pub mod events;
|
||||
mod extensions;
|
||||
@@ -106,13 +107,16 @@ use serde_json::{Value, json};
|
||||
mod derived;
|
||||
mod doc_state;
|
||||
mod error;
|
||||
mod file_views;
|
||||
mod prefs;
|
||||
mod reopen;
|
||||
mod session;
|
||||
mod view_state;
|
||||
|
||||
pub use derived::{changed_nodes, normalize};
|
||||
pub use doc_state::{DocState, History, HistoryEntry, Interaction, PREVIEW_READ_ONLY, Preedit, TextEdit, VersionPreview};
|
||||
pub use error::{EngineError, Result, bad};
|
||||
pub use file_views::{FileView, MAX_FILE_VIEWS, PageView};
|
||||
pub use prefs::{Clipboard, DefaultProps, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UI_SCALE_SIZES, UiRequest, clamp_ui_scale};
|
||||
pub use session::Forward;
|
||||
pub use view_state::ViewState;
|
||||
@@ -488,6 +492,8 @@ mod panels_behaviour_tests;
|
||||
#[cfg(test)]
|
||||
mod paste_missing_image_tests;
|
||||
#[cfg(test)]
|
||||
mod paste_over_tests;
|
||||
#[cfg(test)]
|
||||
mod paste_sibling_tests;
|
||||
#[cfg(test)]
|
||||
mod path_read_caps_tests;
|
||||
@@ -548,6 +554,8 @@ mod proto_run_tests;
|
||||
#[cfg(test)]
|
||||
mod proto_tail_tests;
|
||||
#[cfg(test)]
|
||||
mod reopen_tests;
|
||||
#[cfg(test)]
|
||||
mod rest_slot_tests;
|
||||
#[cfg(test)]
|
||||
mod retained_walk_tests;
|
||||
@@ -624,6 +632,8 @@ mod text_motion_tests;
|
||||
#[cfg(test)]
|
||||
mod text_style_picker_tests;
|
||||
#[cfg(test)]
|
||||
mod text_tab_tests;
|
||||
#[cfg(test)]
|
||||
mod text_tail_tests;
|
||||
#[cfg(test)]
|
||||
mod text_weight_step_tests;
|
||||
@@ -697,6 +707,8 @@ mod export_bounds_tests;
|
||||
#[cfg(test)]
|
||||
mod page_view_tests;
|
||||
#[cfg(test)]
|
||||
mod paste_properties_tests;
|
||||
#[cfg(test)]
|
||||
mod selection_reorder_tests;
|
||||
#[cfg(test)]
|
||||
mod selection_spacing_tests;
|
||||
@@ -471,3 +471,26 @@ fn joining_takes_a_code_of_either_kind_or_a_link() {
|
||||
assert_eq!((&r["status"], &r["reason"]), (&json!("failed"), &json!("No session with that code")));
|
||||
assert_eq!(s.message.as_deref(), Some("No session with that code"));
|
||||
}
|
||||
|
||||
/// A file whose review settings are past this build's limits is not shared, hosted or published:
|
||||
/// joining clients apply arriving values against the limits they were built with, so a file
|
||||
/// written by a looser build would break them. Nothing reaches the link; the error names the
|
||||
/// lists and the way out.
|
||||
#[test]
|
||||
fn a_file_past_the_review_limits_is_not_shared() {
|
||||
use figcraft_doc::{DesignReview, MAX_RADII};
|
||||
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().design_review = DesignReview { radii: (0..MAX_RADII + 1).map(|i| i as f64).collect(), ..Default::default() };
|
||||
for (cmd, p) in [
|
||||
("collab.host", json!({})),
|
||||
("collab.share", json!({"via": "local"})),
|
||||
("collab.share", json!({"via": "online", "server": "wss://s.example/"})),
|
||||
("collab.publish", json!({"server": "wss://s.example/"})),
|
||||
] {
|
||||
let e = err(&mut s, cmd, p);
|
||||
assert!(e.contains("can't be shared"), "{cmd}: {e}");
|
||||
assert!(e.contains(&format!("{} corner radii (this build keeps at most {MAX_RADII})", MAX_RADII + 1)), "{cmd}: {e}");
|
||||
assert!(e.contains("design.configure"), "{cmd}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Shift+Cmd/Ctrl+V with several layers selected pastes after the last of them as seen.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::params::id_of;
|
||||
use figcraft_doc::NodeId;
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
id_of(&v["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
id(&s.execute("frame.create", &json!({"x": x, "y": y, "width": 200, "height": 100})).unwrap())
|
||||
}
|
||||
|
||||
fn kids(s: &Session, parent: NodeId) -> Vec<NodeId> {
|
||||
s.doc().unwrap().node(parent).unwrap().children.clone()
|
||||
}
|
||||
|
||||
fn paste_over(s: &mut Session, sel: Vec<NodeId>) -> Vec<NodeId> {
|
||||
s.set_selection(sel);
|
||||
s.execute("edit.pasteOver", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(id_of).collect()
|
||||
}
|
||||
|
||||
fn top_left(s: &Session, n: NodeId) -> (f64, f64) {
|
||||
let b = s.doc().unwrap().world_bounds(n).unwrap();
|
||||
(b.x0, b.y0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_rows_of_an_auto_layout_selected_get_the_copy_after_the_last_row() {
|
||||
let mut s = Session::new();
|
||||
let rows: Vec<NodeId> =
|
||||
(0..4).map(|k| id(&s.execute("shape.rectangle", &json!({"x": 0, "y": k * 30, "width": 40, "height": 20})).unwrap())).collect();
|
||||
let r = s.execute("layout.add", &json!({"ids": rows, "direction": "vertical"})).unwrap();
|
||||
let list = id_of(&r["ids"][0]).unwrap();
|
||||
assert_eq!(kids(&s, list), rows);
|
||||
s.execute("edit.copy", &json!({"ids": [rows[0]]})).unwrap();
|
||||
// Clicked from the middle down and back: the click order isn't the order on screen.
|
||||
let pasted = paste_over(&mut s, vec![rows[1], rows[3], rows[2]]);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(kids(&s, list), vec![rows[0], rows[1], rows[2], rows[3], pasted[0]], "after the last selected row");
|
||||
assert_eq!(s.selection(), pasted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_artboards_in_a_column_get_the_copy_below_the_lowest_with_their_gap() {
|
||||
let mut s = Session::new();
|
||||
let (a, b, c) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 0.0, 140.0), frame(&mut s, 0.0, 280.0));
|
||||
let source = frame(&mut s, 1000.0, 0.0);
|
||||
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
|
||||
let pasted = paste_over(&mut s, vec![a, c, b]);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(top_left(&s, pasted[0]), (0.0, 420.0), "below the lowest artboard, 40 below it like the others");
|
||||
let page = s.doc().unwrap().node(c).unwrap().parent.unwrap();
|
||||
let order = kids(&s, page);
|
||||
let at = |n: NodeId| order.iter().position(|i| *i == n).unwrap();
|
||||
assert_eq!(at(pasted[0]), at(c) + 1, "just above the lowest artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_artboards_in_a_row_get_the_copy_right_of_the_rightmost_with_their_gap() {
|
||||
let mut s = Session::new();
|
||||
let (a, b, c) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 260.0, 0.0), frame(&mut s, 520.0, 0.0));
|
||||
let source = frame(&mut s, 0.0, 1000.0);
|
||||
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
|
||||
let pasted = paste_over(&mut s, vec![b, a, c]);
|
||||
assert_eq!(top_left(&s, pasted[0]), (780.0, 0.0), "right of the rightmost, 60 from it like the others");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_overlapping_layers_get_the_copy_right_under_the_lowest() {
|
||||
let mut s = Session::new();
|
||||
let (a, b) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 50.0, 30.0));
|
||||
let source = frame(&mut s, 1000.0, 0.0);
|
||||
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
|
||||
let pasted = paste_over(&mut s, vec![b, a]);
|
||||
assert_eq!(top_left(&s, pasted[0]), (50.0, 130.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_absolute_layers_of_an_auto_layout_get_the_copy_below_the_lowest() {
|
||||
let mut s = Session::new();
|
||||
let rows: Vec<NodeId> =
|
||||
(0..3).map(|k| id(&s.execute("shape.rectangle", &json!({"x": 0, "y": k * 30, "width": 40, "height": 20})).unwrap())).collect();
|
||||
s.execute("layout.add", &json!({"ids": rows, "direction": "vertical"})).unwrap();
|
||||
s.execute("node.set", &json!({"ids": rows, "props": {"absolute": true}})).unwrap();
|
||||
s.execute("edit.copy", &json!({"ids": [rows[0]]})).unwrap();
|
||||
let (x, y0) = top_left(&s, rows[1]);
|
||||
let (_, y1) = top_left(&s, rows[2]);
|
||||
let pasted = paste_over(&mut s, vec![rows[2], rows[0], rows[1]]);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(top_left(&s, pasted[0]), (x, y1 + 20.0 + (y1 - y0 - 20.0)), "the layout doesn't place them, so below the lowest");
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Copy properties and Paste properties (Alt+Cmd/Ctrl+C and V) carry what a layer's look comes
|
||||
//! from as well as its values: its colour, effect and grid styles, the variables bound to what is
|
||||
//! copied and a frame's layout grids. A link the file pasted into doesn't have is left out.
|
||||
|
||||
use figcraft_doc::{LayoutGrid, NodeId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn id(v: Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, x: f64) -> NodeId {
|
||||
id(s.execute("frame.create", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap())
|
||||
}
|
||||
|
||||
fn copy_onto(s: &mut Session, from: NodeId, to: NodeId) {
|
||||
s.execute("edit.copyProperties", &json!({"id": from})).unwrap();
|
||||
s.execute("edit.pasteProperties", &json!({"ids": [to]})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_pastes_its_styles_variables_and_layout_grids() {
|
||||
let mut s = Session::new();
|
||||
let (a, b, c) = (frame(&mut s, 0.0), frame(&mut s, 200.0), frame(&mut s, 400.0));
|
||||
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
|
||||
for (name, value) in [("surface", "#FF0000"), ("other", "#0000FF")] {
|
||||
s.execute("variable.create", &json!({"collection": "Tokens", "name": name, "type": "color", "value": value})).unwrap();
|
||||
}
|
||||
s.execute("variable.create", &json!({"collection": "Tokens", "name": "radius", "type": "number", "value": 16})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [a], "field": "cornerRadius", "variable": "radius"})).unwrap();
|
||||
s.execute("node.set", &json!({"ids": [a], "props": {"grids": [serde_json::to_value(LayoutGrid::default()).unwrap()]}})).unwrap();
|
||||
// B is bound to another colour, which the paste replaces.
|
||||
s.execute("variable.bind", &json!({"ids": [b], "field": "fills/0/color", "variable": "other"})).unwrap();
|
||||
let shadow = s.execute("style.create", &json!({"type": "effect", "name": "Shadow", "value": [{"type": "dropShadow"}]})).unwrap()["id"].clone();
|
||||
let green = s.execute("style.create", &json!({"type": "paint", "name": "Green", "value": "#00FF00"})).unwrap()["id"].clone();
|
||||
s.execute("style.apply", &json!({"ids": [c], "style": green})).unwrap();
|
||||
s.execute("style.apply", &json!({"ids": [c], "style": shadow})).unwrap();
|
||||
|
||||
copy_onto(&mut s, a, b);
|
||||
let (na, nb) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(b).unwrap().clone());
|
||||
assert_eq!(nb.bound.get("fills/0/color"), na.bound.get("fills/0/color"), "the fill follows the same variable");
|
||||
assert_eq!(nb.bound.get("cornerRadius"), na.bound.get("cornerRadius"), "and so do the corners");
|
||||
assert_eq!(nb.corners.radii, [16.0; 4]);
|
||||
assert_eq!(nb.grids, na.grids, "a frame's layout grids come along");
|
||||
|
||||
copy_onto(&mut s, c, a);
|
||||
let (na, nc) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(c).unwrap().clone());
|
||||
assert_eq!(na.styles.fill, nc.styles.fill, "the fill style is linked");
|
||||
assert!(nc.styles.effect.is_some() && na.styles.effect == nc.styles.effect, "the effect style too");
|
||||
assert!(!na.bound.contains_key("fills/0/color"), "the style replaces the fill's variable");
|
||||
assert!(!na.bound.contains_key("cornerRadius"), "C's corners aren't bound, so A's aren't any more");
|
||||
assert!(na.grids.is_empty(), "nor has it layout grids");
|
||||
assert_eq!(na.fills, nc.fills);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_another_file_lacks_paste_as_values() {
|
||||
let mut s = Session::new();
|
||||
let a = frame(&mut s, 0.0);
|
||||
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
|
||||
s.execute("variable.create", &json!({"collection": "Tokens", "name": "surface", "type": "color", "value": "#FF0000"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
|
||||
let st = s.execute("style.create", &json!({"type": "paint", "name": "Line", "value": "#00FF00"})).unwrap()["id"].clone();
|
||||
s.execute("node.set", &json!({"ids": [a], "props": {"strokes": [{"type": "solid", "color": "#000000"}]}})).unwrap();
|
||||
s.execute("style.apply", &json!({"ids": [a], "style": st, "target": "stroke"})).unwrap();
|
||||
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
|
||||
let copied = s.doc().unwrap().node(a).unwrap().clone();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let b = frame(&mut s, 0.0);
|
||||
// This file's own style and variable come out with the copied ids: they are not the copied ones.
|
||||
s.execute("variable.createCollection", &json!({"name": "Theirs"})).unwrap();
|
||||
s.execute("variable.create", &json!({"collection": "Theirs", "name": "ink", "type": "color", "value": "#0000FF"})).unwrap();
|
||||
s.execute("style.create", &json!({"type": "paint", "name": "Ink", "value": "#0000FF"})).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let vid = copied.bound["fills/0/color"].as_str();
|
||||
assert!(doc.style(st.as_str().unwrap()).is_some() && doc.variables.get_by_id(vid).is_some(), "the ids are taken here");
|
||||
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
|
||||
let nb = s.doc().unwrap().node(b).unwrap();
|
||||
assert_eq!((nb.fills.clone(), nb.strokes.clone()), (copied.fills, copied.strokes), "the values arrive");
|
||||
assert!(nb.bound.is_empty() && nb.styles.fill.is_none() && nb.styles.stroke.is_none(), "{:?} {:?}", nb.bound, nb.styles);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_style_unlinks_the_layers_own() {
|
||||
let mut s = Session::new();
|
||||
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
|
||||
// B's own style gives the same colour, so the paste changes no value that would unlink it.
|
||||
let gone = s.execute("style.create", &json!({"type": "paint", "name": "Gone", "value": "#00FF00"})).unwrap()["id"].clone();
|
||||
let own = s.execute("style.create", &json!({"type": "paint", "name": "Own", "value": "#00FF00"})).unwrap()["id"].clone();
|
||||
s.execute("style.apply", &json!({"ids": [a], "style": gone, "target": "stroke"})).unwrap();
|
||||
s.execute("style.apply", &json!({"ids": [b], "style": own, "target": "stroke"})).unwrap();
|
||||
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
|
||||
s.execute("style.delete", &json!({"style": gone})).unwrap();
|
||||
|
||||
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
|
||||
let nb = s.doc().unwrap().node(b).unwrap();
|
||||
assert!(nb.styles.stroke.is_none(), "A's strokes had no style here, so B's aren't linked: {:?}", nb.styles);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_binding_on_what_the_copy_doesnt_carry_stays() {
|
||||
let mut s = Session::new();
|
||||
let a = frame(&mut s, 0.0);
|
||||
let t = id(s.execute("text.create", &json!({"text": "Hi", "x": 0, "y": 200})).unwrap());
|
||||
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
|
||||
s.execute("variable.create", &json!({"collection": "Tokens", "name": "body", "type": "number", "value": 18})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [t], "field": "fontSize", "variable": "body"})).unwrap();
|
||||
let before = s.doc().unwrap().node(t).unwrap().bound.get("fontSize").cloned();
|
||||
|
||||
copy_onto(&mut s, a, t);
|
||||
let nt = s.doc().unwrap().node(t).unwrap();
|
||||
assert!(before.is_some() && nt.bound.get("fontSize") == before.as_ref(), "a frame carries no font size: {:?}", nt.bound);
|
||||
}
|
||||
@@ -63,7 +63,8 @@ pub struct Prefs {
|
||||
/// Files that have a path are saved by themselves a few seconds after they change (the app's
|
||||
/// timer; off: only File ▸ Save writes them).
|
||||
pub auto_save: bool,
|
||||
/// The desktop app starts on the Home screen instead of in a new file.
|
||||
/// The desktop app starts on the Home screen instead of reopening the files open when it last
|
||||
/// quit.
|
||||
pub start_on_home: bool,
|
||||
/// `figcraft://` invite links open this app (`collab.registerLinks`); `None`: on for installed
|
||||
/// builds, off for development builds.
|
||||
@@ -85,6 +86,18 @@ pub struct Prefs {
|
||||
/// Recently opened or saved files, newest first (File ▸ Open recent; at most
|
||||
/// [`cmd::file::MAX_RECENT`]).
|
||||
pub recent_files: Vec<String>,
|
||||
/// The files open when the desktop app last quit, in tab order: the next start opens them again
|
||||
/// ([`Session::reopen_files`](crate::Session::reopen_files)).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub open_files: Vec<String>,
|
||||
/// Which of [`open_files`](Self::open_files) was in front.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub front_file: Option<String>,
|
||||
/// Where each file was left when its tab closed or the app quit, the most recently left first,
|
||||
/// at most [`MAX_FILE_VIEWS`](crate::MAX_FILE_VIEWS): opening it again shows that page at that
|
||||
/// view ([`Session::remember_views`](crate::Session::remember_views)).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub file_views: Vec<crate::FileView>,
|
||||
/// The files you put on a server without its key, with their owner tokens (passwords: see
|
||||
/// [`online`]), most recently opened first, at most [`online::MAX_ONLINE_FILES`].
|
||||
#[serde(skip_serializing_if = "Vec::is_empty", deserialize_with = "online::read")]
|
||||
@@ -109,6 +122,9 @@ pub struct Prefs {
|
||||
/// files opened or made later start with them. Missing: the toggle's default.
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub view: BTreeMap<String, bool>,
|
||||
/// Design review ignores, by document path: whole rule ids and `rule@layer` entries.
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub design_review_ignored: BTreeMap<String, Vec<String>>,
|
||||
/// The board canvas's background grid (`board.grid`).
|
||||
#[serde(deserialize_with = "crate::board_grid::read")]
|
||||
pub board_grid: crate::board_grid::BoardGrid,
|
||||
@@ -155,6 +171,9 @@ impl Default for Prefs {
|
||||
plugin_directory: None,
|
||||
publish_server: live::DEFAULT_SERVER.into(),
|
||||
recent_files: Vec::new(),
|
||||
open_files: Vec::new(),
|
||||
front_file: None,
|
||||
file_views: Vec::new(),
|
||||
online_files: Vec::new(),
|
||||
getting_started_dismissed: false,
|
||||
link_notice_skipped: false,
|
||||
@@ -162,6 +181,7 @@ impl Default for Prefs {
|
||||
home_sort: "modified".into(),
|
||||
home_order: "desc".into(),
|
||||
view: BTreeMap::new(),
|
||||
design_review_ignored: BTreeMap::new(),
|
||||
board_grid: Default::default(),
|
||||
recent_actions: Vec::new(),
|
||||
team_libraries: Vec::new(),
|
||||
@@ -197,6 +217,9 @@ pub struct Clipboard {
|
||||
pub images: std::collections::BTreeMap<String, figcraft_doc::ImageData>,
|
||||
/// Copied properties (Copy properties / Paste properties).
|
||||
pub props: Option<Value>,
|
||||
/// The file the copied properties came from: their style and variable ids name its styles and
|
||||
/// variables, and in another file the same ids can name unrelated ones.
|
||||
pub props_source_doc: u64,
|
||||
/// A copied fill or stroke row (`fill.copy`, `stroke.copy`): whether it's a fill, and the paint.
|
||||
pub paint: Option<(bool, figcraft_color::Paint)>,
|
||||
/// The stroke settings (`weight`, alignment, sides…) copied with a stroke's paint.
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! The files open when the desktop app quit open again at its next start, in their tabs' order
|
||||
//! with the same one in front, as Figma's desktop app reopens its tabs.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
impl Session {
|
||||
/// Keep the open files to reopen at the next start: each tab's file that has a path, in tab
|
||||
/// order, and the one in front. Files without one (new, imported, joined from a live session)
|
||||
/// and branch tabs are left out.
|
||||
pub fn remember_open_files(&mut self) {
|
||||
let path = |i: usize| self.docs.get(i).filter(|d| d.branch_of.is_none()).and_then(|d| d.path.clone());
|
||||
self.prefs.open_files = (0..self.docs.len()).filter_map(path).collect();
|
||||
self.prefs.front_file = path(self.active);
|
||||
}
|
||||
|
||||
/// Open the files [`remember_open_files`](Self::remember_open_files) kept, then bring the one
|
||||
/// that was in front forward. A file that is no longer there is skipped; the others that don't
|
||||
/// open come back with why. A file already open (a recovered copy, one named at start) keeps
|
||||
/// its tab.
|
||||
pub fn reopen_files(&mut self) -> Vec<(String, EngineError)> {
|
||||
let mut failed = Vec::new();
|
||||
for path in self.prefs.open_files.clone() {
|
||||
if !crate::file_access::exists(&path) {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = self.execute("file.open", &json!({"path": path})) {
|
||||
failed.push((path, e));
|
||||
}
|
||||
}
|
||||
let front = self.prefs.front_file.as_deref();
|
||||
if let Some(i) = self.docs.iter().position(|d| front.is_some() && d.path.as_deref() == front) {
|
||||
self.active = i;
|
||||
}
|
||||
failed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! The files open when the desktop app quit open again at its next start.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A fresh folder for a test's files, removed when the test ends, a failing one too.
|
||||
struct Folder(PathBuf);
|
||||
|
||||
impl std::ops::Deref for Folder {
|
||||
type Target = Path;
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Folder {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn folder(name: &str) -> Folder {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-reopen-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Folder(dir)
|
||||
}
|
||||
|
||||
fn saved(s: &mut Session, dir: &Path, name: &str) -> String {
|
||||
let path = dir.join(format!("{name}.figcraft")).to_string_lossy().into_owned();
|
||||
s.execute("file.new", &json!({"name": name})).unwrap();
|
||||
s.execute("file.save", &json!({"path": path})).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn paths(s: &Session) -> Vec<Option<String>> {
|
||||
s.docs.iter().map(|d| d.path.clone()).collect()
|
||||
}
|
||||
|
||||
/// The next start: the preferences the last run kept, nothing open yet.
|
||||
fn next_start(last: &Session) -> Session {
|
||||
let mut s = Session::empty();
|
||||
s.prefs = last.prefs.clone();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_files_open_at_quit_reopen_in_their_order_with_the_same_one_in_front() {
|
||||
let dir = folder("order");
|
||||
let mut s = Session::empty();
|
||||
let a = saved(&mut s, &dir, "A");
|
||||
s.execute("file.new", &json!({"name": "Untitled"})).unwrap();
|
||||
let b = saved(&mut s, &dir, "B");
|
||||
let c = saved(&mut s, &dir, "C");
|
||||
s.execute("doc.switch", &json!({"index": 2})).unwrap();
|
||||
s.remember_open_files();
|
||||
assert_eq!(s.prefs.open_files, vec![a.clone(), b.clone(), c.clone()], "the new file without a path is left out");
|
||||
assert_eq!(s.prefs.front_file.as_deref(), Some(b.as_str()));
|
||||
|
||||
let mut t = next_start(&s);
|
||||
assert!(t.reopen_files().is_empty());
|
||||
assert_eq!(paths(&t), vec![Some(a), Some(b.clone()), Some(c)]);
|
||||
assert_eq!(t.docs[t.active].path.as_deref(), Some(b.as_str()), "B is in front again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_gone_since_is_skipped_and_one_that_wont_open_says_why() {
|
||||
let dir = folder("gone");
|
||||
let mut s = Session::empty();
|
||||
let kept = saved(&mut s, &dir, "Kept");
|
||||
let gone = saved(&mut s, &dir, "Gone");
|
||||
let broken = saved(&mut s, &dir, "Broken");
|
||||
s.remember_open_files();
|
||||
std::fs::remove_file(&gone).unwrap();
|
||||
std::fs::write(&broken, b"not a figcraft file").unwrap();
|
||||
|
||||
let mut t = next_start(&s);
|
||||
let failed = t.reopen_files();
|
||||
assert_eq!(failed.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>(), vec![broken]);
|
||||
assert_eq!(paths(&t), vec![Some(kept)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_already_open_at_start_keeps_its_one_tab() {
|
||||
let dir = folder("twice");
|
||||
let mut s = Session::empty();
|
||||
let a = saved(&mut s, &dir, "A");
|
||||
let b = saved(&mut s, &dir, "B");
|
||||
s.execute("doc.switch", &json!({"index": 0})).unwrap();
|
||||
s.remember_open_files();
|
||||
|
||||
// B was named on the command line (or came back as a recovered copy).
|
||||
let mut t = next_start(&s);
|
||||
t.execute("file.open", &json!({"path": b})).unwrap();
|
||||
assert!(t.reopen_files().is_empty());
|
||||
assert_eq!(paths(&t), vec![Some(b), Some(a.clone())]);
|
||||
assert_eq!(t.docs[t.active].path.as_deref(), Some(a.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quitting_with_nothing_open_leaves_nothing_to_reopen() {
|
||||
let dir = folder("none");
|
||||
let mut s = Session::empty();
|
||||
saved(&mut s, &dir, "A");
|
||||
s.remember_open_files();
|
||||
s.execute("file.close", &json!({"index": 0})).unwrap();
|
||||
s.remember_open_files();
|
||||
assert!(s.prefs.open_files.is_empty());
|
||||
assert_eq!(s.prefs.front_file, None);
|
||||
let saved = serde_json::to_value(&s.prefs).unwrap();
|
||||
assert!(saved.get("open_files").is_none() && saved.get("front_file").is_none(), "not written when empty");
|
||||
}
|
||||
@@ -94,7 +94,7 @@ fn assert_save_state_unchanged(s: &Session, before: &DocState, recent: &[String]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
|
||||
fn saving_to_another_file_names_the_document_after_it() {
|
||||
let mut files = SaveFiles::new();
|
||||
let path = files.path("Redis.figcraft");
|
||||
let copy = files.path("Redis copy.figcraft");
|
||||
@@ -111,9 +111,19 @@ fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
|
||||
|
||||
s.execute("file.saveAs", &json!({"path": copy.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.ds().unwrap().doc.name, "Redis copy");
|
||||
s.execute("file.rename", &json!({"name": "Chosen title"})).unwrap();
|
||||
s.execute("file.rename", &json!({"name": "Chosen: title"})).unwrap();
|
||||
s.execute("file.save", &json!({})).unwrap();
|
||||
assert_eq!(s.ds().unwrap().doc.name, "Chosen: title", "saving to the same file keeps a name given here");
|
||||
s.execute("file.saveAs", &json!({"path": manual_copy.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.ds().unwrap().doc.name, "Chosen title");
|
||||
assert_eq!(s.ds().unwrap().doc.name, "Other", "a name given here too");
|
||||
assert_eq!(figcraft_format::load_bytes(&std::fs::read(&manual_copy).unwrap()).unwrap().0.name, "Other");
|
||||
|
||||
// A file without one on disk yet: imported, here with its source's name.
|
||||
let imported = files.path("Imported.figcraft");
|
||||
let mut i = Session::new();
|
||||
i.execute("file.rename", &json!({"name": "ШИМ"})).unwrap();
|
||||
i.execute("file.saveAs", &json!({"path": imported.to_string_lossy()})).unwrap();
|
||||
assert_eq!(i.ds().unwrap().doc.name, "Imported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -36,6 +36,24 @@ pub(super) fn unavailable(cmd: &str) -> EngineError {
|
||||
)
|
||||
}
|
||||
|
||||
/// A file whose review settings are past this build's limits can't be shared or published:
|
||||
/// every joining client applies arriving values against the limits it was built with, so a file
|
||||
/// written by an older or looser build would break them (and no build silently trims what the
|
||||
/// file's author set). The error names the lists and the way out.
|
||||
fn check_sharable(cmd: &str, doc: &figcraft_doc::Document) -> Result<()> {
|
||||
let over = doc.design_review.over_limits();
|
||||
if over.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let list = over.iter().map(|(what, have, max)| format!("{have} {what} (this build keeps at most {max})")).collect::<Vec<_>>().join(", ");
|
||||
Err(bad(
|
||||
cmd,
|
||||
format!(
|
||||
"this file can't be shared: its design review settings hold {list}; trim them with design.configure (or reset the settings), then share again"
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
/// `collab.host`: host the open file (on this machine unless `p` says where) with an invite link.
|
||||
pub(super) fn host(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
start_host(s, "collab.host", p, Bind::Local, false, false)?;
|
||||
@@ -57,6 +75,7 @@ fn start_host(s: &mut Session, cmd: &str, p: &Value, bind: Bind, short: bool, vi
|
||||
Some(other) => other.parse::<IpAddr>().map(Bind::Addr).map_err(|_| bad(cmd, "`bind` must be \"local\", \"lan\" or an IP address"))?,
|
||||
};
|
||||
let (doc, uid) = s.ds().map(|ds| (ds.doc.clone(), ds.uid))?;
|
||||
check_sharable(cmd, &doc)?;
|
||||
let opts = HostOptions { port, bind, name: display_name(&s.prefs), doc, short, view };
|
||||
let (id, info) = s.live.start(cmd, |l, id| l.host(id, opts).map_err(|e| EngineError::Other(format!("couldn't start the live session: {e}"))))?;
|
||||
s.live.open(Live { id, status: Status::Live, info: Some(info), doc_uid: Some(uid), tab: Some(uid), ..Live::default() });
|
||||
@@ -75,6 +94,7 @@ pub(super) fn publish(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn start_publish(s: &mut Session, cmd: &str, server: &str, p: &Value, share: bool) -> Result<SessionId> {
|
||||
let key = string(p, "key").map(|k| k.trim().to_string()).filter(|k| !k.is_empty());
|
||||
let (doc, uid) = s.ds().map(|ds| (ds.doc.clone(), ds.uid))?;
|
||||
check_sharable(cmd, &doc)?;
|
||||
let name = string(p, "name").map(|n| n.trim().chars().filter(|c| !c.is_control()).take(256).collect::<String>()).filter(|n| !n.is_empty());
|
||||
let me = display_name(&s.prefs);
|
||||
let opts = PublishOptions { server: server.trim().to_string(), key, name: name.unwrap_or_else(|| doc.name.clone()), me, doc, share };
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Tab and Shift+Tab while editing a text layer move editing to the next or previous text layer
|
||||
//! of the same top-level frame, in reading order (rows top to bottom, each left to right), with
|
||||
//! all of its text selected; hidden and locked text is passed over, and at either end the key
|
||||
//! does nothing.
|
||||
|
||||
use figcraft_doc::NodeId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::params::id_of;
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
fn text(s: &mut Session, chars: &str, x: f64, y: f64, parent: NodeId) -> NodeId {
|
||||
id_of(&ex(s, "text.create", json!({"text": chars, "x": x, "y": y, "parent": parent}))["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
id_of(&ex(s, "frame.create", json!({"x": x, "y": y, "width": 400, "height": 300}))["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn tab(s: &mut Session, shift: bool) {
|
||||
ex(s, "text.edit.key", json!({"key": "Tab", "shift": shift}));
|
||||
}
|
||||
|
||||
/// The text being edited and whether all of it is selected.
|
||||
fn editing(s: &Session) -> (NodeId, bool) {
|
||||
let te = s.ds().unwrap().text_edit.clone().expect("still editing");
|
||||
let n = s.doc().unwrap().node(te.id).unwrap().kind.text().unwrap().char_count();
|
||||
(te.id, te.anchor.min(te.caret) == 0 && te.anchor.max(te.caret) == n)
|
||||
}
|
||||
|
||||
fn chars(s: &Session, id: NodeId) -> String {
|
||||
s.doc().unwrap().node(id).unwrap().kind.text().unwrap().characters.clone()
|
||||
}
|
||||
|
||||
/// A frame with a row of three texts whose tops differ by a few pixels, out of order in the
|
||||
/// layer list, and a second row below; a text in another frame beside it.
|
||||
fn two_rows(s: &mut Session) -> Vec<NodeId> {
|
||||
let f = frame(s, 0.0, 0.0);
|
||||
let b = text(s, "B", 150.0, 12.0, f);
|
||||
let a = text(s, "A", 10.0, 10.0, f);
|
||||
let e = text(s, "E", 150.0, 100.0, f);
|
||||
let c = text(s, "C", 290.0, 6.0, f);
|
||||
let d = text(s, "D", 10.0, 101.0, f);
|
||||
let other = frame(s, 500.0, 0.0);
|
||||
text(s, "Elsewhere", 10.0, 10.0, other);
|
||||
vec![a, b, c, d, e]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_reads_a_row_left_to_right_then_the_next_row() {
|
||||
let mut s = Session::new();
|
||||
let order = two_rows(&mut s);
|
||||
ex(&mut s, "text.edit.begin", json!({"id": order[0], "caret": 0}));
|
||||
for want in &order[1..] {
|
||||
tab(&mut s, false);
|
||||
assert_eq!(editing(&s), (*want, true), "on to {} with all of it selected", chars(&s, *want));
|
||||
}
|
||||
assert!(order.iter().all(|t| !chars(&s, *t).contains('\t')), "no tab typed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_tab_goes_back() {
|
||||
let mut s = Session::new();
|
||||
let order = two_rows(&mut s);
|
||||
ex(&mut s, "text.edit.begin", json!({"id": order[4], "caret": 0}));
|
||||
for want in order[..4].iter().rev() {
|
||||
tab(&mut s, true);
|
||||
assert_eq!(editing(&s).0, *want, "back to {}", chars(&s, *want));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_on_the_last_text_keeps_editing_it() {
|
||||
let mut s = Session::new();
|
||||
let order = two_rows(&mut s);
|
||||
let undo = s.ds().unwrap().history.undo.len();
|
||||
ex(&mut s, "text.edit.begin", json!({"id": order[4], "caret": 1}));
|
||||
tab(&mut s, false);
|
||||
let te = s.ds().unwrap().text_edit.clone().expect("still editing");
|
||||
assert_eq!((te.id, te.caret, te.anchor), (order[4], 1, 1), "the last one: nothing moves");
|
||||
assert_eq!(chars(&s, order[4]), "E", "and nothing is typed");
|
||||
// Shift+Tab on the first one does nothing either.
|
||||
ex(&mut s, "text.edit.end", json!({}));
|
||||
ex(&mut s, "text.edit.begin", json!({"id": order[0], "caret": 0}));
|
||||
tab(&mut s, true);
|
||||
assert_eq!(editing(&s).0, order[0]);
|
||||
ex(&mut s, "text.edit.end", json!({}));
|
||||
assert_eq!(s.ds().unwrap().history.undo.len(), undo, "no undo step for it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_and_locked_text_is_skipped() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0);
|
||||
let first = text(&mut s, "First", 10.0, 10.0, f);
|
||||
let hidden = text(&mut s, "Hidden", 10.0, 50.0, f);
|
||||
ex(&mut s, "node.set", json!({"id": hidden, "props": {"visible": false}}));
|
||||
let locked = text(&mut s, "Locked", 10.0, 90.0, f);
|
||||
ex(&mut s, "node.set", json!({"id": locked, "props": {"locked": true}}));
|
||||
let inner = id_of(&ex(&mut s, "frame.create", json!({"x": 10, "y": 130, "width": 200, "height": 60, "parent": f}))["id"]).unwrap();
|
||||
text(&mut s, "In a locked frame", 0.0, 0.0, inner);
|
||||
ex(&mut s, "node.set", json!({"id": inner, "props": {"locked": true}}));
|
||||
let last = text(&mut s, "Last", 10.0, 220.0, f);
|
||||
ex(&mut s, "text.edit.begin", json!({"id": first, "caret": 0}));
|
||||
tab(&mut s, false);
|
||||
assert_eq!(editing(&s).0, last, "past the hidden text, the locked one and the text in a locked frame");
|
||||
tab(&mut s, true);
|
||||
assert_eq!(editing(&s).0, first);
|
||||
}
|
||||
@@ -221,11 +221,11 @@ fn list_keys_at_list_items() {
|
||||
2,
|
||||
"Tab",
|
||||
false,
|
||||
"a\n\tb",
|
||||
"a\nb",
|
||||
vec![(B, 0), (P, 1)],
|
||||
"a plain paragraph at a level isn't an item: Tab types a tab",
|
||||
"a plain paragraph at a level isn't an item: Tab leaves the list alone (and moves to the next text, none here)",
|
||||
),
|
||||
("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb\t", vec![(P, 0), (P, 0)], "outside a list Tab types a tab"),
|
||||
("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb", vec![(P, 0), (P, 0)], "outside a list Tab types no tab"),
|
||||
("a", vec![(B, 8)], 1, "Tab", false, "a", vec![(B, 8)], "silent: nesting stops at 8 levels"),
|
||||
];
|
||||
for (chars, before, caret, k, shift, after, want, why) in cases {
|
||||
|
||||
@@ -217,6 +217,124 @@ fn ordinary_resize_and_scale_keep_image_fill_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_mode_image_resizing_without_cmd_morphs_and_with_cmd_crops() {
|
||||
use figcraft_doc::color::{ImageScaleMode, PaintKind};
|
||||
let mut s = session();
|
||||
let layer = image_layer(&mut s);
|
||||
// Set the image fill mode to Crop without an explicit crop: fill.set initializes placement crop.
|
||||
let mut fills = s.doc().unwrap().node(layer).unwrap().fills.clone();
|
||||
let PaintKind::Image(img) = &mut fills[0].kind else { panic!("image fill") };
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
img.crop = None;
|
||||
ex(&mut s, "fill.set", json!({"ids": [layer], "index": 0, "paint": fills[0]}));
|
||||
|
||||
// Verify fill.set initialized img.crop with placement crop.
|
||||
let initial_node = s.doc().unwrap().node(layer).unwrap().clone();
|
||||
let PaintKind::Image(img) = &initial_node.fills[0].kind else { panic!("image fill") };
|
||||
let Some(initial_crop) = img.crop else { panic!("crop initialized") };
|
||||
|
||||
let before = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
|
||||
assert_eq!((before.width(), before.height()), (200, 100));
|
||||
|
||||
// 1. Resize without Cmd (normal resize from bottom edge: 100 -> 50).
|
||||
// The layer height shrinks to 50, but img.crop stays unchanged, stretching/squishing the image.
|
||||
s.pointer(&ev(PointerKind::Down, Point::new(100.0, 100.0), NONE)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Move, Point::new(100.0, 50.0), NONE)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, Point::new(100.0, 50.0), NONE)).unwrap();
|
||||
assert_eq!(size(&s, layer), (200.0, 50.0));
|
||||
|
||||
let n = s.doc().unwrap().node(layer).unwrap().clone();
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
assert_eq!(img.crop, Some(initial_crop), "normal resize leaves crop transform unchanged");
|
||||
|
||||
let morphed = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
|
||||
assert_eq!((morphed.width(), morphed.height()), (200, 50));
|
||||
|
||||
// 2. Resize with Cmd from right edge: 200 -> 100.
|
||||
// The layer width shrinks to 100, and img.crop is updated so the pixels stay stationary on page (cropping).
|
||||
s.pointer(&ev(PointerKind::Down, Point::new(200.0, 25.0), CMD)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Move, Point::new(100.0, 25.0), CMD)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, Point::new(100.0, 25.0), CMD)).unwrap();
|
||||
assert_eq!(size(&s, layer), (100.0, 50.0));
|
||||
|
||||
let n = s.doc().unwrap().node(layer).unwrap().clone();
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
assert_ne!(img.crop, Some(initial_crop), "Cmd resize updates crop transform");
|
||||
|
||||
let cropped = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
|
||||
assert_eq!((cropped.width(), cropped.height()), (100, 50));
|
||||
// The remaining 100x50 pixels match the top-left 100x50 of morphed (pixels stayed still in layer space).
|
||||
for y in 0..50usize {
|
||||
assert_eq!(&cropped.data()[y * 400..(y + 1) * 400], &morphed.data()[y * 800..y * 800 + 400], "row {y}: stationary cropped pixels");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_layer_crop_mode_selection_computes_placement_per_node() {
|
||||
use figcraft_doc::color::{ImageScaleMode, PaintKind};
|
||||
let mut s = session();
|
||||
let layer1 = image_layer(&mut s); // 200 x 100
|
||||
let layer2 = id(&ex(&mut s, "shape.rectangle", json!({"x": 300, "y": 0, "width": 100, "height": 100})));
|
||||
|
||||
// Choose Crop mode on both layers simultaneously via fill.set with crop: None (as the picker does).
|
||||
let mut fill = s.doc().unwrap().node(layer1).unwrap().fills[0].clone();
|
||||
let PaintKind::Image(img) = &mut fill.kind else { panic!("image fill") };
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
img.crop = None;
|
||||
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": fill}));
|
||||
|
||||
// Verify both layers received crop transforms tailored to their own dimensions, not stretched.
|
||||
let n1 = s.doc().unwrap().node(layer1).unwrap().clone();
|
||||
let n2 = s.doc().unwrap().node(layer2).unwrap().clone();
|
||||
let PaintKind::Image(img1) = &n1.fills[0].kind else { panic!("image fill") };
|
||||
let PaintKind::Image(img2) = &n2.fills[0].kind else { panic!("image fill") };
|
||||
|
||||
let crop1 = img1.crop.expect("layer1 crop initialized");
|
||||
let crop2 = img2.crop.expect("layer2 crop initialized");
|
||||
|
||||
// layer1 (200x100) and layer2 (100x100) have different aspect ratios, so their crop transforms must differ.
|
||||
assert_ne!(crop1, crop2, "differently sized layers must have distinct crop transforms");
|
||||
|
||||
// Both should match expected placement crop for their respective dimensions (iw=200, ih=100 from image_layer):
|
||||
assert_eq!(crop1, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
assert_eq!(crop2, [0.5, 0.0, 0.0, 1.0, 0.25, 0.0]);
|
||||
|
||||
// Rotate 90° on the multi-selection (as the picker's Rotate button does):
|
||||
let mut rot_fill = n1.fills[0].clone();
|
||||
let PaintKind::Image(img) = &mut rot_fill.kind else { panic!("image fill") };
|
||||
img.rotation = 1;
|
||||
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": rot_fill}));
|
||||
|
||||
let n1_rot = s.doc().unwrap().node(layer1).unwrap().clone();
|
||||
let n2_rot = s.doc().unwrap().node(layer2).unwrap().clone();
|
||||
let PaintKind::Image(img1_rot) = &n1_rot.fills[0].kind else { panic!("image fill") };
|
||||
let PaintKind::Image(img2_rot) = &n2_rot.fills[0].kind else { panic!("image fill") };
|
||||
|
||||
let crop1_rot = img1_rot.crop.expect("layer1 rotated crop initialized");
|
||||
let crop2_rot = img2_rot.crop.expect("layer2 rotated crop initialized");
|
||||
assert_ne!(crop1_rot, crop2_rot, "differently sized layers must have distinct rotated crop transforms");
|
||||
assert_eq!(crop1_rot, [1.0, 0.0, 0.0, 0.25, 0.0, 0.375]);
|
||||
assert_eq!(crop2_rot, [1.0, 0.0, 0.0, 0.5, 0.0, 0.25]);
|
||||
|
||||
// Shared filter edit on multi-selection in Crop mode (e.g. Exposure slider):
|
||||
let mut filter_fill = n1_rot.fills[0].clone();
|
||||
let PaintKind::Image(img) = &mut filter_fill.kind else { panic!("image fill") };
|
||||
img.filters.exposure = 0.5;
|
||||
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": filter_fill}));
|
||||
|
||||
let n1_filt = s.doc().unwrap().node(layer1).unwrap().clone();
|
||||
let n2_filt = s.doc().unwrap().node(layer2).unwrap().clone();
|
||||
let PaintKind::Image(img1_filt) = &n1_filt.fills[0].kind else { panic!("image fill") };
|
||||
let PaintKind::Image(img2_filt) = &n2_filt.fills[0].kind else { panic!("image fill") };
|
||||
|
||||
// Both layers keep their distinct crop transforms; neither is overwritten by the other.
|
||||
assert_eq!(img1_filt.crop, Some(crop1_rot));
|
||||
assert_eq!(img2_filt.crop, Some(crop2_rot));
|
||||
assert_eq!(img1_filt.filters.exposure, 0.5);
|
||||
assert_eq!(img2_filt.filters.exposure, 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_crop_preserves_each_image_fill_and_leaves_tiles() {
|
||||
use figcraft_doc::color::{Color, ImageScaleMode, Paint, PaintKind};
|
||||
@@ -242,43 +360,134 @@ fn command_crop_preserves_each_image_fill_and_leaves_tiles() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_resize_leaves_fills_when_text_or_auto_layout_recomputes_the_box() {
|
||||
for case in ["text", "child", "frame"] {
|
||||
fn command_resize_leaves_a_texts_fills() {
|
||||
let mut s = session();
|
||||
let image = image_layer(&mut s);
|
||||
let fills = s.doc().unwrap().node(image).unwrap().fills.clone();
|
||||
let layer = id(&ex(
|
||||
&mut s,
|
||||
"text.create",
|
||||
json!({"text": "hello world hello world hello world", "props": {
|
||||
"width": 200, "height": 100, "fontSize": 24, "textAutoResize": "none", "fills": fills
|
||||
}}),
|
||||
));
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
let doc = s.doc().unwrap();
|
||||
let world = doc.world_transform(layer);
|
||||
let n = doc.node(layer).unwrap();
|
||||
let (from, to) = (world * Point::new(n.width, n.height / 2.0), world * Point::new(10.0, n.height / 2.0));
|
||||
drag(&mut s, from, to, CMD);
|
||||
assert_eq!(s.doc().unwrap().node(layer).unwrap().fills, fills, "a text reflows: keep the existing resize behaviour");
|
||||
}
|
||||
|
||||
fn image_units_per_layer_unit(s: &Session, layer: NodeId) -> (f64, f64, f64, f64) {
|
||||
use figcraft_doc::color::PaintKind;
|
||||
let doc = s.doc().unwrap();
|
||||
let n = doc.node(layer).unwrap();
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
let data = doc.images.get(&img.image).unwrap();
|
||||
let c = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
|
||||
(c[0] / n.width, c[3] / n.height, c[4], c[5])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_resize_crops_in_auto_layout_against_the_box_layout_leaves() {
|
||||
use figcraft_doc::color::{ImageScaleMode, PaintKind};
|
||||
for case in ["child", "child with a minimum width", "auto layout frame"] {
|
||||
let mut s = session();
|
||||
let image = image_layer(&mut s);
|
||||
let fills = s.doc().unwrap().node(image).unwrap().fills.clone();
|
||||
let layer = match case {
|
||||
"text" => id(&ex(
|
||||
&mut s,
|
||||
"text.create",
|
||||
json!({"text": "hello world hello world hello world", "props": {
|
||||
"width": 200, "height": 100, "fontSize": 24, "textAutoResize": "none", "fills": fills
|
||||
}}),
|
||||
)),
|
||||
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 140})));
|
||||
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
|
||||
let (layer, to_x, width) = match case {
|
||||
"auto layout frame" => {
|
||||
set(&mut s, &[frame], json!({"fills": fills}));
|
||||
(frame, 10.0, 40.0)
|
||||
}
|
||||
_ => {
|
||||
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 100})));
|
||||
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
|
||||
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
|
||||
if case == "child" {
|
||||
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
|
||||
set(&mut s, &[image], json!({"minWidth": 150}));
|
||||
image
|
||||
(image, 150.0, 150.0)
|
||||
} else {
|
||||
set(&mut s, &[frame], json!({"fills": fills}));
|
||||
frame
|
||||
set(&mut s, &[image], json!({"minWidth": 150}));
|
||||
(image, 10.0, 150.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
let before = image_units_per_layer_unit(&s, layer);
|
||||
let doc = s.doc().unwrap();
|
||||
let world = doc.world_transform(layer);
|
||||
let n = doc.node(layer).unwrap();
|
||||
let from = world * Point::new(n.width, n.height / 2.0);
|
||||
let to = world * Point::new(10.0, n.height / 2.0);
|
||||
let (from, to) = (world * Point::new(n.width, n.height / 2.0), world * Point::new(to_x, n.height / 2.0));
|
||||
drag(&mut s, from, to, CMD);
|
||||
assert_eq!(s.doc().unwrap().node(layer).unwrap().fills, fills, "{case}: keep the existing resize behaviour");
|
||||
let n = s.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!(near(n.width, width), "{case}: {} wide, as auto layout leaves it", n.width);
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
assert_eq!(img.scale_mode, ImageScaleMode::Crop, "{case}: cropped");
|
||||
let after = image_units_per_layer_unit(&s, layer);
|
||||
assert!(near(after.0, before.0) && near(after.1, before.1), "{case}: the image keeps its scale, not stretched: {before:?} -> {after:?}");
|
||||
assert!(near(after.2, before.2) && near(after.3, before.3), "{case}: its left edge stays where it was in the layer: {before:?} -> {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimum width can give a layer back the width its left side was dragged in by: the crop then
|
||||
/// slides back along the image instead of running past its right edge.
|
||||
#[test]
|
||||
fn command_crop_slides_back_onto_the_image_when_layout_widens_the_layer() {
|
||||
use figcraft_doc::color::{ImagePaint, PaintKind};
|
||||
let mut s = session();
|
||||
let image = image_layer(&mut s);
|
||||
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 140})));
|
||||
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
|
||||
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
|
||||
set(&mut s, &[image], json!({"minWidth": 150}));
|
||||
ex(&mut s, "select.set", json!({"ids": [image]}));
|
||||
let before = image_units_per_layer_unit(&s, image);
|
||||
let world = s.doc().unwrap().world_transform(image);
|
||||
drag(&mut s, world * Point::new(0.0, 50.0), world * Point::new(190.0, 50.0), CMD);
|
||||
let doc = s.doc().unwrap();
|
||||
let n = doc.node(image).unwrap();
|
||||
assert!(near(n.width, 150.0), "{} wide, as the minimum width leaves it", n.width);
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
let data = doc.images.get(&img.image).unwrap();
|
||||
let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
|
||||
let (x0, _, x1, _) = ImagePaint::crop_rect(crop);
|
||||
assert!(x0 <= 1e-9 && x1 >= 1.0 - 1e-9, "the image covers the layer: {x0}..{x1}");
|
||||
let after = image_units_per_layer_unit(&s, image);
|
||||
assert!(near(after.0, before.0) && near(after.1, before.1), "the image keeps its scale: {before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
/// Where the image's edge stops a crop, Shift still keeps the ratio (both axes stop together) and
|
||||
/// Alt still keeps the box centred (both sides stop together).
|
||||
#[test]
|
||||
fn command_crop_stopped_by_the_image_keeps_the_ratio_with_shift_and_the_centre_with_alt() {
|
||||
let mut s = session();
|
||||
let layer = image_layer(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
drag(&mut s, Point::new(200.0, 100.0), Point::new(150.0, 80.0), CMD);
|
||||
assert_eq!(size(&s, layer), (150.0, 80.0));
|
||||
drag(&mut s, Point::new(150.0, 80.0), Point::new(240.0, 128.0), Mods { shift: true, alt: false, cmd: true });
|
||||
assert!(
|
||||
near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 187.5, 100.0)),
|
||||
"the bottom stops at the image, the right side with it: {:?}",
|
||||
bounds(&s, layer)
|
||||
);
|
||||
|
||||
let mut s = session();
|
||||
let layer = image_layer(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
drag(&mut s, Point::new(0.0, 50.0), Point::new(20.0, 50.0), CMD);
|
||||
drag(&mut s, Point::new(200.0, 50.0), Point::new(150.0, 50.0), CMD);
|
||||
assert!(near_rect(bounds(&s, layer), Rect::new(20.0, 0.0, 150.0, 100.0)), "{:?}", bounds(&s, layer));
|
||||
drag(&mut s, Point::new(150.0, 50.0), Point::new(190.0, 50.0), Mods { shift: false, alt: true, cmd: true });
|
||||
assert!(
|
||||
near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 170.0, 100.0)),
|
||||
"the left side stops at the image, the right side as far: {:?}",
|
||||
bounds(&s, layer)
|
||||
);
|
||||
}
|
||||
|
||||
/// A resize is an explicit edit of the size: a size bound to a variable lets go of it (#809), so
|
||||
/// Cmd/Ctrl crops a bound layer's image as any other's; other bindings stay.
|
||||
#[test]
|
||||
@@ -795,6 +1004,73 @@ fn snapping_to_layers_wins_over_the_pixel_grid() {
|
||||
assert_eq!(size(&s, b), (100.0, 151.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_land_on_whole_pixels_whatever_they_snap_to() {
|
||||
// Figma's help: frames, sections and components "always snap to the pixel grid, even if Snap
|
||||
// to pixel grid is disabled". Other layers follow the setting.
|
||||
let frame = |s: &mut Session, x: f64, y: f64| id(&ex(s, "frame.create", json!({"x": x, "y": y, "width": 100, "height": 100})));
|
||||
let whole = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.fract() == 0.0);
|
||||
let mut s = Session::new();
|
||||
// A neighbour off the pixel grid, as a scaled or imported layer leaves one: its right edge at
|
||||
// 100.4.
|
||||
rect(&mut s, 0.4, 0.0, 100.0, 100.0, None);
|
||||
let f = frame(&mut s, 300.0, 300.0);
|
||||
let r = rect(&mut s, 300.0, 600.0, 100.0, 100.0, None);
|
||||
// Moved next to it, a rectangle snaps onto 100.4 and the frame to the whole pixel there.
|
||||
ex(&mut s, "select.set", json!({"ids": [r]}));
|
||||
drag(&mut s, Point::new(350.0, 650.0), Point::new(151.5, 650.0), Mods::default());
|
||||
assert!(near(bounds(&s, r).x0, 100.4), "{:?}", bounds(&s, r));
|
||||
ex(&mut s, "select.set", json!({"ids": [f]}));
|
||||
drag(&mut s, Point::new(350.0, 350.0), Point::new(151.5, 350.0), Mods::default());
|
||||
assert_eq!(bounds(&s, f).origin(), Point::new(100.0, 300.0), "moved by the snap, onto the whole pixel");
|
||||
// With Snap to pixel grid off, frames still move, resize and draw on whole pixels.
|
||||
ex(&mut s, "view.snapPixel", json!({"on": false}));
|
||||
ex(&mut s, "view.snapObjects", json!({"on": false}));
|
||||
drag(&mut s, Point::new(150.0, 350.0), Point::new(160.3, 360.6), Mods::default());
|
||||
assert_eq!(bounds(&s, f).origin(), Point::new(110.0, 311.0), "moved");
|
||||
drag(&mut s, Point::new(210.0, 411.0), Point::new(250.4, 450.6), Mods::default());
|
||||
assert_eq!(size(&s, f), (140.0, 140.0), "resized");
|
||||
ex(&mut s, "tool.set", json!({"tool": "frame"}));
|
||||
drag(&mut s, Point::new(500.3, 500.6), Point::new(560.6, 540.2), Mods::default());
|
||||
let drawn = s.selection()[0];
|
||||
assert!(whole(bounds(&s, drawn)), "drawn: {:?}", bounds(&s, drawn));
|
||||
// A frame already off the pixel grid lands on it once moved.
|
||||
ex(&mut s, "tool.set", json!({"tool": "move"}));
|
||||
let off = frame(&mut s, 800.4, 800.7);
|
||||
ex(&mut s, "select.set", json!({"ids": [off]}));
|
||||
drag(&mut s, Point::new(850.0, 850.0), Point::new(860.0, 850.0), Mods::default());
|
||||
assert!(whole(bounds(&s, off)), "{:?}", bounds(&s, off));
|
||||
// A rectangle follows the pointer.
|
||||
ex(&mut s, "select.set", json!({"ids": [r]}));
|
||||
drag(&mut s, Point::new(150.0, 650.0), Point::new(160.3, 650.0), Mods::default());
|
||||
assert!(near(bounds(&s, r).x0, 110.7), "{:?}", bounds(&s, r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_resized_together_each_land_on_whole_pixels() {
|
||||
let mut s = session();
|
||||
let frame = |s: &mut Session, x: f64| id(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 100, "height": 100})));
|
||||
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
|
||||
ex(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
// 300 wide to 400: a third more, so each frame alone would be 133.33 wide.
|
||||
drag(&mut s, Point::new(300.0, 100.0), Point::new(400.0, 100.0), Mods::default());
|
||||
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 133.0, 100.0));
|
||||
assert_eq!(bounds(&s, b), Rect::new(267.0, 0.0, 400.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_dropped_into_a_frame_off_the_pixel_grid_lands_on_its_whole_pixels() {
|
||||
let mut s = session();
|
||||
let target = id(&ex(&mut s, "frame.create", json!({"x": 300.5, "y": 0.5, "width": 300, "height": 300})));
|
||||
let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50})));
|
||||
ex(&mut s, "select.set", json!({"ids": [f]}));
|
||||
drag(&mut s, Point::new(25.0, 25.0), Point::new(425.0, 125.0), Mods::default());
|
||||
let n = s.doc().unwrap().node(f).unwrap().clone();
|
||||
assert_eq!(n.parent, Some(target));
|
||||
let [.., x, y] = n.transform.as_coeffs();
|
||||
assert_eq!((x.fract(), y.fract()), (0.0, 0.0), "at {x}, {y} in the frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_cursors_stay_diagonal_whatever_the_proportions() {
|
||||
let mut s = session();
|
||||
@@ -856,3 +1132,19 @@ fn the_transform_box_and_its_handles() {
|
||||
// At a larger zoom the same layer is big enough on screen for its handles inside it.
|
||||
assert_eq!(handle_at(s.doc().unwrap(), &[tiny], Point::new(320.2, 10.2), 20.0), Some(Handle::Corner(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_crop_changes_a_locked_ratio_and_stops_at_the_images_edges() {
|
||||
let mut s = session();
|
||||
let layer = image_layer(&mut s);
|
||||
set(&mut s, &[layer], json!({"constrainProportions": true}));
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
drag(&mut s, Point::new(200.0, 50.0), Point::new(150.0, 50.0), CMD);
|
||||
assert_eq!(size(&s, layer), (150.0, 100.0), "a side changes the ratio, lock or not");
|
||||
drag(&mut s, Point::new(150.0, 50.0), Point::new(260.0, 50.0), CMD);
|
||||
assert_eq!(size(&s, layer), (200.0, 100.0), "the side stops at the image's edge");
|
||||
drag(&mut s, Point::new(100.0, 0.0), Point::new(100.0, -40.0), CMD);
|
||||
assert!(near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 200.0, 100.0)), "the top stops at the image's top: {:?}", bounds(&s, layer));
|
||||
drag(&mut s, Point::new(200.0, 50.0), Point::new(100.0, 50.0), Mods { shift: true, alt: false, cmd: true });
|
||||
assert_eq!(size(&s, layer), (100.0, 50.0), "Shift keeps the ratio");
|
||||
}
|
||||
@@ -18,7 +18,7 @@ pub struct PromptDef {
|
||||
pub defaults: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text; call screenshot at the end and look at it. Fix anything that is off before finishing, then report the ids of the frames you made.";
|
||||
const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made or changed.";
|
||||
|
||||
pub const PROMPTS: &[PromptDef] = &[
|
||||
PromptDef {
|
||||
@@ -30,7 +30,7 @@ pub const PROMPTS: &[PromptDef] = &[
|
||||
PromptArg { name: "device", description: "Frame preset (default \"iPhone 16\"; see run_command frame.presets)", required: false },
|
||||
PromptArg { name: "brand_color", description: "Primary colour (default #3B5BDB)", required: false },
|
||||
],
|
||||
template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [14,24,14,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Bold text inside).\n4. Keep spacing on an 8-point grid and text left-aligned.{verify}",
|
||||
template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Semi Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [16,24,16,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Semi Bold text inside). Name every layer by what it is.\n4. Keep spacing on an 8-point grid, text left-aligned, and no emoji in the interface.{verify}",
|
||||
defaults: &[("device", "iPhone 16"), ("brand_color", "#3B5BDB")],
|
||||
},
|
||||
PromptDef {
|
||||
@@ -41,7 +41,7 @@ pub const PROMPTS: &[PromptDef] = &[
|
||||
PromptArg { name: "name", description: "Design system name (default \"Core\")", required: false },
|
||||
PromptArg { name: "primary", description: "Primary colour (default #3B5BDB)", required: false },
|
||||
],
|
||||
template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": <id>}; text styles likewise from text layers (Heading 32 Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": <id>} and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}",
|
||||
template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": <id>}; text styles likewise from text layers (Heading 32 Semi Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": <id>} and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}",
|
||||
defaults: &[("name", "Core"), ("primary", "#3B5BDB")],
|
||||
},
|
||||
PromptDef {
|
||||
@@ -51,10 +51,18 @@ pub const PROMPTS: &[PromptDef] = &[
|
||||
args: &[
|
||||
PromptArg { name: "product", description: "What the page sells", required: true },
|
||||
PromptArg { name: "width", description: "Page width (default 1440)", required: false },
|
||||
PromptArg { name: "accent", description: "Accent colour (default #7048E8)", required: false },
|
||||
PromptArg { name: "accent", description: "Accent colour (default #2563EB)", required: false },
|
||||
],
|
||||
template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Bold headline, an 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft dropShadow effect, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text).\n3. Use batch to apply repeated styling to several ids in one undo step.\n4. Finish with sizingV hug on the page frame so it fits its content.{verify}",
|
||||
defaults: &[("width", "1440"), ("accent", "#7048E8")],
|
||||
template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Semi Bold headline, a 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft neutral dropShadow, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text, no lower than #6B7280).\n3. Name every layer by what it is. Use one accent, one neutral ramp and at most three text colours; no emoji, gradient text or glows.\n4. Use batch to apply repeated styling to several ids in one undo step.\n5. Finish with sizingV hug on the page frame so it fits its content.{verify}",
|
||||
defaults: &[("width", "1440"), ("accent", "#2563EB")],
|
||||
},
|
||||
PromptDef {
|
||||
name: "design_review",
|
||||
title: "Review a design",
|
||||
description: "Audit the selection, page or document for the usual AI-generated UI tells, fix the mechanical ones, then use judgment for copy, naming, gradients and overflow; re-audit and report what a person still has to decide.",
|
||||
args: &[PromptArg { name: "target", description: "selection, page or document (default page)", required: false }],
|
||||
template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}",
|
||||
defaults: &[("target", "page")],
|
||||
},
|
||||
PromptDef {
|
||||
name: "prototype_flow",
|
||||
|
||||
@@ -51,8 +51,12 @@ screenshot returns a PNG of the page or of given layers to look at. undo/redo st
|
||||
Comments: comment.list returns threads (text, anchor node id, frame, page, x/y, replies); fix open ones, \
|
||||
reply with what changed, then resolve (a reply reopens a thread). To react to new feedback, call \
|
||||
wait_for_changes {after, timeoutMs} and pass the returned cursor back. \
|
||||
Design review: design.audit {scope} reports spacing, radii, type, colour, contrast, copy and naming findings \
|
||||
with severities; design.fix repairs the fixable ones as one undo step; design.rules lists the rules and \
|
||||
presets; design.configure {preset, grid, radii, brand, disabled} sets the file's design system, and \
|
||||
design.assert {failOn, minScore} is a read-only CI gate. \
|
||||
Resources: figcraft://document, figcraft://node/{id}, figcraft://command/{id}, figcraft://comments. \
|
||||
prompts/list has workflows, including fix_comments.";
|
||||
prompts/list has workflows, including fix_comments and design_review.";
|
||||
|
||||
/// An MCP server bound to one backend.
|
||||
pub struct Server {
|
||||
|
||||
@@ -102,6 +102,8 @@ pub const TOOL_NAMES: &[&str] = &[
|
||||
"get_node",
|
||||
"design_context",
|
||||
"export_assets",
|
||||
"component_mappings",
|
||||
"sync_mappings",
|
||||
"select",
|
||||
"export",
|
||||
"screenshot",
|
||||
@@ -126,6 +128,8 @@ const DOCUMENT_TOOLS: &[&str] = &[
|
||||
"get_node",
|
||||
"design_context",
|
||||
"export_assets",
|
||||
"component_mappings",
|
||||
"sync_mappings",
|
||||
"select",
|
||||
"export",
|
||||
"screenshot",
|
||||
@@ -286,6 +290,33 @@ fn tools() -> Vec<Value> {
|
||||
),
|
||||
false,
|
||||
),
|
||||
tool(
|
||||
"component_mappings",
|
||||
"Component mappings",
|
||||
"Which code component each design component is: its import, code name, source file, a ready snippet, its properties and variants, and which design values need translating. Check this before writing a component: reuse a mapped one, never recreate it. `unmapped` lists those with no code component yet.",
|
||||
obj(
|
||||
json!({
|
||||
"ids": ids_schema("Layers: the components they are, use or hold (default every component in the file)"),
|
||||
"unmapped": boolean("Only components without a mapping"),
|
||||
"root": string("The code repository, to check each link's source file is there (default where this server runs)")
|
||||
}),
|
||||
&[],
|
||||
),
|
||||
true,
|
||||
),
|
||||
tool(
|
||||
"sync_mappings",
|
||||
"Sync mappings with a repository",
|
||||
"Apply a code repository's figcraft.connect.json to the open design (`import`, one undo step), or write the design's mappings to it (`export`, keeping its other keys and the links of components this design doesn't have). Run `import` first when component_mappings shows less than the repository should have.",
|
||||
obj(
|
||||
json!({
|
||||
"direction": {"type": "string", "enum": ["import", "export"], "description": "import: file to design. export: design to file"},
|
||||
"path": string("The file (default figcraft.connect.json where this server runs)")
|
||||
}),
|
||||
&["direction"],
|
||||
),
|
||||
false,
|
||||
),
|
||||
tool(
|
||||
"select",
|
||||
"Select layers",
|
||||
@@ -490,6 +521,26 @@ fn export_assets(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResu
|
||||
exec(b, "file.exportAssets", Value::Object(params)).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
/// `codeConnect.list`, checking source files against `root`, else where this server runs.
|
||||
fn component_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
let mut params = a.clone();
|
||||
let root = std::path::absolute(s_arg(a, "root")?.unwrap_or(".")).map_err(|e| format!("root: {e}"))?;
|
||||
params.insert("root".into(), json!(root.to_string_lossy()));
|
||||
exec(b, "codeConnect.list", Value::Object(params)).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
/// `codeConnect.import` or `.export` with a code repository's connect file, made absolute here: an
|
||||
/// attached app runs in another folder.
|
||||
fn sync_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
let command = match s_arg(a, "direction")? {
|
||||
Some("import") => "codeConnect.import",
|
||||
Some("export") => "codeConnect.export",
|
||||
_ => return Err("`direction`: import or export".into()),
|
||||
};
|
||||
let path = std::path::absolute(s_arg(a, "path")?.unwrap_or("figcraft.connect.json")).map_err(|e| format!("path: {e}"))?;
|
||||
exec(b, command, json!({"path": path.to_string_lossy()})).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
fn wait_for_changes(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
b.call("events.poll", Value::Object(a.clone())).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
@@ -637,6 +688,8 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
|
||||
"get_node" => get_node(b, &a),
|
||||
"design_context" => design_context(b, &a),
|
||||
"export_assets" => export_assets(b, &a),
|
||||
"component_mappings" => component_mappings(b, &a),
|
||||
"sync_mappings" => sync_mappings(b, &a),
|
||||
"select" => select(b, &a),
|
||||
"export" => export(b, &a),
|
||||
"screenshot" => screenshot(b, &a),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! `component_mappings` and `sync_mappings` against a code repository's connect file.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::common::Client;
|
||||
|
||||
fn repo(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-mcp-connect-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mappings_travel_through_a_repositorys_file() {
|
||||
let dir = repo("travel");
|
||||
let mut c = Client::new();
|
||||
let frame = c.create(json!({"type": "frame", "name": "Tag", "width": 80, "height": 24}));
|
||||
let main = c.run("component.create", json!({"ids": [frame]}))["id"].clone();
|
||||
let file = dir.join("figcraft.connect.json");
|
||||
std::fs::write(&file, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Tag","language":"react","importPath":"@/ui/tag","name":"Tag","template":"<Tag />","source":"src/tag.tsx"}]}"#).unwrap();
|
||||
let before = c.ok("component_mappings", json!({"unmapped": true, "root": dir}));
|
||||
assert_eq!(before["unmapped"], 1);
|
||||
c.ok("sync_mappings", json!({"direction": "import", "path": file}));
|
||||
let after = c.ok("component_mappings", json!({"ids": [main], "root": dir}));
|
||||
let link = &after["components"][0]["links"][0];
|
||||
assert_eq!(link["import"], r#"import { Tag } from "@/ui/tag";"#);
|
||||
assert_eq!(link["sourceFound"], false, "src/tag.tsx isn't there yet");
|
||||
std::fs::create_dir_all(dir.join("src")).unwrap();
|
||||
std::fs::write(dir.join("src/tag.tsx"), "").unwrap();
|
||||
assert_eq!(c.ok("component_mappings", json!({"ids": [main], "root": dir}))["components"][0]["links"][0]["sourceFound"], true);
|
||||
c.ok("sync_mappings", json!({"direction": "export", "path": file}));
|
||||
let written: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
|
||||
assert_eq!(written["project"]["name"], "shop", "keys the export doesn't own stay");
|
||||
assert_eq!(written["links"][0]["source"], "src/tag.tsx");
|
||||
assert!(c.err("sync_mappings", json!({"direction": "sideways"})).contains("import or export"));
|
||||
}
|
||||
@@ -8,6 +8,8 @@ mod agent_tasks;
|
||||
mod attached;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::disallowed_methods)]
|
||||
mod automation_roots;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod code_connect;
|
||||
#[allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod common;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
@@ -219,13 +219,16 @@ fn prompts_list_and_get() {
|
||||
let mut c = Client::new();
|
||||
let r = c.rpc("prompts/list", json!({}));
|
||||
let names: Vec<&str> = r["result"]["prompts"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "prototype_flow", "fix_comments", "watch_comments"]);
|
||||
assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments"]);
|
||||
let r = c.rpc("prompts/get", json!({"name": "mobile_screen", "arguments": {"screen": "login"}}));
|
||||
let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap();
|
||||
assert!(text.contains("login") && text.contains("iPhone 16") && text.contains("#3B5BDB") && !text.contains("{device}"));
|
||||
assert_eq!(c.rpc("prompts/get", json!({"name": "mobile_screen"}))["error"]["code"], -32602);
|
||||
assert_eq!(c.rpc("prompts/get", json!({"name": "nope"}))["error"]["code"], -32602);
|
||||
assert_eq!(c.rpc("prompts/get", json!({"name": "landing_page", "arguments": {"product": ["x"]}}))["error"]["code"], -32602);
|
||||
let r = c.rpc("prompts/get", json!({"name": "design_review", "arguments": {"target": "document"}}));
|
||||
let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap();
|
||||
assert!(text.contains("design.audit") && text.contains("\"document\"") && !text.contains("{target}"), "{text}");
|
||||
let r = c.rpc("prompts/get", json!({"name": "prototype_flow"}));
|
||||
assert!(r["result"]["messages"][0]["content"]["text"].as_str().unwrap().contains("Home, Details, Checkout"));
|
||||
let r = c.rpc("prompts/get", json!({"name": "fix_comments", "arguments": {"auto_resolve": "no", "author": "Ada"}}));
|
||||
|
||||
@@ -392,6 +392,9 @@ name = "English"
|
||||
"Ctrl+arrows" = "Ctrl+arrows"
|
||||
"Ctrl+click" = "Ctrl+click"
|
||||
"Ctrl+click a padding field" = "Ctrl+click a padding field"
|
||||
"In code" = "In code"
|
||||
"Source file" = "Source file"
|
||||
"Variant value" = "Variant value"
|
||||
"⌘ click a padding field" = "⌘ click a padding field"
|
||||
"Ctrl+scroll" = "Ctrl+scroll"
|
||||
"Current name" = "Current name"
|
||||
@@ -1469,6 +1472,8 @@ name = "English"
|
||||
"Small caps" = "Small caps"
|
||||
"Smart animate" = "Smart animate"
|
||||
"Snap to pixel grid" = "Snap to pixel grid"
|
||||
"Snap to pixel grid off" = "Snap to pixel grid off"
|
||||
"Snap to pixel grid on" = "Snap to pixel grid on"
|
||||
"Social and slides" = "Social and slides"
|
||||
"Social media" = "Social media"
|
||||
"Social post sizes" = "Social post sizes"
|
||||
@@ -1759,6 +1764,7 @@ name = "English"
|
||||
"What it's for" = "What it's for"
|
||||
"What this changed from isn't known: it changed before FigCraft kept a copy of ready-for-dev frames. Resolve the change (or mark it ready again) to compare from now on." = "What this changed from isn't known: it changed before FigCraft kept a copy of ready-for-dev frames. Resolve the change (or mark it ready again) to compare from now on."
|
||||
"When marked ready" = "When marked ready"
|
||||
"While editing text: next or previous text layer" = "While editing text: next or previous text layer"
|
||||
"While hovering" = "While hovering"
|
||||
"While pressing" = "While pressing"
|
||||
"White" = "White"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1346,6 +1346,8 @@ name = "Русский"
|
||||
"Small caps" = "Капитель"
|
||||
"Smart animate" = "Smart animate"
|
||||
"Snap to pixel grid" = "Привязка к пиксельной сетке"
|
||||
"Snap to pixel grid off" = "Привязка к пиксельной сетке выключена"
|
||||
"Snap to pixel grid on" = "Привязка к пиксельной сетке включена"
|
||||
"Social and slides" = "Соцсети и слайды"
|
||||
"Social media" = "Соцсети"
|
||||
"Social post sizes" = "Размеры публикаций для соцсетей"
|
||||
@@ -1864,6 +1866,183 @@ name = "Русский"
|
||||
"⌘ click" = "⌘ нажатие"
|
||||
"⌘ scroll" = "⌘ прокрутка"
|
||||
"⌥ drag" = "⌥ перетаскивание"
|
||||
"1 year" = "1 год"
|
||||
"30 days" = "30 дней"
|
||||
"90 days" = "90 дней"
|
||||
"A layer in an auto layout frame is placed by its frame" = "Слой в Frame с автолейаутом размещается своим Frame"
|
||||
"Allow and download" = "Разрешить и загрузить"
|
||||
"Allow downloading fonts?" = "Разрешить загрузку шрифтов?"
|
||||
"Alt+double-click an edge of an auto layout child" = "Alt+двойное нажатие по краю дочернего объекта автолейаута"
|
||||
"Android Vector Drawable" = "Android Vector Drawable"
|
||||
"Annotation" = "Аннотация"
|
||||
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Все в вашей сети с этим кодом могут смотреть файл, но не менять его, пока это приложение открыто."
|
||||
"Auto: as many words as fit on each line" = "Авто: столько слов, сколько помещается в строке"
|
||||
"Auto: by the first letter with a direction" = "Авто: по первой букве, у которой есть направление"
|
||||
"Balance" = "Баланс"
|
||||
"Balance: every line close to the same length" = "Баланс: все строки примерно одной длины"
|
||||
"Best effort" = "По возможности"
|
||||
"Board grid" = "Сетка доски"
|
||||
"Calculated from other variables; it follows them" = "Вычисляется из других переменных и следует за ними"
|
||||
"Changed {date}" = "Изменено {date}"
|
||||
"Check for Updates" = "Проверить обновления"
|
||||
"Check for updates…" = "Проверить обновления…"
|
||||
"Compare with" = "Сравнить с"
|
||||
"Compatibility" = "Совместимость"
|
||||
"Copied comments for AI" = "Комментарии скопированы для ИИ"
|
||||
"Copy browser link" = "Копировать ссылку для браузера"
|
||||
"Copy effect" = "Копировать эффект"
|
||||
"Copy fill" = "Копировать заливку"
|
||||
"Copy for AI" = "Копировать для ИИ"
|
||||
"Copy link to page" = "Копировать ссылку на страницу"
|
||||
"Copy stroke" = "Копировать обводку"
|
||||
"Couldn't download {name}" = "Не удалось загрузить {name}"
|
||||
"Couldn't reach {server} for its team list." = "Не удалось связаться с {server}, чтобы получить список команды."
|
||||
"Crop image" = "Обрезать изображение"
|
||||
"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓"
|
||||
"Ctrl+click a padding field" = "Ctrl+нажатие по полю внутреннего отступа"
|
||||
"Dart constants for Flutter…" = "Константы Dart для Flutter…"
|
||||
"Delete {n} variables" = { one = "Удалить {n} переменную", few = "Удалить {n} переменные", many = "Удалить {n} переменных", other = "Удалить {n} переменных" }
|
||||
"Detach calculation" = "Отвязать вычисление"
|
||||
"Developer Mode only inspects: switch to Design (Shift+D) to edit" = "Режим разработчика только просматривает: чтобы редактировать, перейдите в «Дизайн» (Shift+D)"
|
||||
"Disconnected. Reconnecting…" = "Соединение разорвано. Повторное подключение…"
|
||||
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Соединение разорвано. Ваши правки остаются здесь и синхронизируются, когда связь восстановится. Повторное подключение…"
|
||||
"Dismiss" = "Закрыть"
|
||||
"Don't show this again" = "Больше не показывать"
|
||||
"Double-click an edge of an auto layout frame" = "Двойное нажатие по краю Frame с автолейаутом"
|
||||
"Download" = "Загрузить"
|
||||
"Downloading… {percent}%" = "Загрузка… {percent}%"
|
||||
"Drop to use this image" = "Перетащите, чтобы использовать это изображение"
|
||||
"Duplicate group" = "Дублировать группу"
|
||||
"Edit padding on all sides" = "Изменить внутренние отступы со всех сторон"
|
||||
"Edit variables" = "Редактировать переменные"
|
||||
"Enter / Shift+Enter" = "Enter / Shift+Enter"
|
||||
"Everyone who reaches this server can open these files while they are shared." = "Все, кто имеет доступ к этому серверу, могут открывать эти файлы, пока они опубликованы."
|
||||
"Exact only" = "Только точные"
|
||||
"Expand the interface" = "Развернуть интерфейс"
|
||||
"Exported {name}; {n} kinds of content were changed or left out" = { one = "Файл {name} экспортирован; {n} тип содержимого изменён или пропущен", few = "Файл {name} экспортирован; {n} типа содержимого изменены или пропущены", many = "Файл {name} экспортирован; {n} типов содержимого изменены или пропущены", other = "Файл {name} экспортирован; {n} типов содержимого изменены или пропущены" }
|
||||
"Exported {n} files; some content was changed or left out" = { one = "Экспортирован {n} файл; часть содержимого изменена или пропущена", few = "Экспортировано {n} файла; часть содержимого изменена или пропущена", many = "Экспортировано {n} файлов; часть содержимого изменена или пропущена", other = "Экспортировано {n} файлов; часть содержимого изменена или пропущена" }
|
||||
"Extra large" = "Очень крупный"
|
||||
"FigCraft stopped because of an internal error." = "FigCraft остановился из-за внутренней ошибки."
|
||||
"Format" = "Формат"
|
||||
"Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "Бесплатные шрифты поступают из Google Fonts и Noto через jsDelivr и GitHub. Каждый файл сверяется с указателем шрифтов, прежде чем будет установлен в общую папку шрифтов программ Craft. Ничего не загружается, пока вы это не разрешите."
|
||||
"Graph paper" = "Бумага в клетку"
|
||||
"Hide UI" = "Скрыть интерфейс"
|
||||
"Huge" = "Огромный"
|
||||
"Ignore unsupported" = "Пропускать неподдерживаемое"
|
||||
"Invert zoom direction" = "Инвертировать направление масштабирования"
|
||||
"Joining live session…" = "Подключение к сеансу…"
|
||||
"Large" = "Крупный"
|
||||
"Leaving the prototype" = "Выход из прототипа"
|
||||
"Left to right" = "Слева направо"
|
||||
"Link copied: it opens the file in FigCraft" = "Ссылка скопирована: она открывает файл в FigCraft"
|
||||
"Link copied: it opens the file in the browser" = "Ссылка скопирована: она открывает файл в браузере"
|
||||
"Medium" = "Средний"
|
||||
"Move out of any group" = "Вынести из любой группы"
|
||||
"Move to group {group}" = "Переместить в группу {group}"
|
||||
"Move up or down while dragging its label" = "Перемещать вверх или вниз, перетаскивая подпись"
|
||||
"New from selection" = "Создать из выделения"
|
||||
"No comments to copy" = "Нет комментариев для копирования"
|
||||
"No scope is shared by all the selected variables" = "У выделенных переменных нет общей области применения"
|
||||
"Nobody shares a file there now." = "Сейчас там никто не публикует файл."
|
||||
"Not connected: {reason}. Your work is still in this tab." = "Нет соединения: {reason}. Ваша работа остаётся в этой вкладке."
|
||||
"Not now" = "Не сейчас"
|
||||
"Nothing changed since this version." = "С этой версии ничего не изменилось."
|
||||
"Nothing counted yet" = "Пока ничего не подсчитано"
|
||||
"Nothing to pick: the page is empty" = "Нечего выбрать: страница пуста"
|
||||
"Past 30 days" = "За 30 дней"
|
||||
"Past 90 days" = "За 90 дней"
|
||||
"Past year" = "За год"
|
||||
"Paste effect" = "Вставить эффект"
|
||||
"Paste fill" = "Вставить заливку"
|
||||
"Paste stroke" = "Вставить обводку"
|
||||
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Выбор указанием: Tab и Shift+Tab переходят между слоями, Enter входит в слой, Shift+Enter выходит, Space выделяет, Escape отменяет"
|
||||
"Pick select: into a layer, out to its parent" = "Выбор указанием: войти в слой, выйти к родителю"
|
||||
"Pick select: next or previous layer" = "Выбор указанием: следующий или предыдущий слой"
|
||||
"Pick select: select the picked layer" = "Выбор указанием: выделить указанный слой"
|
||||
"Pretty" = "Аккуратно"
|
||||
"Pretty: full lines, no one word alone on the last" = "Аккуратно: полные строки, без одного слова в последней"
|
||||
"Reload the page to get back the unsaved files the browser had room for." = "Перезагрузите страницу, чтобы вернуть несохранённые файлы, для которых в браузере хватило места."
|
||||
"Reload the page to get your unsaved files back." = "Перезагрузите страницу, чтобы вернуть несохранённые файлы."
|
||||
"Reload the page to start again." = "Перезагрузите страницу, чтобы начать снова."
|
||||
"Remove all auto layout" = "Убрать весь автолейаут"
|
||||
"Removed since this version" = "Удалено с этой версии"
|
||||
"Reset grid" = "Сбросить сетку"
|
||||
"Retry now" = "Повторить сейчас"
|
||||
"Right to left" = "Справа налево"
|
||||
"Rotate a degree (Shift: 15)" = "Повернуть на градус (Shift: на 15)"
|
||||
"Same as file ({profile})" = "Как в файле ({profile})"
|
||||
"Save a copy…" = "Сохранить копию…"
|
||||
"Scope" = "Область применения"
|
||||
"Scope: all supported properties" = "Область применения: все поддерживаемые свойства"
|
||||
"Scope: hidden from pickers" = "Область применения: скрыто в списках выбора"
|
||||
"Scope: only {scope}" = "Область применения: только {scope}"
|
||||
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Менять значение поля быстрее (2x) или медленнее (1/2, 1/4)"
|
||||
"Scrubbing at 1/2" = "Изменение со скоростью 1/2"
|
||||
"Scrubbing at 1/4" = "Изменение со скоростью 1/4"
|
||||
"Scrubbing at 1x" = "Изменение со скоростью 1x"
|
||||
"Scrubbing at 2x" = "Изменение со скоростью 2x"
|
||||
"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Выделите строку, столбец или полную сетку из трёх и более слоёв вне потока автолейаута"
|
||||
"Selection box: switch to pick select" = "Рамка выделения: переключиться на выбор указанием"
|
||||
"Server key" = "Ключ сервера"
|
||||
"Set as opening page" = "Сделать стартовой страницей"
|
||||
"Set corner smoothing to 60%" = "Задать сглаживание углов 60%"
|
||||
"Set fill container" = "Задать: заполнить контейнер"
|
||||
"Set hug contents" = "Задать: по размеру содержимого"
|
||||
"Shared by your team on {server}" = "Опубликовано вашей командой на {server}"
|
||||
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Показать и перемещать перекрестие размещения (когда выбран его инструмент и ничего не выделено)"
|
||||
"Small" = "Мелкий"
|
||||
"Space" = "Space"
|
||||
"Strong line every" = "Жирная линия каждые"
|
||||
"Subscript" = "Нижний индекс"
|
||||
"Superscript" = "Верхний индекс"
|
||||
"Tab or Ctrl+Space again" = "Tab или Ctrl+Space ещё раз"
|
||||
"Text direction" = "Направление текста"
|
||||
"Text on a path" = "Текст по контуру"
|
||||
"The bars are hidden. {shortcut} shows them again" = "Панели скрыты. {shortcut} показывает их снова"
|
||||
"This link opens a website outside the prototype:" = "Эта ссылка открывает сайт вне прототипа:"
|
||||
"This link opens your mail app to write a message:" = "Эта ссылка открывает почтовую программу, чтобы написать сообщение:"
|
||||
"This server doesn't count detached instances" = "Этот сервер не считает отвязанные экземпляры"
|
||||
"This server doesn't count insertions" = "Этот сервер не считает вставки"
|
||||
"This server doesn't count styles and variables" = "Этот сервер не считает стили и переменные"
|
||||
"This variant's value" = "Значение этого варианта"
|
||||
"This version can't be read." = "Эту версию не удалось прочитать."
|
||||
"This version doesn't have it: all of it is new." = "В этой версии этого нет: всё появилось позже."
|
||||
"Update check is not supported in the web browser." = "Проверка обновлений в браузере не поддерживается."
|
||||
"Upload from computer" = "Загрузить с компьютера"
|
||||
"What changed since a saved version" = "Что изменилось с сохранённой версии"
|
||||
"When marked ready" = "Когда отмечено готовым"
|
||||
"Wrap style" = "Стиль переноса"
|
||||
"Your unsaved files were too large for the browser to keep." = "Несохранённые файлы оказались слишком большими, чтобы браузер их сохранил."
|
||||
"connector labels without a saved snapshot are centred on the line, without their background" = "подписи соединителей без сохранённого снимка центрируются на линии, без фона"
|
||||
"elbowed and curved connectors without a saved path are routed afresh" = "ломаные и кривые соединители без сохранённого контура прокладываются заново"
|
||||
"instance swap properties whose default component was past the layer limit were skipped" = "свойства замены экземпляра, у которых компонент по умолчанию выходил за предел слоёв, пропущены"
|
||||
"instances whose component was past the layer limit were imported as frames" = "экземпляры, чей компонент выходил за предел слоёв, импортированы как Frame"
|
||||
"invalid vector region fill paint list; layer fill used" = "недопустимый список заливок векторной области; использована заливка слоя"
|
||||
"invalid vector region paints were skipped" = "недопустимые заливки векторной области пропущены"
|
||||
"linked vector region fill styles keep resolved appearance; live style links were left out" = "связанные стили заливки векторной области сохраняют вычисленное оформление; живые связи стилей опущены"
|
||||
"note or shape generated child has invalid bounds; child skipped" = "у сгенерированного потомка заметки или фигуры недопустимые границы; потомок пропущен"
|
||||
"note or shape generated child is missing its style or bounds; child skipped" = "у сгенерированного потомка заметки или фигуры нет стиля или границ; потомок пропущен"
|
||||
"note or shape generated children exceed the layer or nesting limit; remaining children skipped" = "сгенерированные потомки заметки или фигуры превышают предел слоёв или вложенности; остальные потомки пропущены"
|
||||
"note or shape generated layout is missing or unsupported; using its outer frame" = "сгенерированная вёрстка заметки или фигуры отсутствует или не поддерживается; использован внешний Frame"
|
||||
"shape generated outline is missing or damaged; using its rectangle" = "сгенерированный контур фигуры отсутствует или повреждён; использован её прямоугольник"
|
||||
"sticky layers import as frames with their text" = "слои стикеров импортируются как Frame вместе со своим текстом"
|
||||
"swapped instances whose previous component isn't in the file took the new component's look" = "заменённые экземпляры, чей прежний компонент отсутствует в файле, получили вид нового компонента"
|
||||
"variable-bound vector region paints keep resolved appearance; live bindings were left out" = "привязанные к переменным заливки векторной области сохраняют вычисленное оформление; живые привязки опущены"
|
||||
"vector region paint data exceeded import limits and was skipped" = "данные заливки векторной области превысили пределы импорта и пропущены"
|
||||
"vector region references a missing fill style; layer fill used" = "векторная область ссылается на отсутствующий стиль заливки; использована заливка слоя"
|
||||
"{count} in it now · Changed {date}" = "Сейчас в нём {count} · Изменено {date}"
|
||||
"{insertions} · {detachments}" = "{insertions} · {detachments}"
|
||||
"{name}, disconnected from its live session" = "{name}, отключён от сеанса"
|
||||
"{n} detached" = { one = "{n} отвязан", few = "{n} отвязаны", many = "{n} отвязано", other = "{n} отвязано" }
|
||||
"{n} inserted" = { one = "{n} вставлен", few = "{n} вставлены", many = "{n} вставлено", other = "{n} вставлено" }
|
||||
"{period}: {counts}" = "{period}: {counts}"
|
||||
"{used} · {detached}" = "{used} · {detached}"
|
||||
"{used} · {inserted}" = "{used} · {inserted}"
|
||||
"↵ / ⇧↵" = "↵ / ⇧↵"
|
||||
"⇥ or ⌥ Space again" = "⇥ или ⌥ Space ещё раз"
|
||||
"⌘ click a padding field" = "⌘ нажатие по полю внутреннего отступа"
|
||||
"⌥ double-click an edge of an auto layout child" = "⌥ двойное нажатие по краю дочернего объекта автолейаута"
|
||||
"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓"
|
||||
|
||||
[commands]
|
||||
"align.bottom" = "Выровнять по нижнему краю"
|
||||
@@ -2479,6 +2658,44 @@ name = "Русский"
|
||||
"window.focus" = "Вывести окно на передний план"
|
||||
"window.new" = "Новое окно"
|
||||
"template.list" = "Список шаблонов"
|
||||
"board.grid" = "Сетка доски"
|
||||
"board.reshape" = "Изменить форму соединителя"
|
||||
"collab.reconnect" = "Переподключить сеанс"
|
||||
"comment.prompt" = "Копировать комментарии для ИИ"
|
||||
"data.fill" = "Заполнить копии данными"
|
||||
"effect.copy" = "Копировать эффект"
|
||||
"effect.paste" = "Вставить эффект"
|
||||
"file.fontReport" = "Проверить шрифты документа"
|
||||
"file.markSaved" = "Отметить как сохранённый"
|
||||
"fill.copy" = "Копировать заливку"
|
||||
"fill.paste" = "Вставить заливку"
|
||||
"font.download" = "Загрузить шрифт"
|
||||
"font.downloads" = "Загрузки шрифтов"
|
||||
"image.crop" = "Обрезать изображение"
|
||||
"image.replace" = "Заменить изображение"
|
||||
"layout.removeAll" = "Убрать весь автолейаут"
|
||||
"library.check" = "Проверить обновления библиотек команды"
|
||||
"pref.invertZoom" = "Инвертировать направление масштабирования"
|
||||
"pref.uiScaleDown" = "Меньший интерфейс"
|
||||
"pref.uiScaleReset" = "Размер интерфейса по умолчанию"
|
||||
"pref.uiScaleUp" = "Больший интерфейс"
|
||||
"proto.linkNotice" = "Уведомление перед переходом по ссылке"
|
||||
"selection.createColorStyle" = "Создать стиль цвета из выделения"
|
||||
"stroke.copy" = "Копировать обводку"
|
||||
"stroke.paste" = "Вставить обводку"
|
||||
"text.direction" = "Направление текста"
|
||||
"text.directionAuto" = "Направление текста: авто"
|
||||
"text.directionLtr" = "Направление текста: слева направо"
|
||||
"text.directionRtl" = "Направление текста: справа налево"
|
||||
"text.fit" = "Вписать текст в блок"
|
||||
"text.openLink" = "Открыть ссылку"
|
||||
"text.wrapStyle" = "Стиль переноса"
|
||||
"tool.annotation" = "Аннотация"
|
||||
"tool.crosshair" = "Переместить перекрестие размещения"
|
||||
"tool.textOnPath" = "Текст по контуру"
|
||||
"variable.extendCollection" = "Расширить коллекцию"
|
||||
"view.minimize" = "Свернуть интерфейс"
|
||||
"widget.hover" = "Виджет наведения"
|
||||
|
||||
[menu]
|
||||
"bool.exclude" = "Исключение"
|
||||
@@ -2512,3 +2729,6 @@ name = "Русский"
|
||||
"view.themeDark" = "Тёмная"
|
||||
"view.themeLight" = "Светлая"
|
||||
"view.themeSystem" = "Системная"
|
||||
"text.directionAuto" = "Авто"
|
||||
"text.directionLtr" = "Слева направо"
|
||||
"text.directionRtl" = "Справа налево"
|
||||
@@ -1574,7 +1574,7 @@ status = "draft — needs native review"
|
||||
"Texts" = "உரைகள்"
|
||||
"Texture" = "அமைப்பு"
|
||||
"The bars are hidden. {shortcut} shows them again" = "பட்டைகள் மறைக்கப்பட்டுள்ளன. {shortcut} அவற்றை மீண்டும் காட்டும்"
|
||||
"The destination document is unavailable. Nothing was imported." = "இலக்கு ஆவணம் கிடைக்கவில்லை. எதுவும் இறக்குமதி செய்யப்படவில்லை."
|
||||
"The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "கேன்வாஸ் நிறங்களை sRGB இல் காட்டுகிறது; ஏற்றுமதி செய்த PNG, JPG, WebP கோப்புகள் Display P3 எனக் குறிக்கப்படும்."
|
||||
"The destination document was closed. Nothing was imported." = "இலக்கு ஆவணம் மூடப்பட்டது. எதுவும் இறக்குமதி செய்யப்படவில்லை."
|
||||
"The destination page was removed. Nothing was imported." = "இலக்குப் பக்கம் அகற்றப்பட்டது. எதுவும் இறக்குமதி செய்யப்படவில்லை."
|
||||
"The file is deleted from the server: nobody can open or join it from there again, and this can't be undone. Copies that are open stay with whoever has them." = "கோப்பு சர்வரிலிருந்து நீக்கப்படும்: இனி யாரும் அங்கிருந்து அதைத் திறக்கவோ சேரவோ முடியாது, இதைச் செயல்தவிர்க்க முடியாது. திறந்திருக்கும் நகல்கள் அவற்றை வைத்திருப்பவர்களிடமே இருக்கும்."
|
||||
|
||||
@@ -1815,6 +1815,235 @@ name = "Türkçe"
|
||||
"⌘ scroll" = "⌘ kaydırma"
|
||||
"⌥ drag" = "⌥ sürükle"
|
||||
|
||||
"1 year" = "1 yıl"
|
||||
"30 days" = "30 gün"
|
||||
"90 days" = "90 gün"
|
||||
"A layer in an auto layout frame is placed by its frame" = "Otomatik yerleşim çerçevesindeki bir katman, çerçevesi tarafından yerleştirilir"
|
||||
"A layer on its own aligns to its frame: select more layers, or one in a frame" = "Tek başına bir katman çerçevesine hizalanır: daha fazla katman veya çerçeve içindeki bir katmanı seçin"
|
||||
"Adding to {name}" = "{name} öğesine ekleniyor"
|
||||
"All the fonts this file uses are installed" = "Bu dosyanın kullandığı tüm yazı tipleri yüklü"
|
||||
"Allow and download" = "İzin ver ve indir"
|
||||
"Allow downloading fonts?" = "Yazı tiplerinin indirilmesine izin verilsin mi?"
|
||||
"Alt+double-click an edge of an auto layout child" = "Otomatik yerleşim alt öğesinin bir kenarına Alt+çift tıklayın"
|
||||
"Android Vector Drawable" = "Android Vector Drawable"
|
||||
"Annotation" = "Ek açıklama"
|
||||
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Ağınızdaki bu koda sahip herkes, bu uygulama açık kaldığı sürece dosyayı değiştirmeden görüntüleyebilir."
|
||||
"Auto: as many words as fit on each line" = "Otomatik: her satıra sığdığı kadar sözcük"
|
||||
"Auto: by the first letter with a direction" = "Otomatik: yönü olan ilk harfe göre"
|
||||
"Balance" = "Dengeli"
|
||||
"Balance: every line close to the same length" = "Dengeli: her satır yaklaşık aynı uzunlukta"
|
||||
"Best effort" = "En iyi uyum"
|
||||
"Board grid" = "Pano ızgarası"
|
||||
"Bottom padding" = "Alt iç boşluk"
|
||||
"Calculated from other variables; it follows them" = "Diğer değişkenlerden hesaplanır; onları izler"
|
||||
"Changed {date}" = "{date} tarihinde değiştirildi"
|
||||
"Check for Updates" = "Güncellemeleri Denetle"
|
||||
"Check for updates…" = "Güncellemeleri denetle…"
|
||||
"Checking the fonts installed on this computer…" = "Bu bilgisayarda yüklü yazı tipleri denetleniyor…"
|
||||
"Compare with" = "Şununla karşılaştır"
|
||||
"Compatibility" = "Uyumluluk"
|
||||
"Convert to frame" = "Çerçeveye dönüştür"
|
||||
"Convert to section" = "Bölüme dönüştür"
|
||||
"Copied comments for AI" = "Yorumlar yapay zeka için kopyalandı"
|
||||
"Copy browser link" = "Tarayıcı bağlantısını kopyala"
|
||||
"Copy effect" = "Efekti kopyala"
|
||||
"Copy fill" = "Dolguyu kopyala"
|
||||
"Copy for AI" = "Yapay zeka için kopyala"
|
||||
"Copy link to page" = "Sayfa bağlantısını kopyala"
|
||||
"Copy stroke" = "Konturu kopyala"
|
||||
"Couldn't download the variables" = "Değişkenler indirilemedi"
|
||||
"Couldn't download {name}" = "{name} indirilemedi"
|
||||
"Couldn't reach {server} for its team list." = "Ekip listesi için {server} sunucusuna ulaşılamadı."
|
||||
"Couldn't save automatically: {error}" = "Otomatik olarak kaydedilemedi: {error}"
|
||||
"Crop image" = "Görseli kırp"
|
||||
"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓"
|
||||
"Ctrl+click a padding field" = "Bir iç boşluk alanına Ctrl+tıklayın"
|
||||
"Dart constants for Flutter…" = "Flutter için Dart sabitleri…"
|
||||
"Delete {n} variables" = { other = "{n} değişkeni sil" }
|
||||
"Detach calculation" = "Hesaplamayı ayır"
|
||||
"Developer Mode only inspects: switch to Design (Shift+D) to edit" = "Geliştirici Modu yalnızca inceler: düzenlemek için Tasarım (Shift+D) moduna geçin"
|
||||
"Disconnected. Reconnecting…" = "Bağlantı kesildi. Yeniden bağlanılıyor…"
|
||||
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Bağlantı kesildi. Düzenlemeleriniz burada kalır ve bağlantı geri geldiğinde eşitlenir. Yeniden bağlanılıyor…"
|
||||
"Dismiss" = "Kapat"
|
||||
"Don't show this again" = "Bunu bir daha gösterme"
|
||||
"Double-click an edge of an auto layout frame" = "Otomatik yerleşim çerçevesinin bir kenarına çift tıklayın"
|
||||
"Download" = "İndir"
|
||||
"Downloading… {percent}%" = "İndiriliyor… %{percent}"
|
||||
"Drop a .figcraft, .fig, .jam, .sketch, .json, .svg or image file." = "Bir .figcraft, .fig, .jam, .sketch, .json, .svg veya görsel dosyası bırakın."
|
||||
"Drop to import" = "İçe aktarmak için bırakın"
|
||||
"Drop to open" = "Açmak için bırakın"
|
||||
"Drop to use this image" = "Bu görseli kullanmak için bırakın"
|
||||
"Duplicate group" = "Grubu çoğalt"
|
||||
"Edit padding on all sides" = "Tüm kenarlardaki iç boşluğu düzenle"
|
||||
"Edit variables" = "Değişkenleri düzenle"
|
||||
"Enter / Shift+Enter" = "Enter / Shift+Enter"
|
||||
"Everyone who reaches this server can open these files while they are shared." = "Bu sunucuya erişebilen herkes, paylaşıldıkları sürece bu dosyaları açabilir."
|
||||
"Exact only" = "Yalnızca birebir"
|
||||
"Expand the interface" = "Arayüzü genişlet"
|
||||
"Exported {name}; {n} kinds of content were changed or left out" = { other = "{name} dışa aktarıldı; {n} tür içerik değiştirildi veya dışarıda bırakıldı" }
|
||||
"Exported {n} files; some content was changed or left out" = { other = "{n} dosya dışa aktarıldı; bazı içerikler değiştirildi veya dışarıda bırakıldı" }
|
||||
"Extra large" = "Çok büyük"
|
||||
"FigCraft couldn't open its window: {error}" = "FigCraft penceresini açamadı: {error}"
|
||||
"FigCraft stopped because of an internal error." = "FigCraft bir iç hata nedeniyle durdu."
|
||||
"FigCraft tried {apis}, then again with lower requirements on the power-saving GPU. Updating the graphics driver often helps." = "FigCraft {apis} ile denedi, ardından güç tasarruflu GPU üzerinde daha düşük gereksinimlerle yeniden denedi. Grafik sürücüsünü güncellemek genellikle yardımcı olur."
|
||||
"Format" = "Biçim"
|
||||
"Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "Ücretsiz yazı tipleri, jsDelivr ve GitHub aracılığıyla Google Fonts ve Noto'dan sağlanır. Her dosya, Craft uygulamalarının ortak kullandığı yazı tipi klasörüne yüklenmeden önce yazı tipi diziniyle karşılaştırılarak denetlenir. Siz izin verene kadar hiçbir şey indirilmez."
|
||||
"Graph paper" = "Milimetrik kâğıt"
|
||||
"Hide UI" = "Arayüzü gizle"
|
||||
"Huge" = "Devasa"
|
||||
"If it keeps happening, please report it at {link} with this message." = "Sorun devam ederse lütfen bu mesajla birlikte {link} adresinden bildirin."
|
||||
"Ignore unsupported" = "Desteklenmeyenleri yoksay"
|
||||
"Individual padding" = "Ayrı ayrı iç boşluk"
|
||||
"Interface size" = "Arayüz boyutu"
|
||||
"Invert zoom direction" = "Yakınlaştırma yönünü tersine çevir"
|
||||
"Joining live session…" = "Canlı oturuma katılınıyor…"
|
||||
"Large" = "Büyük"
|
||||
"Leaving the prototype" = "Prototipten çıkılıyor"
|
||||
"Left padding" = "Sol iç boşluk"
|
||||
"Left to right" = "Soldan sağa"
|
||||
"Link copied: it opens the file in FigCraft" = "Bağlantı kopyalandı: dosyayı FigCraft'ta açar"
|
||||
"Link copied: it opens the file in the browser" = "Bağlantı kopyalandı: dosyayı tarayıcıda açar"
|
||||
"Medium" = "Orta"
|
||||
"Missing fonts" = "Eksik yazı tipleri"
|
||||
"Move out of any group" = "Tüm grupların dışına taşı"
|
||||
"Move to group {group}" = "{group} grubuna taşı"
|
||||
"Move up or down while dragging its label" = "Etiketini sürüklerken yukarı veya aşağı hareket ettirin"
|
||||
"New from selection" = "Seçimden yeni oluştur"
|
||||
"No comments to copy" = "Kopyalanacak yorum yok"
|
||||
"No files or templates match your search" = "Aramanızla eşleşen dosya veya şablon yok"
|
||||
"No other pages" = "Başka sayfa yok"
|
||||
"No scope is shared by all the selected variables" = "Seçili tüm değişkenlerin paylaştığı bir kapsam yok"
|
||||
"Nobody shares a file there now." = "Şu anda orada kimse dosya paylaşmıyor."
|
||||
"Not connected: {reason}. Your work is still in this tab." = "Bağlı değil: {reason}. Çalışmanız hâlâ bu sekmede."
|
||||
"Not now" = "Şimdi değil"
|
||||
"Nothing changed since this version." = "Bu sürümden bu yana hiçbir şey değişmedi."
|
||||
"Nothing counted yet" = "Henüz sayılan bir şey yok"
|
||||
"Nothing to pick: the page is empty" = "Seçilecek bir şey yok: sayfa boş"
|
||||
"Opening the file…" = "Dosya açılıyor…"
|
||||
"Opening {n} files as new files" = { other = "{n} dosya yeni dosya olarak açılıyor" }
|
||||
"Other" = "Diğer"
|
||||
"Past 30 days" = "Son 30 gün"
|
||||
"Past 90 days" = "Son 90 gün"
|
||||
"Past year" = "Son 1 yıl"
|
||||
"Paste effect" = "Efekti yapıştır"
|
||||
"Paste fill" = "Dolguyu yapıştır"
|
||||
"Paste stroke" = "Konturu yapıştır"
|
||||
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Katman seçici: Tab ve Shift+Tab katmanlar arasında gezinir, Enter katmanın içine girer, Shift+Enter dışına çıkar, Space seçer, Escape iptal eder"
|
||||
"Pick select: into a layer, out to its parent" = "Katman seçici: katmanın içine gir, üst katmana çık"
|
||||
"Pick select: next or previous layer" = "Katman seçici: sonraki veya önceki katman"
|
||||
"Pick select: select the picked layer" = "Katman seçici: işaretlenen katmanı seç"
|
||||
"Plugin" = "Eklenti"
|
||||
"Plugins & widgets" = "Eklentiler ve widget'lar"
|
||||
"Pretty" = "Düzenli"
|
||||
"Pretty: full lines, no one word alone on the last" = "Dengeli: tam satırlar, son satırda tek sözcük kalmaz"
|
||||
"Relative to your system's display scaling (100% is the system's own size). Document zoom is separate." = "Sisteminizin ekran ölçeklendirmesine göredir (%100 sistemin kendi boyutudur). Belge yakınlaştırması ayrıdır."
|
||||
"Reload the page to get back the unsaved files the browser had room for." = "Tarayıcının yer ayırabildiği kaydedilmemiş dosyaları geri almak için sayfayı yeniden yükleyin."
|
||||
"Reload the page to get your unsaved files back." = "Kaydedilmemiş dosyalarınızı geri almak için sayfayı yeniden yükleyin."
|
||||
"Reload the page to start again." = "Yeniden başlamak için sayfayı yeniden yükleyin."
|
||||
"Remove all auto layout" = "Tüm otomatik yerleşimleri kaldır"
|
||||
"Remove {name} from session" = "{name} adlı kişiyi oturumdan kaldır"
|
||||
"Removed since this version" = "Bu sürümden bu yana kaldırıldı"
|
||||
"Reorder selection" = "Seçimi yeniden sırala"
|
||||
"Reset grid" = "Izgarayı sıfırla"
|
||||
"Retry now" = "Şimdi yeniden dene"
|
||||
"Right padding" = "Sağ iç boşluk"
|
||||
"Right to left" = "Sağdan sola"
|
||||
"Rotate a degree (Shift: 15)" = "Bir derece döndür (Shift: 15)"
|
||||
"Same as file ({profile})" = "Dosyayla aynı ({profile})"
|
||||
"Save a copy…" = "Kopyasını kaydet…"
|
||||
"Save files automatically" = "Dosyaları otomatik kaydet"
|
||||
"Scope" = "Kapsam"
|
||||
"Scope: all supported properties" = "Kapsam: desteklenen tüm özellikler"
|
||||
"Scope: hidden from pickers" = "Kapsam: seçicilerden gizli"
|
||||
"Scope: only {scope}" = "Kapsam: yalnızca {scope}"
|
||||
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Bir alanı daha hızlı (2x) veya daha yavaş (1/2, 1/4) kaydırarak ayarlayın"
|
||||
"Scrubbing at 1/2" = "1/2 hızında kaydırma"
|
||||
"Scrubbing at 1/4" = "1/4 hızında kaydırma"
|
||||
"Scrubbing at 1x" = "1x hızında kaydırma"
|
||||
"Scrubbing at 2x" = "2x hızında kaydırma"
|
||||
"Search files and templates" = "Dosya ve şablonlarda ara"
|
||||
"Search pages" = "Sayfalarda ara"
|
||||
"Search results" = "Arama sonuçları"
|
||||
"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Otomatik yerleşim akışı dışında üç veya daha fazla katmandan oluşan bir satır, sütun veya tam ızgara seçin"
|
||||
"Selection box: switch to pick select" = "Seçim kutusu: tıklayarak seçime geç"
|
||||
"Server key" = "Sunucu anahtarı"
|
||||
"Set as opening page" = "Açılış sayfası olarak ayarla"
|
||||
"Set corner smoothing to 60%" = "Köşe yumuşatmayı %60 olarak ayarla"
|
||||
"Set fill container" = "Kapsayıcıyı doldur olarak ayarla"
|
||||
"Set hug contents" = "İçeriği sar olarak ayarla"
|
||||
"Shared by your team on {server}" = "{server} üzerinde ekibiniz tarafından paylaşıldı"
|
||||
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Yerleştirme artı işaretini göster ve taşı (aracı seçiliyken, hiçbir şey seçili değilken)"
|
||||
"Small" = "Küçük"
|
||||
"Space" = "Boşluk"
|
||||
"Start on the Home screen" = "Ana ekranda başlat"
|
||||
"Strong line every" = "Kalın çizgi aralığı"
|
||||
"Subscript" = "Alt simge"
|
||||
"Superscript" = "Üst simge"
|
||||
"Tab or Ctrl+Space again" = "Tekrar Tab veya Ctrl+Space"
|
||||
"Text direction" = "Metin yönü"
|
||||
"Text on a path" = "Yol üzerinde metin"
|
||||
"The bars are hidden. {shortcut} shows them again" = "Çubuklar gizli. {shortcut} bunları yeniden gösterir"
|
||||
"The destination document is unavailable. Nothing was imported." = "Hedef belge kullanılamıyor. Hiçbir şey içe aktarılmadı."
|
||||
"The destination document was closed. Nothing was imported." = "Hedef belge kapatılmış. Hiçbir şey içe aktarılmadı."
|
||||
"The destination page was removed. Nothing was imported." = "Hedef sayfa kaldırılmış. Hiçbir şey içe aktarılmadı."
|
||||
"The window is too small for {size}%, so the interface is drawn at {drawn}%. Make the window larger to use {size}%." = "Pencere %{size} için çok küçük olduğundan arayüz %{drawn} olarak çiziliyor. %{size} kullanmak için pencereyi büyütün."
|
||||
"This file is too large to join here (up to {mb} MB)" = "Bu dosya buraya eklenmek için çok büyük (en fazla {mb} MB)"
|
||||
"This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Bu dosya, bu bilgisayarda yüklü olmayan yazı tiplerini kullanıyor. Siz yükleyene kadar ilgili metinler yedek bir yazı tipiyle çizilir."
|
||||
"This link opens a website outside the prototype:" = "Bu bağlantı prototip dışında bir web sitesi açar:"
|
||||
"This link opens your mail app to write a message:" = "Bu bağlantı ileti yazmak için e-posta uygulamanızı açar:"
|
||||
"This server doesn't count detached instances" = "Bu sunucu ayrılmış örnekleri saymaz"
|
||||
"This server doesn't count insertions" = "Bu sunucu eklemeleri saymaz"
|
||||
"This server doesn't count styles and variables" = "Bu sunucu stilleri ve değişkenleri saymaz"
|
||||
"This variant's value" = "Bu varyantın değeri"
|
||||
"This version can't be read." = "Bu sürüm okunamıyor."
|
||||
"This version doesn't have it: all of it is new." = "Bu sürümde yok: tamamı yeni."
|
||||
"Top padding" = "Üst iç boşluk"
|
||||
"Try another search, or browse templates." = "Başka bir arama deneyin veya şablonlara göz atın."
|
||||
"Update check is not supported in the web browser." = "Güncelleme denetimi web tarayıcısında desteklenmiyor."
|
||||
"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "Grafik sürücüsünü güncellemek genellikle işe yarar. Yalnızca OpenGL kullanmak için FigCraft'ı Komut İstemi'nden şu komutla başlatın:"
|
||||
"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "Grafik sürücüsünü güncellemek genellikle işe yarar. WGPU_BACKEND (vulkan, gl, metal) denenecek başka bir grafik API'sini belirtir."
|
||||
"Upload from computer" = "Bilgisayardan yükle"
|
||||
"Use your browser's zoom to change the interface size." = "Arayüz boyutunu değiştirmek için tarayıcınızın yakınlaştırma ayarını kullanın."
|
||||
"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND ayarlı ve kullanılacak grafik API'sini belirtiyor; bu ayarı kaldırmak seçimi FigCraft'a bırakır."
|
||||
"What changed since a saved version" = "Kaydedilmiş bir sürümden bu yana değişenler"
|
||||
"When marked ready" = "Hazır olarak işaretlendiğinde"
|
||||
"Widget" = "Widget"
|
||||
"Wrap style" = "Satır kaydırma stili"
|
||||
"Your unsaved files were too large for the browser to keep." = "Kaydedilmemiş dosyalarınız tarayıcının saklayabileceği boyuttan büyüktü."
|
||||
"connector labels without a saved snapshot are centred on the line, without their background" = "kaydedilmiş anlık görüntüsü olmayan bağlayıcı etiketleri, arka planları olmadan çizginin ortasına hizalandı"
|
||||
"elbowed and curved connectors without a saved path are routed afresh" = "kaydedilmiş yolu olmayan dirsekli ve kavisli bağlayıcılar yeniden yönlendirildi"
|
||||
"instance swap properties whose default component was past the layer limit were skipped" = "varsayılan bileşeni katman sınırını aşan örnek değiştirme özellikleri atlandı"
|
||||
"instances whose component was past the layer limit were imported as frames" = "bileşeni katman sınırını aşan örnekler çerçeve olarak içe aktarıldı"
|
||||
"invalid vector region fill paint list; layer fill used" = "geçersiz vektör bölgesi dolgu boyası listesi; katman dolgusu kullanıldı"
|
||||
"invalid vector region paints were skipped" = "geçersiz vektör bölgesi boyaları atlandı"
|
||||
"linked vector region fill styles keep resolved appearance; live style links were left out" = "bağlı vektör bölgesi dolgu stilleri çözümlenmiş görünümü korur; canlı stil bağlantıları dışarıda bırakıldı"
|
||||
"note or shape generated child has invalid bounds; child skipped" = "not veya şekil tarafından oluşturulan alt öğenin sınırları geçersiz; alt öğe atlandı"
|
||||
"note or shape generated child is missing its style or bounds; child skipped" = "not veya şekil tarafından oluşturulan alt öğenin stili veya sınırları eksik; alt öğe atlandı"
|
||||
"note or shape generated children exceed the layer or nesting limit; remaining children skipped" = "not veya şekil tarafından oluşturulan alt öğeler katman veya iç içe geçme sınırını aşıyor; kalan alt öğeler atlandı"
|
||||
"note or shape generated layout is missing or unsupported; using its outer frame" = "not veya şekil tarafından oluşturulan yerleşim eksik veya desteklenmiyor; dış çerçevesi kullanılıyor"
|
||||
"only in a text style or variable" = "yalnızca bir metin stilinde veya değişkende"
|
||||
"shape generated outline is missing or damaged; using its rectangle" = "şekil tarafından oluşturulan dış hat eksik veya bozuk; dikdörtgeni kullanılıyor"
|
||||
"slot layers without a matching slot property were imported as frames" = "eşleşen yuva özelliği olmayan yuva katmanları çerçeve olarak içe aktarıldı"
|
||||
"sticky layers import as frames with their text" = "yapışkan not katmanları metinleriyle birlikte çerçeve olarak içe aktarılır"
|
||||
"swapped instances whose previous component isn't in the file took the new component's look" = "önceki bileşeni dosyada bulunmayan değiştirilmiş örnekler yeni bileşenin görünümünü aldı"
|
||||
"variable-bound vector region paints keep resolved appearance; live bindings were left out" = "değişkene bağlı vektör bölgesi boyaları çözümlenmiş görünümü korur; canlı bağlamalar dışarıda bırakıldı"
|
||||
"vector region paint data exceeded import limits and was skipped" = "vektör bölgesi boya verileri içe aktarma sınırlarını aştığı için atlandı"
|
||||
"vector region references a missing fill style; layer fill used" = "vektör bölgesi eksik bir dolgu stiline başvuruyor; katman dolgusu kullanıldı"
|
||||
"{count} in it now · Changed {date}" = "Şu anda {count} · Değiştirilme: {date}"
|
||||
"{insertions} · {detachments}" = "{insertions} · {detachments}"
|
||||
"{name}, disconnected from its live session" = "{name}, canlı oturum bağlantısı kesildi"
|
||||
"{n} detached" = { other = "{n} ayrıldı" }
|
||||
"{n} inserted" = { other = "{n} eklendi" }
|
||||
"{n} text layers" = { other = "{n} metin katmanı" }
|
||||
"{percent}%" = "%{percent}"
|
||||
"{period}: {counts}" = "{period}: {counts}"
|
||||
"{used} · {detached}" = "{used} · {detached}"
|
||||
"{used} · {inserted}" = "{used} · {inserted}"
|
||||
"↵ / ⇧↵" = "↵ / ⇧↵"
|
||||
"⇥ or ⌥ Space again" = "Tekrar ⇥ veya ⌥ Space"
|
||||
"⌘ click a padding field" = "⌘ tuşuyla bir iç boşluk alanına tıklayın"
|
||||
"⌥ double-click an edge of an auto layout child" = "⌥ tuşuyla otomatik yerleşim alt öğesinin bir kenarına çift tıklayın"
|
||||
"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓"
|
||||
[commands]
|
||||
"align.bottom" = "Alta hizala"
|
||||
"align.hcenter" = "Yatay merkezleri hizala"
|
||||
@@ -2420,6 +2649,60 @@ name = "Türkçe"
|
||||
"window.new" = "Yeni pencere"
|
||||
"template.list" = "Şablonları listele"
|
||||
|
||||
"arrange.reorder" = "Yeniden sırala"
|
||||
"board.codeBlock" = "Kod bloğu"
|
||||
"board.grid" = "Pano ızgarası"
|
||||
"board.mindMap" = "Zihin haritası"
|
||||
"board.mindMapAdd" = "Zihin haritası düğümü ekle"
|
||||
"board.reshape" = "Panoyu yeniden şekillendir"
|
||||
"board.setLanguage" = "Kod dili"
|
||||
"collab.reconnect" = "Yeniden bağlan"
|
||||
"collab.removePerson" = "Kişiyi oturumdan kaldır"
|
||||
"comment.prompt" = "Yorumları yapay zeka için kopyala"
|
||||
"data.fill" = "Veri doldur"
|
||||
"effect.copy" = "Efekti kopyala"
|
||||
"effect.paste" = "Efekti yapıştır"
|
||||
"file.fontReport" = "Yazı tipi raporu"
|
||||
"file.markSaved" = "Kaydedildi olarak işaretle"
|
||||
"fill.copy" = "Dolguyu kopyala"
|
||||
"fill.paste" = "Dolguyu yapıştır"
|
||||
"font.download" = "Yazı tipini indir"
|
||||
"font.downloads" = "Yazı tipi indirmeleri"
|
||||
"image.crop" = "Görseli kırp"
|
||||
"image.replace" = "Görseli değiştir"
|
||||
"inspect.designContext" = "Tasarım bağlamı"
|
||||
"layout.removeAll" = "Tüm yerleşimleri kaldır"
|
||||
"library.check" = "Kitaplığı denetle"
|
||||
"object.convertToSection" = "Bölüme dönüştür"
|
||||
"page.setOpening" = "Açılış sayfası olarak ayarla"
|
||||
"pref.autoSave" = "Otomatik kaydet"
|
||||
"pref.invertZoom" = "Yakınlaştırmayı ters çevir"
|
||||
"pref.startOnHome" = "Ana sayfada başlat"
|
||||
"pref.uiScale" = "Arayüz ölçeği"
|
||||
"pref.uiScaleDown" = "Arayüz ölçeğini küçült"
|
||||
"pref.uiScaleReset" = "Arayüz ölçeğini sıfırla"
|
||||
"pref.uiScaleUp" = "Arayüz ölçeğini büyüt"
|
||||
"proto.linkNotice" = "Prototip bağlantı bildirimi"
|
||||
"selection.createColorStyle" = "Seçimden renk stili oluştur"
|
||||
"stroke.copy" = "Konturu kopyala"
|
||||
"stroke.paste" = "Konturu yapıştır"
|
||||
"text.direction" = "Metin yönü"
|
||||
"text.directionAuto" = "Metin yönü: Otomatik"
|
||||
"text.directionLtr" = "Metin yönü: Soldan sağa"
|
||||
"text.directionRtl" = "Metin yönü: Sağdan sola"
|
||||
"text.fit" = "Metni sığdır"
|
||||
"text.loadFont" = "Yazı tipini yükle"
|
||||
"text.missingFonts" = "Eksik yazı tipleri"
|
||||
"text.openLink" = "Bağlantıyı aç"
|
||||
"text.refit" = "Metni yeniden sığdır"
|
||||
"text.rescanFonts" = "Yazı tiplerini yeniden tara"
|
||||
"text.wrapStyle" = "Metin kaydırma stili"
|
||||
"tool.annotation" = "Ek açıklama aracı"
|
||||
"tool.crosshair" = "Artı işareti aracı"
|
||||
"tool.textOnPath" = "Yol üzerinde metin aracı"
|
||||
"variable.extendCollection" = "Değişken koleksiyonunu genişlet"
|
||||
"view.minimize" = "Simge durumuna küçült"
|
||||
"widget.hover" = "Araç takımı üzerine gelme"
|
||||
[menu]
|
||||
"bool.exclude" = "Hariç tut"
|
||||
"bool.flatten" = "Düzleştir"
|
||||
@@ -2452,3 +2735,6 @@ name = "Türkçe"
|
||||
"view.themeDark" = "Koyu"
|
||||
"view.themeLight" = "Açık"
|
||||
"view.themeSystem" = "Sistemi izle"
|
||||
"text.directionAuto" = "Otomatik"
|
||||
"text.directionLtr" = "Soldan sağa"
|
||||
"text.directionRtl" = "Sağdan sola"
|
||||
@@ -22,9 +22,23 @@ impl FigApp {
|
||||
// `file.open`/`file.close`). Record that presentation before returning, so an in-flight
|
||||
// screenshot admitted on the old file cannot accept pixels from the new one.
|
||||
self.observe_presentation();
|
||||
if let Ok(v) = &r {
|
||||
self.note_snapping(id, v);
|
||||
}
|
||||
r.map_err(|e| self.failed(id, &e)).ok()
|
||||
}
|
||||
|
||||
/// Snap to pixel grid turned on or off says which at the bottom, as in Figma: its shortcut
|
||||
/// (Shift+Cmd/Ctrl+') changes nothing on the canvas until the next drag.
|
||||
fn note_snapping(&mut self, id: &str, result: &Value) {
|
||||
let msg = match (id, result.get("on").and_then(Value::as_bool)) {
|
||||
("view.snapPixel", Some(true)) => crate::i18n::tr("Snap to pixel grid on"),
|
||||
("view.snapPixel", Some(false)) => crate::i18n::tr("Snap to pixel grid off"),
|
||||
_ => return,
|
||||
};
|
||||
self.toast(msg);
|
||||
}
|
||||
|
||||
/// A programmatic command that changed the engine clipboard never wrote the system clipboard:
|
||||
/// forget the old system mirror so a later user paste does not trust it as our own copy.
|
||||
/// `before` is the layers generation captured before the command ran.
|
||||
|
||||
@@ -72,6 +72,44 @@ impl FigApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the colour picker is being used right now for the selected layers' own look (a
|
||||
/// paint, an effect, a text range or Selection colors): a drag on its value controls (the
|
||||
/// palette, the hue and alpha sliders, a number field, the gradient bar and its stops), the
|
||||
/// keyboard in one of its fields, the eyedropper sampling, or a drag of the canvas handles it
|
||||
/// owns (gradient stops and handles, image crop). Only then does the canvas hide the selection
|
||||
/// frame and a text's coloured selection, so the colour being chosen shows against the page.
|
||||
/// Merely having the picker open, or pressing a button, a menu or a swatch, leaves it visible.
|
||||
pub(crate) fn picker_hides_selection(&self, ctx: &egui::Context) -> bool {
|
||||
let edits_selection = matches!(
|
||||
self.ui.picker,
|
||||
Some(
|
||||
crate::colorpicker::PickerTarget::Paint { .. }
|
||||
| crate::colorpicker::PickerTarget::Effect { .. }
|
||||
| crate::colorpicker::PickerTarget::TextRange { .. }
|
||||
| crate::colorpicker::PickerTarget::SelectionColor { .. }
|
||||
)
|
||||
);
|
||||
if !edits_selection {
|
||||
return false;
|
||||
}
|
||||
// The picker draws after the canvas, so its card comes from the previous frame.
|
||||
let card = self.ui.picker_popover.as_ref();
|
||||
// A drag changes the colour live; a press alone does not. Buttons, menus, swatches and the
|
||||
// paint-type switches are clicks and must not hide the selection while held (they used to,
|
||||
// which flickered it). Dragging the card by its header moves the popover, not the colour.
|
||||
let header_drag = card.map(|c| c.header_drag_id());
|
||||
let dragging = ctx.dragged_id().is_some_and(|id| header_drag != Some(id))
|
||||
&& ctx.input(|i| i.pointer.any_down() && i.pointer.press_origin().is_some_and(|p| card.is_some_and(|c| c.rect.contains(p))));
|
||||
// A value field keeps the keyboard after its click: hide until focus leaves the picker.
|
||||
// Only a text edit counts: every clicked control takes focus in egui, and a focused
|
||||
// palette square or swatch must not keep the selection hidden after the drag.
|
||||
let typing = ctx.text_edit_focused()
|
||||
&& ctx
|
||||
.memory(|m| m.focused())
|
||||
.is_some_and(|id| ctx.read_response(id).is_some_and(|r| card.is_some_and(|c| c.rect.contains_rect(r.rect))));
|
||||
dragging || typing || self.session.tool.pick_only || crate::handles::gradient_dragging(ctx) || crate::handles::crop_dragging(ctx)
|
||||
}
|
||||
|
||||
/// Leaving Design ends a pen path as Escape does and goes back to Move: Prototype and Inspect
|
||||
/// don't draw (#307). Checked as the frame starts (the control channel) and after the panels
|
||||
/// and shortcuts (the mode switcher, the tabs, Shift+E/Shift+D), before the canvas sees more.
|
||||
|
||||
@@ -21,7 +21,7 @@ mod drag_sprite;
|
||||
mod input;
|
||||
pub(crate) use input::release_fields_for_press;
|
||||
mod outline;
|
||||
mod overlays;
|
||||
pub(crate) mod overlays;
|
||||
mod render;
|
||||
mod rulers;
|
||||
|
||||
@@ -280,8 +280,9 @@ fn pointer_event(app: &FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers
|
||||
sy: f64::from(pos.y),
|
||||
shift: m.shift,
|
||||
alt: m.alt,
|
||||
// Crop mode: resizing the layer crops it, as Cmd/Ctrl-resizing does.
|
||||
cmd: m.command || app.ui.crop.is_some(),
|
||||
// Crop mode: resizing the layer crops it, as Cmd/Ctrl-resizing does (not while its points
|
||||
// are being edited, where Cmd/Ctrl bends a segment).
|
||||
cmd: m.command || (app.ui.crop.is_some() && app.session.ds().is_ok_and(|d| d.vector_edit.is_none())),
|
||||
ctrl: m.ctrl,
|
||||
zoom,
|
||||
pressure: app.canvas.pressure,
|
||||
@@ -326,7 +327,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
|
||||
// Otherwise keep the centre.
|
||||
ds.view.vw = f64::from(rect.width());
|
||||
ds.view.vh = f64::from(rect.height());
|
||||
if first {
|
||||
if first && ds.fit_when_sized {
|
||||
ds.zoom_to_fit();
|
||||
}
|
||||
}
|
||||
@@ -350,7 +351,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
|
||||
Some((rect, _)) => crate::drop_overlay(&ctx, rect, tr("Drop to use this image")),
|
||||
None => crate::drop_overlay(&ctx, ctx.content_rect(), label),
|
||||
}
|
||||
crate::guides::end_released(&ctx);
|
||||
crate::guides::end_released(app, &ctx);
|
||||
crate::live::track_pointer(app, &ctx);
|
||||
app.sync_preedit();
|
||||
// Retained rendering snaps the view outward and adds one pixel on each axis.
|
||||
|
||||
@@ -229,13 +229,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
d.remove::<GuideDrag>(drag_id());
|
||||
d.remove::<Placed>(preview_id());
|
||||
});
|
||||
// Released over its own ruler (the left one for a guide running down the screen): no
|
||||
// guide (a moved one is removed).
|
||||
let down = at.map_or(vertical, |g| {
|
||||
let [a, b] = segment(app, &g, r);
|
||||
(b.y - a.y).abs() >= (b.x - a.x).abs()
|
||||
});
|
||||
let on_ruler = if down { pos.x < r.min.x + RULER } else { pos.y < r.min.y + RULER };
|
||||
let on_ruler = on_own_ruler(app, at, vertical, pos);
|
||||
let page = app.session.ds().map(|d| d.page).ok();
|
||||
let before = app.session.doc().ok().and_then(|d| match drag {
|
||||
GuideDrag::Move { owner, index, .. } => d.node(owner).and_then(|n| n.guides().get(index)).map(|g| g.offset),
|
||||
@@ -297,17 +291,45 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `pos` is over the ruler a guide comes back to, or past it: the left ruler for a guide
|
||||
/// running down the screen, the top one otherwise. `at` is where the guide would land, if anywhere.
|
||||
fn on_own_ruler(app: &FigApp, at: Option<Placed>, vertical: bool, pos: Pos2) -> bool {
|
||||
let r = app.canvas.rect;
|
||||
let down = at.map_or(vertical, |g| {
|
||||
let [a, b] = segment(app, &g, r);
|
||||
(b.y - a.y).abs() >= (b.x - a.x).abs()
|
||||
});
|
||||
if down { pos.x < r.min.x + RULER } else { pos.y < r.min.y + RULER }
|
||||
}
|
||||
|
||||
/// Ends a guide drag whose button is up by the end of the frame without [`input`] taking the
|
||||
/// release (released off the canvas, or over something on it): the gesture is dropped, so a later
|
||||
/// click doesn't add or move a guide.
|
||||
pub fn end_released(ctx: &egui::Context) {
|
||||
/// click doesn't add or move a guide. A moved guide released past its own ruler is removed, as on
|
||||
/// the ruler: the ruler is thin, and a drag back onto it often overshoots onto the panel beside it.
|
||||
pub fn end_released(app: &mut FigApp, ctx: &egui::Context) {
|
||||
if ctx.input(|i| i.pointer.primary_down()) {
|
||||
return;
|
||||
}
|
||||
ctx.data_mut(|d| {
|
||||
let (drag, at) = ctx.data_mut(|d| {
|
||||
let taken = (d.get_temp::<GuideDrag>(drag_id()), d.get_temp::<Placed>(preview_id()));
|
||||
d.remove::<GuideDrag>(drag_id());
|
||||
d.remove::<Placed>(preview_id());
|
||||
taken
|
||||
});
|
||||
let Some(GuideDrag::Move { owner, index, vertical, copy: false, .. }) = drag else { return };
|
||||
// Where the button came up: a later move in the same frame, or a touch's end clearing the
|
||||
// pointer, doesn't change it.
|
||||
let released_at = ctx.input(|i| {
|
||||
i.events.iter().rev().find_map(|e| match e {
|
||||
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(*pos),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
let Some(pos) = released_at else { return };
|
||||
if rulers_on(app) && on_own_ruler(app, at, vertical, pos) {
|
||||
let page = app.session.ds().map(|d| d.page).ok();
|
||||
app.run("guide.remove", owned(owner, page, json!({"index": index})));
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the page's and its frames' guides (under the rulers) and the one being dragged with its
|
||||
|
||||
@@ -529,9 +529,10 @@ fn draw_crop(app: &FigApp, painter: &egui::Painter, id: NodeId, img: &ImagePaint
|
||||
|
||||
/// Draw the handles.
|
||||
pub fn draw(app: &mut FigApp, painter: &egui::Painter) {
|
||||
// Crop mode ends when a colour picker opens, or when its layer leaves the selection or its fill
|
||||
// is no longer a Crop image (an undo).
|
||||
if app.ui.crop.is_some() && (app.ui.picker.is_some() || crop_target(app).is_none()) {
|
||||
// Crop mode ends when a colour picker opens, when its layer leaves the selection or its fill
|
||||
// is no longer a Crop image (an undo), or when the layer's points are being edited.
|
||||
let editing_points = app.session.ds().is_ok_and(|d| d.vector_edit.is_some());
|
||||
if app.ui.crop.is_some() && (app.ui.picker.is_some() || crop_target(app).is_none() || editing_points) {
|
||||
app.ui.crop = None;
|
||||
}
|
||||
let app = &*app;
|
||||
@@ -697,8 +698,8 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> Input {
|
||||
}
|
||||
}
|
||||
if let Some((id, fills, index, _, rect)) = crop_target(app) {
|
||||
// Crop mode: the layer's own resize handles crop it (the pointer events carry Cmd/Ctrl).
|
||||
if app.ui.crop.is_some() && on_resize_handle(app, pos) {
|
||||
// The layer's own resize handles resize/crop the layer, not the crop handles.
|
||||
if on_resize_handle(app, pos) {
|
||||
return Input::Ignored;
|
||||
}
|
||||
let Some(c) = crop_corners(app, id, rect) else { return Input::Ignored };
|
||||
@@ -821,13 +822,13 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, modifiers: egui::Modifiers) {
|
||||
let (dx, dy) = (u.0 - start.0, u.1 - start.1);
|
||||
(x0 + dx, y0 + dy, x1 + dx, y1 + dy)
|
||||
} else {
|
||||
// Scale about the opposite corner, keeping the image's aspect ratio unless Shift.
|
||||
// Scale about the opposite corner, keeping the image's aspect ratio with Shift.
|
||||
let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)];
|
||||
let (ax, ay) = corners.get((*which + 2) % 4).copied().unwrap_or((x0, y0));
|
||||
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 !modifiers.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));
|
||||
|
||||
@@ -321,6 +321,9 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo
|
||||
open_context_menu(app, pos, mods.command);
|
||||
return true;
|
||||
}
|
||||
if crop_mode_multi_click(app, resp, pos, &mods) {
|
||||
return true;
|
||||
}
|
||||
// A third quick click is counted as a triple, not a double (a click elsewhere in between still
|
||||
// leaves its time in the sequence): it means the same here — edit, enter, open — unless a
|
||||
// vector or text is being edited, where a triple already has its own meaning. A triple on
|
||||
@@ -432,6 +435,18 @@ fn pan_past_edge(app: &mut FigApp, ctx: &egui::Context, mods: &egui::Modifiers)
|
||||
}
|
||||
}
|
||||
|
||||
/// A double- or triple-click in crop mode stays in crop mode (it would edit the points), and is
|
||||
/// taken here. Its last press may have begun a resize on a side of the layer: its release ends that.
|
||||
fn crop_mode_multi_click(app: &mut FigApp, resp: &egui::Response, pos: Pos2, mods: &egui::Modifiers) -> bool {
|
||||
if app.ui.crop.is_none() || !(resp.double_clicked() || resp.triple_clicked()) {
|
||||
return false;
|
||||
}
|
||||
if std::mem::take(&mut app.canvas.dragging) {
|
||||
send(app, PointerKind::Up, pos, mods);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) {
|
||||
let ev = pointer_event(app, kind, pos, m);
|
||||
// A hover where nothing changed since the last one finds what that one found (the state is
|
||||
|
||||
@@ -124,7 +124,10 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec
|
||||
}
|
||||
// Selection.
|
||||
let editing = ds.text_edit.clone();
|
||||
if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() {
|
||||
// While the colour picker is being used on the selection, hide its frame and handles so the
|
||||
// colour being picked shows on the layer itself (a text's coloured selection would hide it
|
||||
// too).
|
||||
if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() && !app.picker_hides_selection(painter.ctx()) {
|
||||
size_label = selection_overlay(app, painter, ds, &doc, &sel, zoom);
|
||||
}
|
||||
if app.session.tool.tool == ToolId::ShapeBuilder
|
||||
@@ -171,22 +174,27 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec
|
||||
labels
|
||||
}
|
||||
|
||||
/// The pixel grid's lines: one screen pixel wide, a light grey at a fifth of its strength, so
|
||||
/// they darken white and lighten a dark canvas or fill alike. Measured in Figma (2026-11-24):
|
||||
/// 242 on white and 78 on a grey of 50, which this grey gives.
|
||||
pub(crate) const PIXEL_GRID: Color32 = Color32::from_rgba_unmultiplied_const(190, 190, 190, 51);
|
||||
|
||||
/// Pixel grid at high zoom.
|
||||
fn pixel_grid(app: &FigApp, painter: &egui::Painter) {
|
||||
let r = app.canvas.rect;
|
||||
let p0 = app.to_page(r.min);
|
||||
let p1 = app.to_page(r.max);
|
||||
let col = Color32::from_black_alpha(18);
|
||||
let line = stroke(PIXEL_GRID, 1.0 / painter.pixels_per_point());
|
||||
let mut x = p0.x.floor();
|
||||
while x <= p1.x {
|
||||
let s = app.to_screen(x, 0.0).x;
|
||||
painter.line_segment([pos2(s, r.min.y), pos2(s, r.max.y)], stroke(col, 1.0));
|
||||
let s = painter.round_to_pixel_center(app.to_screen(x, 0.0).x);
|
||||
painter.line_segment([pos2(s, r.min.y), pos2(s, r.max.y)], line);
|
||||
x += 1.0;
|
||||
}
|
||||
let mut y = p0.y.floor();
|
||||
while y <= p1.y {
|
||||
let s = app.to_screen(0.0, y).y;
|
||||
painter.line_segment([pos2(r.min.x, s), pos2(r.max.x, s)], stroke(col, 1.0));
|
||||
let s = painter.round_to_pixel_center(app.to_screen(0.0, y).y);
|
||||
painter.line_segment([pos2(r.min.x, s), pos2(r.max.x, s)], line);
|
||||
y += 1.0;
|
||||
}
|
||||
}
|
||||
@@ -268,12 +276,16 @@ fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Do
|
||||
let preedit = app.preedit_view();
|
||||
let edoc: &Document = preedit.map(|p| &*p.doc).unwrap_or(doc);
|
||||
let Some(text) = TextOnScreen::of(edoc, te.id) else { return };
|
||||
// While the colour picker is being used on this text, its frame and coloured selection hide
|
||||
// too: the selection colour tinted the very characters whose colour is being chosen. The
|
||||
// caret stays.
|
||||
let picking = app.picker_hides_selection(painter.ctx());
|
||||
let layout = &text.layout;
|
||||
if let Some(q) = node_quad(app, edoc, te.id) {
|
||||
if !picking && let Some(q) = node_quad(app, edoc, te.id) {
|
||||
quad(painter, q, stroke(accent(painter), 1.0));
|
||||
}
|
||||
let (a, b) = (te.caret.min(te.anchor), te.caret.max(te.anchor));
|
||||
if a != b && preedit.is_none() {
|
||||
if a != b && preedit.is_none() && !picking {
|
||||
for q in text.selection(app, a, b) {
|
||||
painter.add(Shape::convex_polygon(q.to_vec(), accent(painter).gamma_multiply(0.3), Stroke::NONE));
|
||||
}
|
||||
|
||||
@@ -131,6 +131,11 @@ fn shows(code: &str, web: bool) -> bool {
|
||||
// Arabic; keep the catalog out until an embedded Arabic fallback is supplied.
|
||||
return figcraft_text::face_with_char('ع', &["Noto Sans Arabic"]).is_some();
|
||||
}
|
||||
if code.split(['-', '_']).next().is_some_and(|b| b.eq_ignore_ascii_case("he") || b.eq_ignore_ascii_case("iw")) {
|
||||
// Desktop draws Hebrew with a system face (or bundled craft-fonts); the web leaves it out
|
||||
// unless Noto Sans Hebrew is embedded (FIGCRAFT_EMBED_SCRIPTS=Hebr).
|
||||
return figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]).is_some();
|
||||
}
|
||||
if code.split('-').next() == Some("ta") {
|
||||
// Desktop draws Tamil with a system face (#2018); the web has none until craft-fonts
|
||||
// carries Noto Sans Tamil.
|
||||
@@ -233,6 +238,15 @@ mod tests {
|
||||
assert_eq!(shows("ar-SA", true), face);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_web_offers_hebrew_only_with_its_face() {
|
||||
assert!(shows("he", false), "desktop always lists Hebrew");
|
||||
let face = figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]).is_some();
|
||||
assert_eq!(shows("he", true), face);
|
||||
assert_eq!(shows("he-IL", true), face);
|
||||
assert_eq!(shows("iw-IL", true), face);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_web_offers_tamil_only_with_its_face() {
|
||||
assert!(shows("ta", false), "desktop always lists Tamil");
|
||||
|
||||
@@ -372,3 +372,172 @@ fn a_gradient_drag_whose_gesture_closes_under_the_held_button_stops_editing() {
|
||||
u.button(u.app.to_screen(180.0, 200.0), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `shape` is painted in `col`, as a fill or a stroke.
|
||||
fn painted_in(shape: &egui::Shape, col: egui::Color32) -> bool {
|
||||
use egui::epaint::ColorMode;
|
||||
match shape {
|
||||
egui::Shape::Path(p) => p.fill == col || matches!(p.stroke.color, ColorMode::Solid(c) if c == col),
|
||||
egui::Shape::Rect(r) => r.fill == col || r.stroke.color == col,
|
||||
egui::Shape::LineSegment { stroke, .. } => stroke.color == col,
|
||||
egui::Shape::Circle(c) => c.fill == col || c.stroke.color == col,
|
||||
egui::Shape::Vec(v) => v.iter().any(|s| painted_in(s, col)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many shapes painted in `col` this frame draws inside `area`. On the page those are the
|
||||
/// selection's frame, its handles and a text's coloured selection.
|
||||
fn painted_around(out: &egui::FullOutput, area: egui::Rect, col: egui::Color32) -> usize {
|
||||
out.shapes.iter().filter(|c| painted_in(&c.shape, col) && c.shape.visual_bounding_rect().intersects(area)).count()
|
||||
}
|
||||
|
||||
/// A text layer's box on screen, with room for its handles.
|
||||
fn text_area(u: &Ui, id: NodeId) -> egui::Rect {
|
||||
let b = u.app.session.doc().unwrap().world_bounds(id).unwrap();
|
||||
egui::Rect::from_two_pos(u.app.to_screen(b.x0, b.y0), u.app.to_screen(b.x1, b.y1)).expand(20.0)
|
||||
}
|
||||
|
||||
fn selected_text(s: &mut Session) -> NodeId {
|
||||
let id =
|
||||
NodeId(s.execute("text.create", &json!({"text": "Hello", "x": 300, "y": 200, "props": {"fontSize": 48}})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
// The colour picker only hides the selection while it is being used: opening it leaves the frame in
|
||||
// view, and the press/drag on its controls hides it. A text makes this matter: its frame runs
|
||||
// through the glyphs and its selection is tinted.
|
||||
#[test]
|
||||
fn a_selected_texts_frame_hides_only_while_its_colour_picker_is_used() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let accent = crate::theme::canvas_accent(&u.ctx);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "the selected text's frame shows");
|
||||
|
||||
let target = PickerTarget::Paint { fills: true, index: 0, ids: vec![text] };
|
||||
u.app.open_picker(target.clone(), None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(u.app.ui.picker, Some(target.clone()), "the picker is open");
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "an open picker alone leaves the frame in view");
|
||||
|
||||
// A press alone changes nothing; dragging the saturation/value square uses the picker.
|
||||
let square = u.ctx.read_response(egui::Id::unique("cp_sv")).expect("the saturation/value square").rect;
|
||||
let from = square.center();
|
||||
let to = from + egui::vec2(12.0, 8.0);
|
||||
u.button(from, true);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "holding the palette still leaves the frame");
|
||||
u.frame(vec![egui::Event::PointerMoved(to)]);
|
||||
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "dragging the palette hides the frame");
|
||||
u.button(to, false);
|
||||
assert_eq!(u.app.ui.picker, Some(target), "releasing does not close the picker");
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "releasing brings the frame back");
|
||||
|
||||
// A button in the picker (the blend dropdown) is a click, not a value drag.
|
||||
let button = egui::pos2(square.center().x, square.min.y - 30.0);
|
||||
u.button(button, true);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "holding a picker button leaves the frame");
|
||||
u.button(button, false);
|
||||
}
|
||||
|
||||
// The picker's header is its drag handle: moving the card is not choosing a colour.
|
||||
#[test]
|
||||
fn dragging_the_picker_by_its_header_does_not_hide_the_selection() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let accent = crate::theme::canvas_accent(&u.ctx);
|
||||
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let header = u.app.ui.picker_popover.as_ref().expect("the picker is open").header.center();
|
||||
let before = u.app.ui.picker_popover.as_ref().unwrap().rect;
|
||||
u.button(header, true);
|
||||
for k in 1..=5 {
|
||||
u.frame(vec![egui::Event::PointerMoved(header - egui::vec2(0.0, 6.0 * k as f32))]);
|
||||
}
|
||||
assert!(u.app.ui.picker_popover.as_ref().unwrap().rect.min.y < before.min.y - 10.0, "the header drag moved the picker");
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "moving the picker leaves the frame in view");
|
||||
u.button(header - egui::vec2(0.0, 30.0), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texts_coloured_selection_hides_only_while_its_colour_picker_is_used() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
// Select all of it: the selection highlight the colour picker's own layer would otherwise wear.
|
||||
figcraft_engine::textedit::begin(&mut s, text, None, false).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let tint = crate::theme::canvas_accent(&u.ctx).gamma_multiply(0.3);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "the text selection is tinted");
|
||||
|
||||
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "an open picker alone leaves it tinted");
|
||||
|
||||
let square = u.ctx.read_response(egui::Id::unique("cp_sv")).expect("the saturation/value square").rect;
|
||||
let from = square.center();
|
||||
let to = from + egui::vec2(10.0, 6.0);
|
||||
u.button(from, true);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "holding the palette still leaves the tint");
|
||||
u.frame(vec![egui::Event::PointerMoved(to)]);
|
||||
assert_eq!(painted_around(&u.frame_output(vec![]), area, tint), 0, "dragging the palette hides the tint");
|
||||
u.button(to, false);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "releasing brings the tint back");
|
||||
}
|
||||
|
||||
// Typing a colour value counts as using the picker even when no mouse button is down.
|
||||
#[test]
|
||||
fn a_focused_colour_field_hides_the_selection_while_it_is_edited() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let accent = crate::theme::canvas_accent(&u.ctx);
|
||||
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "the frame shows while the picker is idle");
|
||||
|
||||
let hex = u.ctx.read_response(egui::Id::unique("cp_hex").with("click")).expect("the Hex field").rect;
|
||||
u.button(hex.center(), true);
|
||||
u.button(hex.center(), false);
|
||||
for _ in 0..2 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "a focused value field hides the frame");
|
||||
u.frame(vec![egui::Event::Text("0".into())]);
|
||||
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "and typing in it keeps the frame hidden");
|
||||
}
|
||||
|
||||
// egui gives every clicked control the keyboard, a palette square and a swatch included. Only a
|
||||
// text field means the picker is being used: a square that keeps focus must not keep the
|
||||
// selection hidden after its drag ends.
|
||||
#[test]
|
||||
fn a_focused_palette_square_does_not_hide_the_selection() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let accent = crate::theme::canvas_accent(&u.ctx);
|
||||
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
// What egui does to a clicked square.
|
||||
u.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("cp_sv")));
|
||||
for _ in 0..2 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "focus on a palette square leaves the frame in view");
|
||||
}
|
||||
@@ -141,11 +141,11 @@ fn choose_mode(u: &mut Ui, shown: &str, item: &str) {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
|
||||
/// Crop chosen as the image fill's mode in the colour picker enters crop mode, as Crop image does
|
||||
/// (#2150): the picker closes, the picture keeps its place, and a corner handle then crops it
|
||||
/// with the layer still selected. The other modes only set the mode.
|
||||
/// Crop chosen as the image fill's mode in the colour picker sets the mode with a placement crop
|
||||
/// (#2499): the picker stays open, crop mode on the canvas does not start, and dragging a corner
|
||||
/// handle without Cmd resizes the layer and morphs/squishes the image.
|
||||
#[test]
|
||||
fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
|
||||
fn crop_chosen_in_the_colour_picker_sets_mode_and_morphs_on_resize() {
|
||||
let (mut u, layer, _) = setup();
|
||||
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] });
|
||||
for _ in 0..4 {
|
||||
@@ -155,8 +155,8 @@ fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
|
||||
assert_eq!(mode(&u, layer), (ImageScaleMode::Fit, None));
|
||||
assert!(u.app.ui.picker.is_some() && u.app.ui.crop.is_none(), "Fit is only a mode");
|
||||
choose_mode(&mut u, "Fit", "Crop");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "crop mode on the image fill");
|
||||
assert!(u.app.ui.picker.is_none(), "crop mode takes the canvas from the picker");
|
||||
assert_eq!(u.app.ui.crop, None, "Crop in picker does not enter canvas crop mode");
|
||||
assert!(u.app.ui.picker.is_some(), "picker stays open");
|
||||
// The picture keeps its place: the crop is the one Crop image makes of the fitted image.
|
||||
let (m, Some(before)) = mode(&u, layer) else { panic!("a crop where the picture was") };
|
||||
assert_eq!(m, ImageScaleMode::Crop);
|
||||
@@ -169,29 +169,18 @@ fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
|
||||
assert_eq!(mode(&menu, other), (ImageScaleMode::Fit, None));
|
||||
menu.app.run("image.crop", json!({}));
|
||||
assert_eq!(mode(&menu, other), (ImageScaleMode::Crop, Some(before)));
|
||||
// The bottom right corner, dragged in, crops the picture to the top left 3/4 of the layer.
|
||||
// Close the picker to drag the canvas resize handles.
|
||||
u.app.ui.picker = None;
|
||||
u.frame(vec![]);
|
||||
// Dragging the bottom right corner without Cmd resizes the layer to 150x75 and morphs/squishes the image.
|
||||
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(150.0, 75.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
assert_eq!(u.app.session.selection(), vec![layer], "the layer stays selected");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!((n.width - 150.0).abs() < 1e-6 && (n.height - 75.0).abs() < 1e-6, "{} x {}", n.width, n.height);
|
||||
let (_, Some(after)) = mode(&u, layer) else { panic!("a crop") };
|
||||
assert!((after[0] - before[0] * 0.75).abs() < 1e-9 && (after[3] - before[3] * 0.75).abs() < 1e-9, "{before:?} -> {after:?}");
|
||||
assert!((after[4] - before[4]).abs() < 1e-9 && (after[5] - before[5]).abs() < 1e-9, "the top left stays: {before:?} -> {after:?}");
|
||||
// The picture's own corner, now outside the layer at (200, 100), scales the picture inside the
|
||||
// layer, which keeps its size and its selection.
|
||||
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(240.0, 120.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
assert_eq!(u.app.session.selection(), vec![layer], "the layer stays selected");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!((n.width - 150.0).abs() < 1e-6 && (n.height - 75.0).abs() < 1e-6, "the layer keeps its size: {} x {}", n.width, n.height);
|
||||
let (_, Some(scaled)) = mode(&u, layer) else { panic!("a crop") };
|
||||
// The picture grew from 200 x 100 to 240 x 120: the layer shows 5/6 of what it showed.
|
||||
assert!((scaled[0] - after[0] * 5.0 / 6.0).abs() < 1e-6 && (scaled[3] - after[3] * 5.0 / 6.0).abs() < 1e-6, "{after:?} -> {scaled:?}");
|
||||
assert_eq!(after, before, "normal resize without Cmd leaves crop transform unchanged to morph/squish");
|
||||
}
|
||||
|
||||
/// The reporter's sequence (#2307): the colour picker open on an image fill held in Crop mode
|
||||
@@ -206,12 +195,7 @@ fn crop_from_the_colour_picker_then_a_drag_on_the_image_moves_the_crop_not_the_l
|
||||
u.frame(vec![]);
|
||||
}
|
||||
choose_mode(&mut u, "Fill", "Crop");
|
||||
// Crop mode on the canvas ended (a click away from the image); the picker opens on the Crop fill.
|
||||
u.app.ui.crop = None;
|
||||
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] });
|
||||
for _ in 0..4 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(u.app.ui.picker.is_some());
|
||||
let (_, Some(before)) = mode(&u, layer) else { panic!("a crop") };
|
||||
let at = u.app.session.doc().unwrap().node(layer).unwrap().transform.as_coeffs();
|
||||
let from = u.app.to_screen(100.0, 50.0);
|
||||
@@ -267,7 +251,7 @@ fn image_at(u: &Ui, id: NodeId, fills: bool, region: Option<usize>) -> figcraft_
|
||||
/// fill have nothing for Crop image to crop either.
|
||||
#[test]
|
||||
fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply() {
|
||||
use crate::colorpicker::{PickerTarget, crop_on_canvas};
|
||||
use crate::colorpicker::PickerTarget;
|
||||
let picture = |u: &Ui, id: NodeId| u.app.session.doc().unwrap().node(id).unwrap().fills[0].clone();
|
||||
// Opens the picker on `target`, chooses Crop and checks crop mode stays off.
|
||||
let crop_only_sets_the_mode = |u: &mut Ui, target: PickerTarget, what: &str| {
|
||||
@@ -288,7 +272,7 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
|
||||
assert_eq!(image_at(&u, layer, false, None).scale_mode, ImageScaleMode::Crop);
|
||||
assert_eq!(mode(&u, layer), (ImageScaleMode::Fill, None), "the fill is untouched");
|
||||
|
||||
// Two image layers at once: both take the mode.
|
||||
// Two image layers at once: both take the mode, with each layer's crop sized to its own dimensions.
|
||||
let (mut u, layer, rect) = setup();
|
||||
let paint = picture(&u, layer);
|
||||
u.app.run("fill.set", json!({"ids": [rect], "index": 0, "paint": paint}));
|
||||
@@ -296,6 +280,8 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
|
||||
crop_only_sets_the_mode(&mut u, PickerTarget::Paint { fills: true, index: 0, ids: vec![layer, rect] }, "two layers");
|
||||
assert_eq!(mode(&u, layer).0, ImageScaleMode::Crop);
|
||||
assert_eq!(mode(&u, rect).0, ImageScaleMode::Crop);
|
||||
let (crop1, crop2) = (mode(&u, layer).1.unwrap(), mode(&u, rect).1.unwrap());
|
||||
assert_ne!(crop1, crop2, "differently sized layers must have distinct placement crops without stretching");
|
||||
|
||||
// A region's own image fill in vector edit mode: the region's mode is set, the layer's image
|
||||
// fill is untouched.
|
||||
@@ -313,12 +299,133 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
|
||||
crop_only_sets_the_mode(&mut u, PickerTarget::Paint { fills: true, index: 0, ids: vec![vector] }, "a region");
|
||||
assert_eq!(image_at(&u, vector, true, Some(1)).scale_mode, ImageScaleMode::Crop);
|
||||
assert_eq!(u.app.session.doc().unwrap().node(vector).unwrap().fills, layer_fills, "the layer's fills are untouched");
|
||||
}
|
||||
|
||||
// A fill that isn't an image, and targets that aren't a layer's paint, have no crop on the canvas.
|
||||
let (u, layer, rect) = setup();
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] }), Some((layer, 0)));
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 0, ids: vec![rect] }), None, "a solid fill");
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 1, ids: vec![layer] }), None, "no fill there");
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::PageBackground), None);
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Style { id: "S:1".into(), index: 0 }), None);
|
||||
#[test]
|
||||
fn in_crop_mode_the_edges_of_an_image_in_auto_layout_crop_it_too() {
|
||||
let (mut u, layer, _) = setup();
|
||||
let column = id(&u.app.session.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap());
|
||||
u.app.run("node.reparent", json!({"ids": [layer], "parent": column}));
|
||||
u.app.run("node.set", json!({"ids": [column], "props": {"layout": "vertical", "sizingV": "hug"}}));
|
||||
u.app.run("select.set", json!({"ids": [layer]}));
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let (_, Some(before)) = mode(&u, layer) else { panic!("a crop") };
|
||||
let (from, to) = (u.app.to_screen(100.0, 100.0), u.app.to_screen(100.0, 60.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!((n.height - 60.0).abs() < 1e-6 && (n.width - 200.0).abs() < 1e-6, "the bottom edge moved up: {} x {}", n.width, n.height);
|
||||
let (m, Some(after)) = mode(&u, layer) else { panic!("a crop") };
|
||||
assert_eq!(m, ImageScaleMode::Crop);
|
||||
assert!((after[3] - before[3] * 0.6).abs() < 1e-9 && (after[0] - before[0]).abs() < 1e-9, "cropped, not squashed: {before:?} -> {after:?}");
|
||||
assert!((after[5] - before[5]).abs() < 1e-9, "the top stays: {before:?} -> {after:?}");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_in_crop_mode_keeps_cropping_and_vector_edit_ends_crop_mode() {
|
||||
let (mut u, layer, _) = setup();
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let at = u.app.to_screen(100.0, 50.0);
|
||||
for _ in 0..2 {
|
||||
u.button(at, true);
|
||||
u.button(at, false);
|
||||
}
|
||||
u.frame(vec![]);
|
||||
assert!(u.app.session.ds().unwrap().vector_edit.is_none(), "a double-click while cropping doesn't edit the points");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
let (from, to) = (u.app.to_screen(200.0, 50.0), u.app.to_screen(150.0, 50.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!((n.width - 150.0).abs() < 1e-6 && matches!(n.kind, figcraft_doc::NodeKind::Rectangle), "the side crops; the layer stays a rectangle");
|
||||
u.app.run("vector.edit.begin", json!({"id": layer}));
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.ui.crop, None, "editing the points ends crop mode");
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
assert!(u.app.session.ds().unwrap().vector_edit.is_none(), "cropping ends editing the points");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)));
|
||||
}
|
||||
|
||||
/// The second press of a double-click on a side of the layer begins a resize; its release, which
|
||||
/// is the double-click, ends it, and crop mode stays.
|
||||
#[test]
|
||||
fn a_double_click_on_a_side_in_crop_mode_leaves_no_resize_open() {
|
||||
let (mut u, layer, _) = setup();
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let at = u.app.to_screen(200.0, 50.0);
|
||||
for _ in 0..2 {
|
||||
u.button(at, true);
|
||||
u.button(at, false);
|
||||
}
|
||||
u.frame(vec![]);
|
||||
assert!(u.app.session.ds().unwrap().interaction.is_none(), "the resize the second press began is over");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_crop_mode_the_images_corners_scale_freely_and_with_shift_in_proportion() {
|
||||
let image_size = |u: &Ui, layer: NodeId| {
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
let (_, Some(c)) = mode(u, layer) else { panic!("a crop") };
|
||||
let (x0, y0, x1, y1) = figcraft_color::ImagePaint::crop_rect(c);
|
||||
((x1 - x0) * n.width, (y1 - y0) * n.height)
|
||||
};
|
||||
for shift in [false, true] {
|
||||
let (mut u, layer, _) = setup();
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let (from, to) = (u.app.to_screen(200.0, 50.0), u.app.to_screen(150.0, 50.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
let (w0, h0) = image_size(&u, layer);
|
||||
let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE };
|
||||
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(260.0, 110.0));
|
||||
u.frame_with(
|
||||
vec![Event::PointerMoved(from), Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }],
|
||||
modifiers,
|
||||
);
|
||||
for k in 1..=10 {
|
||||
u.frame_with(vec![Event::PointerMoved(from + (to - from) * (k as f32 / 10.0))], modifiers);
|
||||
}
|
||||
u.frame_with(vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }], modifiers);
|
||||
let (w1, h1) = image_size(&u, layer);
|
||||
let kept = (w1 / h1 - w0 / h0).abs() < 1e-6;
|
||||
assert!(w1 > w0, "the corner scaled the image: {w0}x{h0} -> {w1}x{h1}");
|
||||
assert_eq!(kept, shift, "Shift {shift}: {w0}x{h0} -> {w1}x{h1}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_auto_layout_a_side_dragged_past_the_image_leaves_no_empty_strip() {
|
||||
let mut s = Session::new();
|
||||
let image = image::RgbaImage::from_fn(300, 200, |x, y| image::Rgba([(x % 255) as u8, (y % 255) as u8, 120, 255]));
|
||||
let mut png = std::io::Cursor::new(Vec::new());
|
||||
image.write_to(&mut png, image::ImageFormat::Png).unwrap();
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(png.into_inner());
|
||||
let content = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 1092, "height": 1400})).unwrap());
|
||||
id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 300, "height": 160, "parent": content})).unwrap());
|
||||
let layer = id(&s.execute("image.place", &json!({"data": data, "x": 0, "y": 300, "width": 804, "height": 969})).unwrap());
|
||||
s.execute("node.reparent", &json!({"ids": [layer], "parent": content})).unwrap();
|
||||
s.execute("node.set", &json!({"ids": [content], "props": {"layout": "vertical", "sizingV": "hug", "padding": [112, 0, 100, 0]}})).unwrap();
|
||||
s.execute("node.set", &json!({"ids": [layer], "props": {"constrainProportions": true}})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [layer]})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.app.run("view.set", json!({"zoom": 0.5, "cx": 546, "cy": 700}));
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let b = u.app.session.doc().unwrap().world_bounds(layer).unwrap();
|
||||
let (from, to) = (u.app.to_screen(400.0, b.y0), u.app.to_screen(400.0, b.y0 - 120.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
let (_, Some(c)) = mode(&u, layer) else { panic!("a crop") };
|
||||
let (x0, y0, x1, y1) = figcraft_color::ImagePaint::crop_rect(c);
|
||||
assert!(x0 <= 1e-9 && y0 <= 1e-9 && x1 >= 1.0 - 1e-9 && y1 >= 1.0 - 1e-9, "the image covers the layer: {:?}", (x0, y0, x1, y1));
|
||||
assert!(n.width >= 1.0 && n.height >= 1.0, "{} x {}", n.width, n.height);
|
||||
assert!(u.app.session.ds().unwrap().vector_edit.is_none());
|
||||
}
|
||||
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user