M6: app project layouts in figcraft-cli export --layout and the Export dialog (part of #1689)

This commit is contained in:
bflatastic
2026-12-02 08:06:29 +07:00
parent c7546e9e0e
commit 96d437acc2
10 changed files with 136 additions and 37 deletions
+20 -1
View File
@@ -151,6 +151,11 @@ pub struct ExportArgs {
/// content. For fig, penpot and xml, the formats that report what they can't hold
#[arg(long)]
pub strict: bool,
/// Write PNGs in the folders an app project reads, at the scales it wants: flat (one file per
/// layer, the default), flutter (name.png, 2.0x/ and 3.0x/), ios (name.imageset/ with its
/// Contents.json) or android (drawable-mdpi/ to drawable-xxxhdpi/). <OUT> is a folder
#[arg(long, value_name = "flat|flutter|ios|android", value_parser = layout, conflicts_with_all = ["format", "scale"])]
pub layout: Option<String>,
#[command(flatten)]
pub roots: RootArgs,
}
@@ -343,6 +348,8 @@ enum ValueError {
VdCompat,
#[error("expected png, jpg, svg, webp, pdf, xml, fig or penpot")]
Format,
#[error("expected flat, flutter, ios or android")]
Layout,
#[error("expected whole numbers, like 1000,10_000")]
WholeNumber,
#[error("expected a port number or host:port")]
@@ -383,6 +390,12 @@ fn format(s: &str) -> Result<String, ValueError> {
}
}
/// `--layout`, any case; `file.exportLayers` reads the same names.
fn layout(s: &str) -> Result<String, ValueError> {
let l = s.to_ascii_lowercase();
matches!(l.as_str(), "flat" | "flutter" | "ios" | "android").then_some(l).ok_or(ValueError::Layout)
}
fn whole_number(s: &str) -> Result<usize, ValueError> {
s.trim().replace('_', "").parse().map_err(|_| ValueError::WholeNumber)
}
@@ -506,7 +519,9 @@ mod tests {
// The defaults, and `--out` for `-o`.
let Command::Export(a) = ok(&["export", "app.figcraft", "--out=exports/"]) else { panic!("export") };
assert_eq!((a.out.as_str(), a.format.as_deref(), a.scale.scale, a.print().bleed), ("exports/", None, 1.0, 0.0));
assert_eq!(a.vd_compat, figcraft_doc::VdCompat::default());
assert_eq!((a.vd_compat, a.layout.as_deref()), (figcraft_doc::VdCompat::default(), None));
let Command::Export(a) = ok(&["export", "app.figcraft", "-o", "assets/", "--layout", "iOS"]) else { panic!("export") };
assert_eq!(a.layout.as_deref(), Some("ios"));
}
#[test]
@@ -600,6 +615,10 @@ mod tests {
(&["export", "a", "-o", "b", "--bleed", "3in"], ValueValidation),
(&["export", "a", "-o", "b", "--vd-compat", "sloppy"], ValueValidation),
(&["export", "a", "-o", "b", "--format", "bmp"], ValueValidation),
(&["export", "a", "-o", "b", "--layout", "windows"], ValueValidation),
// A layout picks the format and the scales itself.
(&["export", "a", "-o", "b", "--layout", "ios", "--format", "svg"], ArgumentConflict),
(&["export", "a", "-o", "b", "--layout", "android", "--scale", "2"], ArgumentConflict),
(&["export", "a", "-o", "b", "--page", "A", "--page", "B"], ArgumentConflict),
(&["perf", "--shapes", "lots"], UnknownArgument),
(&["perf", "--layers", "10,x"], ValueValidation),
+28 -8
View File
@@ -294,6 +294,18 @@ pub struct Target {
pub vd_compat: VdCompat,
/// Fail, writing nothing, when the export would leave something out (`.fig`, `.penpot` and XML).
pub strict: bool,
/// An app project's folder layout (`file.exportLayers`): flat, flutter, ios or android.
pub layout: Option<String>,
}
/// What a folder export writes: `target`, else the page's top-level frames, else its top-level layers.
fn folder_ids(doc: &Document, page: NodeId, target: Option<NodeId>) -> Vec<NodeId> {
if let Some(t) = target {
return vec![t];
}
let kids = children(doc, page);
let frames: Vec<NodeId> = kids.iter().copied().filter(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like())).collect();
if frames.is_empty() { kids } else { frames }
}
pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32> {
@@ -318,6 +330,21 @@ 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();
if let Some(layout) = t.layout.as_deref().filter(|l| *l != "flat") {
if single {
return Err(CliError::Usage(format!("--layout {layout} writes a folder: give --out a folder, not {out}")));
}
let ids = folder_ids(&doc, page, target);
if ids.is_empty() {
return Err(CliError::Failed("the page is empty: nothing to export".into()));
}
let mut s = Session::with_document(doc);
let r = s.execute("file.exportLayers", &json!({"ids": ids, "layout": layout, "dir": out})).map_err(|e| CliError::Failed(e.to_string()))?;
for f in r["files"].as_array().into_iter().flatten() {
outln!(io, "{}", f["path"].as_str().unwrap_or_default());
}
return Ok(0);
}
// 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() };
@@ -338,14 +365,7 @@ pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32>
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 => {
let kids = children(&doc, page);
let frames: Vec<NodeId> = kids.iter().copied().filter(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like())).collect();
if frames.is_empty() { kids } else { frames }
}
};
let ids = folder_ids(&doc, page, target);
if ids.is_empty() {
return Err(CliError::Failed("the page is empty: nothing to export".into()));
}
+1
View File
@@ -105,6 +105,7 @@ fn dispatch(cli: Cli, io: &mut Io) -> CliResult<i32> {
page: a.page,
node: a.node,
strict: a.strict,
layout: a.layout,
};
confined(&a.roots, || files::export(&a.file, &a.out, &target, io))
}
+22
View File
@@ -224,6 +224,28 @@ fn export_file_names_keep_what_the_app_keeps() {
std::fs::remove_dir_all(&d).ok();
}
/// `export --layout` writes the folders an app project reads (#1689), and only into a folder.
#[test]
fn export_layout_writes_an_app_projects_folders() {
let d = tmp("layout");
let script = d.join("s.json");
std::fs::write(&script, r#"[{"command":"frame.create","params":{"x":0,"y":0,"width":24,"height":24,"name":"Home Icon"}}]"#).unwrap();
let file = d.join("doc.figcraft");
assert!(bin().arg("run").arg(&script).arg("--out").arg(&file).output().unwrap().status.success());
let dir = d.join("res");
let out = bin().arg("export").arg(&file).arg("-o").arg(&dir).args(["--layout", "android"]).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let densities = ["mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"];
for density in densities {
let png = dir.join(format!("drawable-{density}")).join("home_icon.png");
assert!(png.is_file(), "{png:?}");
}
assert_eq!(String::from_utf8_lossy(&out.stdout).lines().count(), densities.len(), "one line per file written");
let one = bin().arg("export").arg(&file).arg("-o").arg(d.join("icon.png")).args(["--layout", "ios"]).output().unwrap();
assert!(!one.status.success() && !d.join("icon.png").exists(), "an image file is no folder for an image set");
std::fs::remove_dir_all(&d).ok();
}
#[test]
fn run_takes_the_documented_gradient_shorthand() {
// #252: only MCP used to accept it; `run` said "`fills` must be paints or colours".
+7
View File
@@ -88,6 +88,7 @@ name = "English"
"Allow" = "Allow"
"Always check with a screenshot" = "Always check with a screenshot"
"API key" = "API key"
"Android: mdpi to xxxhdpi" = "Android: mdpi to xxxhdpi"
"Ask" = "Ask"
"Ask agent…" = "Ask agent…"
"At most {count} images go with one request." = "At most {count} images go with one request."
@@ -140,6 +141,7 @@ name = "English"
"Fill this with realistic content" = "Fill this with realistic content"
"Fine" = "Fine"
"Fix the type hierarchy" = "Fix the type hierarchy"
"Flutter: 1x, 2x and 3x" = "Flutter: 1x, 2x and 3x"
"Frame {start} isn't in this file: presenting from the start." = "Frame {start} isn't in this file: presenting from the start."
"Get a key" = "Get a key"
"How many versions of the design to build" = "How many versions of the design to build"
@@ -521,6 +523,10 @@ name = "English"
"When to use it" = "When to use it"
"Working…" = "Working…"
"Write a description for this component" = "Write a description for this component"
"drawable-mdpi/ to drawable-xxxhdpi/, at 1x, 1.5x, 2x, 3x and 4x" = "drawable-mdpi/ to drawable-xxxhdpi/, at 1x, 1.5x, 2x, 3x and 4x"
"iOS image set: 1x, 2x and 3x" = "iOS image set: 1x, 2x and 3x"
"name.imageset/ with name.png, name@2x.png, name@3x.png and Contents.json" = "name.imageset/ with name.png, name@2x.png, name@3x.png and Contents.json"
"name.png, 2.0x/name.png and 3.0x/name.png" = "name.png, 2.0x/name.png and 3.0x/name.png"
"reads from the web: {hosts}" = "reads from the web: {hosts}"
"{count} steps" = "{count} steps"
"{count} steps, {failed} failed" = "{count} steps, {failed} failed"
@@ -590,6 +596,7 @@ name = "English"
"Variant value" = "Variant value"
"{m} min {s} s" = "{m} min {s} s"
"{name} is not an image this app reads: {error}" = "{name} is not an image this app reads: {error}"
"{n} layers as PNGs in an app project's folders" = { one = "{n} layer as PNGs in an app project's folders", other = "{n} layers as PNGs in an app project's folders" }
"{n} s" = "{n} s"
"≈ ${cost} at API rates" = "≈ ${cost} at API rates"
"⌘ click a padding field" = "⌘ click a padding field"
+1 -1
View File
@@ -10,7 +10,7 @@ use figcraft_engine::cmd::file::{export_jobs, exportable_layers};
use serde_json::{Value, json};
use crate::FigApp;
use crate::export_panel::{export_layers, save_one, suggested_name};
use crate::export_panel::{export_files, export_layers, save_one, suggested_name};
use crate::i18n::{self, tr, tr_noop, trf, trn};
use crate::theme::{Tokens, regular, semibold};
+21 -3
View File
@@ -1,6 +1,6 @@
use super::{
Align2, Context, CornerRadius, ExportFormat, ExportSetting, ExportSize, FigApp, Path, RichText, Sense, Stroke, Tokens, Value, export_jobs,
export_layers, exportable_layers, json, regular, save_one, suggested_name, tr, trf, trn, vec2, window,
Align2, Context, CornerRadius, ExportFormat, ExportSetting, ExportSize, FigApp, Path, RichText, Sense, Stroke, Tokens, Value, export_files,
export_jobs, export_layers, exportable_layers, json, regular, save_one, suggested_name, tr, tr_noop, trf, trn, vec2, window,
};
/// A `.fig` Save as result is an export; only native saves report that the document was saved.
@@ -56,10 +56,19 @@ enum ExportChoice {
Layers,
/// The layers together as one file.
Once(ExportSetting),
/// The layers as PNGs in an app project's folders (`file.exportLayers {layout}`, #1689).
App(&'static str),
/// The whole file as `.fig` (experimental).
Fig,
}
/// The app project layouts the Export dialog offers: `layout`, its row and the files it writes.
const APP_LAYOUTS: [(&str, &str, &str); 3] = [
("flutter", tr_noop("Flutter: 1x, 2x and 3x"), tr_noop("name.png, 2.0x/name.png and 3.0x/name.png")),
("ios", tr_noop("iOS image set: 1x, 2x and 3x"), tr_noop("name.imageset/ with name.png, name@2x.png, name@3x.png and Contents.json")),
("android", tr_noop("Android: mdpi to xxxhdpi"), tr_noop("drawable-mdpi/ to drawable-xxxhdpi/, at 1x, 1.5x, 2x, 3x and 4x")),
];
/// The Export dialog: the layers' own export settings when they have some, and one-off presets for
/// the selection (or the page) as one file.
pub(super) fn export_dialog(app: &mut FigApp, ctx: &Context) {
@@ -143,6 +152,14 @@ pub(super) fn export_dialog(app: &mut FigApp, ctx: &Context) {
app.ui.pdf_print = next;
}
divider(ui);
caption(ui, &trn("{n} layers as PNGs in an app project's folders", ids.len(), &[]));
ui.add_space(4.0);
for (layout, label, tip) in APP_LAYOUTS {
if row_tip(ui, tr(label), Some(tr(tip))) {
choice = Some(ExportChoice::App(layout));
}
}
divider(ui);
caption(ui, tr("The whole file"));
ui.add_space(4.0);
if row(ui, tr(".fig (experimental)")) {
@@ -154,7 +171,8 @@ pub(super) fn export_dialog(app: &mut FigApp, ctx: &Context) {
match choice {
Some(ExportChoice::Layers) => export_layers(app, &with_settings, false),
Some(ExportChoice::Once(s)) if !ids.is_empty() => save_one(app, &ids, &s, &suggested_name(&doc, &ids, &s, "Export")),
Some(ExportChoice::Once(_)) => app.toast(tr("Nothing to export")),
Some(ExportChoice::App(layout)) if !ids.is_empty() => export_files(app, json!({"ids": ids, "layout": layout})),
Some(ExportChoice::Once(_) | ExportChoice::App(_)) => app.toast(tr("Nothing to export")),
Some(ExportChoice::Fig) => save_fig(app, &doc.name),
None => {}
}
+27 -23
View File
@@ -463,32 +463,36 @@ pub(crate) fn export_layers(app: &mut FigApp, ids: &[NodeId], assets: bool) {
[] => {}
// The suggested name keeps only the file's own name (a layer's folders apply to folders).
[one] => save_one(app, &[one.id], &one.setting, one.file.rsplit('/').next().unwrap_or(&one.file)),
// No folders in the browser, and it lets a page start one download at a time: the files
// arrive together as one zip (#969).
_ if app.services.downloads() => {
let name = format!("{}.zip", app.session.doc().map_or("Export", |d| d.name.as_str()));
if let Some(r) = app.run("file.exportLayers", json!({"ids": ids, "assets": assets, "zip": true}))
&& app.download(&name, &r)
{
app.toast(trn("Exported {n} files", r["files"].as_array().map_or(0, Vec::len), &[]));
}
_ => export_files(app, json!({"ids": ids, "assets": assets})),
}
}
/// Run `file.exportLayers` with `params` into a folder the user picks. No folders in the browser,
/// and it lets a page start one download at a time: the files arrive together as one zip (#969).
pub(crate) fn export_files(app: &mut FigApp, mut params: Value) {
if app.services.downloads() {
let name = format!("{}.zip", app.session.doc().map_or("Export", |d| d.name.as_str()));
params["zip"] = json!(true);
if let Some(r) = app.run("file.exportLayers", params)
&& app.download(&name, &r)
{
app.toast(trn("Exported {n} files", r["files"].as_array().map_or(0, Vec::len), &[]));
}
_ => {
let ids = ids.to_vec();
app.pick_folder(tr("Export"), move |app, dir| {
if let Some(r) = app.run("file.exportLayers", json!({"ids": ids, "dir": dir.to_string_lossy(), "assets": assets})) {
let files = r["files"].as_array().cloned().unwrap_or_default();
// Android Vector Drawables say what they changed or left out.
let changed = files.iter().any(|f| f["warnings"].as_array().is_some_and(|w| !w.is_empty()));
app.toast(if changed {
trn("Exported {n} files; some content was changed or left out", files.len(), &[])
} else {
trn("Exported {n} files", files.len(), &[])
});
}
return;
}
app.pick_folder(tr("Export"), move |app, dir| {
params["dir"] = json!(dir.to_string_lossy());
if let Some(r) = app.run("file.exportLayers", params) {
let files = r["files"].as_array().cloned().unwrap_or_default();
// Android Vector Drawables say what they changed or left out.
let changed = files.iter().any(|f| f["warnings"].as_array().is_some_and(|w| !w.is_empty()));
app.toast(if changed {
trn("Exported {n} files; some content was changed or left out", files.len(), &[])
} else {
trn("Exported {n} files", files.len(), &[])
});
}
}
});
}
/// Export `ids` together as one file with `setting`, through a save dialog suggesting `file`.
+8 -1
View File
@@ -142,7 +142,7 @@ $ figcraft-cli diff design.fig roundtrip.fig
show what was dropped or added, not what changed inside a layer: equal counts don't prove the files
are identical.
### `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]`
### `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] [--layout flat|flutter|ios|android]`
- `<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.
@@ -182,6 +182,13 @@ are identical.
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.
- `--layout` writes the layers (the folder's usual frames or layers, or `--node`) as PNGs in the
folders an app project reads images from, at the scales it wants, named in lower snake case
(`Home Icon` → `home_icon`): `flutter` writes `name.png`, `2.0x/name.png` and `3.0x/name.png`;
`ios` an image set, `name.imageset/` with `name.png`, `name@2x.png`, `name@3x.png` and its
`Contents.json`; `android` `drawable-mdpi/` to `drawable-xxxhdpi/` at 1x, 1.5x, 2x, 3x and 4x.
`flat` (the default) is the usual export. `<out>` must be a folder, and `--format` and `--scale`
don't go with it. It is `file.exportLayers {layout}` (see `docs/mcp.md`).
- 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
+1
View File
@@ -206,6 +206,7 @@ scales and empty-style clears; they have not been checked in other software.
| Date | Change | Summary |
|---|---|---|
| 2026-12-02 | minor | M6, part of #1689: the app project layouts reach the CLI and the app. `figcraft-cli export -o <folder> --layout flutter\|ios\|android` writes the page's frames (or `--node`) in that layout through `file.exportLayers {layout}`; `--layout` with `--format`, `--scale` or an image file as `<out>` is refused. The Export dialog lists the three layouts for the selection (or the page's top-level layers), writing into a folder the user picks, or one zip in the browser. Not yet: Android Vector Drawables in `drawable/`. Tests: `cli::export_layout_writes_an_app_projects_folders`, the argument tests. Numbers unchanged |
| 2026-12-02 | minor | M6, #2077: `.xd` files open and import (best effort): artboards, groups, shapes and paths, fills, strokes, shadows and blurs, clip paths, images and text with styled ranges, mapped onto the REST importer like `.sketch`; File ▸ Open, Import, drop, CLI and MCP, in the browser too. Components, prototype links and asset panel entries are not read yet |
| 2026-12-02 | patch | M6, #2442 follow-up: `library.relink` set the text and boolean values the import kept even when the frame's text or visibility was changed after the import, so the edit was lost; it now reads each value from the frame's own layer bound to the property (whatever it is named now), else the one in the place of the main's bound layer, falling back to the kept value; a property the import kept no value of takes the frame's value when it is no longer the default. The import keeps no instance swap values any more: they named a layer by its id in the importing file, which a copy of the frame into another file carried along unchanged (the swap still comes back as the nested instance's own component). Tests: `library_relink_tests`. |
| 2026-12-02 | minor | M6, part of #2338: `.fig` export wrote superscript and subscript nowhere and warned that they were left out. Each text style, the layer's and every override, now carries its position as the format's `fontVariantPosition` (`SUPER`, `SUB`; `NORMAL` only on an override that puts characters of a raised or lowered layer back on the line), so a footnote mark stays raised in a saved `.fig`, and the warning is gone. `.fig` import doesn't read the field yet (craft-libs' `craft-fig`). Tests: `fig::interop_tests::superscript_and_subscript_are_written_per_style`. Numbers unchanged |