Merge main into #2121

This commit is contained in:
bflatastic committed 2026-11-12 09:30:04 +07:00
commit 34b2bba9d3
49 files changed
+4291 -62

No files matched your search

+38
View File
@@ -886,6 +886,25 @@ impl TextData {
}
pl.indent = pl.indent.min(MAX_LIST_INDENT);
}
self.fold_paragraph_lists();
}
/// Give paragraphs `a..=b` (by index) no start number of their own, as an item made by Enter
/// has none. Touches nothing else: a plain paragraph keeps its level, a bullet its settings.
/// One pass over the range, and nothing at all when no paragraph carries a start.
pub fn clear_list_starts(&mut self, a: usize, b: usize) {
if self.paragraphs.iter().all(|p| p.start_offset == 0) {
return;
}
self.fill_paragraphs();
for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) {
pl.start_offset = 0;
}
self.fold_paragraph_lists();
}
/// One style for all paragraphs with no nesting or start folds back into `list`.
fn fold_paragraph_lists(&mut self) {
if let Some(first) = self.paragraphs.first().copied()
&& first == (ParaList { list: first.list, ..ParaList::default() })
&& self.paragraphs.iter().all(|p| *p == first)
@@ -1104,6 +1123,25 @@ mod case_tests {
t.set_para_lists(0, 0, |p| p.list = P);
assert_eq!(t.para_list(0), ParaList::default());
}
#[test]
fn clear_list_starts_touches_only_starts() {
use ListStyle::{None as P, Numbered as N};
let mut t = TextData { characters: "a\nb\nc".into(), ..Default::default() };
t.paragraphs = vec![
ParaList { list: N, start_offset: 4, ..ParaList::default() },
ParaList { list: P, indent: 1, ..ParaList::default() },
ParaList { list: N, indent: 2, start_offset: 7, ..ParaList::default() },
];
t.clear_list_starts(1, 2);
assert_eq!(t.para_list(0).start_offset, 4, "outside the range");
assert_eq!(t.para_list(1), ParaList { list: P, indent: 1, ..ParaList::default() }, "a plain paragraph keeps its level");
assert_eq!(t.para_list(2), ParaList { list: N, indent: 2, start_offset: 0, ..ParaList::default() });
// Out of range and no-start cases leave it alone.
t.clear_list_starts(5, 9);
t.clear_list_starts(0, 0);
assert_eq!(t.para_list(0).start_offset, 0);
}
}
#[cfg(test)]
+97
View File
@@ -69,3 +69,100 @@ fn grid_drag_takes_the_cell_under_the_pointer() {
let cl = s.doc().unwrap().node(kids[0]).unwrap().child_layout.clone();
assert_eq!((cl.grid_column, cl.grid_row), (None, None), "one undo step");
}
/// Three 60 x 60 rectangles in a row (or column), gap 20, at 0, 80 and 160 along the flow.
fn three(s: &mut Session, mode: &str) -> (NodeId, [NodeId; 3]) {
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 300})).unwrap());
let kids: Vec<NodeId> =
(0..3).map(|_| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 60, "height": 60, "parent": f})).unwrap())).collect();
s.execute("layout.add", &json!({"ids": [f]})).unwrap();
s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed"}})).unwrap();
s.execute("select.none", &json!({})).unwrap();
(f, [kids[0], kids[1], kids[2]])
}
/// The order after dragging kid `which` by `by` along the flow, grabbed `grab` from its start edge.
fn dragged_order(mode: &str, which: usize, grab: f64, by: f64) -> Vec<usize> {
let mut s = Session::new();
let (f, kids) = three(&mut s, mode);
let vertical = mode == "vertical";
let b = s.doc().unwrap().world_bounds(kids[which]).unwrap();
let from = if vertical { (b.center().x, b.y0 + grab) } else { (b.x0 + grab, b.center().y) };
let to = if vertical { (from.0, from.1 + by) } else { (from.0 + by, from.1) };
drag(&mut s, from, to);
let order = s.doc().unwrap().node(f).unwrap().children.clone();
order.iter().map(|c| kids.iter().position(|k| k == c).unwrap()).collect()
}
#[test]
fn a_child_dragged_right_passes_a_sibling_when_its_leading_edge_reaches_the_siblings_middle() {
assert_eq!(dragged_order("horizontal", 0, 30.0, 49.0), vec![0, 1, 2]);
assert_eq!(dragged_order("horizontal", 0, 30.0, 50.0), vec![1, 0, 2]);
assert_eq!(dragged_order("horizontal", 0, 30.0, 129.0), vec![1, 0, 2]);
assert_eq!(dragged_order("horizontal", 0, 30.0, 130.0), vec![1, 2, 0]);
}
#[test]
fn where_the_child_is_grabbed_does_not_change_its_slot() {
assert_eq!(dragged_order("horizontal", 0, 10.0, 49.0), vec![0, 1, 2]);
assert_eq!(dragged_order("horizontal", 0, 10.0, 50.0), vec![1, 0, 2]);
assert_eq!(dragged_order("horizontal", 0, 10.0, 129.0), vec![1, 0, 2]);
assert_eq!(dragged_order("horizontal", 0, 10.0, 130.0), vec![1, 2, 0]);
}
#[test]
fn a_child_dragged_left_passes_a_sibling_by_its_left_edge() {
assert_eq!(dragged_order("horizontal", 2, 30.0, -49.0), vec![0, 1, 2]);
assert_eq!(dragged_order("horizontal", 2, 30.0, -50.0), vec![0, 2, 1]);
assert_eq!(dragged_order("horizontal", 2, 30.0, -130.0), vec![2, 0, 1]);
}
#[test]
fn a_column_reorders_by_the_bottom_edge() {
assert_eq!(dragged_order("vertical", 0, 30.0, 50.0), vec![1, 0, 2]);
assert_eq!(dragged_order("vertical", 0, 30.0, 130.0), vec![1, 2, 0]);
}
#[test]
fn a_child_dragged_left_passes_the_second_sibling_one_pixel_later() {
assert_eq!(dragged_order("horizontal", 2, 30.0, -129.0), vec![0, 2, 1]);
}
#[test]
fn a_column_reorders_at_the_boundaries_both_ways() {
assert_eq!(dragged_order("vertical", 0, 30.0, 49.0), vec![0, 1, 2]);
assert_eq!(dragged_order("vertical", 0, 30.0, 129.0), vec![1, 0, 2]);
assert_eq!(dragged_order("vertical", 2, 30.0, -49.0), vec![0, 1, 2]);
assert_eq!(dragged_order("vertical", 2, 30.0, -50.0), vec![0, 2, 1]);
assert_eq!(dragged_order("vertical", 2, 30.0, -129.0), vec![0, 2, 1]);
assert_eq!(dragged_order("vertical", 2, 30.0, -130.0), vec![2, 0, 1]);
}
#[test]
fn a_drag_with_no_move_along_the_flow_keeps_the_slot() {
// Back at the start, and a drag across the flow only, with snapping on (the default).
assert_eq!(dragged_order("horizontal", 1, 30.0, 0.0), vec![0, 1, 2]);
assert_eq!(dragged_order("vertical", 1, 30.0, 0.0), vec![0, 1, 2]);
let mut s = Session::new();
let (f, kids) = three(&mut s, "horizontal");
let b = s.doc().unwrap().world_bounds(kids[1]).unwrap();
let from = (b.center().x, b.center().y);
drag(&mut s, from, (from.0, from.1 + 40.0));
let order = s.doc().unwrap().node(f).unwrap().children.clone();
assert_eq!(order, kids.to_vec());
}
#[test]
fn several_dragged_children_use_their_combined_box() {
// Kids 0 and 1 together span 0..140; moved right by 49 the leading edge is at 189, just short of the middle of kid 2 (190).
for (by, expected) in [(49.0, vec![0, 1, 2]), (50.0, vec![2, 0, 1])] {
let mut s = Session::new();
let (f, kids) = three(&mut s, "horizontal");
s.execute("select.set", &json!({"ids": [kids[0], kids[1]]})).unwrap();
let b = s.doc().unwrap().world_bounds(kids[0]).unwrap();
let from = (b.center().x, b.center().y);
drag(&mut s, from, (from.0 + by, from.1));
let order: Vec<usize> = s.doc().unwrap().node(f).unwrap().children.iter().map(|c| kids.iter().position(|k| k == c).unwrap()).collect();
assert_eq!(order, expected, "by {by}");
}
}
+186 -22
View File
@@ -12,6 +12,11 @@
//! existing folder is resolved and the rest must be plain names. The comparison is by whole
//! components (`/work2` is not inside `/work`), and the I/O uses the resolved path, so what was
//! checked is what is opened.
//!
//! On Windows, resolving a path opens it, and opening a path on another computer contacts that
//! computer and may send it the signed-in user's credentials. So on Windows, before anything is
//! resolved, a path on another computer whose share no root is on, a device path, or one reached
//! through a link that leads to them is refused by how it is spelled (#1094).
#![allow(clippy::disallowed_methods)]
use std::cell::RefCell;
@@ -19,6 +24,8 @@ use std::ffi::{OsStr, OsString};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use craft_docpath::Refused;
use crate::{EngineError, Result};
/// What a command does with a file.
@@ -58,6 +65,19 @@ impl Roots {
Access::Read => ([self.read.as_slice(), self.write.as_slice()].concat(), "read"),
Access::Write => (self.write.clone(), "written"),
};
if cfg!(windows) {
match refused_unresolved(path, &roots) {
Some(Unresolved::Spelled(Refused::Network)) => {
return Err(format!(
"automation path rejected: {asked} is on another computer, and no folder that may be {what} is on its share"
));
}
Some(Unresolved::Spelled(_)) => return Err(format!("automation path rejected: {asked} names a device, not a file")),
// Where a link leads is only told by the usual message: it would say what is there.
Some(Unresolved::Linked) => return Err(outside(asked, &roots, what)),
None => {}
}
}
match resolve(path) {
Ok(resolved) if roots.iter().any(|r| resolved.starts_with(r)) => return Ok(resolved),
Ok(_) => {}
@@ -65,11 +85,7 @@ impl Roots {
Err(why) if inside_as_far_as_it_exists(path, &roots) => return Err(format!("automation path rejected: {asked}: {why}")),
Err(_) => {}
}
if roots.is_empty() {
return Err(format!("automation path rejected: no folder may be {what} (no root for it was given): {asked}"));
}
let shown: Vec<String> = roots.iter().map(|r| shown(r)).collect();
Err(format!("automation path rejected: {asked} is outside the folders that may be {what}: {}", shown.join(", ")))
Err(outside(asked, &roots, what))
}
/// The folders as JSON, resolved: `{read: [every folder that may be read], write: [the write roots]}`.
@@ -79,23 +95,165 @@ impl Roots {
}
}
/// Why `asked` is refused: it is outside every one of `roots`, the folders that may be `what`
/// ("read" or "written"). The message lists those folders, or says that no folder may be `what`
/// when `roots` is empty.
fn outside(asked: std::path::Display<'_>, roots: &[PathBuf], what: &str) -> String {
if roots.is_empty() {
return format!("automation path rejected: no folder may be {what} (no root for it was given): {asked}");
}
let shown: Vec<String> = roots.iter().map(|r| shown(r)).collect();
format!("automation path rejected: {asked} is outside the folders that may be {what}: {}", shown.join(", "))
}
/// Why a path is refused before it is resolved (#1094).
#[derive(Debug, PartialEq, Eq)]
enum Unresolved {
/// Its spelling leads to another computer ([`Refused::Network`]) or a device ([`Refused::Device`]).
Spelled(Refused),
/// A link on the way leads there, or the way there can't be looked at: a link or folder on it
/// can't be read, it has more than [`MAX_LINKS`] links, or the path can't be made absolute.
Linked,
}
/// How many links are followed on the way to a path before it is given up on, as on Linux.
const MAX_LINKS: u8 = 40;
/// Why `path` is refused before anything on the way to it is opened, if it is: resolving it would
/// open a path on another computer, which on Windows contacts that computer and may send it the
/// signed-in user's credentials, or open a device (#1094). That is the case when the path as
/// given or made absolute is refused by its spelling ([`refused_spelling`]), or when a link on
/// the way, or on the way on from where one leads, leads to such a path ([`link_refused`]). A path
/// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute
/// is refused as well, rather than left to what comes next.
fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option<Unresolved> {
// Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a
// bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes
// `..` by name, so `link\..\x` is `x` and never goes through the link.
let Ok(abs) = std::path::absolute(path) else { return Some(Unresolved::Linked) };
if let Some(why) = [path, abs.as_path()].into_iter().find_map(|p| refused_spelling(&p.to_string_lossy(), roots)) {
return Some(Unresolved::Spelled(why));
}
link_refused(&abs, roots, MAX_LINKS, &on_disk).then_some(Unresolved::Linked)
}
/// What is at a path, looked at without following a link there.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Entry {
/// Nothing ([`nothing_there`]): resolving the path meets the same there and goes no further.
Missing,
/// Something that can't be looked at (no permission, for one). It may be a link that resolving
/// the path would still follow, so the path is refused.
Unreadable,
/// A file or a folder.
Plain,
/// A link, with where it leads (`None` when that can't be read).
Link(Option<PathBuf>),
}
/// What is at `p` on disk (see [`Entry`]), looked at with [`std::fs::symlink_metadata`], which
/// doesn't follow a link there; a link's target is read with [`std::fs::read_link`].
fn on_disk(p: &Path) -> Entry {
match std::fs::symlink_metadata(p) {
Ok(m) if m.is_symlink() => Entry::Link(std::fs::read_link(p).ok()),
Ok(_) => Entry::Plain,
Err(e) if nothing_there(&e) => Entry::Missing,
Err(_) => Entry::Unreadable,
}
}
/// Whether looking at a path failed with `e` because nothing is there: no such name, a file where
/// a folder was expected, or a name no file can have. Any other failure says nothing about what is
/// there.
fn nothing_there(e: &std::io::Error) -> bool {
use std::io::ErrorKind::{InvalidFilename, NotADirectory, NotFound};
matches!(e.kind(), NotFound | NotADirectory | InvalidFilename)
}
/// Why path `p` is refused by its spelling alone, if it is (see [`craft_docpath::resolve`], which
/// reads both `/` and `\` as separators and compares names ignoring case):
/// - on another computer (`\\server\share`, `//server/share`, `\\?\UNC\…`, `\\.\UNC\…`, or a
/// server without a share) and on no root's share;
/// - a device path (`\\.\pipe\…`, `\\?\GLOBALROOT\…`, `\\.\C:\…`), other than a local volume's
/// `\\?\Volume{…}\` or `\\.\Volume{…}\`, which a folder can be mounted as;
/// - or with a device name (`CON`, `NUL`, `COM1.png`, `lpt1 `…) as any of its names: each folder on
/// the way is opened in turn while the path is resolved, and the device behind a name such as
/// `LPT1` can be a printer on another computer.
fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option<Refused> {
match craft_docpath::resolve(p, None) {
// With a root passed as the document path (what a link would be relative to), a path on
// that root's share is allowed.
Err(Refused::Network) if !roots.iter().any(|r| craft_docpath::resolve(p, Some(r)) != Err(Refused::Network)) => {
return Some(Refused::Network);
}
Err(Refused::Device) if !is_volume(p) => return Some(Refused::Device),
_ => {}
}
// `craft_docpath` stops at the first name it refuses, which may not be the device's.
p.split(['\\', '/']).any(device_name).then_some(Refused::Device)
}
/// Whether `p` is in a local volume by its `\\?\Volume{…}` (or `\\.\Volume{…}`) name.
fn is_volume(p: &str) -> bool {
let mut names = p.split(['\\', '/']);
let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else {
return false;
};
volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}')
}
/// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`]
/// refuses, following at most `links` links: one that leads to another, or on through further
/// links, is followed too, as resolving the path would. A link that can't be read, a name on the
/// way that can't be looked at ([`Entry::Unreadable`]), or more links than that, are refused as
/// well. Each name on the way is looked at with `look` ([`on_disk`]), which doesn't follow a
/// link: where a link leads is looked at only once its spelling is known not to be refused.
fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -> Entry) -> bool {
let mut at = PathBuf::new();
let mut rest = abs.components();
while let Some(c) = rest.next() {
at.push(c);
if !matches!(c, Component::Normal(_)) {
continue;
}
let target = match look(&at) {
Entry::Plain => continue,
// Nothing is below what isn't there, so no link either.
Entry::Missing => return false,
Entry::Unreadable => return true,
Entry::Link(target) => target,
};
let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true };
// A relative target is relative to the link's folder; an absolute one replaces it.
let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path()));
return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look);
}
false
}
/// `p` with its `.` and `..` taken by name, as Windows takes them.
fn lexical(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::ParentDir => {
out.pop();
}
Component::CurDir => {}
c => out.push(c),
}
}
out
}
/// Whether `path` lies in one of `roots` once made absolute with its `.` and `..` taken by name and
/// its longest leading part that exists resolved, so links on the way are followed as the roots'
/// were (`/tmp/work/x` is inside root `/private/tmp/work`, a link out of a root leads out of it).
fn inside_as_far_as_it_exists(path: &Path, roots: &[PathBuf]) -> bool {
let Ok(abs) = std::path::absolute(path) else { return false };
let mut lexical = PathBuf::new();
for c in abs.components() {
match c {
Component::ParentDir => {
lexical.pop();
}
Component::CurDir => {}
c => lexical.push(c),
}
}
let folded = lexical(&abs);
let mut rest: Vec<&OsStr> = Vec::new();
let mut at = lexical.as_path();
let mut at = folded.as_path();
let resolved = loop {
if let Ok(mut base) = std::fs::canonicalize(at) {
base.extend(rest.iter().rev());
@@ -169,18 +327,24 @@ fn resolve(path: &Path) -> std::result::Result<PathBuf, String> {
fn plain_name(name: &OsStr) -> std::result::Result<(), String> {
if cfg!(windows) {
let n = name.to_string_lossy();
let stem = n.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
&& stem.chars().count() == 4
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')));
if device || n.contains(':') {
if device_name(&n) || n.contains(':') {
return Err(format!("`{n}` is a device or stream name, not a file"));
}
}
Ok(())
}
/// Whether Windows opens a device for file or folder name `n`: `CON`, `PRN`, `AUX`, `NUL`,
/// `CONIN$`, `CONOUT$`, `COM1`…`COM9` and `LPT1`…`LPT9` (also with `¹`, `²` or `³`), in any case,
/// and with anything after a dot or a colon or trailing spaces (`nul.txt`, `COM1 .png`, `con:x`).
fn device_name(n: &str) -> bool {
let stem = n.split(['.', ':']).next().unwrap_or_default().trim_end().to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
&& stem.chars().count() == 4
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')))
}
thread_local! {
static ROOTS: RefCell<Option<Arc<Roots>>> = const { RefCell::new(None) };
}
@@ -191,6 +191,283 @@ fn windows_case_devices_and_streams() {
assert!(!e.contains(r"\\?\"), "{e}");
}
/// How each spelling of a path on another computer or of a device is told apart from a local path
/// (#1094), on every system: only Windows checks them, but they are spelled the same everywhere.
#[test]
fn spellings_of_other_computers_and_devices_are_refused() {
use super::refused_spelling;
use craft_docpath::Refused::{Device, Network};
let local = [PathBuf::from(r"C:\work")];
// On `\\192.0.2.1\share`.
let on_the_share = [
r"\\192.0.2.1\share\x.png",
"//192.0.2.1/share/x.png",
r"\/192.0.2.1/share\x.png",
r"\\?\UNC\192.0.2.1\share\x.png",
r"\\?\unc\192.0.2.1\share\x.png",
"//?/UNC/192.0.2.1/share/x.png",
r"\\.\UNC\192.0.2.1\share\x.png",
];
let elsewhere = [
// A server without a share is contacted too.
r"\\192.0.2.1",
r"\\192.0.2.1\",
r"\\SERVER.\share \x.png",
];
let network = [&on_the_share[..], &elsewhere[..]].concat();
let device = [
r"\\.\pipe\figcraft",
r"\\?\GLOBALROOT\Device\Mup\192.0.2.1\share\x.png",
r"\\.\C:\work\x.png",
r"\\.\COM1",
r"\??\UNC\192.0.2.1\share\x.png",
// A device name anywhere: each folder on the way is opened as the path is resolved.
r"C:\work\COM1",
r"C:\work\nul.txt",
r"C:\work\Com1 .png",
r"C:\work\lpt1.\x.png",
r"C:\work\LPT³\x.png",
r"C:\work\conout$",
r"C:\work\aux:stream",
// After a name `craft_docpath` refuses for another reason.
r"C:\work\a:b\prn.png",
];
let fine = [
r"C:\work\x.png",
r"\\?\C:\work\x.png",
r"C:\work\console.png",
r"C:\work\com10.png",
r"C:\work\lpt.png",
r"C:\work\nul-ish.txt",
r"\\?\Volume{0b3b1c63-0000-0000-0000-100000000000}\x.png",
r"\\.\Volume{0b3b1c63-0000-0000-0000-100000000000}\x.png",
"/home/u/work/x.png",
"x.png",
r"..\x.png",
];
for (paths, want) in [(&network[..], Some(Network)), (&device[..], Some(Device)), (&fine[..], None)] {
for p in paths {
assert_eq!(refused_spelling(p, &[]), want, "{p}");
assert_eq!(refused_spelling(p, &local), want, "{p} with a local root");
}
}
// A root on a share lets the paths on that share through, in any case and spelling, and only them:
// every spelling above of a path on `\\192.0.2.1\share`, but not the server without a share
// or another server.
for root in [r"\\?\UNC\192.0.2.1\share", r"\\192.0.2.1\share\work"] {
let on_share = [PathBuf::from(root)];
for p in on_the_share {
assert_eq!(refused_spelling(p, &on_share), None, "{p} with root {root}");
}
for p in elsewhere {
assert_eq!(refused_spelling(p, &on_share), Some(Network), "{p} with root {root}");
}
}
let shared = [PathBuf::from(r"\\?\UNC\Server\Share\work")];
for p in [r"\\server\SHARE\work\x.png", r"\\?\UNC\SERVER\share\elsewhere\x.png", "//Server/Share/work/x.png"] {
assert_eq!(refused_spelling(p, &shared), None, "{p}");
}
for p in [r"\\server\other\x.png", r"\\other\share\x.png", r"\\server", r"\\server.\share\x.png"] {
assert_eq!(refused_spelling(p, &shared), Some(Network), "{p}");
}
assert_eq!(refused_spelling(r"\\server\share\work\COM1", &shared), Some(Device));
}
/// The links on the way to a path are followed by their spelling before anything they lead to is
/// opened (#1094). The links are made up here, so this runs where tests may not make links.
#[test]
fn links_on_the_way_are_followed_by_their_spelling_first() {
use super::{Entry, MAX_LINKS, link_refused};
use std::cell::RefCell;
use std::collections::HashMap;
let base = std::env::temp_dir().join("figcraft-links");
let at = |rel: &str| base.join(rel);
let mut links: HashMap<PathBuf, Option<PathBuf>> = HashMap::from([
// Relative to the link's folder, to a device name.
(at("root/dev"), Some(PathBuf::from("../outside/nul"))),
// To another link.
(at("root/hop"), Some(at("root/dev"))),
// Within the root.
(at("root/alias"), Some(PathBuf::from("sub"))),
(at("root/loop"), Some(at("root/loop"))),
(at("root/unreadable"), None),
// Below a name that isn't there: never looked at.
(at("missing/dev"), Some(PathBuf::from("nul"))),
]);
if cfg!(windows) {
links.insert(at("root/remote"), Some(PathBuf::from(r"\\192.0.2.1\share")));
links.insert(at("root/far"), Some(at("root/remote/work")));
}
// Chains of `n` links, `root/<n>-1` to `root/<n>-2` and so on, the last one to `root/sub`.
for n in [MAX_LINKS - 1, MAX_LINKS, MAX_LINKS + 1] {
for i in 1..=n {
let next = if i == n { at("root/sub") } else { at(&format!("root/{n}-{}", i + 1)) };
links.insert(at(&format!("root/{n}-{i}")), Some(next));
}
}
let plain = [at("root"), at("root/sub"), at("outside")];
// What can't be looked at (no permission, say) may be a link, so it isn't taken for nothing.
let unreadable = at("root/locked");
let looked = RefCell::new(Vec::new());
let look = |p: &Path| {
looked.borrow_mut().push(p.to_path_buf());
match links.get(p) {
Some(target) => Entry::Link(target.clone()),
None if base.starts_with(p) || plain.iter().any(|q| q == p) => Entry::Plain,
None if p == unreadable => Entry::Unreadable,
None => Entry::Missing,
}
};
let refused = |rel: &str, roots: &[PathBuf]| link_refused(&at(rel), roots, MAX_LINKS, &look);
for rel in ["root/dev/x.png", "root/hop/x.png", "root/loop/x.png", "root/unreadable/x.png", "root/locked/x.png", "root/locked"] {
assert!(refused(rel, &[]), "{rel}");
}
for rel in ["root/alias/x.png", "root/sub/x.png", "root/x.png", "missing/dev/x.png"] {
assert!(!refused(rel, &[]), "{rel}");
}
// As many links as are followed lead on; one more is refused.
assert!(!refused(&format!("root/{}-1/x.png", MAX_LINKS - 1), &[]));
assert!(!refused(&format!("root/{MAX_LINKS}-1/x.png"), &[]));
assert!(refused(&format!("root/{}-1/x.png", MAX_LINKS + 1), &[]));
// A refused target isn't looked at, nor is anything below what isn't there.
let looked = looked.take();
assert!(!looked.contains(&at("outside/nul")) && !looked.contains(&at("missing/dev")), "{looked:?}");
if cfg!(windows) {
for rel in ["root/remote/x.png", "root/far/x.png"] {
assert!(refused(rel, &[]), "{rel}");
// Unless a root is on that share.
assert!(!refused(rel, &[PathBuf::from(r"\\?\UNC\192.0.2.1\share")]), "{rel}");
}
}
}
/// A path that can't be looked at is refused rather than taken for one with nothing there (#1094):
/// only a failure that says nothing is there lets the walk stop, and a path that can't even be
/// made absolute isn't left to the checks after it.
#[test]
fn what_cannot_be_looked_at_is_refused() {
use super::{Unresolved, nothing_there, refused_unresolved};
use std::io::{Error, ErrorKind};
for kind in [ErrorKind::NotFound, ErrorKind::NotADirectory, ErrorKind::InvalidFilename] {
assert!(nothing_there(&Error::from(kind)), "{kind:?}");
}
for kind in [ErrorKind::PermissionDenied, ErrorKind::ResourceBusy, ErrorKind::Interrupted, ErrorKind::Other] {
assert!(!nothing_there(&Error::from(kind)), "{kind:?}");
}
assert_eq!(refused_unresolved(Path::new(""), &[]), Some(Unresolved::Linked));
}
/// On Windows a path is classified as Windows opens it (#1094): with `..` taken by name before
/// anything is opened (so a link followed by `..` is never gone through), and with names that
/// aren't Unicode (a lone surrogate) still read for the parts that are spelled in ASCII.
#[cfg(windows)]
#[test]
fn paths_are_classified_as_windows_opens_them() {
use super::{Unresolved, refused_unresolved};
use craft_docpath::Refused::{Device, Network};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
assert_eq!(std::path::absolute(r"C:\work\remote\..\x.png").unwrap(), PathBuf::from(r"C:\work\x.png"));
// `before`, a lone surrogate, then `after`.
let odd = |before: &str, after: &str| {
let wide: Vec<u16> = before.encode_utf16().chain([0xD800]).chain(after.encode_utf16()).collect();
PathBuf::from(OsString::from_wide(&wide))
};
assert_eq!(refused_unresolved(&odd(r"\\192.0.2.1\share\", ".png"), &[]), Some(Unresolved::Spelled(Network)));
assert_eq!(refused_unresolved(&odd(r"C:\figcraft-no-such-folder\", r"\nul"), &[]), Some(Unresolved::Spelled(Device)));
assert_eq!(refused_unresolved(&odd(r"C:\figcraft-no-such-folder\", ".png"), &[]), None);
// A NUL can't be passed to Windows at all, so the path can't be made absolute.
assert_eq!(refused_unresolved(Path::new("C:\\work\\a\0b.png"), &[]), Some(Unresolved::Linked));
}
/// `..` after a link is taken by name, by the check and by Windows when it opens the path, so
/// `root\j\..\in.txt` is `root\in.txt` and the link `j` is never gone through (#1094). Shown with
/// a junction, a link any account can make: `j` leads out of the root to `outside`, and beside
/// `outside` is another `in.txt`, which is what `..` would reach through the link.
#[cfg(windows)]
#[test]
fn a_parent_after_a_link_is_taken_by_name() {
use super::{Entry, on_disk};
let f = Fixture::new("parent");
let r = f.rw();
std::fs::write(f.0.join("in.txt"), b"beside").unwrap();
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(f.0.join(r"root\j")).arg(f.0.join("outside")).output();
assert!(made.is_ok_and(|o| o.status.success()), "a junction can be made");
// The junction is a link to the check, and what is through it is outside.
assert!(matches!(on_disk(&f.0.join(r"root\j")), Entry::Link(Some(_))));
assert!(r.check(Path::new(&f.p(r"root\j\secret.txt")), Access::Read).is_err());
let through = f.p(r"root\j\..\in.txt");
assert_eq!(r.check(Path::new(&through), Access::Read), r.check(Path::new(&f.p(r"root\in.txt")), Access::Read));
assert!(r.check(Path::new(&through), Access::Read).is_ok());
assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root");
}
/// A path on another computer and a device path are refused before anything is opened: resolving
/// them made Windows contact the server, which may send it the signed-in user's credentials
/// (#1094). Each is refused with a message that only the check before resolving gives: had the
/// path been resolved, 192.0.2.1 (an address for documentation, where nothing answers) would have
/// been contacted and the message would be the one for a path that can't be resolved.
#[cfg(windows)]
#[test]
fn other_computers_and_devices_are_refused_before_anything_is_opened() {
let f = Fixture::new("network");
let r = f.rw();
let read_only = Roots::new(&[f.p("root")], &[]).unwrap();
let refused = |roots: &Roots, p: &str, access: Access| roots.check(Path::new(p), access).expect_err(p);
for p in
[r"\\192.0.2.1\share\x.png", "//192.0.2.1/share/x.png", r"\\?\UNC\192.0.2.1\share\x.png", r"\\.\UNC\192.0.2.1\share\x.png", r"\\192.0.2.1"]
{
for access in [Access::Read, Access::Write] {
let e = refused(&r, p, access);
assert!(e.contains("is on another computer, and no folder that may be"), "{p}: {e}");
}
let e = refused(&read_only, p, Access::Write);
assert!(e.ends_with("is on another computer, and no folder that may be written is on its share"), "{p}: {e}");
}
for p in [r"\\.\pipe\figcraft-roots", r"\\?\GLOBALROOT\Device\Mup\192.0.2.1\share\x.png", &f.p(r"root\COM1\x.png"), "nul"] {
for access in [Access::Read, Access::Write] {
let e = refused(&r, p, access);
assert!(e.ends_with("names a device, not a file"), "{p}: {e}");
}
}
// Local paths, in either spelling, are checked as before.
let inside = std::fs::canonicalize(f.p("root")).unwrap().join("in.txt");
assert!(r.check(&inside, Access::Read).is_ok());
assert!(r.check(Path::new(&f.p(r"root\in.txt")), Access::Read).is_ok());
}
/// A link in a root to another computer is refused before it is followed (#1094), also through
/// another link, and with the message any path outside gets: it doesn't tell where the link
/// leads. Had the link been followed, the message would be the one for a path that can't be
/// resolved. This needs real links, which Windows lets only some accounts make: elsewhere it
/// says so and checks nothing (`links_on_the_way_are_followed_by_their_spelling_first` covers the
/// same walk with made-up links on every system).
#[cfg(windows)]
#[test]
fn links_to_other_computers_are_refused_before_they_are_followed() {
let f = Fixture::new("network-links");
let r = f.rw();
if !symlink_dir(Path::new(r"\\192.0.2.1\share"), &f.0.join("root/remote")) || !symlink_dir(&f.0.join("root/remote/work"), &f.0.join("root/hop")) {
eprintln!("skipped: this system doesn't let tests make symbolic links");
return;
}
// Relative to the link's folder.
assert!(symlink_dir(Path::new(r"..\remote"), &f.0.join("root/sub/up")));
assert!(symlink_file(Path::new(r"\\.\pipe\figcraft-roots"), &f.0.join("root/pipe")));
let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be");
for p in [f.p("root/remote/x.png"), f.p("root/hop/x.png"), f.p("root/sub/up/x.png"), f.p("root/pipe")] {
for access in [Access::Read, Access::Write] {
let e = r.check(Path::new(&p), access).expect_err(&p);
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
}
}
// `..` after the link is taken by name, so the link isn't gone through.
assert!(r.check(Path::new(&f.p(r"root\remote\..\in.txt")), Access::Read).is_ok());
// A link to a folder in the root still leads there.
assert!(symlink_dir(&f.0.join("root/sub"), &f.0.join("root/alias")));
assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok());
}
#[test]
fn a_scope_confines_the_thread_and_ends_with_it() {
let f = Fixture::new("scope");
+37 -5
View File
@@ -20,6 +20,32 @@ pub struct DropSlot {
/// placed child whose centre is past the pointer, and the line to draw there. Hidden children and
/// those ignoring auto layout don't take part.
pub fn auto_layout_slot(doc: &Document, parent: NodeId, p: Point, exclude: &[NodeId]) -> Option<(usize, Option<[f64; 4]>)> {
slot_in(doc, parent, p, exclude, None)
}
/// [`auto_layout_slot`] for layers dragged within their own frame (measured in Figma's web app,
/// 2026-11-09): the slot follows the leading edge of `moved` in the direction of `delta`. The caller
/// passes `moved` as the layers' combined start bounds plus the raw (unsnapped) drag, and `delta`
/// as that same drag on the page; only its sign along the flow axis matters, and a zero delta uses
/// the low edge. Wrapping layouts keep the pointer rule.
pub fn auto_layout_slot_within(
doc: &Document,
parent: NodeId,
p: Point,
exclude: &[NodeId],
moved: figcraft_geom::Rect,
delta: Point,
) -> Option<(usize, Option<[f64; 4]>)> {
slot_in(doc, parent, p, exclude, Some((moved, delta)))
}
fn slot_in(
doc: &Document,
parent: NodeId,
p: Point,
exclude: &[NodeId],
dragged: Option<(figcraft_geom::Rect, Point)>,
) -> Option<(usize, Option<[f64; 4]>)> {
let pn = doc.node(parent)?;
let layout = pn.layout.as_ref()?;
let vertical = layout.mode == LayoutMode::Vertical;
@@ -34,11 +60,17 @@ pub fn auto_layout_slot(doc: &Document, parent: NodeId, p: Point, exclude: &[Nod
let (k, line) = wrap_slot(doc, &flow_ids, p, vertical);
return Some((index(k), line));
}
let pos = if vertical { p.y } else { p.x };
let k = flow_ids
.iter()
.position(|c| doc.world_bounds(*c).is_some_and(|b| pos < if vertical { b.center().y } else { b.center().x }))
.unwrap_or(flow_ids.len());
let mid = |c: &NodeId| doc.world_bounds(*c).map(|b| if vertical { b.center().y } else { b.center().x });
let k = if let Some((r, d)) = dragged {
let (lo, hi, dd) = if vertical { (r.y0, r.y1, d.y) } else { (r.x0, r.x1, d.x) };
// Forward: past every sibling whose middle the leading (high) edge has reached; backward: past
// every one whose middle lies before the leading (low) edge. A zero delta (no move along the
// flow) takes the backward rule, which leaves the layers where they were.
flow_ids.iter().position(|c| mid(c).is_some_and(|m| if dd > 0.0 { m > hi } else { m >= lo })).unwrap_or(flow_ids.len())
} else {
let pos = if vertical { p.y } else { p.x };
flow_ids.iter().position(|c| mid(c).is_some_and(|m| pos < m)).unwrap_or(flow_ids.len())
};
let line = flow_ids.get(k).and_then(|c| doc.world_bounds(*c)).map(|b| line_before(b, vertical, 2.0)).or_else(|| {
flow_ids
.last()
+30 -5
View File
@@ -284,32 +284,57 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result<ImeInse
let text = normalized;
edit(s, |t, te| {
let (a, b) = range(te);
// "- ", "* ", "1. " or "1) " typed at the start of a plain paragraph starts a list (the
// creation characters of Create bulleted and numbered lists).
// "- ", "* ", "<number>. " or "1) " typed at the start of a plain paragraph starts a list
// (the creation characters of Create bulleted and numbered lists). As measured in Figma
// (2026-11-11), a typed "5. " starts the numbered list at 5 (there is no start-number
// field). "0. " and a bracket after a number other than 1 are not measured: plain text.
if text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None {
let chars: Vec<char> = t.characters.chars().collect();
let start = line_start(&chars, a);
let typed: String = chars.get(start..a).unwrap_or(&[]).iter().collect();
let mut first = 1_u32;
let list = match typed.as_str() {
"-" | "*" => ListStyle::Bulleted,
"1." | "1)" => ListStyle::Numbered,
_ => ListStyle::None,
"1)" => ListStyle::Numbered,
_ => match typed.strip_suffix('.').filter(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())) {
Some(d) => match d.parse::<u32>() {
Ok(n) if (1..=MAX_TYPED_LIST_START).contains(&n) => {
first = n;
ListStyle::Numbered
}
_ => ListStyle::None,
},
None => ListStyle::None,
},
};
if list != ListStyle::None {
t.replace_range(start, a, "");
t.set_para_lists(start, start, |pl| pl.list = list);
t.set_para_lists(start, start, |pl| {
pl.list = list;
pl.start_offset = first - 1;
});
(te.caret, te.anchor) = (start, start);
outcome = ImeInsertion::Transformed;
return;
}
}
t.replace_range(a, b, &text);
// As measured in Figma (2026-11-11): an item made by Enter has no start of its own, so
// unlisting the item before it makes it restart at 1 rather than at the copied start.
// Every paragraph after the first that the insertion made loses the start it was copied.
if text.contains('\n') {
let end = a + text.chars().count();
t.clear_list_starts(t.para_of(a) + 1, t.para_of(end));
}
te.caret = a + text.chars().count();
te.anchor = te.caret;
})?;
Ok(outcome)
}
/// The largest number a typed `N. ` can start a numbered list at.
const MAX_TYPED_LIST_START: u32 = 9999;
/// What a list key does to the selected items.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ListMove {
+14 -2
View File
@@ -216,6 +216,8 @@ impl Session {
}
}
// Cmd/Ctrl (and Control on macOS) held while dragging suspends snapping.
// The pointer's own drag, before snapping: a reorder in auto layout follows it.
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) {
@@ -268,8 +270,18 @@ impl Session {
// cell) under the pointer, as the frame shows it now. A frame other than the
// one they come from is outlined too.
let cell = if mode == LayoutMode::Grid { crate::drop::grid_cell_at(doc, target, p) } else { None };
let idx =
if mode == LayoutMode::Grid { 0 } else { crate::drop::auto_layout_slot(doc, target, p, &moving).map_or(0, |(i, _)| i) };
// Within the frame they came from, the slot follows the leading edge of the
// box they would fill (their combined start bounds moved by the drag), not
// the pointer. The preview starts from the document as the drag began.
let within = moving.iter().all(|m| doc.node(*m).is_some_and(|n| n.parent == Some(target)));
let idx = if mode == LayoutMode::Grid {
0
} else if let (true, Some(b)) = (within, doc.bounds_of(&moving)) {
let moved = Rect::new(b.x0 + raw.x, b.y0 + raw.y, b.x1 + raw.x, b.y1 + raw.y);
crate::drop::auto_layout_slot_within(doc, target, p, &moving, moved, Point::new(raw.x, raw.y)).map_or(0, |(i, _)| i)
} else {
crate::drop::auto_layout_slot(doc, target, p, &moving).map_or(0, |(i, _)| i)
};
for m in &moving {
if doc.get(*m)?.parent != Some(target) {
doc.reparent(*m, target, None)?;
+9 -2
View File
@@ -24,8 +24,8 @@ 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};
use variants::{add_variant, combine};
pub use variants::{can_add_variant, can_combine_variants};
use variants::{add_variant, combine, create_set};
pub use variants::{can_add_variant, can_combine_variants, can_create_set};
/// `component.hideWhenPublishing`: the leading `.` of the names of this file's components and
/// sets (those `ids` are or are in), put on or taken off.
@@ -72,6 +72,13 @@ pub fn specs() -> Vec<CommandSpec> {
s.set_selection(out.iter().filter_map(id_of).collect());
Ok(json!({"ids": out}))
}),
spec!(
"component.createSet",
"Create component set",
"{ids? (layers, not components, sets or instances)} (each becomes a component, wrapped in place in a component set: variants \"Property 1=<name>\" left to right, 20 px around)",
true,
create_set
),
spec!(
"component.combineVariants",
"Combine as variants",
+71 -2
View File
@@ -1,6 +1,6 @@
use super::{
BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, inside_instance, json, owning_instance,
req_targets, roots, set_name_from, string, targets, variant_name, variant_options, variant_props, variant_set, z_sorted,
BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, create, id_of, inside_instance, json,
owning_instance, req_targets, roots, set_name_from, string, targets, variant_name, variant_options, variant_props, variant_set, z_sorted,
};
/// Wrap components in a new component set (named after the first) placed around them.
@@ -94,6 +94,75 @@ pub(super) fn combine(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"id": set}))
}
/// Why `ids` (distinct) can't each become a component of a new set (`component.createSet`), or
/// `None` when they can: layers inside an instance, library copies, instances, components and
/// component sets, and a layer inside another one of `ids`.
fn create_set_refusal(doc: &Document, ids: &[NodeId]) -> Option<&'static str> {
if ids.iter().any(|i| inside_instance(doc, *i)) {
Some("layers inside an instance can't become components")
} else if ids.iter().any(|i| doc.is_remote(*i)) {
Some(crate::library::READ_ONLY)
} else if ids.iter().any(|i| {
doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Instance { .. } | NodeKind::Component { .. } | NodeKind::ComponentSet { .. }))
}) {
Some("select layers that aren't components, component sets or instances")
} else if roots(doc, ids).len() != ids.len() {
Some("a layer can't be in a set with one inside it")
} else {
None
}
}
/// Whether "Create component set" is on offer for `ids`: at least one layer that
/// [`create_set_refusal`] lets through.
pub fn can_create_set(doc: &Document, ids: &[NodeId]) -> bool {
let distinct: Vec<NodeId> = ids.iter().copied().collect::<BTreeSet<_>>().into_iter().collect();
!distinct.is_empty() && distinct.iter().all(|i| doc.contains(*i)) && create_set_refusal(doc, &distinct).is_none()
}
/// `component.createSet`: each target becomes a component (as `component.createMultiple` makes
/// them) and all are wrapped in place in a component set, 20 px around, named as Figma names them:
/// variants "Property 1=<layer name>" in left-to-right order (a name holding `=` is kept); layers
/// that all share a name give a set of that name with "Property 1=Default" variants; otherwise the
/// set is "Component N".
pub(super) fn create_set(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.createSet";
let mut seen = BTreeSet::new();
let ids: Vec<NodeId> = req_targets(cmd, s, p)?.into_iter().filter(|i| seen.insert(*i)).collect();
let doc = s.doc()?;
if let Some(why) = create_set_refusal(doc, &ids) {
return Err(EngineError::Disabled(cmd.into(), why.into()));
}
let mut made = Vec::new();
for i in roots(doc, &ids) {
let r = create(s, &json!({"ids": [i]}))?;
made.push(id_of(&r["id"]).ok_or_else(|| bad(cmd, "component creation failed"))?);
}
let doc = s.doc_mut()?;
// Left to right by world x, ties by y: the variants' order, and the values' order.
let mut by_x: Vec<(NodeId, f64, f64)> = made.iter().map(|i| doc.world_bounds(*i).map_or((*i, 0.0, 0.0), |b| (*i, b.x0, b.y0))).collect();
by_x.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.2.total_cmp(&b.2)));
let names: Vec<String> = by_x.iter().map(|(i, ..)| doc.node(*i).map(|n| n.name.clone()).unwrap_or_default()).collect();
let same = names.windows(2).all(|w| w.first() == w.get(1)) && names.first().is_some_and(|n| !n.is_empty() && !n.contains('='));
let set_name = match names.first() {
Some(n) if same => n.clone(),
_ => doc.next_name("Component"),
};
for ((i, ..), name) in by_x.iter().zip(&names) {
let node = doc.get_mut(*i)?;
if same {
node.name = "Property 1=Default".into();
} else if !name.contains('=') {
node.name = format!("Property 1={name}");
}
}
let ordered = z_sorted(doc, &made);
let set = wrap_in_set(cmd, doc, &ordered)?;
doc.get_mut(set)?.name = set_name;
s.set_selection(vec![set]);
Ok(json!({"id": set}))
}
/// 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) {
let Some(kids) = doc.node(set).map(|n| n.children.clone()) else { return };
+1 -1
View File
@@ -245,7 +245,7 @@ pub(super) fn stroke_brush(s: &mut Session, p: &Value) -> Result<Value> {
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 = num(p, "index").map(|i| i.max(0.0) as usize);
let index = opt_index("node.reparent", p, "index")?;
let doc = s.doc_mut()?;
let ids = z_sorted(doc, &roots(doc, &ids));
// `index` is where the first moved layer ends up among the parent's children (bottom first),
+14 -3
View File
@@ -1,7 +1,7 @@
use super::load::{ext, write};
use super::save::thumbnail;
use super::*;
use crate::params::f64_of;
use crate::params::{f64_of, req_targets};
/// Encode `ids` (or the page) in `format` at `scale`.
pub fn export_bytes(doc: &Document, ids: &[NodeId], format: ExportFormat, scale: f64) -> Result<Vec<u8>> {
@@ -86,7 +86,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
_ => {}
}
let doc = s.doc()?;
let mut ids = targets(s, p);
let mut ids = export_targets(cmd, s, p)?;
if ids.is_empty() {
ids = doc.get(s.page()?)?.children.clone();
}
@@ -325,11 +325,22 @@ pub fn exportable_layers(doc: &Document, page: NodeId) -> Vec<NodeId> {
doc.subtree(page).into_iter().skip(1).filter(|i| doc.node(*i).is_some_and(|n| !n.exports.is_empty())).collect()
}
/// Named layers (`ids` / `id`), checked like other commands; empty when none are named, so the
/// caller can fall back to its default instead of silently dropping a bad id.
fn export_targets(cmd: &str, s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let named = match get(p, "ids") {
Some(Value::Array(a)) if !a.is_empty() => true,
Some(Value::Array(_) | Value::Null) | None => get(p, "id").is_some_and(|v| !v.is_null()),
Some(_) => true,
};
if named { req_targets(cmd, s, p) } else { Ok(targets(s, p)) }
}
pub(super) fn export_layers(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.exportLayers";
let doc = s.doc()?;
let assets = boolean(p, "assets").unwrap_or(false);
let mut ids = targets(s, p);
let mut ids = export_targets(cmd, s, p)?;
if ids.is_empty() {
ids = if assets { vec![s.page()?] } else { exportable_layers(doc, s.page()?) };
}
@@ -7,6 +7,7 @@
use serde_json::{Value, json};
use crate::Session;
use crate::automation::params::id_of;
use crate::components::tests::{chars, copy_of, ex, fill, healthy, idv, kids, node};
use figcraft_doc::*;
@@ -1000,3 +1001,245 @@ fn deleting_a_layer_inside_an_instance_hides_it_instead() {
s.execute("edit.delete", &json!({"ids": [k.inst]})).unwrap();
assert!(s.doc().unwrap().node(k.inst).is_none());
}
/// Create multiple components (#2088): each selected layer becomes its own component in place,
/// keeping its name and position; all stay selected and one undo reverts them all.
#[test]
fn create_multiple_components_keeps_names_and_places_and_is_one_undo_step() {
let mut s = Session::new();
let mut frames = Vec::new();
for (i, name) in ["Card", "Badge", "Tile"].into_iter().enumerate() {
let x = 150.0 * i as f64;
let v = s.execute("frame.create", &json!({"x": x, "y": 20, "width": 100, "height": 60})).unwrap();
let f = id_of(&v["id"]).unwrap();
s.execute("object.rename", &json!({"ids": [f], "name": name})).unwrap();
frames.push(f);
}
let before = undo_len(&s);
let out = s.execute("component.createMultiple", &json!({"ids": frames})).unwrap();
assert_eq!(undo_len(&s), before + 1, "one undo step");
let made: Vec<NodeId> = out["ids"].as_array().unwrap().iter().filter_map(id_of).collect();
assert_eq!(made.len(), 3);
assert_eq!(s.selection(), made, "all of them stay selected");
let doc = s.doc().unwrap();
for (i, (c, name)) in made.iter().zip(["Card", "Badge", "Tile"]).enumerate() {
let n = doc.node(*c).unwrap();
assert!(matches!(n.kind, NodeKind::Component { .. }), "{name} is a component");
assert_eq!(n.name, name);
let b = doc.world_bounds(*c).unwrap();
assert_eq!((b.x0, b.y0), (150.0 * i as f64, 20.0), "{name} stays in place");
}
s.undo().unwrap();
let doc = s.doc().unwrap();
assert!(frames.iter().all(|f| matches!(doc.node(*f).map(|n| &n.kind), Some(NodeKind::Frame))), "one undo restores the frames");
}
/// Frames named `names` at x = 150 * i (mirrored when `reverse`), y 20, 100 x 60.
fn named_frames(s: &mut Session, names: &[&str], reverse: bool) -> Vec<NodeId> {
let n = names.len();
names
.iter()
.enumerate()
.map(|(i, name)| {
let x = 150.0 * if reverse { n - 1 - i } else { i } as f64;
let v = s.execute("frame.create", &json!({"x": x, "y": 20, "width": 100, "height": 60})).unwrap();
let f = id_of(&v["id"]).unwrap();
s.execute("object.rename", &json!({"ids": [f], "name": name})).unwrap();
f
})
.collect()
}
/// The set's name and its children's names in layer order.
fn set_names(s: &Session, set: NodeId) -> (String, Vec<String>) {
let doc = s.doc().unwrap();
let n = doc.node(set).unwrap();
(n.name.clone(), n.children.iter().map(|c| doc.node(*c).unwrap().name.clone()).collect())
}
/// The set's variant names ordered by world x.
fn names_by_x(s: &Session, set: NodeId) -> Vec<String> {
let doc = s.doc().unwrap();
let mut v: Vec<(f64, String)> =
doc.node(set).unwrap().children.iter().map(|c| (doc.world_bounds(*c).unwrap().x0, doc.node(*c).unwrap().name.clone())).collect();
v.sort_by(|a, b| a.0.total_cmp(&b.0));
v.into_iter().map(|(_, n)| n).collect()
}
/// Create component set (#2088, measured in Figma): variants "Property 1=<name>" in left-to-right
/// order, the set "Component 1", wrapped in place 20 px around, selected, one undo step.
#[test]
fn create_set_names_variants_by_layer_name_and_wraps_in_place() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Primary", "Secondary", "Ghost"], false);
let before = undo_len(&s);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
assert_eq!(undo_len(&s), before + 1, "one undo step");
let set = id_of(&out["id"]).unwrap();
assert_eq!(s.selection(), vec![set], "the set is selected");
assert_eq!(set_names(&s, set).0, "Component 1");
assert_eq!(names_by_x(&s, set), ["Property 1=Primary", "Property 1=Secondary", "Property 1=Ghost"]);
let doc = s.doc().unwrap();
for (i, c) in doc.node(set).unwrap().children.iter().enumerate() {
assert!(matches!(doc.node(*c).unwrap().kind, NodeKind::Component { .. }));
let b = doc.world_bounds(*c).unwrap();
assert_eq!((b.x0, b.y0), (150.0 * i as f64, 20.0), "frames stay put");
}
let sb = doc.world_bounds(set).unwrap();
assert_eq!((sb.x0, sb.y0, sb.x1, sb.y1), (-20.0, 0.0, 420.0, 100.0), "20 px on every side");
s.undo().unwrap();
let doc = s.doc().unwrap();
assert!(doc.node(set).is_none());
assert!(frames.iter().all(|f| matches!(doc.node(*f).map(|n| &n.kind), Some(NodeKind::Frame))), "one undo restores the frames");
}
#[test]
fn create_set_orders_left_to_right_whatever_the_selection_order() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["A", "B", "C"], true);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
let set = id_of(&out["id"]).unwrap();
assert_eq!(names_by_x(&s, set), ["Property 1=C", "Property 1=B", "Property 1=A"]);
let (_, kids) = set_names(&s, set);
assert_eq!(kids.len(), 3);
}
#[test]
fn create_set_keeps_names_already_in_prop_value_form() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Size=Small", "Size=Large", "Size=Medium"], false);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
let set = id_of(&out["id"]).unwrap();
assert_eq!(set_names(&s, set).0, "Component 1");
assert_eq!(names_by_x(&s, set), ["Size=Small", "Size=Large", "Size=Medium"]);
}
#[test]
fn create_set_with_one_shared_name_names_the_set_and_makes_default_variants() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Card", "Card", "Card"], false);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
let set = id_of(&out["id"]).unwrap();
let (name, kids) = set_names(&s, set);
assert_eq!(name, "Card");
assert_eq!(kids, ["Property 1=Default", "Property 1=Default", "Property 1=Default"]);
}
#[test]
fn create_set_refuses_instances_and_leaves_the_document_alone() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["A", "B"], false);
let c = s.execute("component.create", &json!({"ids": [frames[0]]})).unwrap();
let comp = id_of(&c["id"]).unwrap();
let inst = s.execute("instance.create", &json!({"component": comp})).unwrap();
let inst = id_of(&inst["id"]).unwrap();
let before = undo_len(&s);
let e = s.execute("component.createSet", &json!({"ids": [inst, frames[1]]})).unwrap_err();
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
assert_eq!(undo_len(&s), before);
assert!(matches!(s.doc().unwrap().node(frames[1]).unwrap().kind, NodeKind::Frame));
}
#[test]
fn create_set_refuses_a_target_inside_another_target_and_leaves_the_document_alone() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Outer", "Inner"], false);
s.execute("node.reparent", &json!({"ids": [frames[1]], "parent": frames[0]})).unwrap();
let before = undo_len(&s);
let e = s.execute("component.createSet", &json!({"ids": [frames[0], frames[1]]})).unwrap_err();
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
assert_eq!(undo_len(&s), before);
let doc = s.doc().unwrap();
assert!(matches!(doc.node(frames[0]).unwrap().kind, NodeKind::Frame));
assert!(matches!(doc.node(frames[1]).unwrap().kind, NodeKind::Frame));
}
/// Every node's id, parent, name and kind, to compare a document before and after a refused command.
fn snapshot(s: &Session) -> Vec<String> {
s.doc().unwrap().nodes().map(|n| format!("{:?}|{:?}|{}|{:?}", n.id, n.parent, n.name, n.kind)).collect()
}
/// A refused `component.createSet`: `Disabled`, no undo step, the document and the selection as they were.
fn assert_create_set_refused(s: &mut Session, ids: &[NodeId]) {
let (before, undo, selection) = (snapshot(s), undo_len(s), s.selection());
let e = s.execute("component.createSet", &json!({"ids": ids})).unwrap_err();
assert!(matches!(e, crate::EngineError::Disabled(..)), "{e:?}");
assert_eq!(undo_len(s), undo, "no undo step");
assert_eq!(snapshot(s), before, "the document is unchanged");
assert_eq!(s.selection(), selection, "the selection is unchanged");
}
/// Nothing to wrap is refused before anything is created.
#[test]
fn create_set_refuses_no_layers_and_leaves_the_document_alone() {
let mut s = Session::new();
named_frames(&mut s, &["A"], false);
s.execute("select.set", &json!({"ids": []})).unwrap();
assert_create_set_refused(&mut s, &[]);
}
/// One layer is allowed: a set of one variant, as many layers would make.
#[test]
fn create_set_with_one_layer_makes_a_one_variant_set() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["Solo"], false);
let before = undo_len(&s);
let out = s.execute("component.createSet", &json!({"ids": frames})).unwrap();
assert_eq!(undo_len(&s), before + 1, "one undo step");
let set = id_of(&out["id"]).unwrap();
let doc = s.doc().unwrap();
assert_eq!(doc.node(set).unwrap().children.len(), 1);
assert_eq!(names_by_x(&s, set), ["Property 1=Default"], "a lone layer shares its name with itself");
assert!(matches!(doc.node(doc.node(set).unwrap().children[0]).unwrap().kind, NodeKind::Component { .. }));
s.undo().unwrap();
assert!(matches!(s.doc().unwrap().node(frames[0]).unwrap().kind, NodeKind::Frame));
}
/// Each refusal branch of `create_set`, with `can_create_set` agreeing with it.
#[test]
fn create_set_refuses_every_ineligible_selection_and_leaves_the_document_alone() {
use crate::cmd::component::can_create_set;
let mut s = Session::new();
let frames = named_frames(&mut s, &["A", "B", "C"], false);
let comp = id_of(&s.execute("component.create", &json!({"ids": [frames[0]]})).unwrap()["id"]).unwrap();
let inst = id_of(&s.execute("instance.create", &json!({"component": comp})).unwrap()["id"]).unwrap();
let set_frames = named_frames(&mut s, &["V1", "V2"], false);
let set = id_of(&s.execute("component.createSet", &json!({"ids": set_frames})).unwrap()["id"]).unwrap();
// A layer inside the instance (its copy of the card's content).
let in_inst = s.doc().unwrap().node(inst).unwrap().children.first().copied();
// A library copy.
let remote = {
let doc = s.doc_mut().unwrap();
let store = doc.ensure_library_store();
let remote = doc.alloc_id();
doc.insert(Node::new(remote, NodeKind::Frame, "Remote", 10.0, 10.0), store, None).unwrap();
remote
};
let ok = frames[1];
assert!(can_create_set(s.doc().unwrap(), &[ok, frames[2]]));
assert!(!can_create_set(s.doc().unwrap(), &[]));
let mut cases = vec![("instance", inst), ("library copy", remote), ("component", comp), ("component set", set)];
if let Some(i) = in_inst {
cases.push(("inside an instance", i));
}
for (what, bad) in cases {
assert!(!can_create_set(s.doc().unwrap(), &[ok, bad]), "{what}: not offered");
assert_create_set_refused(&mut s, &[ok, bad]);
assert_create_set_refused(&mut s, &[bad]);
}
}
/// A command that fails leaves no trace: the checks before the creation loop catch every
/// refusal the loop's own commands could hit, and `Session::execute` restores the document, the
/// selection and the undo stack on any error, so no half-made components can survive.
#[test]
fn a_failing_create_set_leaves_no_components_behind() {
let mut s = Session::new();
let frames = named_frames(&mut s, &["A", "B"], false);
let (before, undo, selection) = (snapshot(&s), undo_len(&s), s.selection());
let e = s.execute("component.createSet", &json!({"ids": [frames[0], NodeId(u64::MAX)]}));
assert!(e.is_err());
assert_eq!(undo_len(&s), undo);
assert_eq!(snapshot(&s), before);
assert_eq!(s.selection(), selection);
}
@@ -384,3 +384,17 @@ fn copy_as_png_svg_and_code() {
let css = crate::codegen::code_for(doc, a, crate::codegen::CodeLang::Css);
assert!(css.contains("background: #FF0000;"), "Copy as CSS is the layer's CSS from Inspect");
}
#[test]
fn export_rejects_an_invalid_layer_id_instead_of_exporting_the_page() {
let mut s = Session::new();
let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0, "#ff0000", None);
ex(&mut s, "export.add", json!({"ids": [r]}));
for cmd in ["file.export", "file.exportLayers"] {
for p in [json!({"ids": ["abc"], "format": "svg"}), json!({"id": "abc", "format": "svg"}), json!({"ids": [], "id": "abc", "format": "svg"})] {
let res = s.execute(cmd, &p);
assert!(res.is_err(), "{cmd} {p} exported for an invalid id: {res:?}");
}
}
assert!(s.execute("file.export", &json!({"format": "svg"})).is_ok());
}
@@ -200,6 +200,22 @@ fn reparent_index_is_the_final_position_in_auto_layout_and_across_parents() {
assert!(kids(&s, row).is_empty());
}
#[test]
fn reparent_rejects_a_negative_or_fractional_index() {
let mut s = Session::new();
let frame = id(&ex(&mut s, "node.create", json!({"type": "frame", "name": "F"})));
let rect = |s: &mut Session, n: &str, parent: NodeId| id(&ex(s, "node.create", json!({"type": "rectangle", "name": n, "parent": parent})));
let (a, b) = (rect(&mut s, "a", frame), rect(&mut s, "b", frame));
let free = id(&ex(&mut s, "node.create", json!({"type": "rectangle", "name": "free"})));
for bad in [json!(-1), json!(1.5), json!("x")] {
let r = s.execute("node.reparent", &json!({"ids": [free], "parent": frame, "index": bad}));
assert!(r.is_err(), "index {bad} accepted");
assert_eq!(kids(&s, frame), [a, b], "the tree is unchanged for index {bad}");
}
ex(&mut s, "node.reparent", json!({"ids": [free], "parent": frame, "index": 0}));
assert_eq!(kids(&s, frame), [free, a, b]);
}
#[test]
fn renaming_several_layers_by_the_documented_codes() {
// Three layers named `names`, bottom to top; (names, params, new names, derivation).
+111 -1
View File
@@ -84,7 +84,11 @@ fn typed_list_starts() {
("- ", "", B, "hyphen and space: bullets"),
("* ", "", B, "asterisk and space: bullets"),
("1. ", "", N, "one, full stop, space: numbers"),
("2. ", "2. ", P, "silent: only 1. starts a numbered list"),
("2. ", "", N, "as measured in Figma: a typed number starts the list there"),
("0. ", "0. ", P, "zero is not measured: text"),
("12a. ", "12a. ", P, "digits only: text"),
("1) ", "", N, "one and a closing bracket: numbers"),
("2) ", "2) ", P, "silent: only 1) starts with a bracket"),
("a- ", "a- ", P, "not at the paragraph's start: text"),
("-x ", "-x ", P, "the space must follow the marker"),
];
@@ -108,6 +112,76 @@ fn typed_list_starts() {
assert_eq!((data(&s, t).characters.as_str(), lists(&s, t)), ("Intro\n- ", vec![(P, 0), (B, 0)]), "an item's own text stays text");
}
#[test]
fn typed_number_starts_the_list_there() {
// As measured in Figma (2026-11-11): typing "5. x", Enter, "y" reads 5. then 6.; the start
// is the typed number less one, and the next item goes on counting from it.
let mut s = Session::new();
let t = text(&mut s, "x");
s.execute("node.set", &json!({"id": t, "props": {"characters": ""}})).unwrap();
begin(&mut s, t, Some(0), false).unwrap();
for c in "5. x".chars() {
insert(&mut s, &c.to_string()).unwrap();
}
assert_eq!(data(&s, t).para_list(0).start_offset, 4, "5 starts at offset 4");
key(&mut s, "Enter", false, false, false).unwrap();
insert(&mut s, "y").unwrap();
crate::textedit::end(&mut s).unwrap();
let d = data(&s, t);
assert_eq!(d.characters, "x\ny");
assert_eq!(lists(&s, t), [(N, 0), (N, 0)]);
// An item made by Enter has no start of its own and goes on counting: 5. then 6.
assert_eq!((d.para_list(0).start_offset, d.para_list(1).start_offset), (4, 0), "the new item has no start");
s.undo().unwrap();
assert_eq!(data(&s, t).characters, "", "one undo step for the session");
assert_eq!(data(&s, t).para_list(0).start_offset, 0);
}
/// Type `first` ("5. a" style), then Enter, "b", Enter, "c", leaving the caret in "c".
fn three_typed_items(s: &mut Session, first: &str) -> NodeId {
let t = text(s, "x");
s.execute("node.set", &json!({"id": t, "props": {"characters": ""}})).unwrap();
begin(s, t, Some(0), false).unwrap();
for c in first.chars() {
insert(s, &c.to_string()).unwrap();
}
for step in ["Enter", "b", "Enter", "c"] {
if step == "Enter" {
key(s, step, false, false, false).unwrap();
} else {
insert(s, step).unwrap();
}
}
t
}
#[test]
fn a_list_split_by_unlisting_a_middle_item_restarts_at_one() {
// As measured in Figma (2026-11-11): typed "5. a", Enter, "b", Enter, "c" reads 5. 6. 7.;
// Backspace at the start of "b" takes its marker and "c" then reads 1., for "1. " too.
// `list_markers` counts on after a numbered item and restarts a numbered item that follows a
// plain paragraph at its own start, so the starts and the neighbours give the markers.
for (first, start) in [("5. a", 4), ("1. a", 0)] {
let mut s = Session::new();
let t = three_typed_items(&mut s, first);
assert_eq!(
data(&s, t).characters,
"a
b
c"
);
// The guard: unsplit, "b" and "c" go on counting (5. 6. 7.).
let d = data(&s, t);
assert_eq!(lists(&s, t), [(N, 0); 3], "{first}: no split");
assert_eq!((d.para_list(0).start_offset, d.para_list(1).start_offset, d.para_list(2).start_offset), (start, 0, 0), "{first}");
set_caret(&mut s, 2, false).unwrap();
key(&mut s, "Backspace", false, false, false).unwrap();
let d = data(&s, t);
assert_eq!(lists(&s, t), [(N, 0), (P, 0), (N, 0)], "{first}: split");
assert_eq!(d.para_list(2).start_offset, 0, "{first}: c restarts at 1 (the item made by Enter has no start)");
}
}
#[test]
fn list_keys_at_list_items() {
// (chars, lists before, caret, key, shift, chars after, lists after, derivation)
@@ -372,3 +446,39 @@ fn typing_a_creation_character_and_a_space_starts_a_list() {
}
assert_eq!((data(&s, t).characters.as_str(), lists(&s, t)), ("2) ", vec![(P, 0)]));
}
#[test]
fn splitting_a_plain_paragraph_that_kept_its_level_keeps_the_level() {
// Backspace at a nested item's start unlists it but keeps indent 1; Enter inside it then
// splits it, and neither half loses the level (the start reset changes only starts).
let mut s = Session::new();
let t = text(&mut s, "ab\ncd");
let ps = vec![ParaList { list: N, start_offset: 4, ..ParaList::default() }, ParaList { list: N, indent: 1, ..ParaList::default() }];
if let figcraft_doc::NodeKind::Text(td) = &mut s.doc_mut().unwrap().get_mut(t).unwrap().kind {
td.paragraphs = ps;
}
begin(&mut s, t, Some(3), false).unwrap();
key(&mut s, "Backspace", false, false, false).unwrap();
assert_eq!(lists(&s, t), [(N, 0), (P, 1)], "unlisted, level kept");
set_caret(&mut s, 4, false).unwrap();
key(&mut s, "Enter", false, false, false).unwrap();
assert_eq!(data(&s, t).characters, "ab\nc\nd");
assert_eq!(lists(&s, t), [(N, 0), (P, 1), (P, 1)], "both halves keep indent 1");
}
#[test]
fn a_many_line_paste_clears_every_created_start() {
let mut s = Session::new();
let t = text(&mut s, "x");
s.execute("node.set", &json!({"id": t, "props": {"characters": ""}})).unwrap();
begin(&mut s, t, Some(0), false).unwrap();
for c in "5. x".chars() {
insert(&mut s, &c.to_string()).unwrap();
}
let lines: Vec<String> = (0..2001).map(|i| format!("l{i}")).collect();
insert(&mut s, &lines.join("\n")).unwrap();
let d = data(&s, t);
assert_eq!(d.paragraph_count(), 2001);
assert_eq!(d.para_list(0).start_offset, 4, "the first item keeps its start");
assert!((1..d.paragraph_count()).all(|p| d.para_list(p).start_offset == 0 && d.para_list(p).list == N));
}
+10 -2
View File
@@ -93,8 +93,16 @@ fn list_numbering_by_level() {
vec!["\u{2022}", "\u{2022}", "\u{2022}", "\u{2022}"],
"bullets keep the same styling at all levels of indentation",
),
(vec![pl(N, 0), pl(N, 0), pl(P, 0), pl(N, 0)], vec!["1.", "2.", "", "1."], "silent: a plain paragraph ends a list, the next starts at 1"),
(vec![pl(N, 0), pl(B, 0), pl(N, 0)], vec!["1.", "\u{2022}", "1."], "silent: the other kind of list at the same level starts the count again"),
(
vec![pl(N, 0), pl(N, 0), pl(P, 0), pl(N, 0)],
vec!["1.", "2.", "", "1."],
"as measured in Figma (2026-11-11): a plain paragraph ends a list, the next starts at 1",
),
(
vec![pl(N, 0), pl(B, 0), pl(N, 0)],
vec!["1.", "\u{2022}", "1."],
"as measured in Figma (2026-11-11): a bullet item between numbered ones starts the count again",
),
(vec![pl(N, 0), pl(N, 1), pl(N, 0), pl(N, 1)], vec!["1.", "a.", "2.", "a."], "a shallower item starts the deeper count again"),
(vec![pl(N, 2), pl(N, 2), pl(N, 2), pl(N, 2)], vec!["i.", "ii.", "iii.", "iv."], "roman numerals at the third level"),
];
+1
View File
@@ -2009,6 +2009,7 @@ status = "draft — needs native review"
"component.combineVariants" = "جمع كتنويعات"
"component.create" = "إنشاء مكوّن"
"component.createMultiple" = "إنشاء مكونات متعددة"
"component.createSet" = "إنشاء مجموعة مكونات"
"component.deleteProperty" = "حذف خاصية المكوّن"
"component.detach" = "فصل النسخة المثيلة"
"component.editProperty" = "تحرير خاصية المكوّن"
+1
View File
@@ -2038,6 +2038,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Kombinuj kao varijante"
"component.create" = "Kreiraj komponentu"
"component.createMultiple" = "Kreiraj više komponenti"
"component.createSet" = "Kreiraj skup komponenti"
"component.deleteProperty" = "Izbriši svojstvo komponente"
"component.detach" = "Odvoji instancu"
"component.editProperty" = "Uredi svojstvo komponente"
+1
View File
@@ -1913,6 +1913,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Sloučit jako varianty"
"component.create" = "Vytvořit komponentu"
"component.createMultiple" = "Vytvořit více komponent"
"component.createSet" = "Vytvořit sadu komponent"
"component.deleteProperty" = "Smazat vlastnost komponenty"
"component.detach" = "Odpojit instanci"
"component.editProperty" = "Upravit vlastnost komponenty"
+1
View File
@@ -2079,6 +2079,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Als Varianten kombinieren"
"component.create" = "Komponente erstellen"
"component.createMultiple" = "Mehrere Komponenten erstellen"
"component.createSet" = "Komponentensatz erstellen"
"component.deleteProperty" = "Komponenteneigenschaft löschen"
"component.detach" = "Instanz lösen"
"component.editProperty" = "Komponenteneigenschaft bearbeiten"
+1
View File
@@ -2002,6 +2002,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combinar como variantes"
"component.create" = "Crear componente"
"component.createMultiple" = "Crear varios componentes"
"component.createSet" = "Crear conjunto de componentes"
"component.deleteProperty" = "Eliminar propiedad de componente"
"component.detach" = "Separar instancia"
"component.editProperty" = "Editar propiedad de componente"
+1
View File
@@ -2086,6 +2086,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Yhdistä varianteiksi"
"component.create" = "Luo komponentti"
"component.createMultiple" = "Luo useita komponentteja"
"component.createSet" = "Luo komponenttijoukko"
"component.deleteProperty" = "Poista komponentin ominaisuus"
"component.detach" = "Irrota ilmentymä"
"component.editProperty" = "Muokkaa komponentin ominaisuutta"
+1
View File
@@ -1958,6 +1958,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combiner en variantes"
"component.create" = "Créer un composant"
"component.createMultiple" = "Créer plusieurs composants"
"component.createSet" = "Créer un ensemble de composants"
"component.deleteProperty" = "Supprimer la propriété de composant"
"component.detach" = "Détacher l’instance"
"component.editProperty" = "Modifier la propriété de composant"
+1
View File
@@ -1917,6 +1917,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Gabungkan sebagai variant"
"component.create" = "Buat component"
"component.createMultiple" = "Buat beberapa component"
"component.createSet" = "Buat set component"
"component.deleteProperty" = "Hapus properti component"
"component.detach" = "Lepaskan instance"
"component.editProperty" = "Edit properti component"
+1
View File
@@ -1861,6 +1861,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combina come varianti"
"component.create" = "Crea componente"
"component.createMultiple" = "Crea più componenti"
"component.createSet" = "Crea set di componenti"
"component.deleteProperty" = "Elimina proprietà del componente"
"component.detach" = "Scollega istanza"
"component.editProperty" = "Modifica proprietà del componente"
+1
View File
@@ -1938,6 +1938,7 @@ status = "draft — needs native review"
"component.combineVariants" = "バリアントとして結合"
"component.create" = "コンポーネントを作成"
"component.createMultiple" = "複数のコンポーネントを作成"
"component.createSet" = "コンポーネントセットを作成"
"component.deleteProperty" = "コンポーネントプロパティを削除"
"component.detach" = "インスタンスを切り離す"
"component.editProperty" = "コンポーネントプロパティを編集"
+1
View File
@@ -2013,6 +2013,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"component.combineVariants" = "ვარიანტებად გაერთიანება"
"component.create" = "კომპონენტის შექმნა"
"component.createMultiple" = "რამდენიმე კომპონენტის შექმნა"
"component.createSet" = "კომპონენტების ნაკრების შექმნა"
"component.deleteProperty" = "კომპონენტის თვისების წაშლა"
"component.detach" = "ინსტანსის გამოყოფა"
"component.editProperty" = "კომპონენტის თვისების რედაქტირება"
+1
View File
@@ -1978,6 +1978,7 @@ status = "draft — needs native review"
"component.combineVariants" = "배리언트로 결합"
"component.create" = "컴포넌트 만들기"
"component.createMultiple" = "여러 컴포넌트 만들기"
"component.createSet" = "컴포넌트 세트 만들기"
"component.deleteProperty" = "컴포넌트 속성 삭제"
"component.detach" = "인스턴스 분리"
"component.editProperty" = "컴포넌트 속성 편집"
+1
View File
@@ -1956,6 +1956,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combineren als varianten"
"component.create" = "Component maken"
"component.createMultiple" = "Meerdere componenten maken"
"component.createSet" = "Componentenset maken"
"component.deleteProperty" = "Componenteigenschap verwijderen"
"component.detach" = "Instance loskoppelen"
"component.editProperty" = "Componenteigenschap bewerken"
+1
View File
@@ -1970,6 +1970,7 @@ name = "Polski"
"component.combineVariants" = "Połącz jako warianty"
"component.create" = "Utwórz komponent"
"component.createMultiple" = "Utwórz wiele komponentów"
"component.createSet" = "Utwórz zestaw komponentów"
"component.deleteProperty" = "Usuń właściwość komponentu"
"component.detach" = "Odłącz instancję"
"component.editProperty" = "Edytuj właściwość komponentu"
+1
View File
@@ -1975,6 +1975,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Combinar como variantes"
"component.create" = "Criar componente"
"component.createMultiple" = "Criar vários componentes"
"component.createSet" = "Criar conjunto de componentes"
"component.deleteProperty" = "Excluir propriedade de componente"
"component.detach" = "Desvincular instância"
"component.editProperty" = "Editar propriedade de componente"
+1
View File
@@ -1970,6 +1970,7 @@ name = "Русский"
"component.combineVariants" = "Объединить в варианты"
"component.create" = "Создать компонент"
"component.createMultiple" = "Создать несколько компонентов"
"component.createSet" = "Создать набор компонентов"
"component.deleteProperty" = "Удалить свойство компонента"
"component.detach" = "Отсоединить экземпляр"
"component.editProperty" = "Изменить свойство компонента"
+1
View File
@@ -2077,6 +2077,7 @@ name = "Svenska"
"component.combineVariants" = "Kombinera som varianter"
"component.create" = "Skapa komponent"
"component.createMultiple" = "Skapa flera komponenter"
"component.createSet" = "Skapa komponentuppsättning"
"component.deleteProperty" = "Radera komponentegenskap"
"component.detach" = "Koppla bort instans"
"component.editProperty" = "Redigera komponentegenskap"
File diff suppressed because it is too large. Load diff
+1
View File
@@ -1934,6 +1934,7 @@ status = "draft — needs native review"
"component.combineVariants" = "รวมเป็นแวเรียนต์"
"component.create" = "สร้างคอมโพเนนต์"
"component.createMultiple" = "สร้างหลายคอมโพเนนต์"
"component.createSet" = "สร้างชุดคอมโพเนนต์"
"component.deleteProperty" = "ลบพร็อพเพอร์ตีของคอมโพเนนต์"
"component.detach" = "ถอดอินสแตนซ์"
"component.editProperty" = "แก้ไขพร็อพเพอร์ตีของคอมโพเนนต์"
+1
View File
@@ -1918,6 +1918,7 @@ name = "Türkçe"
"component.combineVariants" = "Varyant olarak birleştir"
"component.create" = "Bileşen oluştur"
"component.createMultiple" = "Birden çok bileşen oluştur"
"component.createSet" = "Bileşen kümesi oluştur"
"component.deleteProperty" = "Bileşen özelliğini sil"
"component.detach" = "Örneği ayır"
"component.editProperty" = "Bileşen özelliğini düzenle"
+1
View File
@@ -1862,6 +1862,7 @@ status = "draft — needs native review"
"component.combineVariants" = "Kết hợp thành các biến thể"
"component.create" = "Tạo thành phần"
"component.createMultiple" = "Tạo nhiều thành phần"
"component.createSet" = "Tạo bộ thành phần"
"component.deleteProperty" = "Xóa thuộc tính thành phần"
"component.detach" = "Tách bản thể"
"component.editProperty" = "Chỉnh sửa thuộc tính thành phần"
+1
View File
@@ -1871,6 +1871,7 @@ status = "draft — needs native review"
"component.combineVariants" = "合并为变体"
"component.create" = "创建组件"
"component.createMultiple" = "创建多个组件"
"component.createSet" = "创建组件集"
"component.deleteProperty" = "删除组件属性"
"component.detach" = "分离实例"
"component.editProperty" = "编辑组件属性"
+1
View File
@@ -2089,6 +2089,7 @@ status = "draft — needs native review"
"component.combineVariants" = "合併為變體"
"component.create" = "建立元件"
"component.createMultiple" = "建立多個元件"
"component.createSet" = "建立元件集"
"component.deleteProperty" = "刪除元件屬性"
"component.detach" = "分離實例"
"component.editProperty" = "編輯元件屬性"
+13
View File
@@ -131,6 +131,11 @@ fn shows(code: &str, web: bool) -> bool {
// Arabic; keep the catalog out until an embedded Arabic fallback is supplied.
return figcraft_text::face_with_char('ع', &["Noto Sans Arabic"]).is_some();
}
if code.split('-').next() == Some("ta") {
// Desktop draws Tamil with a system face (#2018); the web has none until craft-fonts
// carries Noto Sans Tamil.
return figcraft_text::face_with_char('த', &["Noto Sans Tamil"]).is_some();
}
let need = language(code);
need == 0 || samples(need, 0, traditional(code)).iter().all(|(c, families)| figcraft_text::face_with_char(*c, families).is_some())
}
@@ -228,6 +233,14 @@ mod tests {
assert_eq!(shows("ar-SA", true), face);
}
#[test]
fn the_web_offers_tamil_only_with_its_face() {
assert!(shows("ta", false), "desktop always lists Tamil");
let face = figcraft_text::face_with_char('த', &["Noto Sans Tamil"]).is_some();
assert_eq!(shows("ta", true), face);
assert_eq!(shows("ta-IN", true), face);
}
/// The UI language's script leads the fallback order; the others follow.
#[test]
fn the_ui_language_script_comes_first() {
@@ -0,0 +1,165 @@
//! With two or more layers selected the Design panel's component button opens a menu (Create
//! component, Create multiple components, Create component set); one layer keeps the plain click (#2088): drawn headless.
use egui::accesskit::Node;
use egui::{Event, PointerButton, Pos2, Rect, pos2};
use figcraft_doc::{NodeId, NodeKind};
use figcraft_engine::Session;
use serde_json::json;
use crate::layers_drag_tests::Ui;
const NAMES: [&str; 3] = ["Card", "Badge", "Tile"];
fn id(v: serde_json::Value) -> NodeId {
serde_json::from_value(v["id"].clone()).unwrap()
}
/// Frames named `NAMES[..n]`, all selected, headless.
fn frames(n: usize) -> (Ui, Vec<NodeId>) {
let mut s = Session::new();
let mut ids = Vec::new();
for (i, name) in NAMES.into_iter().take(n).enumerate() {
let f = id(s.execute("frame.create", &json!({"x": 150 * i, "y": 0, "width": 100, "height": 60})).unwrap());
s.execute("object.rename", &json!({"ids": [f], "name": name})).unwrap();
ids.push(f);
}
s.execute("select.set", &json!({"ids": ids})).unwrap();
let mut u = Ui::new(s);
u.frame(vec![]);
(u, ids)
}
fn nodes(u: &mut Ui) -> Vec<Node> {
u.ctx.enable_accesskit();
u.frame(vec![]);
u.frame_output(vec![]).platform_output.accesskit_update.expect("an AccessKit update").nodes.into_iter().map(|(_, n)| n).collect()
}
fn bounds(n: &Node) -> Rect {
let b = n.bounds().unwrap();
Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))
}
fn click(u: &mut Ui, at: Pos2) {
for pressed in [true, false] {
u.frame(vec![
Event::PointerMoved(at),
Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() },
]);
}
}
fn settle(u: &mut Ui) {
for _ in 0..10 {
u.frame(vec![]);
}
}
/// The header's component button (its tooltip may carry the shortcut).
fn click_button(u: &mut Ui) {
let all = nodes(u);
let button = all.iter().find(|n| n.label().is_some_and(|l| l.starts_with("Create component"))).expect("the Design panel's component button");
click(u, bounds(button).center());
settle(u);
}
fn undo_len(u: &Ui) -> usize {
u.app.session.ds().unwrap().history.undo.len()
}
#[test]
fn several_layers_open_a_menu_and_create_multiple_components_in_one_undo_step() {
let (mut u, ids) = frames(3);
let before = undo_len(&u);
click_button(&mut u);
assert_eq!(undo_len(&u), before, "opening the menu changes nothing");
let all = nodes(&mut u);
// The menu's rows share an x with Create multiple components: exactly these two, in this order.
let multiple = all.iter().find(|n| n.label() == Some("Create multiple components")).expect("the menu's second entry");
let mb = bounds(multiple);
let mut rows: Vec<(f32, String)> = all
.iter()
.filter(|n| n.label().is_some() && (bounds(n).min.x - mb.min.x).abs() < 1.0 && (bounds(n).min.y - mb.min.y).abs() < 90.0)
.map(|n| (bounds(n).min.y, n.label().unwrap_or("").to_owned()))
.collect();
rows.sort_by(|a, b| a.0.total_cmp(&b.0));
let labels: Vec<&str> = rows.iter().map(|(_, l)| l.as_str()).collect();
assert_eq!(labels, ["Create component", "Create multiple components", "Create component set"], "the menu's entries");
click(&mut u, bounds(multiple).center());
settle(&mut u);
let sel = u.app.session.selection();
assert_eq!(sel.len(), 3);
let doc = u.app.session.doc().unwrap();
let names: Vec<&str> = sel.iter().map(|i| doc.node(*i).unwrap().name.as_str()).collect();
assert_eq!(names, NAMES);
assert!(sel.iter().all(|i| matches!(doc.node(*i).unwrap().kind, NodeKind::Component { .. })));
assert_eq!(undo_len(&u), before + 1);
u.app.session.undo().unwrap();
let doc = u.app.session.doc().unwrap();
assert!(ids.iter().all(|i| matches!(doc.node(*i).map(|n| &n.kind), Some(NodeKind::Frame))), "one undo reverts all three");
}
#[test]
fn one_layer_keeps_the_plain_button() {
let (mut u, ids) = frames(1);
click_button(&mut u);
let all = nodes(&mut u);
assert!(all.iter().all(|n| n.label() != Some("Create multiple components")), "no menu opens");
let sel = u.app.session.selection();
assert_eq!(sel.len(), 1);
let doc = u.app.session.doc().unwrap();
assert!(matches!(doc.node(sel[0]).unwrap().kind, NodeKind::Component { .. }));
assert_eq!(doc.node(sel[0]).unwrap().name, NAMES[0]);
let _ = ids;
}
#[test]
fn the_third_entry_creates_one_component_set() {
let (mut u, ids) = frames(3);
let before = undo_len(&u);
click_button(&mut u);
let all = nodes(&mut u);
let entry = all.iter().find(|n| n.label() == Some("Create component set")).expect("the menu's third entry");
click(&mut u, bounds(entry).center());
settle(&mut u);
let sel = u.app.session.selection();
assert_eq!(sel.len(), 1, "the set is selected");
let doc = u.app.session.doc().unwrap();
let set = doc.node(sel[0]).unwrap();
assert!(matches!(set.kind, NodeKind::ComponentSet { .. }));
assert_eq!(set.children.len(), 3);
assert_eq!(undo_len(&u), before + 1);
u.app.session.undo().unwrap();
let doc = u.app.session.doc().unwrap();
assert!(ids.iter().all(|i| matches!(doc.node(*i).map(|n| &n.kind), Some(NodeKind::Frame))), "one undo reverts it all");
}
/// The component button's width in the Design panel: wider with a dropdown chevron beside the icon.
fn button_width(u: &mut Ui) -> f32 {
let all = nodes(u);
let button = all.iter().find(|n| n.label().is_some_and(|l| l.starts_with("Create component"))).expect("the Design panel's component button");
bounds(button).width()
}
#[test]
fn the_dropdown_chevron_is_there_only_for_several_layers() {
let (mut one, _) = frames(1);
let (mut two, _) = frames(2);
let (single, several) = (button_width(&mut one), button_width(&mut two));
assert_eq!(single, 24.0, "one layer: the plain icon button");
assert_eq!(several, 34.0, "several layers: room for the chevron");
}
#[test]
fn create_component_set_is_offered_only_where_it_works() {
let (mut u, ids) = frames(3);
// Make the first a component: the set can't take it, so the entry is left out.
u.app.session.execute("component.create", &json!({"ids": [ids[0]]})).unwrap();
u.app.session.execute("select.set", &json!({"ids": ids})).unwrap();
u.frame(vec![]);
click_button(&mut u);
let all = nodes(&mut u);
assert!(all.iter().any(|n| n.label() == Some("Create multiple components")), "the menu is open");
assert!(all.iter().all(|n| n.label() != Some("Create component set")), "left out for a selection with a component");
}
+144
View File
@@ -128,3 +128,147 @@ fn in_crop_mode_the_layers_edges_crop_without_moving_the_picture() {
key(&mut u, Key::Escape);
assert!(ghost(&mut u).is_none(), "gone with crop mode");
}
/// Choose `item` from the image mode dropdown of the open colour picker, which reads `shown`.
fn choose_mode(u: &mut Ui, shown: &str, item: &str) {
for text in [shown, item] {
// The picker is drawn over the Design panel, so its text comes last.
let shapes = flat(&u.frame_output(vec![]).shapes);
let (_, p, size) = crate::live_tests::texts(&shapes).into_iter().rfind(|(t, _, _)| t == text).unwrap_or_else(|| panic!("no {text:?}"));
u.button(p + size / 2.0, true);
u.button(p + size / 2.0, false);
}
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.
#[test]
fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
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 {
u.frame(vec![]);
}
choose_mode(&mut u, "Fill", "Fit");
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");
// 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);
let (mut menu, other, _) = setup();
let mut fit = menu.app.session.doc().unwrap().node(other).unwrap().fills[0].clone();
if let PaintKind::Image(img) = &mut fit.kind {
img.scale_mode = ImageScaleMode::Fit;
}
menu.app.run("fill.set", json!({"ids": [other], "index": 0, "paint": fit}));
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.
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:?}");
}
/// The first paint, an image, of `id`'s fills (`fills`) or strokes, or of region `region` of a vector.
fn image_at(u: &Ui, id: NodeId, fills: bool, region: Option<usize>) -> figcraft_color::ImagePaint {
let n = u.app.session.doc().unwrap().node(id).unwrap();
let list = match region {
Some(r) => match &n.kind {
figcraft_doc::NodeKind::Vector { network } => network.regions[r].fills.clone().unwrap(),
_ => panic!("not a vector"),
},
None if fills => n.fills.clone(),
None => n.strokes.clone(),
};
match &list[0].kind {
PaintKind::Image(img) => img.clone(),
k => panic!("not an image: {k:?}"),
}
}
/// Crop chosen in the picker for a paint that has no crop mode on the canvas (#2150) — a stroke,
/// several layers' fills at once, or a region's fill in vector edit mode — only sets the paint's
/// mode: crop mode doesn't start and the picker stays open. Targets that aren't one layer's image
/// 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};
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| {
u.app.ui.picker = Some(target.clone());
for _ in 0..4 {
u.frame(vec![]);
}
choose_mode(u, "Fill", "Crop");
assert_eq!(u.app.ui.crop, None, "{what}: no crop mode");
assert_eq!(u.app.ui.picker, Some(target), "{what}: the picker stays open");
};
// The layer's image as its stroke: the stroke's mode is set, the fill is left alone.
let (mut u, layer, _) = setup();
let paint = picture(&u, layer);
u.app.run("stroke.add", json!({"ids": [layer], "paint": paint}));
crop_only_sets_the_mode(&mut u, PickerTarget::Paint { fills: false, index: 0, ids: vec![layer] }, "a stroke");
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.
let (mut u, layer, rect) = setup();
let paint = picture(&u, layer);
u.app.run("fill.set", json!({"ids": [rect], "index": 0, "paint": paint}));
u.app.run("select.set", json!({"ids": [layer, rect]}));
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);
// A region's own image fill in vector edit mode: the region's mode is set, the layer's image
// fill is untouched.
let (u0, layer, _) = setup();
let paint = picture(&u0, layer);
let mut s = Session::new();
let vector = crate::region_fill_rows_tests::two_region_vector(&mut s);
// The layer's own fill is an image too, so cropping it instead would be possible, and wrong.
s.execute("fill.set", &json!({"ids": [vector.0], "index": 0, "paint": paint})).unwrap();
s.execute("vector.edit.begin", &json!({"id": vector.0})).unwrap();
s.execute("vector.edit.select", &json!({"regions": [1]})).unwrap();
s.execute("fill.set", &json!({"ids": [vector.0], "index": 0, "paint": paint})).unwrap();
let layer_fills = s.doc().unwrap().node(vector).unwrap().fills.clone();
let mut u = Ui::new(s);
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);
}
+2
View File
@@ -88,6 +88,8 @@ mod context_menu_tests;
#[cfg(test)]
mod corner_individual_tests;
#[cfg(test)]
mod create_multiple_menu_tests;
#[cfg(test)]
mod crop_image_tests;
#[cfg(test)]
mod cursors_tests;
+35 -3
View File
@@ -497,7 +497,10 @@ fn header(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
// Layers in boolean groups, or one boolean group: the operation they use (checked in the menu).
let current = figcraft_engine::booleans::shown_op(doc, sel);
for (icon, label, cmd) in actions.into_iter().rev() {
let br = Rect::from_min_size(pos2(x - 24.0, r.center().y - 12.0), vec2(24.0, 24.0));
// With several layers the component button is a dropdown: a small chevron sits beside its icon.
let dropdown = cmd == "component.create" && sel.len() > 1;
let bw = if dropdown { 34.0 } else { 24.0 };
let br = Rect::from_min_size(pos2(x - bw, r.center().y - 12.0), vec2(bw, 24.0));
let tip = if cmd == "bool.union" { label } else { crate::shortcuts::tip(label, cmd) };
let bresp = ui.interact(br, ui.scope_id().with(("qa", cmd)), Sense::click()).tip(tip);
if bresp.hovered() {
@@ -508,7 +511,11 @@ fn header(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
("bool.union", Some(op)) => crate::layers::op_icon(op),
_ => icon,
};
icons::paint(ui.painter(), br.shrink(5.0), icon, t.icon);
let icon_rect = Rect::from_min_size(br.min, vec2(24.0, 24.0)).shrink(5.0);
icons::paint(ui.painter(), icon_rect, icon, t.icon);
if dropdown {
icons::paint(ui.painter(), Rect::from_center_size(pos2(br.max.x - 6.0, br.center().y), vec2(8.0, 8.0)), Icon::Chevron, t.icon_secondary);
}
if cmd == "bool.union" {
menu_popup(&bresp).width(180.0).show(|ui| {
for (op, c) in [
@@ -533,10 +540,35 @@ fn header(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
ui.close();
}
});
} else if cmd == "component.create" && sel.len() > 1 {
// Several layers: the button opens a menu, as Figma's does (#2088). One layer keeps the plain click.
let create = crate::i18n::command("component.create", "Create component");
let multiple = crate::i18n::command("component.createMultiple", "Create multiple components");
let set = crate::i18n::command("component.createSet", "Create component set");
// Like the layers menu, leave out what the selection can't use.
let can_set = figcraft_engine::cmd::component::can_create_set(doc, sel);
let mut entries = vec![("component.create", &create), ("component.createMultiple", &multiple)];
if can_set {
entries.push(("component.createSet", &set));
}
// Wide enough for the longest translated label (the rows grow with it, the menu never clips).
let widest = entries
.iter()
.map(|(_, l)| ui.painter().layout_no_wrap(l.to_string(), regular(11.5), Color32::PLACEHOLDER).size().x)
.fold(0.0f32, f32::max);
menu_popup(&bresp).width(menu::menu_row_width(widest, 0.0).ceil().max(160.0)).show(|ui| {
for (c, label) in &entries {
let key = crate::shortcuts::shortcut(c).unwrap_or("");
if menu_item(ui, label, key) {
app.run(c, json!({}));
ui.close();
}
}
});
} else if bresp.clicked() {
app.run(cmd, json!({}));
}
x -= 26.0;
x -= bw + 2.0;
}
crate::component_panel::instance_section(app, ui, doc, sel);
}
+28 -3
View File
@@ -760,6 +760,21 @@ fn blend_row(ui: &mut Ui, app: &mut FigApp, target: &PickerTarget, paint: &mut P
});
}
/// The layer and fill index to crop on the canvas (`image.crop`) when Crop is chosen for `target`:
/// one layer's image fill as the Fill section shows it (a text's characters' shared fills
/// included). Strokes, several layers at once and the regions selected in vector edit mode have
/// no crop mode, so for them Crop only sets the paint's mode.
pub(crate) fn crop_on_canvas(app: &FigApp, target: &PickerTarget) -> Option<(NodeId, usize)> {
let PickerTarget::Paint { fills: true, index, ids } = target else { return None };
let [id] = ids[..] else { return None };
if figcraft_engine::vectoredit::selected_region_fills(&app.session, id).is_some() {
return None;
}
let doc = app.session.doc().ok()?;
let shown = figcraft_engine::cmd::lists::character_fills(doc.node(id)?)?;
matches!(shown.get(*index)?.kind, PaintKind::Image(_)).then_some((id, *index))
}
/// The image paint's scale mode, rotation, colour profile, presets and filter sliders.
fn image_controls(app: &mut FigApp, ui: &mut Ui, target: &PickerTarget, paint: &mut Paint, mut img: ImagePaint, t: &Tokens) {
ui.horizontal(|ui| {
@@ -773,9 +788,19 @@ fn image_controls(app: &mut FigApp, ui: &mut Ui, target: &PickerTarget, paint: &
(tr("Tile"), ImageScaleMode::Tile),
] {
if crate::right::menu_item(ui, l, "") {
img.scale_mode = m;
paint.kind = PaintKind::Image(img.clone());
write(app, target, paint, false);
match crop_on_canvas(app, target).filter(|_| m == ImageScaleMode::Crop) {
// Crop for a layer's own image fill is Crop image (#2150): the picture keeps
// its place and crop mode takes the canvas, closing the picker, so its
// handles crop it as they do when crop mode comes from the menu.
Some((id, index)) => {
app.run("image.crop", json!({"ids": [id], "index": index}));
}
None => {
img.scale_mode = m;
paint.kind = PaintKind::Image(img.clone());
write(app, target, paint, false);
}
}
ui.close();
}
}
+3 -2
View File
@@ -1,6 +1,6 @@
# Auto layout and constraints parity
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-03 · **Change:** patch (a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7)
Auto layout is the most used layout feature in Figma and the one where small differences (a
hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%,
@@ -88,7 +88,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver
| Absolute position (ignore auto layout) with constraints | done | |
| Strokes included in layout (inside strokes), canvas stacking | done | |
| On-canvas padding and gap handles, incl. wrap row/column gap and grid gaps | done | an automatic gap's handle shows the distance it has; dragging it fixes the gap from there (silent in the documentation) |
| Drag to reorder (wrap-aware, by row or column), into grid cells, across nested frames | done | `al_drag_tests.rs` |
| Drag to reorder (wrap-aware, by row or column), into grid cells, across nested frames | done | `al_drag_tests.rs`. A child dragged within its own row or column takes its slot by the dragged box's leading edge, not the pointer: it passes a sibling when the edge facing the drag reaches the sibling's middle (right or bottom edge going forward, left or top edge going back), wherever it was grabbed. Measured in Figma's web app, 2026-11-09 (three 60 x 60 rectangles, gap 20: after B at 50, after C at 130; the mirror for a leftward drag; the same along y). Several moving layers use their combined box. Layers dragged in from outside, wrapping layouts, grids and a drag out of the frame keep their earlier rules (unmeasured). The measurement was made in the web app; the desktop target was not re-checked. Tests: `a_child_dragged_right_passes_a_sibling_when_its_leading_edge_reaches_the_siblings_middle`, `where_the_child_is_grabbed_does_not_change_its_slot`, `a_child_dragged_left_passes_a_sibling_by_its_left_edge`, `a_column_reorders_by_the_bottom_edge`, `a_column_reorders_at_the_boundaries_both_ways`, `a_drag_with_no_move_along_the_flow_keeps_the_slot`, `several_dragged_children_use_their_combined_box` |
| Arrow keys move children one place (flows, rows, columns, grid cells, into neighbours) | done | `al_keys_tests.rs` |
| Constraints: left, right, left and right, centre, scale; top/bottom likewise | done | |
| Layout grids: columns, rows, grid; stretch/left/centre/right; variables bound | done | |
@@ -104,6 +104,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver
| 2026-11-05 | patch | M2, #1823: Suggest auto layout is no longer Add auto layout under another name: `layout.suggest` splits a frame's layers into rows (Vertical) or else columns (Horizontal) by the gaps between their boxes, wraps each band of several layers in a new frame without fill or clipping that hugs it, and repeats inside it (16 levels, 1,000 layers per frame at most). The frame keeps its size; gap and padding come from the bands, so layers keep their boxes where the gaps are even and the bands start at the same offset; instances and layers inside them are refused; uneven gaps (smallest used), bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes come back as `warnings`. A band frame hugs only when its own split succeeds: a band whose layers overlap along both axes gets no auto layout and stays Fixed, so it cannot reflow those children. `direction` sets the top level only; one undo step; `layout.add` is unchanged. Tests in `layout_suggest_tests.rs` |
| 2026-11-02 | patch | M2: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. The modifier was ignored before. Test: `padding_individual_tests` |
| 2026-11-03 | patch | M2, #1825: baseline alignment of a layer without text (an icon next to a text) puts its bottom on the line's baseline, as the help center's figure shows ("the bottoms of the icon and the word home are aligned on the red line"); it kept to the top of the line. A layer reaching below the text's baseline moves the text down, and a line with no text lines the layers' bottoms up (the documentation is silent; CSS baseline alignment does the same). Tests: `alignment_rules` (three cases), engine `baseline_alignment_puts_an_icons_bottom_on_the_text_baseline`. Numbers unchanged. |
| 2026-11-09 | patch | M2: a child dragged within its own auto layout row or column takes its slot by the dragged box's leading edge instead of the pointer, as measured in Figma's web app on 2026-11-09: it passes a sibling when the edge facing the drag reaches the sibling's middle, so the result no longer depends on where the child was grabbed. Several moving layers use their combined box. Dragging in from outside, wrapping layouts and grids are unchanged. Tests in `al_drag_tests.rs` |
| 2026-11-02 | patch | M2, #1824: fill container children share the free space by their content area: each one's own insets (padding and an included inside stroke, from the same `insets` the frame uses) come off the free space before the equal split and go back on its share, so a child with more padding or a thicker inside stroke takes a little more and the content areas match ("Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model", Use auto layout with CSS Flexbox in mind). Min and max still clamp the outer sizes and the frozen-share loop is as it was; children without insets split as before. Test: `nested_tests::fill_children_share_by_content_area` |
| 2026-11-02 | patch | M2, #1838: a double-click on an edge of an auto layout frame's bounding box sets Hug contents on that axis, Alt+double-click on an edge of a child's Fill container ("Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents", "Hold ⌥ Option or Alt and double-click ... to set it to Fill container", Guide to auto layout); a vertical edge sizes the width, a horizontal one the height; the Keyboard shortcuts panel lists both gestures. Test: `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills`. Numbers unchanged. |
| 2026-11-02 | patch | M2: a child of an auto layout frame resized to the full space available to it on an axis (the frame's size less its padding: across the flow for any child, along the flow for a lone child) becomes Fill container on that axis, whether by `transform.resize`, the W/H fields or a canvas handle ("Child objects of an auto layout frame will also be set to Fill container if they are manually resized to the full available space of the parent frame", Guide to auto layout). Any other size keeps the axis Fixed as before; beside siblings along the flow, in a hugging or wrapping frame, in a grid and for a layer that ignores the layout nothing changes. Test: `al_behaviour_tests::a_child_resized_to_the_full_available_space_becomes_fill` |
+3 -2
View File
@@ -1,6 +1,6 @@
# Components, variants, styles and variables parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and
variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300
@@ -12,7 +12,7 @@ accounts).
| Feature | Status | Notes |
|---|---|---|
| Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main |
| Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main; with two or more layers selected the Design panel header's component button opens a menu with Create component, Create multiple components (each layer its own component in place, one undo step) and Create component set (each layer a component, wrapped in place in a set 20 px around: variants `Property 1=<layer name>` left to right, `prop=value` names kept, layers that all share a name give a set of that name with `Property 1=Default` variants; measured in Figma), one layer keeps the plain click (#2088) |
| Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances |
| What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push |
| What it doesn't: position, rotation, constraints and absolute or grid placement of layers inside it, its auto layout direction and other settings, its structure | done | refused with a message, the fields greyed out (Delete on a layer inside an instance hides it instead of removing it, as the help center says it does); the instance itself resizes and its layers follow the main's constraints |
@@ -79,6 +79,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
| Date | Change | Summary |
|---|---|---|
| 2026-11-07 | patch | M3, #2088: with two or more layers selected the Design panel header's component button opens a menu with Create component, Create multiple components and Create component set (`component.createSet`, naming measured in Figma), as Figma's does; one layer keeps the plain button. Tests: `create_multiple_menu_tests`, `components_behaviour_tests::create_multiple_components_keeps_names_and_places_and_is_one_undo_step`, `components_behaviour_tests::create_set_*`. Grade unchanged. |
| 2026-11-05 | minor | M3, #2002: the Local variables window selects several variables, as the Layers panel selects layers. A click selects one row, Shift+click the range from the anchor through the rows shown, Cmd/Ctrl+click toggles a row, Escape or a click on the empty space below the rows clears; selected rows use the sidebar's selected-row colour. Right-clicking a row that is part of a selection of several offers Delete, Move to group and Scope (all supported properties, hidden from pickers, or only one scope) for the selected local variables, each sent as one `command.batch`, so one undo step; no engine command changed. Renaming and value edits stay single-row. Tests: `variables_select_tests` (headless UI). Grade unchanged |
| 2026-11-02 | minor | M3, #1829: text styles carry paragraph spacing and indent, the list style and the OpenType features ("Supported in text styles": "Paragraph spacing and indentation", "Lists", "OpenType features", Create and apply text styles) beside the character properties: `style.create` takes them from the layer (or the selected paragraphs' list) or from a `value` (`paragraphSpacing`, `paragraphIndent`, `listStyle`, `features`), `style.apply` sets them (on a range, the list goes to the paragraphs touched; the rest is the layer's, as in Figma), `style.update` moves them on every linked layer, editing one on a styled text unlinks it as editing its font does, the style editor lists them, and a `.fig` file keeps them with the style (its sample layer). Grade unchanged. |
| 2026-11-06 | patch | M3: a glass's light angle bound to a number past ±180 turns round to the same direction (270 is -90), as the angle drawn from it does, instead of stopping at 180. Tests: `effects_tests::a_bound_light_angle_turns_round_instead_of_stopping`. Grade unchanged. |
+5 -6
View File
@@ -1,6 +1,6 @@
# FigCraft parity with Figma
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and Line truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; a typed number and a full stop at the start of a paragraph starts a numbered list at that number, as measured in Figma 2026-11-11; justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version historLine truncated
The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md)
summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is
@@ -303,13 +303,11 @@ Hours in this narrative are the builders' estimates; the tables above supersede
Backspace by grapheme cluster; double-click and word moves by script run; IME composition with
CJK; vertical trim (cap height to baseline). The tail suite (`crates/text/src/tail_tests.rs`,
`crates/engine/src/text_tail_tests.rs`): lists per paragraph, nested up to 8 levels with Tab and
Shift+Tab (1. a. i. and • ◦ ▪ per level, counts restarting after plain paragraphs), Enter on an
empty item and Backspace at an item's start stepping out, `- `/`* `/`1. ` starting a list; list
Shift+Tab (1. a. i. and • ◦ ▪ per level, counts restarting after plain paragraphs and bullet items, as measured in Figma), Enter on an
empty item and Backspace at an item's start stepping out, `- `/`* `/`N. ` starting a list (a typed `5. ` starts the numbering at 5, as measured in Figma); list
spacing between items; hanging lists and hanging punctuation; decoration style (solid, dotted,
wavy), thickness, underline offset, skip ink and colour, with inspect, CSS and the REST import.
*Left:* visual QA; hanging punctuation in right-to-left paragraphs and centred text, list
numbering that continues across a plain paragraph and a list's own start number (documentation
silent); decoration colour in SVG exports (drawn with the text's fill, like run fills); Korean
*Left:* visual QA; hanging punctuation in right-to-left paragraphs and centred text; decoration colour in SVG exports (drawn with the text's fill, like run fills); Korean
keeps breaking by syllable and Han runs aren't split by a dictionary (documentation silent). 0.5 h.
3. **Auto layout and sections depth**: *landed:* on-canvas padding/gap handles (also wrapped-row
and grid column/row gaps, grid tracks outlined), min/max width/height (UI, Hug/Fill/Fixed,
@@ -653,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th
| Date | Change | Summary |
|---|---|---|
| 2026-11-08 | minor | M8: measured in Figma on 2026-11-08, vector edit mode's Point section: X and Y show the value the selected points share, or Mixed when they differ, and a typed value sets every selected point's own coordinate in the layer being edited, points of other edited layers left as they are (it moved the group's top-left before); a relative edit (`+10`, `*2`, `/2`) typed into a Mixed field applies to each point's own value (`vector.edit.position` takes a number or `{add}`, `{mul}`, `{div}` per axis); the W and H row and other edited layers' points are unchanged. |
| 2026-11-11 | patch | M4: typing a number, a full stop and a space at the start of a plain paragraph starts a numbered list at that number (`5. ` then "x", Enter, "y" reads 5. then 6.), as measured in Figma web on 2026-11-11 (it has no start-number field: the start comes only from the typed number); before, only `1. ` and `1)` started a list. `0. `, `12a. ` and a bracket after a number other than 1 stay text (not measured), and the number is capped at 9999. Also measured: a plain paragraph or a bullet item between numbered items restarts the count at 1, and an indented sub-item does not break the outer count; those rows were pinned as silent. Tests: `text_tail_tests::typed_list_starts`, `typed_number_starts_the_list_there`, `tail_tests` restart rows. Numbers unchanged |
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged |
| 2026-11-04 | patch | M4, #1970: justified Chinese, Japanese and Korean text, written without spaces between words, aligns its right edge: the room on each line but a paragraph's last goes between its characters, each a word of its own as for line breaking ("Justify aligns the first word in each line of text to the left-most edge, and the last to the right-most edge"), wherever a line could break there, so none opens before a full stop or closing bracket, nor after an opening one. Latin text widens its spaces as before; mixed text widens both. A gap is reordered with the line's runs as a space of no width would be, so one beside a Hebrew word in Chinese text, or beside a Chinese word within that Hebrew, opens beside the word, not inside it. `figcraft_text::breaks::justify_between`, beside `break_between`, says where. Evidence: `tests::justified_ideographs_spread_the_room_between_characters` (fails on main). |
| 2026-11-04 | patch | M8, #1951 (#1506 again): a path broken open by deleting a point (Delete, not Shift+Delete) is filled closed by a straight line across the gap, as an open path's fill is; joining its two ends again (the pen onto the other end, Connect, ⌘J) left the loop without the new segment, so once the points were rounded the fill and the selection outline ran straight across while the stroke followed the segment and its arcs. Joining now closes the loop through the new segment ("Click to close the path."; "You can use the Paint tool to add fills to any closed regions of a vector network."): `ops::connect` puts it into the loop whose segments are the chain between the ends, at the gap and in the loop's own order, so a hole keeps its winding whichever end was clicked first; a loop listed out of walking order is left as it was. Evidence: `vectoredit::tests::a_rounded_chamfer_made_other_ways_fills_along_its_arcs` (fails on main: the loop kept 4 of 5 segments), `a_rounded_chamfer_cut_in_the_editor_fills_along_its_arcs` (Shift+Delete, with and without a region fill), `doc::tests::a_chamfered_rectangles_rounded_fill_is_cut_at_every_point` (fill, region path and stroke agree for every loop order and segment direction of a chamfered rectangle). |
+18 -1
View File
@@ -24,6 +24,8 @@ assistance and reviewed by a native speaker, and stays a draft until a maintaine
Russian (`ru`, Русский) was reviewed and approved by VanTan; its catalog keeps Frame and
Smart animate as familiar tool names and uses « » quotes. Turkish (`tr`) was machine-drafted and
reviewed by a native speaker, and Swedish (`sv`) translates every UI string, command label and menu wording.
Tamil (`ta`, தமிழ்) was machine-drafted and reviewed by a native speaker, and stays a draft until a
maintainer changes its status.
## The catalogs
@@ -76,7 +78,11 @@ written in Latin script with ijekavian forms and Bosnian words (historija, hilja
sedmica), uses bare imperatives for buttons and menu items (Sačuvaj, Izbriši) and the formal Vi for
instructions (Odaberite, Kliknite), „ “ quotes, and consistent design terms (okvir, sloj,
komponenta, instanca, varijanta, automatski raspored, ograničenja, ispuna, obrub, efekat, varijabla,
stil, način for a variable mode, dodatak for a plugin).
stil, način for a variable mode, dodatak for a plugin). Tamil uses modern written Tamil, bare
imperatives for buttons and menu items (சேமி, நீக்கு), the polite -கவும் for instructions
(தேர்ந்தெடுக்கவும்), Western digits, and design terms in Tamil script as Tamil designers say them
(ஃப்ரேம், லேயர், காம்போனென்ட், இன்ஸ்டன்ஸ், ஆட்டோ லேஅவுட்) while everyday words are translated
(கோப்பு, பக்கம், நிறம், ஏற்றுமதி). A case ending follows a placeholder after a space (`{name} கோப்பை`).
CJK and Thai text need their own fonts, which egui and Inter lack: the desktop app adds an installed
one when something on screen needs it, so layer and page names in those scripts show whatever the
@@ -117,6 +123,17 @@ that face out, so Arabic is not offered on the web yet. No font is added to
this repository. The interface's panels are not mirrored; this catalog does not claim a complete
right-to-left interface. Native review and representative in-app checks remain required.
## Tamil draft
`ta.toml` adds தமிழ் as a draft: 2,012 UI entries, 630 command labels and 31 menu wordings
(2,673 entries, measured 2026-11-09), covering every English key. Drafted with AI assistance against a
fixed style guide and glossary, then reviewed by a native speaker (#2159).
The desktop UI draws Tamil in an installed face (Tamil Sangam MN, Nirmala UI or Noto Sans Tamil,
#2018); no font is added to this repository. The web picker leaves Tamil out until craft-fonts has
Noto Sans Tamil. Tamil runs longer than English: the left rail's Variables label and the frame type
dropdown cut it off.
## Traditional Chinese (Taiwan) draft
`zh-Hant.toml` adds 繁體中文(台灣) as a draft: 1,975 UI entries, 641 command labels and 31 menu