Skip to content

AI-native design editor. Open-source Figma alternative.

fix(cli): render the .fig thumbnail whenever the CLI saves a .fig (#1544)

Danila Poyarkov330935b2696d
diff --git a/bun.lock b/bun.lock
index a4079d613..aed6072c2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -207,6 +207,7 @@
"valibot": "^1.5.0",
},
"devDependencies": {
+ "@open-pencil/fig": "workspace:*",
"@types/bun": "^1.3.14",
},
},
diff --git a/changes/1544/fixed.md b/changes/1544/fixed.md
new file mode 100644
index 000000000..b3c8adfee
--- /dev/null
+++ b/changes/1544/fixed.md
@@ -0,0 +1 @@
+- The CLI saves a `.fig` with a rendered thumbnail, as `openpencil export` does, instead of a blank 1×1 placeholder: `convert`, `import`, `lint --fix`, and `eval`, `tool call`, and `diff apply` with `--write` or `--output`.
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 088fc2a5d..57db3916c 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -57,6 +57,7 @@
"valibot": "^1.5.0"
},
"devDependencies": {
+ "@open-pencil/fig": "workspace:*",
"@types/bun": "^1.3.14"
}
}
diff --git a/packages/cli/src/commands/convert.ts b/packages/cli/src/commands/convert.ts
index 3b27337a5..84048d4a9 100644
--- a/packages/cli/src/commands/convert.ts
+++ b/packages/cli/src/commands/convert.ts
@@ -9,7 +9,12 @@ import { layoutAuthoredNodes } from '@open-pencil/core/layout'
import { requireFile } from '#cli/app/client'
import { FONT_POLICIES, reportFontStatus } from '#cli/commands/export/font-policy'
import { ok, printError } from '#cli/format'
-import { loadDocument, measureDocumentText, populateWholeDocument } from '#cli/headless'
+import {
+ loadDocument,
+ measureDocumentText,
+ populateWholeDocument,
+ writeFigDocument
+} from '#cli/headless'
const io = new IORegistry(BUILTIN_IO_FORMATS)
@@ -75,9 +80,9 @@ export default defineCommand({
graph.getPages(true).map((page) => page.id)
)
}
- const result = await io.writeDocument(format, graph)
const output = args.output ? resolve(args.output) : defaultOutput(file, format)
- await writeFile(output, result.data as Uint8Array)
+ if (format === 'fig') await writeFigDocument(graph, output)
+ else await writeFile(output, (await io.writeDocument(format, graph)).data as Uint8Array)
console.log(ok(`Converted ${file} → ${output}`))
}
})
diff --git a/packages/cli/src/commands/import.ts b/packages/cli/src/commands/import.ts
index 4912e277b..f84abb2c8 100644
--- a/packages/cli/src/commands/import.ts
+++ b/packages/cli/src/commands/import.ts
@@ -3,13 +3,12 @@ import { basename, dirname, extname, resolve } from 'node:path'
import { defineCommand } from 'citty'
-import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
import { readHTMLDocument, type ReadHTMLResult } from '@open-pencil/core/io/formats/html/import'
import { requireFile } from '#cli/app/client'
import { fmtList, ok, printError } from '#cli/format'
+import { writeFigDocument } from '#cli/headless'
-const io = new IORegistry(BUILTIN_IO_FORMATS)
const OUTPUT_FORMATS = new Set(['fig', 'json'])
interface ImportArgs {
@@ -69,8 +68,7 @@ async function writeOutput(args: ImportArgs, { styled, graph }: ReadHTMLResult)
return output
}
- const result = await io.writeDocument('fig', graph)
- await writeFile(output, result.data as Uint8Array)
+ await writeFigDocument(graph, output)
return output
}
diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.ts
index 58c7b1985..f404ed6d3 100644
--- a/packages/cli/src/commands/lint.ts
+++ b/packages/cli/src/commands/lint.ts
@@ -1,9 +1,7 @@
-import { writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { defineCommand } from 'citty'
-import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
import { computeAllLayouts } from '@open-pencil/core/layout'
import {
allRules,
@@ -16,7 +14,7 @@ import {
} from '@open-pencil/core/lint'
import { bold, dim, fail, fmtList, ok, printError } from '#cli/format'
-import { loadDocument, populateWholeDocument } from '#cli/headless'
+import { loadDocument, populateWholeDocument, writeFigDocument } from '#cli/headless'
function formatSeverity(severity: LintMessage['severity']) {
if (severity === 'error') return fail('error')
@@ -100,8 +98,7 @@ export default defineCommand({
const applied = applyLintFixes(graphFixTarget(graph), safeFixes(result.messages))
computeAllLayouts(graph)
const output = resolve(args.output)
- const written = await new IORegistry(BUILTIN_IO_FORMATS).writeDocument('fig', graph)
- await writeFile(output, written.data as Uint8Array)
+ await writeFigDocument(graph, output)
if (!args.json) console.log(ok(`Applied ${applied} fixes → ${output}`))
result = linter.lintGraph(graph)
}
diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.ts
index 81dce7f86..e268bee26 100644
--- a/packages/cli/src/headless.ts
+++ b/packages/cli/src/headless.ts
@@ -90,9 +90,9 @@ export const documentWriteOptions = {
output: { type: 'string', alias: 'o', description: 'Write to a different file', required: false }
} as const
-/** Save a headless document as `.fig`, as `eval --write` and `diff apply --write` do. */
+/** Save a headless document as `.fig`, with the thumbnail `export --format fig` renders. */
export async function writeFigDocument(graph: SceneGraph, filePath: string): Promise<void> {
- const result = await io.writeDocument('fig', graph)
+ const result = await io.writeDocument('fig', graph, { renderThumbnail: true })
await writeFile(filePath, result.data as Uint8Array)
}
diff --git a/packages/cli/tests/commands/convert.test.ts b/packages/cli/tests/commands/convert.test.ts
index 971653fb6..00a876266 100644
--- a/packages/cli/tests/commands/convert.test.ts
+++ b/packages/cli/tests/commands/convert.test.ts
@@ -1,8 +1,9 @@
import { describe, expect, setDefaultTimeout, test } from 'bun:test'
-import { mkdtemp } from 'node:fs/promises'
+import { mkdtemp, readFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { figThumbnailSize } from '#cli-tests/helpers/fig'
import { CLI_ENTRY } from '#cli-tests/helpers/paths'
import { getTextMeasurer } from '@open-pencil/core/layout'
@@ -90,4 +91,21 @@ describe('convert CLI', () => {
expect(strict.exitCode).not.toBe(0)
expect(await Bun.file(join(dir, 'strict.fig')).exists()).toBe(false)
})
+
+ test('saves a .fig with a thumbnail of its layers', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-convert-'))
+ const source = join(dir, 'card.pen')
+ const output = join(dir, 'card.fig')
+ await Bun.write(
+ source,
+ JSON.stringify({
+ version: '2.21',
+ children: [{ id: 'card', type: 'rectangle', width: 300, height: 200, fill: '#111111' }]
+ })
+ )
+ expect((await cli(['convert', source, '-o', output])).exitCode).toBe(0)
+
+ const { width, height } = figThumbnailSize(await readFile(output))
+ expect(width / height).toBeCloseTo(300 / 200, 2)
+ })
})
diff --git a/packages/cli/tests/commands/eval.test.ts b/packages/cli/tests/commands/eval.test.ts
index c56edfef3..597c3ee22 100644
--- a/packages/cli/tests/commands/eval.test.ts
+++ b/packages/cli/tests/commands/eval.test.ts
@@ -1,8 +1,9 @@
import { describe, expect, setDefaultTimeout, test } from 'bun:test'
-import { mkdtemp } from 'node:fs/promises'
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { figThumbnailSize } from '#cli-tests/helpers/fig'
import { CLI_ENTRY, FIXTURES } from '#cli-tests/helpers/paths'
import * as v from 'valibot'
@@ -137,4 +138,26 @@ describe('eval CLI', () => {
const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), v.array(v.boolean())), read.stdout)
expect(parsed.success && parsed.output).toEqual([true, true])
})
+
+ test('--write saves a thumbnail of the Cover page', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-eval-'))
+ const html = join(dir, 'tall.html')
+ const file = join(dir, 'cover.fig')
+ await writeFile(html, '<div style="width:100px;height:400px;background:#000"></div>')
+ expect((await cli(['import', html, '-o', file])).exitCode).toBe(0)
+
+ const script = `
+ const cover = figma.createPage()
+ cover.name = 'Cover'
+ const card = figma.createRectangle()
+ card.resize(300, 200)
+ cover.appendChild(card)
+ `
+ expect((await cli(['eval', file, '--stdin', '-w', '-q'], script)).exitCode).toBe(0)
+
+ const { width, height } = figThumbnailSize(await readFile(file))
+ // Not the 1 × 1 placeholder, and the Cover page's 3:2 card rather than the first page's.
+ expect(Math.min(width, height)).toBeGreaterThan(1)
+ expect(width / height).toBeCloseTo(300 / 200, 2)
+ })
})
diff --git a/packages/cli/tests/commands/import.test.ts b/packages/cli/tests/commands/import.test.ts
index a743c7aca..e97ff1d3f 100644
--- a/packages/cli/tests/commands/import.test.ts
+++ b/packages/cli/tests/commands/import.test.ts
@@ -3,6 +3,7 @@ import { mkdtemp, readFile, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { figThumbnailSize } from '#cli-tests/helpers/fig'
import { CLI_ENTRY } from '#cli-tests/helpers/paths'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
@@ -45,4 +46,15 @@ describe('import CLI', () => {
expect(first).toMatchObject({ x: 24, y: 24, width: 100, height: 40 })
expect(second).toMatchObject({ x: 24, y: 80, width: 200, height: 60 })
})
+
+ test('saves a thumbnail of the imported layers', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-import-'))
+ const htmlPath = join(dir, 'tall.html')
+ const figPath = join(dir, 'tall.fig')
+ await writeFile(htmlPath, '<div style="width:100px;height:400px;background:#000"></div>')
+ expect((await cli(['import', htmlPath, '-o', figPath])).exitCode).toBe(0)
+
+ const { width, height } = figThumbnailSize(await readFile(figPath))
+ expect(width / height).toBeCloseTo(100 / 400, 2)
+ })
})
diff --git a/packages/cli/tests/commands/lint.test.ts b/packages/cli/tests/commands/lint.test.ts
new file mode 100644
index 000000000..6baac7138
--- /dev/null
+++ b/packages/cli/tests/commands/lint.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, setDefaultTimeout, test } from 'bun:test'
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { figThumbnailSize } from '#cli-tests/helpers/fig'
+import { CLI_ENTRY } from '#cli-tests/helpers/paths'
+
+setDefaultTimeout(60_000)
+
+async function cli(args: string[]) {
+ const proc = Bun.spawn([process.execPath, CLI_ENTRY, ...args], { stdout: 'pipe', stderr: 'pipe' })
+ return { exitCode: await proc.exited }
+}
+
+describe('lint CLI', () => {
+ test('--fix --output saves a thumbnail of the fixed layers', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-lint-'))
+ const htmlPath = join(dir, 'tall.html')
+ const figPath = join(dir, 'tall.fig')
+ const fixedPath = join(dir, 'fixed.fig')
+ await writeFile(htmlPath, '<div style="width:100px;height:400px;background:#000"></div>')
+ expect((await cli(['import', htmlPath, '-o', figPath])).exitCode).toBe(0)
+
+ await cli(['lint', figPath, '--fix', '-o', fixedPath])
+
+ const { width, height } = figThumbnailSize(await readFile(fixedPath))
+ expect(width / height).toBeCloseTo(100 / 400, 2)
+ })
+})
diff --git a/packages/cli/tests/helpers/fig.ts b/packages/cli/tests/helpers/fig.ts
new file mode 100644
index 000000000..f5836ca17
--- /dev/null
+++ b/packages/cli/tests/helpers/fig.ts
@@ -0,0 +1,11 @@
+import { parseFigBuffer } from '@open-pencil/fig'
+import { imageSize } from '@open-pencil/scene-graph/images'
+import type { Size } from '@open-pencil/scene-graph/primitives'
+
+/** The size of the `thumbnail.png` a `.fig` carries. */
+export function figThumbnailSize(fig: Uint8Array): Size {
+ const png = parseFigBuffer(fig.slice().buffer).thumbnailPNG
+ const size = png && imageSize(png)
+ if (!size) throw new Error('The archive has no thumbnail.png')
+ return size
+}
diff --git a/packages/core/src/io/formats/raster/headless.ts b/packages/core/src/io/formats/raster/headless.ts
index 4796b79a1..fa0c34f10 100644
--- a/packages/core/src/io/formats/raster/headless.ts
+++ b/packages/core/src/io/formats/raster/headless.ts
@@ -63,5 +63,6 @@ export async function headlessRenderThumbnail(
): Promise<Uint8Array | null> {
const { ck, renderer } = await getRenderer()
renderer.invalidateAllPictures()
+ await renderer.prepareForExport(graph, pageId, graph.getNode(pageId)?.childIds ?? [])
return renderThumbnail(ck, renderer, graph, pageId, width, height)
}
diff --git a/packages/core/tests/io/formats/raster/thumbnail.test.ts b/packages/core/tests/io/formats/raster/thumbnail.test.ts
index bf481695c..beb8364e6 100644
--- a/packages/core/tests/io/formats/raster/thumbnail.test.ts
+++ b/packages/core/tests/io/formats/raster/thumbnail.test.ts
@@ -29,3 +29,22 @@ test('a thumbnail shows the page background between its layers', async () => {
expect([...image.data.subarray(gap, gap + 4)]).toEqual([30, 30, 30, 255])
})
+
+test('a thumbnail loads the faces its text is set in before drawing it', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ // Inter Bold is bundled, so loading it needs no network, but a renderer loads only Regular.
+ graph.createNode('TEXT', page.id, {
+ width: 200,
+ height: 60,
+ text: 'Hello',
+ fontSize: 48,
+ fontWeight: 700
+ })
+
+ const png = expectDefined(await headlessRenderThumbnail(graph, page.id, 200, 60), 'thumbnail')
+ const image = expectDefined(createCanvasKitRasterCodec(await initCanvasKit()).decode(png))
+ const inked = image.data.filter((red, index) => index % 4 === 0 && red < 128).length
+
+ expect(inked).toBeGreaterThan(0)
+})
diff --git a/packages/docs/reference/file-format.md b/packages/docs/reference/file-format.md
index 7d29dfee1..40c2712af 100644
--- a/packages/docs/reference/file-format.md
+++ b/packages/docs/reference/file-format.md
@@ -41,7 +41,7 @@ SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd)
→ write .fig file
```
-Export uses <kbd>⌘</kbd><kbd>S</kbd> (Save) and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. OpenPencil uses the first page named exactly `Cover` (case-insensitive), then the first page whose name contains `Cover`. The desktop app also caches this Cover after opening a file so Recent Files can prefer the generated preview without modifying the source `.fig`.
+Export uses <kbd>⌘</kbd><kbd>S</kbd> (Save) and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. OpenPencil draws it from the first page named exactly `Cover` (case-insensitive), then the first page whose name contains `Cover`, then the first page, and writes a 1×1 placeholder when that page has nothing to draw. The CLI draws it too whenever it saves a `.fig`: `export --format fig`, `convert`, `import`, `lint --fix`, and `eval`, `tool call`, or `diff apply` with `--write` or `--output`. The desktop app also caches this Cover after opening a file so Recent Files can prefer the generated preview without modifying the source `.fig`.
Compression uses Zstd at the level the document asks for (see [Compression](#compression)): through a Tauri Rust command on desktop, Bun's own Zstd in the CLI, and a WebAssembly build in the browser.