Skip to content

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

fix(CLI): measure text in its fonts when converting a .pen file (#1466)

Marcos Velásquez8ef84904d674
diff --git a/changes/1466/added.md b/changes/1466/added.md
new file mode 100644
index 000000000..532a3e1c0
--- /dev/null
+++ b/changes/1466/added.md
@@ -0,0 +1 @@
+- `openpencil convert` reports a font it cannot load and takes `--font-policy`, as `export` does.
diff --git a/changes/1466/fixed.md b/changes/1466/fixed.md
new file mode 100644
index 000000000..5b72faab5
--- /dev/null
+++ b/changes/1466/fixed.md
@@ -0,0 +1 @@
+- `openpencil convert` measures the text of a `.pen` or draw.io file in its own fonts, so converted tags, buttons and labels keep their width.
diff --git a/packages/cli/src/commands/convert.ts b/packages/cli/src/commands/convert.ts
index 1883846e3..3b27337a5 100644
--- a/packages/cli/src/commands/convert.ts
+++ b/packages/cli/src/commands/convert.ts
@@ -4,10 +4,12 @@ import { basename, extname, resolve } from 'node:path'
import { defineCommand } from 'citty'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
+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, populateWholeDocument } from '#cli/headless'
+import { loadDocument, measureDocumentText, populateWholeDocument } from '#cli/headless'
const io = new IORegistry(BUILTIN_IO_FORMATS)
@@ -39,6 +41,12 @@ export default defineCommand({
alias: 'f',
description: 'Output format: fig (default: fig)',
default: 'fig'
+ },
+ 'font-policy': {
+ type: 'string',
+ description:
+ 'When a font of the document is missing: warn, strict (fail without writing), or allow (default: warn)',
+ default: 'warn'
}
},
async run({ args }) {
@@ -49,9 +57,24 @@ export default defineCommand({
process.exit(1)
}
+ if (!FONT_POLICIES.has(args['font-policy'])) {
+ printError(`Invalid font policy "${args['font-policy']}". Use warn, strict, or allow.`)
+ process.exit(1)
+ }
+
const file = requireFile(args.file)
const graph = await loadDocument(file)
populateWholeDocument(graph)
+ // A format that stores layout intent, such as .pen, was laid out as it was read, with its
+ // text estimated. The output keeps those sizes, so lay it out again with its text measured
+ // in its own fonts, as the app and raster export draw it.
+ if (io.findReader(file)?.laysOutOnRead) {
+ reportFontStatus(await measureDocumentText(graph), args['font-policy'])
+ layoutAuthoredNodes(
+ graph,
+ 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)
diff --git a/packages/cli/src/commands/export/font-policy.ts b/packages/cli/src/commands/export/font-policy.ts
index d14a7db6a..6e7b46a3d 100644
--- a/packages/cli/src/commands/export/font-policy.ts
+++ b/packages/cli/src/commands/export/font-policy.ts
@@ -1,19 +1,16 @@
-import { prepareGraphFonts } from '@open-pencil/core/text'
+import { prepareGraphFonts, type DocumentFontStatus } from '@open-pencil/core/text'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { fail, printError } from '#cli/format'
export const FONT_POLICIES = new Set(['allow', 'strict', 'warn'])
-export async function applyExportFontPolicy(
- graph: SceneGraph,
- roots: string[],
- format: string,
- policy: string
-): Promise<void> {
- if (policy === 'allow' || !['PNG', 'JPG', 'WEBP', 'PDF'].includes(format)) return
- const status = await prepareGraphFonts(graph, roots)
- if (status.faithful) return
+/**
+ * Reports the fonts a document could not load as `policy` asks: a warning, a failure before
+ * anything is written (`strict`), or nothing (`allow`).
+ */
+export function reportFontStatus(status: DocumentFontStatus, policy: string): void {
+ if (policy === 'allow' || status.faithful) return
const names = status.issues.map((face) => `${face.family} ${face.style}`).join(', ')
const message = `Font substitution: ${names}`
if (policy === 'strict') {
@@ -23,6 +20,16 @@ export async function applyExportFontPolicy(
console.error(fail(message))
}
+export async function applyExportFontPolicy(
+ graph: SceneGraph,
+ roots: string[],
+ format: string,
+ policy: string
+): Promise<void> {
+ if (policy === 'allow' || !['PNG', 'JPG', 'WEBP', 'PDF'].includes(format)) return
+ reportFontStatus(await prepareGraphFonts(graph, roots), policy)
+}
+
export function exportFontRoots(
nodeId: string | undefined,
pageId: string,
diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.ts
index 9f9d79b0a..fbda6e11e 100644
--- a/packages/cli/src/headless.ts
+++ b/packages/cli/src/headless.ts
@@ -7,7 +7,7 @@ import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/forma
import { headlessHTMLReader } from '@open-pencil/core/io/formats/html/import'
import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
import { computeAllLayouts, installTextMeasurer } from '@open-pencil/core/layout'
-import { prepareGraphFonts } from '@open-pencil/core/text'
+import { prepareGraphFonts, type DocumentFontStatus } from '@open-pencil/core/text'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { printError } from '#cli/format'
@@ -68,11 +68,12 @@ export function measureTextHeadlessly(): Promise<void> {
/**
* Measures the text an edit to `graph` lays out as `measureTextHeadlessly` does, in the fonts the
* document uses: a weight or family the measurer does not start with is otherwise measured in a
- * stand-in, and the edited layer comes out taller or wider than the app draws it.
+ * stand-in, and the edited layer comes out taller or wider than the app draws it. Returns which
+ * of those fonts could not be loaded.
*/
-export async function measureDocumentText(graph: SceneGraph): Promise<void> {
+export async function measureDocumentText(graph: SceneGraph): Promise<DocumentFontStatus> {
await measureTextHeadlessly()
- await prepareGraphFonts(
+ return prepareGraphFonts(
graph,
graph.getPages(true).map((page) => page.id)
)
diff --git a/packages/cli/tests/commands/convert.test.ts b/packages/cli/tests/commands/convert.test.ts
new file mode 100644
index 000000000..971653fb6
--- /dev/null
+++ b/packages/cli/tests/commands/convert.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, setDefaultTimeout, test } from 'bun:test'
+import { mkdtemp } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { CLI_ENTRY } from '#cli-tests/helpers/paths'
+
+import { getTextMeasurer } from '@open-pencil/core/layout'
+
+import { loadDocument, measureDocumentText } from '#cli/headless'
+
+setDefaultTimeout(60_000)
+
+async function cli(args: string[]) {
+ const proc = Bun.spawn([process.execPath, CLI_ENTRY, ...args], { stdout: 'pipe', stderr: 'pipe' })
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text()
+ ])
+ return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode: await proc.exited }
+}
+
+describe('convert CLI', () => {
+ test('saves a .pen document with its text measured in its own fonts', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-convert-'))
+ const source = join(dir, 'tag.pen')
+ const output = join(dir, 'tag.fig')
+ await Bun.write(
+ source,
+ JSON.stringify({
+ version: '2.21',
+ children: [
+ {
+ id: 'tag',
+ type: 'frame',
+ layout: 'horizontal',
+ padding: [4, 10],
+ children: [
+ {
+ id: 'label',
+ type: 'text',
+ content: '1 lote propuesto',
+ fontFamily: 'Inter',
+ fontSize: 12,
+ fontWeight: '600',
+ fill: '#111111'
+ }
+ ]
+ }
+ ]
+ })
+ )
+ expect((await cli(['convert', source, '-o', output])).exitCode).toBe(0)
+
+ const graph = await loadDocument(output)
+ const label = [...graph.getAllNodes()].find((node) => node.type === 'TEXT')
+ if (!label) throw new Error('Expected the label')
+ await measureDocumentText(graph)
+ const measured = getTextMeasurer()?.(label)
+ if (!measured) throw new Error('Expected the label measured in its font')
+ expect(label.width).toBeCloseTo(measured.width, 0)
+ expect(graph.getNode(label.parentId ?? '')?.width).toBeCloseTo(measured.width + 20, 0)
+ })
+
+ test('reports a font it cannot load, and with --font-policy strict writes nothing', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-convert-fonts-'))
+ const source = join(dir, 'note.pen')
+ await Bun.write(
+ source,
+ JSON.stringify({
+ version: '2.21',
+ children: [
+ { id: 'note', type: 'text', content: 'Hola', fontFamily: 'Definitely Missing Font' }
+ ]
+ })
+ )
+ const warned = await cli(['convert', source, '-o', join(dir, 'warned.fig')])
+ expect(warned.exitCode).toBe(0)
+ expect(warned.stderr).toContain('Definitely Missing Font')
+ expect(await Bun.file(join(dir, 'warned.fig')).exists()).toBe(true)
+
+ const strict = await cli([
+ 'convert',
+ source,
+ '-o',
+ join(dir, 'strict.fig'),
+ '--font-policy',
+ 'strict'
+ ])
+ expect(strict.exitCode).not.toBe(0)
+ expect(await Bun.file(join(dir, 'strict.fig')).exists()).toBe(false)
+ })
+})
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index 2ba7e9e57..19239a783 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -301,6 +301,7 @@ export const penFormat: IOFormatAdapter<'pen'> = {
support: {
readDocument: true
},
+ laysOutOnRead: true,
matchesFile(fileName, mimeType) {
return lowerExt(fileName) === 'pen' || mimeType === 'application/json'
},
@@ -341,6 +342,7 @@ export const drawioFormat: IOFormatAdapter<'drawio'> = {
exportNode: true
},
exportOptions: FIXED_SIZE_EXPORT,
+ laysOutOnRead: true,
// A draw.io PNG or SVG export opens as its diagram when its name says it is one.
matchesFile(fileName, mimeType) {
const ext = lowerExt(fileName)
diff --git a/packages/core/src/io/types.ts b/packages/core/src/io/types.ts
index 20f95e8c6..2212e9041 100644
--- a/packages/core/src/io/types.ts
+++ b/packages/core/src/io/types.ts
@@ -139,6 +139,11 @@ export interface IOFormatAdapter<Id extends string = string> {
mimeTypes: string[]
support: IOFormatSupport
exportOptions?: IOFormatExportOptions
+ /**
+ * The format stores layout intent rather than the sizes it implies, so reading lays the layers
+ * out, measuring text with whatever measurer is installed.
+ */
+ laysOutOnRead?: boolean
matchesFile?(fileName: string, mimeType?: string): boolean
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index 7445bdc45..df15dcecd 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -32,12 +32,13 @@ Options:
## Font Substitution Policy
-For file-backed PNG, JPG, WEBP, and PDF exports, choose how missing or substituted fonts are handled:
+For file-backed PNG, JPG, WEBP, and PDF exports, and for `openpencil convert`, choose how missing or substituted fonts are handled:
```sh
openpencil export design.fig -f pdf --font-policy strict
openpencil export design.fig -f png --font-policy warn
openpencil export design.fig -f webp --font-policy allow
+openpencil convert design.pen --font-policy strict
```
- `warn` (default) — report substitutions and continue exporting.
@@ -46,7 +47,9 @@ openpencil export design.fig -f webp --font-policy allow
Run [`openpencil fonts`](./inspecting#font-diagnostics) first to inspect affected faces. Export preparation may use configured font providers, so its result can differ from the offline file diagnostic.
-This policy does not apply to exports from the running app, or to SVG, PowerPoint, JSX, HTML, and `.fig` output. It checks font resolution, not complete visual equivalence with Figma.
+`convert` loads fonts for `.pen` and draw.io files, which store layout intent rather than sizes: it lays them out again with their text measured in their own fonts before writing, so `strict` stops it before anything is written.
+
+This policy does not apply to exports from the running app, or to SVG, PowerPoint, JSX, HTML, and `.fig` exports. It checks font resolution, not complete visual equivalence with Figma.
## JSX Export
@@ -108,12 +111,12 @@ Each collection's default mode goes in `:root`. Every other mode overrides the v
```css
:root {
- --color-blue-500: #3B82F5;
+ --color-blue-500: #3b82f5;
--color-primary: var(--color-blue-500);
}
/* Theme: Dark */
-[data-theme="dark"] {
+[data-theme='dark'] {
--color-primary: var(--color-blue-300);
}
```