mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-30 02:04:54 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # ROADMAP.md
This commit is contained in:
commit
ba151a7087
15 files changed
+424
-67
No files matched your search
@@ -367,6 +367,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-28 | minor | M8: the MCP prompt `implement_design` takes an agent through building the selected design in a codebase: `design_context` for what the designer set, connected components reused through `component_mappings` and `sync_mappings`, tokens before literal values, real files from `export_assets`, the annotations and `responsive` for what the design states beyond its size, and `compare_design` to check the result. With nothing selected it asks which frame to build, and it reports what it approximated, assumed or couldn't check. A test now checks that every tool and result field the server instructions and prompts name exists, as one already did for command ids. Numbers unchanged |
|
||||
| 2026-11-28 | minor | M1, #2185: `node.create` (and the MCP `create_node` tool) takes `children`, a list of `node.create` params made inside the new layer, each with children of its own, in one command and one undo step. The result mirrors the tree (`{id, children: [{id, children?}, …]}`), so a batch step names any layer in it with a `field` path; a refused child names its place (`children[1].children[0]: …`) and nothing is made. A card or a dialog is one call instead of a step per layer. Tests: `node_create_tree_tests`. Numbers unchanged. |
|
||||
| 2026-11-28 | minor | M7, #1687: variables export and import as DTCG design tokens (format 2025.10), the files token build pipelines read. `variable.export {format: "dtcg", mode?}` (also Variables ▸ Export… ▸ Design tokens (DTCG)…, saved as `.tokens.json`) writes a group per collection and a token per variable, nested by the `/` parts of its name: colours as `colorSpace`/`components`/`alpha` objects (with `hex` in sRGB, `display-p3` in a Display P3 file), numbers as px dimensions or plain numbers where layers use them unitless, aliases as `{group.token}` (one leaving the exported collections as the value it shows), colour calculations as the colour they show; strings and booleans, which DTCG has no type for, every mode's value and the variable's scopes go under `$extensions` (`ai.storyteller.figcraft`), and `mode` picks which mode is `$value`. `variable.import` reads a file holding a `$value` as tokens: each top-level group a collection (top-level tokens one named Tokens), types handed down from groups, `color` (object or `#hex`), `dimension` (px, rem at 16 px, or the older `16px` string), `number`, `fontWeight` (number or name), `duration` (ms), `fontFamily`, strings, booleans and aliases (an untyped alias takes its target's type); without our modes a collection fills the default mode of this file's collection of its name. Composite tokens (typography, shadows and the like) are skipped and counted in the warnings, never dropped silently. Tests: `dtcg_tests` (format, three) and `variables_io_tests::design_tokens_export_and_import_round_trip`, `plain_design_tokens_update_the_default_mode` (engine). Numbers unchanged |
|
||||
| 2026-11-27 | minor | M8: visual verification for agents. `inspect.compare` and the MCP tool `compare_design` compare a capture of a built page, made by the agent's own browser tools, with a frame, on this computer: the layers that differ, deepest and largest first, each a position (with its offset), colour (expected and actual) or content difference, with text held to twice the tolerance. A retina capture is the same design. Numbers unchanged. Tests: `visual_compare_tests`, MCP `compare_design`. |
|
||||
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
|
||||
|
||||
@@ -125,6 +125,10 @@ pub struct ExportArgs {
|
||||
/// (exact) or dropped without notes (ignore)
|
||||
#[arg(long, value_name = "bestEffort|exact|ignore", value_parser = vd_compat, default_value = "bestEffort")]
|
||||
pub vd_compat: VdCompat,
|
||||
/// Write nothing and fail (exit 1, listing why) when the export would leave out or change
|
||||
/// content. For fig, penpot and xml, the formats that report what they can't hold
|
||||
#[arg(long)]
|
||||
pub strict: bool,
|
||||
#[command(flatten)]
|
||||
pub roots: RootArgs,
|
||||
}
|
||||
@@ -157,6 +161,10 @@ pub struct ConvertArgs {
|
||||
/// Allow OUT to be the file IN, replacing it
|
||||
#[arg(long)]
|
||||
pub in_place: bool,
|
||||
/// Write nothing and fail (exit 1, listing why) when OUT would leave out or change content.
|
||||
/// For .fig and .penpot, which report what they can't hold, and .figcraft, which holds everything
|
||||
#[arg(long)]
|
||||
pub strict: bool,
|
||||
#[command(flatten)]
|
||||
pub roots: RootArgs,
|
||||
}
|
||||
@@ -197,6 +205,10 @@ pub struct RunArgs {
|
||||
/// Allow --out to be the --in file, replacing it
|
||||
#[arg(long, requires_all = ["input", "out"])]
|
||||
pub in_place: bool,
|
||||
/// Write nothing and fail (exit 1, listing why) when --out would leave out or change content.
|
||||
/// For .fig and .penpot, which report what they can't hold, and .figcraft, which holds everything
|
||||
#[arg(long, requires = "out")]
|
||||
pub strict: bool,
|
||||
#[command(flatten)]
|
||||
pub roots: RootArgs,
|
||||
}
|
||||
|
||||
@@ -113,8 +113,39 @@ fn encode(doc: &Document, pix: &figcraft_render::Pixmap, e: &str) -> CliResult<V
|
||||
figcraft_render::encode_export(pix, format, doc.color_profile).map_err(CliError::Failed)
|
||||
}
|
||||
|
||||
/// Write `doc` to `out`, choosing the format by extension.
|
||||
pub fn write_doc(doc: &Document, page: NodeId, out: &str, io: &mut Io) -> CliResult<()> {
|
||||
/// Whether `export` to `out` (in `format`, else by its extension) reports what it leaves out, so
|
||||
/// `--strict` has something to hold it to.
|
||||
pub(crate) fn export_reports_losses(format: Option<&str>, out: &str) -> bool {
|
||||
let format = format.map_or_else(|| ext(out), str::to_ascii_lowercase);
|
||||
matches!(format.as_str(), "fig" | "penpot" | "xml")
|
||||
}
|
||||
|
||||
/// Whether `export` to `out` (in `format`, else by its extension) writes Android Vector Drawables.
|
||||
pub(crate) fn export_writes_xml(format: Option<&str>, out: &str) -> bool {
|
||||
format.map_or_else(|| ext(out), str::to_ascii_lowercase) == "xml"
|
||||
}
|
||||
|
||||
/// Whether writing a document to `out` reports what it leaves out (.fig, .penpot) or keeps
|
||||
/// everything (.figcraft), so `--strict` has something to hold it to.
|
||||
pub(crate) fn save_reports_losses(out: &str) -> bool {
|
||||
matches!(ext(out).as_str(), "figcraft" | "fig" | "penpot")
|
||||
}
|
||||
|
||||
/// What writing `out` left out or changed: a note each on stderr or, when `strict`, the failure that
|
||||
/// keeps `out` from being written.
|
||||
fn notes(out: &str, warnings: Vec<String>, strict: bool, io: &mut Io) -> CliResult<()> {
|
||||
if strict && !warnings.is_empty() {
|
||||
return Err(CliError::Failed(format!("{out} wasn't written (--strict): the export would leave out or change: {}", warnings.join("; "))));
|
||||
}
|
||||
for w in warnings {
|
||||
errln!(io, "note: {w}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `doc` to `out`, choosing the format by extension. `strict`: fail, writing nothing, when
|
||||
/// the format would leave something out.
|
||||
pub fn write_doc(doc: &Document, page: NodeId, out: &str, strict: bool, io: &mut Io) -> CliResult<()> {
|
||||
let e = ext(out);
|
||||
let bytes = match e.as_str() {
|
||||
"figcraft" => {
|
||||
@@ -130,27 +161,24 @@ pub fn write_doc(doc: &Document, page: NodeId, out: &str, io: &mut Io) -> CliRes
|
||||
.into_bytes(),
|
||||
"png" | "jpg" | "jpeg" | "webp" => encode(doc, &render_page(doc, page, 1.0)?, &e)?,
|
||||
"pdf" => page_pdf(doc, page, &PrintSettings::default())?,
|
||||
"fig" => fig_bytes(doc, io)?,
|
||||
"penpot" => penpot_bytes(doc, io)?,
|
||||
"fig" => fig_bytes(doc, out, strict, io)?,
|
||||
"penpot" => penpot_bytes(doc, out, strict, io)?,
|
||||
other => return Err(CliError::Usage(format!("unknown output format `.{other}` (figcraft, json, svg, png, jpg, webp, pdf, fig, penpot)"))),
|
||||
};
|
||||
write(out, &bytes)
|
||||
}
|
||||
|
||||
/// `doc` as a `.fig` file (experimental), printing what was left out.
|
||||
fn fig_bytes(doc: &Document, io: &mut Io) -> CliResult<Vec<u8>> {
|
||||
/// `doc` as a `.fig` file (experimental) for `out`, with [`notes`] on what was left out.
|
||||
fn fig_bytes(doc: &Document, out: &str, strict: bool, io: &mut Io) -> CliResult<Vec<u8>> {
|
||||
let (bytes, warnings) = figcraft_engine::cmd::file::fig_bytes(doc).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
for w in warnings {
|
||||
errln!(io, "note: {w}");
|
||||
}
|
||||
notes(out, warnings, strict, io)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn penpot_bytes(doc: &Document, io: &mut Io) -> CliResult<Vec<u8>> {
|
||||
/// `doc` as a Penpot archive for `out`, with [`notes`] on what was left out.
|
||||
fn penpot_bytes(doc: &Document, out: &str, strict: bool, io: &mut Io) -> CliResult<Vec<u8>> {
|
||||
let (bytes, warnings) = figcraft_engine::cmd::file::penpot_bytes(doc).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
for w in warnings {
|
||||
errln!(io, "note: {w}");
|
||||
}
|
||||
notes(out, warnings, strict, io)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
@@ -259,18 +287,20 @@ pub struct Target {
|
||||
pub print: PrintSettings,
|
||||
/// Android Vector Drawable (XML) only.
|
||||
pub vd_compat: VdCompat,
|
||||
/// Fail, writing nothing, when the export would leave something out (`.fig`, `.penpot` and XML).
|
||||
pub strict: bool,
|
||||
}
|
||||
|
||||
pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32> {
|
||||
let doc = load(file, io)?;
|
||||
// `.fig`: the whole file.
|
||||
if t.format.as_deref().map_or(ext(out) == "fig", |f| f.eq_ignore_ascii_case("fig")) {
|
||||
write(out, &fig_bytes(&doc, io)?)?;
|
||||
write(out, &fig_bytes(&doc, out, t.strict, io)?)?;
|
||||
outln!(io, "{out}");
|
||||
return Ok(0);
|
||||
}
|
||||
if t.format.as_deref().map_or(ext(out) == "penpot", |f| f.eq_ignore_ascii_case("penpot")) {
|
||||
write(out, &penpot_bytes(&doc, io)?)?;
|
||||
write(out, &penpot_bytes(&doc, out, t.strict, io)?)?;
|
||||
outln!(io, "{out}");
|
||||
return Ok(0);
|
||||
}
|
||||
@@ -283,26 +313,26 @@ pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32>
|
||||
};
|
||||
let target = node.map(|q| find_node(&doc, page, q)).transpose()?;
|
||||
let single = image_format(&ext(out)).is_some();
|
||||
let mut bytes_of = |ids: &[NodeId]| {
|
||||
// The bytes and what an Android Vector Drawable changed or left out, like the .fig notes.
|
||||
let bytes_of = |ids: &[NodeId]| {
|
||||
let setting = ExportSetting { format: fmt, print: *print, vd_compat: t.vd_compat, ..Default::default() };
|
||||
let (bytes, warnings) = figcraft_engine::cmd::file::export_file(&doc, ids, &setting, scale).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
// What an Android Vector Drawable changed or left out, like the .fig notes.
|
||||
for w in warnings {
|
||||
errln!(io, "note: {w}");
|
||||
}
|
||||
Ok::<_, CliError>(bytes)
|
||||
figcraft_engine::cmd::file::export_file(&doc, ids, &setting, scale).map_err(|e| CliError::Failed(e.to_string()))
|
||||
};
|
||||
if single {
|
||||
let bytes = match target {
|
||||
let (bytes, warnings) = match target {
|
||||
Some(t) => bytes_of(&[t])?,
|
||||
None if fmt == ExportFormat::Pdf => page_pdf(&doc, page, print)?,
|
||||
None if fmt == ExportFormat::Pdf => (page_pdf(&doc, page, print)?, Vec::new()),
|
||||
None => bytes_of(&children(&doc, page))?,
|
||||
};
|
||||
notes(out, warnings, t.strict, io)?;
|
||||
write(out, &bytes)?;
|
||||
outln!(io, "{out}");
|
||||
return Ok(0);
|
||||
}
|
||||
figcraft_engine::file_access::create_dir_all(out).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
// `--strict` writes the folder only once every file in it is known to leave nothing out.
|
||||
if !t.strict {
|
||||
figcraft_engine::file_access::create_dir_all(out).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
}
|
||||
let ids = match target {
|
||||
Some(t) => vec![t],
|
||||
None => {
|
||||
@@ -314,6 +344,7 @@ pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32>
|
||||
if ids.is_empty() {
|
||||
return Err(CliError::Failed("the page is empty: nothing to export".into()));
|
||||
}
|
||||
let (mut pending, mut left_out) = (Vec::new(), Vec::new());
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
let mut next_suffix: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
||||
for id in ids {
|
||||
@@ -329,9 +360,28 @@ pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32>
|
||||
}
|
||||
};
|
||||
let path = Path::new(out).join(format!("{name}.{}", fmt.ext())).to_string_lossy().into_owned();
|
||||
write(&path, &bytes_of(&[id])?)?;
|
||||
let (bytes, warnings) = bytes_of(&[id])?;
|
||||
if t.strict {
|
||||
for w in warnings {
|
||||
if !left_out.contains(&w) {
|
||||
left_out.push(w);
|
||||
}
|
||||
}
|
||||
pending.push((path, bytes));
|
||||
continue;
|
||||
}
|
||||
notes(&path, warnings, false, io)?;
|
||||
write(&path, &bytes)?;
|
||||
outln!(io, "{path}");
|
||||
}
|
||||
if t.strict {
|
||||
notes(out, left_out, true, io)?;
|
||||
figcraft_engine::file_access::create_dir_all(out).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
for (path, bytes) in pending {
|
||||
write(&path, &bytes)?;
|
||||
outln!(io, "{path}");
|
||||
}
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
@@ -354,7 +404,7 @@ fn refuse_dropping_images_from_script(input: Option<(&str, usize)>, active: &fig
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn convert(input: &str, out: &str, io: &mut Io) -> CliResult<i32> {
|
||||
pub fn convert(input: &str, out: &str, strict: bool, io: &mut Io) -> CliResult<i32> {
|
||||
let (loaded, _) = figcraft_engine::cmd::file::load_path(input, None).map_err(|e| CliError::Failed(format!("can't open {input}: {e}")))?;
|
||||
refuse_dropping_images(input, out, loaded.images_past_budget)?;
|
||||
if ext(input) == "penpot" {
|
||||
@@ -368,7 +418,7 @@ pub fn convert(input: &str, out: &str, io: &mut Io) -> CliResult<i32> {
|
||||
.filter(|p| doc.pages.contains(p))
|
||||
.or_else(|| doc.first_page())
|
||||
.ok_or_else(|| CliError::Failed("the document has no pages".into()))?;
|
||||
write_doc(&doc, page, out, io)?;
|
||||
write_doc(&doc, page, out, strict, io)?;
|
||||
outln!(io, "{out}");
|
||||
Ok(0)
|
||||
}
|
||||
@@ -423,7 +473,7 @@ pub fn parse_script(text: &str) -> Result<Vec<BatchStep>, String> {
|
||||
/// file is refused before it is read (#1114).
|
||||
pub const MAX_SCRIPT: u64 = 1 << 30;
|
||||
|
||||
pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>, io: &mut Io) -> CliResult<i32> {
|
||||
pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>, strict: bool, io: &mut Io) -> CliResult<i32> {
|
||||
let bytes = figcraft_engine::file_access::read_capped(script, MAX_SCRIPT).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
let text = String::from_utf8(bytes).map_err(|_| CliError::Failed(format!("{script}: not UTF-8")))?;
|
||||
let steps = parse_script(&text).map_err(|e| CliError::Failed(format!("{script}: {e}")))?;
|
||||
@@ -470,7 +520,7 @@ pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>, io: &mut
|
||||
// Through the engine, so the version history is kept.
|
||||
write(out, &figcraft_engine::cmd::file::file_bytes_at(ds, out).map_err(|e| CliError::Failed(e.to_string()))?)?;
|
||||
} else {
|
||||
write_doc(&ds.doc, ds.page, out, io)?;
|
||||
write_doc(&ds.doc, ds.page, out, strict, io)?;
|
||||
}
|
||||
errln!(io, "wrote {out}");
|
||||
}
|
||||
@@ -525,7 +575,7 @@ mod tests {
|
||||
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>"#).unwrap();
|
||||
std::fs::write(&script, r#"[{"command":"no.such\u001b"}]"#).unwrap();
|
||||
assert_eq!(info(svg.to_str().unwrap(), false, io!()).unwrap(), 0);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, None, io!()).unwrap(), 1);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, None, false, io!()).unwrap(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -610,7 +660,7 @@ mod tests {
|
||||
for ext in ["svg", "pdf"] {
|
||||
let path = dir.join(format!("previous.{ext}"));
|
||||
std::fs::write(&path, b"previous export").unwrap();
|
||||
let CliError::Failed(error) = write_doc(&doc, page, path.to_str().unwrap(), io!()).unwrap_err() else {
|
||||
let CliError::Failed(error) = write_doc(&doc, page, path.to_str().unwrap(), false, io!()).unwrap_err() else {
|
||||
panic!("depth overflow must be an operation failure");
|
||||
};
|
||||
assert!(error.contains("maximum export depth of 256"), "{ext}: {error}");
|
||||
@@ -637,7 +687,7 @@ mod tests {
|
||||
bad.push("/dev/zero".into());
|
||||
}
|
||||
for path in bad {
|
||||
let Err(CliError::Failed(e)) = run_script(&path, None, None, io!()) else { panic!("{path} ran") };
|
||||
let Err(CliError::Failed(e)) = run_script(&path, None, None, false, io!()) else { panic!("{path} ran") };
|
||||
assert!(e.contains("is a folder, not a file") || e.contains("isn't a regular file"), "{path}: {e}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
@@ -695,7 +745,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 0);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), false, io!()).unwrap(), 0);
|
||||
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap();
|
||||
@@ -725,7 +775,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 0);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), false, io!()).unwrap(), 0);
|
||||
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap();
|
||||
@@ -742,7 +792,7 @@ mod tests {
|
||||
let dir = temp_dir("run-dup-name");
|
||||
let script = dir.join("script.json");
|
||||
std::fs::write(&script, r#"[{"command": "select.none", "as": "a"}, {"command": "select.none", "as": "a"}]"#).unwrap();
|
||||
let Err(CliError::Failed(e)) = run_script(script.to_str().unwrap(), None, None, io!()) else { panic!("a name twice must fail") };
|
||||
let Err(CliError::Failed(e)) = run_script(script.to_str().unwrap(), None, None, false, io!()) else { panic!("a name twice must fail") };
|
||||
assert!(e.contains("step 1: `as` \"a\" is already step 0's name"), "{e}");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -762,7 +812,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
// The failure is the script's, not the call's: the CLI reports it and exits non-zero.
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 1);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), false, io!()).unwrap(), 1);
|
||||
assert!(!out.exists(), "a script that failed writes nothing");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -93,13 +93,20 @@ fn dispatch(cli: Cli, io: &mut Io) -> CliResult<i32> {
|
||||
match cli.command {
|
||||
Command::Info(a) => confined(&a.roots, || files::info(&a.file, a.json, io)),
|
||||
Command::Export(a) => {
|
||||
let target =
|
||||
files::Target { print: a.print(), vd_compat: a.vd_compat, scale: a.scale.scale, format: a.format, page: a.page, node: a.node };
|
||||
let target = files::Target {
|
||||
print: a.print(),
|
||||
vd_compat: a.vd_compat,
|
||||
scale: a.scale.scale,
|
||||
format: a.format,
|
||||
page: a.page,
|
||||
node: a.node,
|
||||
strict: a.strict,
|
||||
};
|
||||
confined(&a.roots, || files::export(&a.file, &a.out, &target, io))
|
||||
}
|
||||
Command::Convert(a) => confined(&a.roots, || files::convert(&a.input, &a.output, io)),
|
||||
Command::Convert(a) => confined(&a.roots, || files::convert(&a.input, &a.output, a.strict, io)),
|
||||
Command::Render(a) => confined(&a.roots, || files::render(&a.file, &a.out, a.scale.scale, a.page.as_deref(), io)),
|
||||
Command::Run(a) => confined(&a.roots, || files::run_script(&a.script, a.input.as_deref(), a.out.as_deref(), io)),
|
||||
Command::Run(a) => confined(&a.roots, || files::run_script(&a.script, a.input.as_deref(), a.out.as_deref(), a.strict, io)),
|
||||
Command::Commands(a) => {
|
||||
commands(a.json, a.filter.as_deref(), io);
|
||||
Ok(0)
|
||||
@@ -220,6 +227,25 @@ fn check(command: &Command) -> CliResult<()> {
|
||||
}
|
||||
Err(CliError::Usage(format!("{flag} {path} is the input, which it would replace: choose another file, or pass --in-place")))
|
||||
};
|
||||
// `--strict` holds a writer to what it reports, so it is refused where nothing would be checked.
|
||||
let unchecked = |what: &str, formats: &str| {
|
||||
Err(CliError::Usage(format!("--strict checks {formats}, the formats that report what they leave out; {what} isn't one of them")))
|
||||
};
|
||||
match command {
|
||||
Command::Export(a) if a.strict && !files::export_reports_losses(a.format.as_deref(), &a.out) => {
|
||||
return unchecked(&format!("--out {}", a.out), "fig, penpot and xml exports");
|
||||
}
|
||||
Command::Export(a) if a.strict && a.vd_compat == figcraft_doc::VdCompat::Ignore && files::export_writes_xml(a.format.as_deref(), &a.out) => {
|
||||
return Err(CliError::Usage("--strict can't check --vd-compat ignore, which drops what it can't draw without saying so".into()));
|
||||
}
|
||||
Command::Convert(a) if a.strict && !files::save_reports_losses(&a.output) => {
|
||||
return unchecked(&format!("OUT {}", a.output), ".fig, .penpot and .figcraft output");
|
||||
}
|
||||
Command::Run(a) if a.strict && !a.out.as_deref().is_some_and(files::save_reports_losses) => {
|
||||
return unchecked(&format!("--out {}", a.out.as_deref().unwrap_or("")), ".fig, .penpot and .figcraft output");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match command {
|
||||
Command::Convert(a) => refuse("OUT", &a.output, &a.input, a.in_place)?,
|
||||
Command::Run(a) => {
|
||||
|
||||
@@ -220,3 +220,82 @@ fn a_server_key_flag_and_an_unreachable_app_fail_with_exit_1_and_a_message() {
|
||||
assert!(got.err.contains("can't reach the FigCraft app at 127.0.0.1:1"), "{}", got.err);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// `--strict` writes what leaves nothing out as without it, and refuses (exit 1, the reasons listed,
|
||||
/// no file written or replaced) what would leave something out.
|
||||
#[test]
|
||||
fn strict_refuses_to_write_what_would_leave_content_out() {
|
||||
let dir = workdir("strict");
|
||||
let path = |name: &str| dir.join(name).to_str().unwrap().to_string();
|
||||
let frame = r#"{"command": "frame.create", "params": {"x": 0, "y": 0, "width": 10, "height": 10, "name": "F"}}"#;
|
||||
// The .fig format has no place for comments, so the writer reports one as left out.
|
||||
let comment = r#"{"command": "comment.add", "params": {"x": 5, "y": 5, "text": "Check"}}"#;
|
||||
let (clean, noted, script) = (path("clean.figcraft"), path("noted.figcraft"), path("s.json"));
|
||||
for (doc, steps) in [(&clean, format!("[{frame}]")), (¬ed, format!("[{frame}, {comment}]"))] {
|
||||
std::fs::write(&script, steps).unwrap();
|
||||
let made = invoke(["run", script.as_str(), "--out", doc.as_str()]);
|
||||
assert_eq!(made.code, 0, "{}", made.err);
|
||||
}
|
||||
|
||||
let fig = path("clean.fig");
|
||||
let got = invoke(["export", clean.as_str(), "-o", fig.as_str(), "--strict"]);
|
||||
assert_eq!((got.code, got.err.contains("note:")), (0, false), "{}", got.err);
|
||||
assert_eq!(invoke(["info", fig.as_str()]).code, 0, "the strict export reads back");
|
||||
let got = invoke(["convert", clean.as_str(), path("clean.penpot").as_str(), "--strict"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
|
||||
let (absent, previous) = (path("absent.fig"), path("previous.fig"));
|
||||
std::fs::write(&previous, b"previous export").unwrap();
|
||||
for args in [
|
||||
vec!["export", noted.as_str(), "-o", absent.as_str(), "--strict"],
|
||||
vec!["export", noted.as_str(), "-o", previous.as_str(), "--strict"],
|
||||
vec!["convert", noted.as_str(), absent.as_str(), "--strict"],
|
||||
vec!["run", script.as_str(), "--in", clean.as_str(), "--out", previous.as_str(), "--strict"],
|
||||
] {
|
||||
let got = invoke(args.iter().copied());
|
||||
assert_eq!(got.code, 1, "{args:?}: {}", got.err);
|
||||
assert!(
|
||||
got.err.starts_with("error: ") && got.err.contains("--strict") && got.err.contains("comments were left out"),
|
||||
"{args:?}: {}",
|
||||
got.err
|
||||
);
|
||||
assert!(!std::path::Path::new(&absent).exists(), "{args:?} wrote {absent}");
|
||||
assert_eq!(std::fs::read(&previous).unwrap(), b"previous export", "{args:?} replaced {previous}");
|
||||
}
|
||||
// Without --strict the same export writes the file and notes what it left out.
|
||||
let got = invoke(["export", noted.as_str(), "-o", absent.as_str()]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
assert!(got.err.contains("note: comments were left out") && std::path::Path::new(&absent).exists(), "{}", got.err);
|
||||
|
||||
// A folder of drawables is written only when no file in it leaves anything out.
|
||||
let drawables = path("clean-drawables");
|
||||
let got = invoke(["export", clean.as_str(), "-o", drawables.as_str(), "--format", "xml", "--strict"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
assert!(std::path::Path::new(&drawables).join("F.xml").exists(), "{}", got.out);
|
||||
std::fs::write(
|
||||
&script,
|
||||
r##"[{"command": "shape.rectangle", "params": {"x": 0, "y": 0, "width": 24, "height": 24, "name": "Dot", "props": {"fill": "#ff0000", "effects": [{"type": "dropShadow"}]}}}]"##,
|
||||
)
|
||||
.unwrap();
|
||||
let shadowed = path("shadowed.figcraft");
|
||||
assert_eq!(invoke(["run", script.as_str(), "--out", shadowed.as_str()]).code, 0);
|
||||
let folder = path("drawables");
|
||||
let got = invoke(["export", shadowed.as_str(), "-o", folder.as_str(), "--format", "xml", "--strict"]);
|
||||
assert_eq!(got.code, 1, "{}", got.err);
|
||||
assert!(got.err.contains("drop shadows were left out") && !std::path::Path::new(&folder).exists(), "{}", got.err);
|
||||
|
||||
// --vd-compat only matters for drawables.
|
||||
let got = invoke(["export", clean.as_str(), "-o", path("ignored.fig").as_str(), "--vd-compat", "ignore", "--strict"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
// Where nothing would be checked, --strict is a usage error.
|
||||
for args in [
|
||||
vec!["export", clean.as_str(), "-o", "x.png", "--strict"],
|
||||
vec!["export", clean.as_str(), "-o", "frames", "--strict"],
|
||||
vec!["export", shadowed.as_str(), "-o", "x.xml", "--vd-compat", "ignore", "--strict"],
|
||||
vec!["convert", clean.as_str(), "x.svg", "--strict"],
|
||||
vec!["run", script.as_str(), "--strict"],
|
||||
] {
|
||||
assert!(usage_error(&args).contains("--strict"), "{args:?}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"node.create",
|
||||
"Create layer",
|
||||
"{type: rectangle|ellipse|polygon|star|line|arrow|vector|text|frame|section|component|slice, x?, y? (relative to the parent frame; groups don't count), width?, height?, parent? (id; default: the page), index?, name?, text? | characters? (for text), path? | points? (vector: SVG path data | [[x,y],..]; x/y move their own origin, so the layer's left/top is x/y plus their box's unscaled offset), closed? (vector), props? {node.set keys}, select? (default true)}",
|
||||
"{type: rectangle|ellipse|polygon|star|line|arrow|vector|text|frame|section|component|slice, x?, y? (relative to the parent frame; groups don't count), width?, height?, parent? (id; default: the page), index?, name?, text? | characters? (for text), path? | points? (vector: SVG path data | [[x,y],..]; x/y move their own origin, so the layer's left/top is x/y plus their box's unscaled offset), closed? (vector), props? {node.set keys}, select? (default true), children? ([node.create params without parent, each with children? of its own]: made inside it in the same undo step; the result mirrors the tree, {id, children: [{id, children?}, …]})}",
|
||||
true,
|
||||
create
|
||||
),
|
||||
@@ -298,7 +298,41 @@ fn keep_fixed_text_height(cmd: &str, doc: &mut Document, nid: NodeId, p: &Value)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `node.create`: the layer, then each of its `children` inside it (each a `node.create` params
|
||||
/// object, with children of its own), in one command so one undo step. The result mirrors the
|
||||
/// tree: `{id, children: [{id, children: […]}, …]}`, so a batch step names any layer in it with a
|
||||
/// `field` path (`children/1/id`). A refused child names its place (`children[1].children[0]: …`)
|
||||
/// and nothing is made.
|
||||
pub fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "node.create";
|
||||
let mut out = create_layer(s, p)?;
|
||||
let Some(kids) = get(p, "children") else { return Ok(out) };
|
||||
let Value::Array(kids) = kids else { return Err(bad(cmd, "`children` must be a list of node.create params")) };
|
||||
// The path of the child the error came from, in front of the error.
|
||||
let at = |i: usize, e: crate::EngineError| match e {
|
||||
crate::EngineError::BadParams { cmd, msg } => {
|
||||
let msg = if msg.starts_with("children[") { format!("children[{i}].{msg}") } else { format!("children[{i}]: {msg}") };
|
||||
crate::EngineError::BadParams { cmd, msg }
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
let mut made = Vec::with_capacity(kids.len());
|
||||
for (i, kid) in kids.iter().enumerate() {
|
||||
let Value::Object(kid) = kid else { return Err(at(i, bad(cmd, "a child is a node.create params object"))) };
|
||||
if kid.contains_key("parent") {
|
||||
return Err(at(i, bad(cmd, "a child's parent is the layer it is listed under: leave `parent` out")));
|
||||
}
|
||||
let mut kid = kid.clone();
|
||||
kid.insert("parent".into(), out["id"].clone());
|
||||
kid.insert("select".into(), json!(false));
|
||||
let kid = Value::Object(kid);
|
||||
made.push(super::refuse_unknown_params(cmd, &kid).and_then(|()| create(s, &kid)).map_err(|e| at(i, e))?);
|
||||
}
|
||||
out["children"] = Value::Array(made);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn create_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "node.create";
|
||||
let t = string(p, "type").ok_or_else(|| bad(cmd, "`type` is required"))?;
|
||||
let (mut kind, base) = kind_for(&t).ok_or_else(|| bad(cmd, format!("unknown type `{t}`")))?;
|
||||
|
||||
@@ -472,6 +472,8 @@ mod moved_by_tests;
|
||||
#[cfg(test)]
|
||||
mod nested_override_tests;
|
||||
#[cfg(test)]
|
||||
mod node_create_tree_tests;
|
||||
#[cfg(test)]
|
||||
mod node_find_tests;
|
||||
#[cfg(test)]
|
||||
mod node_set_refusals_tests;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! `node.create {children}` builds a layer with the layers inside it in one command (#2185): one
|
||||
//! undo step, a result that mirrors the tree, and a refused child that names its place and leaves
|
||||
//! nothing behind.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
fn id(v: &Value) -> crate::NodeId {
|
||||
crate::params::id_of(v).unwrap()
|
||||
}
|
||||
|
||||
fn card() -> Value {
|
||||
json!({"type": "frame", "name": "Card", "width": 320, "props": {"layout": "vertical", "gap": 8, "padding": 16}, "children": [
|
||||
{"type": "text", "name": "Title", "text": "Title"},
|
||||
{"type": "frame", "name": "Button", "width": 120, "height": 40, "props": {"layout": "horizontal"}, "children": [
|
||||
{"type": "text", "name": "Label", "text": "Go"}
|
||||
]}
|
||||
]})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_is_made_with_its_children_in_one_undo_step() {
|
||||
let mut s = Session::new();
|
||||
let undo = s.ds().unwrap().history.undo.len();
|
||||
let out = s.execute("node.create", &card()).unwrap();
|
||||
let (card, title, button, label) =
|
||||
(id(&out["id"]), id(&out["children"][0]["id"]), id(&out["children"][1]["id"]), id(&out["children"][1]["children"][0]["id"]));
|
||||
let doc = s.doc().unwrap();
|
||||
assert_eq!(doc.node(card).unwrap().children, [title, button], "in the order listed");
|
||||
assert_eq!(doc.node(button).unwrap().children, [label]);
|
||||
assert_eq!(doc.node(label).unwrap().name, "Label");
|
||||
assert!(doc.node(card).unwrap().height > doc.node(button).unwrap().height, "the card's layout holds its children");
|
||||
assert_eq!(s.ds().unwrap().selection, [card], "the layer asked for is selected, not its children");
|
||||
assert_eq!(s.ds().unwrap().history.undo.len(), undo + 1);
|
||||
s.undo().unwrap();
|
||||
assert!(!s.doc().unwrap().contains(card) && !s.doc().unwrap().contains(label));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_child_names_its_place_and_nothing_is_made() {
|
||||
let mut s = Session::new();
|
||||
let before = s.doc().unwrap().nodes().count();
|
||||
let mut tree = card();
|
||||
tree["children"][1]["children"][0]["colour"] = json!("#f00");
|
||||
let Err(EngineError::BadParams { msg, .. }) = s.execute("node.create", &tree) else { panic!("refused") };
|
||||
assert!(msg.starts_with("children[1].children[0]: ") && msg.contains("colour"), "{msg}");
|
||||
tree["children"][1]["children"][0] = json!({"type": "text", "parent": 1});
|
||||
let Err(EngineError::BadParams { msg, .. }) = s.execute("node.create", &tree) else { panic!("refused") };
|
||||
assert!(msg.starts_with("children[1].children[0]: "), "{msg}");
|
||||
assert_eq!(s.doc().unwrap().nodes().count(), before, "rolled back whole");
|
||||
}
|
||||
@@ -289,23 +289,44 @@ impl<'d> Exporter<'d> {
|
||||
));
|
||||
}
|
||||
}
|
||||
if !net.regions.is_empty() {
|
||||
let winding = net.regions.first().map(|r| r.winding).unwrap_or_default();
|
||||
if net.regions.iter().any(|r| r.winding != winding) {
|
||||
self.warn("vectors whose filled areas use different winding rules use the first one's in their outline");
|
||||
if let Some(first) = net.regions.first().map(|r| r.winding) {
|
||||
let drawn = figcraft_doc::geometry::drawn_network(net, n.corners.smoothing);
|
||||
if net.regions.iter().all(|r| r.winding == first) {
|
||||
self.geometry("fillGeometry", &drawn.fill_path(), first, f);
|
||||
} else {
|
||||
// One outline per winding rule, the first area's rule first: each is filled with its own rule.
|
||||
let second = if first == WindingRule::NonZero { WindingRule::EvenOdd } else { WindingRule::NonZero };
|
||||
let parts: Vec<(BezPath, WindingRule)> = [first, second]
|
||||
.into_iter()
|
||||
.map(|rule| {
|
||||
let mut part = drawn.clone().into_owned();
|
||||
part.regions.retain(|r| r.winding == rule);
|
||||
(part.fill_path(), rule)
|
||||
})
|
||||
.collect();
|
||||
let parts: Vec<(&BezPath, WindingRule)> = parts.iter().map(|(p, rule)| (p, *rule)).collect();
|
||||
self.geometries("fillGeometry", &parts, f);
|
||||
}
|
||||
self.geometry("fillGeometry", &figcraft_doc::geometry::drawn_network(net, n.corners.smoothing).fill_path(), winding, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// `fillGeometry` or `strokeGeometry` (`key`) from a local path.
|
||||
pub(super) fn geometry(&mut self, key: &'static str, p: &BezPath, winding: WindingRule, f: &mut Fields) {
|
||||
if p.elements().is_empty() {
|
||||
return;
|
||||
self.geometries(key, &[(p, winding)], f);
|
||||
}
|
||||
|
||||
/// `fillGeometry` or `strokeGeometry` (`key`) from local paths, each filled with its own winding rule (empty paths
|
||||
/// are left out, and the field with them).
|
||||
fn geometries(&mut self, key: &'static str, parts: &[(&BezPath, WindingRule)], f: &mut Fields) {
|
||||
let mut list = Vec::new();
|
||||
for (p, winding) in parts.iter().filter(|(p, _)| !p.elements().is_empty()) {
|
||||
if let Some(i) = self.blob(path_blob(p)) {
|
||||
let rule = if *winding == WindingRule::EvenOdd { "ODD" } else { "NONZERO" };
|
||||
list.push(o(vec![("windingRule", e(rule)), ("commandsBlob", u(i)), ("styleID", u(0))]));
|
||||
}
|
||||
}
|
||||
if let Some(i) = self.blob(path_blob(p)) {
|
||||
let rule = if winding == WindingRule::EvenOdd { "ODD" } else { "NONZERO" };
|
||||
f.push((key, arr(vec![o(vec![("windingRule", e(rule)), ("commandsBlob", u(i)), ("styleID", u(0))])])));
|
||||
if !list.is_empty() {
|
||||
f.push((key, arr(list)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -480,3 +480,55 @@ fn a_whole_ellipse_drawn_backwards_carries_its_stroke_ring() {
|
||||
assert_eq!(forwards.0, "ODD");
|
||||
assert_eq!(ring(-std::f64::consts::TAU), Some(forwards));
|
||||
}
|
||||
|
||||
/// A vector whose filled areas use different winding rules writes one outline per rule, each
|
||||
/// filled with its own, so another reader fills every area as the network does (with rounded
|
||||
/// points too, whose outline comes from the network drawn with its corners); the import keeps each
|
||||
/// area's rule.
|
||||
#[test]
|
||||
fn a_vectors_filled_areas_keep_their_own_winding_rules_in_its_outline() {
|
||||
for radius in [0.0, 5.0] {
|
||||
filled_areas_keep_their_winding_rules(radius);
|
||||
}
|
||||
}
|
||||
|
||||
fn filled_areas_keep_their_winding_rules(radius: f64) {
|
||||
let mut doc = Document::new("Winding");
|
||||
let page = doc.first_page().unwrap();
|
||||
let mut path = figcraft_doc::geom::BezPath::new();
|
||||
for x in [0.0, 60.0] {
|
||||
path.move_to((x, 0.0));
|
||||
path.line_to((x + 40.0, 0.0));
|
||||
path.line_to((x + 40.0, 40.0));
|
||||
path.line_to((x, 40.0));
|
||||
path.close_path();
|
||||
}
|
||||
let mut network = VectorNetwork::from_path(&path);
|
||||
let loops: Vec<Vec<usize>> = network.regions.iter().flat_map(|r| r.loops.clone()).collect();
|
||||
assert_eq!(loops.len(), 2);
|
||||
network.regions = loops
|
||||
.into_iter()
|
||||
.zip([WindingRule::EvenOdd, WindingRule::NonZero])
|
||||
.map(|(lp, winding)| Region { loops: vec![lp], winding, ..Default::default() })
|
||||
.collect();
|
||||
for v in &mut network.vertices {
|
||||
v.radius = radius;
|
||||
}
|
||||
let id = doc.create(page, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 40.0).unwrap();
|
||||
doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)];
|
||||
let (bytes, warnings) = export(&doc, None).unwrap();
|
||||
assert!(!warnings.iter().any(|w| w.contains("winding")), "radius {radius}: {warnings:?}");
|
||||
with_changes(&doc, |of, _| {
|
||||
let vector = of("VECTOR");
|
||||
let rules: Vec<&str> = vector.get("fillGeometry").map(Kv::list).unwrap_or_default().iter().map(|p| name(p, "windingRule")).collect();
|
||||
assert_eq!(rules, ["ODD", "NONZERO"], "radius {radius}: the first area's rule first, then the other");
|
||||
});
|
||||
let windings = |d: &Document| {
|
||||
d.nodes().find_map(|n| match &n.kind {
|
||||
NodeKind::Vector { network } => Some(network.regions.iter().map(|r| r.winding).collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let (back, _) = import(&bytes, "x").unwrap();
|
||||
assert_eq!(windings(&back), windings(&doc), "radius {radius}");
|
||||
}
|
||||
+19
-7
@@ -212,6 +212,7 @@ fn tools() -> Vec<Value> {
|
||||
"closed": boolean("For type vector: close the path"),
|
||||
"select": boolean("Select the new layer (default true)"),
|
||||
"props": {"type": "object", "description": "Any set_properties keys applied at creation, e.g. {\"fill\":\"#3366FF\",\"cornerRadius\":12,\"fontSize\":24,\"layout\":\"vertical\",\"gap\":8,\"padding\":16}"},
|
||||
"children": {"type": "array", "items": {"type": "object"}, "description": "Layers to make inside this one in the same call and undo step: each takes these same keys except parent (and select), including its own children. The result's `children` mirrors the tree ([{id, children?}, ...]), so a batch step can name any of them with a field path such as children/1/id. A refused child is named by its place (children[1].children[0]: ...) and nothing is made"},
|
||||
"fields": fields_schema(),
|
||||
"outline": outline_schema(),
|
||||
}),
|
||||
@@ -647,6 +648,18 @@ fn bounds_of(b: &mut dyn Backend, ids: &[u64]) -> Option<(f64, f64, f64, f64)> {
|
||||
/// Make paint/effect JSON friendlier than the engine's strict serde (see
|
||||
/// [`figcraft_engine::params::normalize_paint`]). The engine reads paints this way itself; effects
|
||||
/// still need it here.
|
||||
/// [`normalize_props`] on a `node.create` params object's `props` and its children's, all the way down.
|
||||
fn normalize_tree(params: &mut Map<String, Value>) {
|
||||
if let Some(Value::Object(p)) = params.get_mut("props") {
|
||||
normalize_props(p);
|
||||
}
|
||||
if let Some(Value::Array(kids)) = params.get_mut("children") {
|
||||
for kid in kids.iter_mut().filter_map(Value::as_object_mut) {
|
||||
normalize_tree(kid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalize_props(props: &mut Map<String, Value>) {
|
||||
for k in ["fills", "strokes", "effects"] {
|
||||
if let Some(v) = props.get_mut(k) {
|
||||
@@ -846,21 +859,20 @@ fn create_node(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult
|
||||
// Checked before the layer is made, so a bad option changes nothing.
|
||||
let options = inspection_options(a)?;
|
||||
let mut params = Map::new();
|
||||
for k in ["type", "x", "y", "width", "height", "parent", "index", "name", "text", "path", "points", "closed", "props", "select"] {
|
||||
for k in ["type", "x", "y", "width", "height", "parent", "index", "name", "text", "path", "points", "closed", "props", "select", "children"] {
|
||||
if let Some(v) = a.get(k).filter(|v| !v.is_null()) {
|
||||
params.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
if let Some(Value::Object(p)) = params.get_mut("props") {
|
||||
normalize_props(p);
|
||||
}
|
||||
normalize_tree(&mut params);
|
||||
let r = exec(b, "node.create", Value::Object(params))?;
|
||||
let id = r.get("id").cloned().ok_or("node.create returned no id")?;
|
||||
let warnings = r.get("warnings").cloned();
|
||||
let node = node_get(b, id_arg(&id)?, 0, &options)?;
|
||||
let mut out = json!({"id": id, "node": node});
|
||||
if let Some(w) = warnings {
|
||||
out["warnings"] = w;
|
||||
for k in ["warnings", "children"] {
|
||||
if let Some(v) = r.get(k) {
|
||||
out[k] = v.clone();
|
||||
}
|
||||
}
|
||||
Ok(ToolResult::json(&out))
|
||||
}
|
||||
|
||||
@@ -105,6 +105,7 @@ fn cmd_or_ctrl_suspends_guide_snapping() {
|
||||
let mut u = rulers(s);
|
||||
let start = from_top_ruler(&u);
|
||||
let to = u.app.to_screen(200.0, 102.0);
|
||||
drag_with(&mut u, start, to, Modifiers::CTRL);
|
||||
// The platform's command key: on macOS a press with Control alone is a secondary press.
|
||||
drag_with(&mut u, start, to, Modifiers::COMMAND);
|
||||
assert_eq!(guides(&u, page(&u)), vec![(false, 102.0)]);
|
||||
}
|
||||
+14
-4
@@ -125,7 +125,7 @@ page 1 "Screens": 380 nodes, 4 top-level
|
||||
…
|
||||
```
|
||||
|
||||
### `export <file> -o <out> [--format png|jpg|svg|webp|pdf|xml|fig|penpot] [--scale N] [--page NAME] [--node ID|NAME] [--bleed LENGTH] [--crop-marks] [--bleed-marks] [--cmyk] [--vd-compat bestEffort|exact|ignore]`
|
||||
### `export <file> -o <out> [--format png|jpg|svg|webp|pdf|xml|fig|penpot] [--scale N] [--page NAME] [--node ID|NAME] [--bleed LENGTH] [--crop-marks] [--bleed-marks] [--cmyk] [--vd-compat bestEffort|exact|ignore] [--strict]`
|
||||
|
||||
- `<out>` is a directory: one file per top-level frame of the selected page, named
|
||||
after the frame (`Home.png`, `Settings.png`…); with no frames, one file per top-level layer.
|
||||
@@ -159,6 +159,12 @@ page 1 "Screens": 380 nodes, 4 top-level
|
||||
Layers opened from a `.penpot` keep their Penpot ids, and unchanged text, layouts, interactions
|
||||
and tokens are written back from the original. What Penpot cannot represent is printed as
|
||||
`note:` lines.
|
||||
- `--strict` (with `fig`, `penpot` or `xml`, the formats that report what they can't hold) turns
|
||||
those notes into a failure: when the export would leave out or change anything, nothing is
|
||||
written or replaced, and the command exits 1 with the reasons on one `error:` line. A folder of
|
||||
drawables is written only when none of its files leaves anything out. With another format, or
|
||||
for xml with `--vd-compat ignore` (which drops content without notes), `--strict` is a usage error.
|
||||
Only what the writer reports counts: what an import of the input left out is not checked.
|
||||
- The format comes from `--format`, else `<out>`'s extension, else png. `--scale` (default 1, max 64)
|
||||
applies to raster formats.
|
||||
- SVG/PDF/XML exports with visible descendants more than 256 levels below an exported root fail with
|
||||
@@ -188,7 +194,7 @@ figcraft-cli export app.figcraft -o poster.pdf --node "Poster" --bleed 3mm --cro
|
||||
figcraft-cli export app.figcraft -o handoff.fig
|
||||
```
|
||||
|
||||
### `convert <in> <out>`
|
||||
### `convert <in> <out> [--in-place] [--strict]`
|
||||
|
||||
By extension. Inputs: `.figcraft`, `.json` (FigCraft or REST API file JSON), `.fig` (best effort), `.sketch` (Sketch 48 or newer, best effort),
|
||||
`.penpot` (Penpot 2.x archive, best effort), `.svg` (an editable frame: groups,
|
||||
@@ -201,13 +207,15 @@ frames, one page each), `.fig` (the whole file, experimental, as `export --forma
|
||||
(the whole file as a Penpot 2.x archive, as `export --format penpot`).
|
||||
|
||||
When converting from a `.penpot` file, import warnings are printed to stderr as `note:` lines.
|
||||
`--strict` refuses to write a `.fig` or `.penpot` `<out>` that would leave out or change content,
|
||||
as for `export` (a `.figcraft` `<out>` keeps everything); with other outputs it is a usage error.
|
||||
|
||||
### `render <file> -o <out.png> [--scale N] [--page NAME]`
|
||||
|
||||
The whole page with its background, as png, jpg or webp. `--page` defaults to the first non-divider
|
||||
page, as for `export`. Large pages are scaled down to fit 16384 px.
|
||||
|
||||
### `run <script.json|script.jsonl> [--in <file>] [--out <file>]`
|
||||
### `run <script.json|script.jsonl> [--in <file>] [--out <file>] [--in-place] [--strict]`
|
||||
|
||||
Runs commands in a headless session (a new document, or `--in`), printing one JSON line per step:
|
||||
|
||||
@@ -234,7 +242,9 @@ created ([Step references](mcp.md#step-references) has the rules):
|
||||
```
|
||||
|
||||
The result lines are printed once the script is through, so none of them reports work a later step
|
||||
took back.
|
||||
took back. `--strict` (with `--out` ending in `.fig`, `.penpot` or `.figcraft`) refuses to save a
|
||||
result that would leave out or change content, as for `export`: the result lines are printed, the
|
||||
file is not written, and the command exits 1.
|
||||
|
||||
To keep going past a failed command, make a step a `command.batch` with `"onError": "continue"`
|
||||
([MCP server](mcp.md) has the rules). If a later top-level step fails, FigCraft rolls back that
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File format parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (`.jam` import: connectors on the page come in as native board connectors attached to the layers they join (#1808); text in a well-known UI or code family that isn't installed draws in a close stand-in in its own style instead of the default sans (#1237); layers pasted from another app drop bindings to variables the file lacks and keep the values they showed (#2524); `.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` filesLine truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (`figcraft-cli export`, `convert` and `run --out` take `--strict`, which writes nothing when the `.fig`, `.penpot` or Android Vector Drawable writer would leave content out (#2384); `.fig` export writes one fill outline per winding rule for vectors whose areas use both; `.jam` import: connectors on the page come in as native board connectors attached to the layers they join (#1808); text in a well-known UI or code family that isn't installed draws in a close stand-in in its own style instead of the default sans (#1237); layers pasted from another app drop bindings to variables the file lacks and keep the values they showed (#2524); `.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB inLine truncated
|
||||
|
||||
Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of
|
||||
`/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's
|
||||
@@ -80,7 +80,9 @@ visible and opaque (a page also its background opacity): a reader takes what is
|
||||
draws nothing below a hidden page. The message
|
||||
lists one node change per layer, parents first, each with its GUID, its parent and a position
|
||||
string that orders it among its siblings; vector networks and outlines go in blobs, written once
|
||||
each. `.fig` export writes a vector's region paint stacks (each filled area's own paints as an entry of the
|
||||
each. `figcraft-cli export`, `convert` and `run --out` take `--strict`: when the writer would leave
|
||||
anything out (the warnings below), no file is written or replaced and the command fails with the
|
||||
list. `.fig` export writes a vector's region paint stacks (each filled area's own paints as an entry of the
|
||||
network's style table, named by the area's style id); a region's kept paint frame is left out with a
|
||||
warning; import and editing preserve their source paint coordinates.
|
||||
|
||||
@@ -94,7 +96,7 @@ scales and empty-style clears; they have not been checked in other software.
|
||||
- **Written:** pages (name, background, ruler guides, prototype background as an opaque colour, for every page); the ruler guides of frames, components and instances, in the layer's own coordinates; frames, groups, sections, rectangles (as rounded
|
||||
rectangles, with their four radii), ellipses (arcs), polygons, stars, lines, vectors (editable
|
||||
network blobs with per-point corner radius, handle mirroring, caps and joins, each filled area's own paints, plus the outline of
|
||||
their filled areas), text, boolean groups, slices; the fill outline of frames and shapes and the
|
||||
their filled areas, one per winding rule when the areas use both), text, boolean groups, slices; the fill outline of frames and shapes and the
|
||||
network blobs with per-point corner radius, handle mirroring, caps and joins, plus the outline of
|
||||
their filled areas), text, text on a path (the first part of its path, where the text starts and its side), boolean groups, slices; the fill outline of frames and shapes and the
|
||||
stroke outline of plain strokes (a ring around boxes and whole ellipses, the widened path of other
|
||||
@@ -206,6 +208,7 @@ scales and empty-style clears; they have not been checked in other software.
|
||||
| 2026-11-28 | patch | M6, part of #2524: layers pasted from another design app kept their bindings to variables the paste didn't bring along, so `boundVariables` named variables the file doesn't have. A pasted layer bound to a variable that isn't in the file (from another app or file, or deleted since the copy) now keeps the value it showed, unbound; bindings to variables the file has stay. Test: `design_paste_tests::bindings_to_variables_the_file_lacks_paste_as_their_values` |
|
||||
| 2026-11-28 | patch | M4, #1237: text set in a family that isn't installed drew in the default face, the first of Inter, Helvetica, Arial… in Regular, whatever the family and style, so code set in Menlo came out proportional and SF Pro Bold came out regular. A well-known UI or code family now draws in the first installed stand-in of similar design and width, in the style asked: SF Pro and SF Compact in Inter (then Pretendard), Google Sans in Roboto, Menlo, Monaco and SF Mono in Cascadia Mono, Consolas or another monospaced font, Euclid in DM Sans; other families keep the default. The stand-in only draws: the family stays listed as missing (Missing fonts, `figcraft-cli info`) and the layer keeps its name. Not built: overriding the table (an environment variable or a command) and naming the stand-in in the missing-fonts list. Test: `fontdb_names_tests::a_well_known_family_that_isnt_installed_draws_with_a_close_stand_in_in_its_style` |
|
||||
| 2026-11-28 | minor | M9, #1808 (step 3): a `.jam` connector came in as a loose vector, so moving a shape it joined left it behind. On a whiteboard the `.fig` mapper's adapter now writes a `board` connector (a FigCraft extension of the REST JSON: `{type: "connector", from, to, routing}`, each end `{node, side, at?}` or a page point `{x, y}`) on a connector drawn as one line on the page: its ends name the layers it joins (a named magnet is that side, `AUTO`, `CENTER` or none the side facing the other end, and an end without a magnet keeps its point on the layer as `at`), and the REST importer, once every layer is in, makes the vector a native board connector (`BoardItem::Connector`) with them, so it is routed again when they move. The line it was drawn with stays until then. A connector with a label (a frame holding its line and label), one inside a frame or section, and every connector in a `.fig` design file stay as they were, and the import report counts only those as vectors. Tests: `board_import_tests::a_jam_connector_is_attached_to_the_layers_it_joins`, `a_fig_connector_stays_a_line`. Numbers unchanged |
|
||||
| 2026-11-28 | minor | #2384: `figcraft-cli export --strict` (also `convert` and `run --out`) refuses to write a `.fig`, `.penpot` or Android Vector Drawable file when the writer reports anything left out or changed: exit 1, the reasons on the error line, no file written or replaced (a folder of drawables only once none of its files leaves anything out). `--strict` with a format that reports nothing, or on a drawable with `--vd-compat ignore`, is a usage error. `.fig` export writes a vector whose filled areas use both winding rules as one fill outline per rule, so other readers fill each area as the network does; the warning about using the first area's rule is gone. Image adjustments, list spacing, hanging punctuation and lists, and vertical trim were already written. OpenType features, variables' publishing, code syntax and inheritance settings, prototype device settings and text styles on part of a text stay left out with their warnings: the `.fig` import (`craft_fig`'s mapping) doesn't read them back yet. |
|
||||
| 2026-11-24 | minor | M8: SVG, PNG, PDF and Android Vector Drawable exports were bigger than what they show around strokes on lines, vectors and polygons. The export took its size from the renderer's bounds, which leave room for a stroke's mitre at the miter limit (4 × the weight on a vector) whatever its corners, so a 24 × 24 icon frame whose outlined strokes stay inside it exported at 26 × 26 to 30 × 25, its content moved off the frame's origin. The export now measures each layer's fill and stroke outlines as drawn (joins, caps and alignment included, a mitre only where a corner keeps one; a dashed stroke as a solid one too, so where the dashes fall doesn't change the size), and grows that by the layer's effects; text and drop shadows with a spread keep the renderer's bounds. The renderer's own bounds are unchanged. Tests: `export_bounds_tests` (3). Numbers unchanged |
|
||||
| 2026-11-23 | patch | M7: Save as to another file left the tab showing the old name unless that name was Untitled or the old file's own name (#935). So a file opened from an import (`.fig`, `.penpot`, `.sketch`), which carries its source's name and has no file yet, kept that name after being saved as `Other.figcraft`, and so did a file renamed here. Now saving to another file always names the document, its tab and the saved file's stored name after the new file, as a desktop app's document window does. Saving to the same file keeps a name given here, so a name with characters a file name can't hold (`aa: design system`) stays until Save as. Test: `save_format_tests::saving_to_another_file_names_the_document_after_it`. |
|
||||
| 2026-11-20 | patch | M6, #2501 follow-up: JPG export inherited 4:2:0 chroma subsampling from the `craft-image-codecs` defaults when #2501 moved it to the shared encoder, so fine colour detail blurred. It asks for 4:4:4 again, as before the cutover (#2521). Tests: `render::tests::jpeg_export_keeps_full_chroma`, and `export_formats_and_what_each_keeps` checks an 8 × 8 corner block clear of the ellipse. Numbers unchanged. |
|
||||
|
||||
@@ -443,6 +443,8 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match.
|
||||
| `batch {commands: [{command, params}], label?}` | Several commands as one undo step (`command.batch`), which keeps one copy of the document however many steps there are (an `edit.undo` step undoes the batch's edits so far together); all-or-nothing for open documents and their document state. Failed inner commands are removed from the journal; preferences, clipboard, tool state and UI requests are not rolled back. A step can use what an earlier step returned: name it with `"as": "card"` and `{"$ref": "card"}` anywhere in a later step's params becomes the `id` in its result (`{"$step": n}` does the same by zero-based position); `"field"` takes another key or a slash path such as `ids/0` (see Step references below). |
|
||||
| `create_node {type, x, y, width, height, parent, index, name, text, path, props, fields?, outline?}` | Create a frame, rectangle, ellipse, polygon, star, line, arrow, text, vector, section, component or slice; returns `{id, node}`. `warnings` reports a fontStyle that draws in another face. `fields` / `outline` shrink `node` as they do for `get_node`; a bad option is an error and creates nothing. |
|
||||
| `set_properties {ids, props, fields?, outline?}` | `node.set` on layers (geometry, fills, strokes, effects, corner radius, auto layout, sizing, constraints, masks (`isMask`, `maskType: alpha\|vector\|luminance`), handoff status (`devStatus: none\|readyForDev\|completed`; marking again clears "Changed"), a section's `sectionContentsHidden`, text…); returns the updated layers (up to 20), which `fields` / `outline` shrink as they do for `get_node`; a bad option is an error and sets nothing. |
|
||||
| `create_node {type, x, y, width, height, parent, index, name, text, path, props, children}` | Create a frame, rectangle, ellipse, polygon, star, line, arrow, text, vector, section, component or slice; returns `{id, node}`. `warnings` reports a fontStyle that draws in another face. `children` makes the layers inside it in the same call and undo step: each takes the same keys but `parent`, its own `children` included, and the result's `children` mirrors the tree (`[{id, children?}, …]`), so a batch step names any of them with a `field` path such as `children/1/id`. A refused child is named by its place (`children[1].children[0]: …`) and nothing is made (#2185). |
|
||||
| `set_properties {ids, props}` | `node.set` on layers (geometry, fills, strokes, effects, corner radius, auto layout, sizing, constraints, masks (`isMask`, `maskType: alpha\|vector\|luminance`), handoff status (`devStatus: none\|readyForDev\|completed`; marking again clears "Changed"), a section's `sectionContentsHidden`, text…); returns the updated layers. |
|
||||
| `inspect_document {depth, allPages, fields?, outline?}` | The document as JSON (its `id`, layer tree, styles, selection, history); `fields` selects layer properties, `outline: true` gives a compact tree (below). The tools that act on a document also take `document` (see Naming the document below). |
|
||||
| `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. |
|
||||
| `design_context {ids?, scope?, depth?, maxNodes?, maxBytes?}` | Everything needed to build a design in one read: see [Design context](#design-context). |
|
||||
|
||||
Reference in new issue
Block a user