Skip to content

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

fix: export PDFs from the CLI, and draw CJK web fonts split into unicode-range files (#1538)

Danila Poyarkov05f90ff3d97a
diff --git a/bun.lock b/bun.lock
index a634c7fa1..a4079d613 100644
--- a/bun.lock
+++ b/bun.lock
@@ -73,6 +73,7 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fuse.js": "^7.5.0",
+ "happy-dom": "^20.14.6",
"harfbuzzjs": "1.6.4",
"hast-util-to-html": "^9.0.5",
"idb": "^8.0.3",
@@ -291,6 +292,7 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fontoxpath": "^3.34.0",
+ "happy-dom": "^20.14.6",
"harfbuzzjs": "1.6.4",
"js-base64": "^3.9.3",
"jsep": "^1.4.0",
@@ -850,6 +852,9 @@
},
},
},
+ "patchedDependencies": {
+ },
"overrides": {
"@codemirror/view": "6.43.9",
"protobufjs": "7.5.5",
@@ -2456,6 +2461,8 @@
"@types/web-bluetooth": ["@types/[email protected]", "", {}, "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA=="],
+ "@types/whatwg-mimetype": ["@types/[email protected]", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
+
"@types/which": ["@types/[email protected]", "", {}, "sha512-113D3mDkZDjo+EeUEHCFy0qniNc1ZpecGiAU7WSo7YDoSzolZIQKpYFHrPpjkB2nuyahcKfrmLXeQlh7gqJYdw=="],
"@types/ws": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
@@ -2870,6 +2877,8 @@
"buffer-from": ["[email protected]", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
+ "buffer-image-size": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ=="],
+
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
@@ -3470,6 +3479,8 @@
"grok-mermaid": ["[email protected]", "", {}, "sha512-XcJEP5dDC8liHBh52mlLjU18fNvu1ckFsu0QpIG3+APZ270fsj9wxpiA6cOURmbUEuoMVgjbC2+UYgTdCqqgzA=="],
+ "happy-dom": ["[email protected]", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-5DDsf4QmEIlRL6NkCv/fxSjYHHkZceL/IaYQdJc2h3G7DRTEai++VTjbfL0LB9geW2VrA3+vrjF3Efx+OTtX0Q=="],
+
"harfbuzzjs": ["[email protected]", "", {}, "sha512-T/PyfhVt1gGR2Tkf5KJUj1DQFkVBXHw552lS1iLEEDhV1Lukb3eq1pk2ov85kgbT2YUiZtJBTak9w+M7YgzUEQ=="],
"has-bigints": ["[email protected]", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],
@@ -4970,7 +4981,7 @@
"whatwg-encoding": ["[email protected]", "", { "dependencies": { "iconv-lite": "0.6.3" } }, "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ=="],
- "whatwg-mimetype": ["[email protected]", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="],
+ "whatwg-mimetype": ["[email protected]", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="],
"which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
@@ -5374,6 +5385,8 @@
"cheerio/undici": ["[email protected]", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="],
+ "cheerio/whatwg-mimetype": ["[email protected]", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="],
+
"cli-highlight/parse5": ["[email protected]", "", {}, "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug=="],
"cli-highlight/yargs": ["[email protected]", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w=="],
@@ -5452,6 +5465,8 @@
"gray-matter/js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w=="],
+ "happy-dom/entities": ["[email protected]", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
+
"htmlparser2/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
"import-fresh/resolve-from": ["[email protected]", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
diff --git a/changes/1538/fixed.md b/changes/1538/fixed.md
new file mode 100644
index 000000000..323f4243a
--- /dev/null
+++ b/changes/1538/fixed.md
@@ -0,0 +1,3 @@
+- `open-pencil export -f pdf` exports PDFs instead of failing with "DOMParser is not defined".
+- Japanese, Chinese, and Korean text in web fonts draws in the browser app, in a CJK family and as a fallback for other fonts, instead of drawing missing-glyph boxes or nothing.
+- Text a CLI script writes in characters its font had not loaded yet, such as Japanese, is saved with its glyphs and at its size, instead of with missing-glyph boxes in a box of the wrong size.
diff --git a/package.json b/package.json
index b42f4ecc0..66e00fe2d 100644
--- a/package.json
+++ b/package.json
@@ -188,6 +188,7 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fuse.js": "^7.5.0",
+ "happy-dom": "^20.14.6",
"harfbuzzjs": "1.6.4",
"hast-util-to-html": "^9.0.5",
"idb": "^8.0.3",
@@ -305,5 +306,8 @@
"protobufjs": "7.5.5",
"websocket-driver": "0.7.5"
},
- "packageManager": "[email protected]"
+ "packageManager": "[email protected]",
+ "patchedDependencies": {
+ }
}
diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.ts
index 44c551bce..4be512541 100644
--- a/packages/cli/src/commands/eval.ts
+++ b/packages/cli/src/commands/eval.ts
@@ -8,6 +8,7 @@ import { appTargetOptions, appTargetRPCArgs } from '#cli/app/target'
import { printError } from '#cli/format'
import {
documentWriteOptions,
+ editDocument,
loadDocument,
measureDocumentText,
populateWholeDocument,
@@ -76,7 +77,7 @@ export default defineCommand({
let result: unknown
try {
- result = await compileScript(code)(figma)
+ result = await editDocument(graph, () => compileScript(code)(figma))
} catch (err) {
printError(err instanceof Error ? err.message : String(err))
process.exit(1)
diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.ts
index fbda6e11e..81dce7f86 100644
--- a/packages/cli/src/headless.ts
+++ b/packages/cli/src/headless.ts
@@ -6,9 +6,14 @@ import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'
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 {
+ computeAllLayouts,
+ installTextMeasurer,
+ sizeAutoResizingText
+} from '@open-pencil/core/layout'
import { prepareGraphFonts, type DocumentFontStatus } from '@open-pencil/core/text'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import { collectSceneMutation } from '@open-pencil/scene-graph/mutation-impact'
import { printError } from '#cli/format'
@@ -147,3 +152,18 @@ export function requirePage(graph: SceneGraph, pageName?: string) {
}
return page
}
+
+/**
+ * Runs `edit` on `graph`, then loads the fonts the text it touched needs and sizes that text again
+ * in them. Text is sized as it is edited, before the fonts for new characters (Japanese in a
+ * Latin-only web font, say) can load, so without this it would save the size and glyphs of a
+ * stand-in.
+ */
+export async function editDocument<T>(graph: SceneGraph, edit: () => T | Promise<T>): Promise<T> {
+ const { result, impact } = await collectSceneMutation(graph, edit)
+ const textIds = [...impact.changedNodeIds].filter((id) => graph.getNode(id)?.type === 'TEXT')
+ if (textIds.length === 0) return result
+ await prepareGraphFonts(graph, textIds)
+ for (const id of textIds) sizeAutoResizingText(graph, id)
+ return result
+}
diff --git a/packages/cli/src/tool-data.ts b/packages/cli/src/tool-data.ts
index 141f5a98a..7797e541c 100644
--- a/packages/cli/src/tool-data.ts
+++ b/packages/cli/src/tool-data.ts
@@ -9,7 +9,12 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { isAppMode, requireFile, rpc } from '#cli/app/client'
import { appTargetRPCArgs, type AppTargetCLIArgs } from '#cli/app/target'
-import { loadDocument, measureDocumentText, populateWholeDocument } from '#cli/headless'
+import {
+ editDocument,
+ loadDocument,
+ measureDocumentText,
+ populateWholeDocument
+} from '#cli/headless'
/** A Figma API over a headless document, with CanvasKit raster export and pixel decoding. */
export async function createHeadlessFigma(graph: SceneGraph): Promise<FigmaAPI> {
@@ -40,5 +45,5 @@ export async function runToolData(
populateWholeDocument(graph)
await measureDocumentText(graph)
const figma = await createHeadlessFigma(graph)
- return { result: await tool.execute(figma, args), graph }
+ return { result: await editDocument(graph, () => tool.execute(figma, args)), graph }
}
diff --git a/packages/cli/tests/headless/edit.test.ts b/packages/cli/tests/headless/edit.test.ts
new file mode 100644
index 000000000..86520dc4d
--- /dev/null
+++ b/packages/cli/tests/headless/edit.test.ts
@@ -0,0 +1,43 @@
+import { expect, test } from 'bun:test'
+import { join } from 'node:path'
+
+import { FIXTURES } from '#cli-tests/helpers/paths'
+
+import { getTextMeasurer } from '@open-pencil/core/layout'
+import { fontManager } from '@open-pencil/core/text'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { editDocument, measureTextHeadlessly } from '#cli/headless'
+
+test('sizes the text an edit writes in the fonts its characters load after it', async () => {
+ // A family nothing loaded yet, as a script's new characters need a web font fetched again.
+ const family = 'Edit Test Han'
+ const font = await Bun.file(join(FIXTURES, 'fonts', 'NotoSansSC-Regular.ttf')).arrayBuffer()
+ fontManager.setHostFontLoader(async (name) => (name === family ? font : null))
+ try {
+ await measureTextHeadlessly()
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const id = await editDocument(
+ graph,
+ () =>
+ graph.createNode('TEXT', pageId, {
+ text: '中文字',
+ fontFamily: family,
+ fontSize: 40,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ }).id
+ )
+ const node = graph.getNode(id)
+ if (!node) throw new Error('Expected the text')
+ const measured = getTextMeasurer()?.(node)
+ if (!measured) throw new Error('Expected the text measured in its font')
+ // Each Han character is one em wide in the font, so three at 40 px are 120 px; a stand-in
+ // measures them otherwise.
+ expect(node.width).toBe(120)
+ expect(node.width).toBe(measured.width)
+ expect(node.height).toBe(measured.height)
+ } finally {
+ fontManager.setHostFontLoader(null)
+ }
+})
diff --git a/packages/core/package.json b/packages/core/package.json
index 5eca83e69..c4100f69c 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -197,6 +197,7 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fontoxpath": "^3.34.0",
+ "happy-dom": "^20.14.6",
"harfbuzzjs": "1.6.4",
"js-base64": "^3.9.3",
"jsep": "^1.4.0",
diff --git a/packages/core/src/canvas/text/font-families.ts b/packages/core/src/canvas/text/font-families.ts
index 344f68b1f..43ab16d81 100644
--- a/packages/core/src/canvas/text/font-families.ts
+++ b/packages/core/src/canvas/text/font-families.ts
@@ -75,9 +75,17 @@ export function paragraphSourceFamilies(
])
}
+/** `style` of `family` by the names CanvasKit draws it under: its own file, then its shards. */
+function renderFamilies(family: string, style: string): string[] {
+ return [
+ fontManager.renderFamily(family, style),
+ ...fontManager.renderShardFamilies(family, style)
+ ]
+}
+
/**
* The paragraph's families as CanvasKit is asked for them: the family in the face it draws the
- * style in, and its fallbacks, each by the name `fontManager.renderFamily` gives it.
+ * style in, and its fallbacks, each by the names `renderFamilies` gives it.
*/
export function resolveParagraphFontFamilies(
primary: string,
@@ -88,21 +96,26 @@ export function resolveParagraphFontFamilies(
// The face the family draws the style in, which may be the nearest one loaded.
const asked = parseFontStyle(style)
const drawn = loadedFace(primary, asked.weight, asked.italic)
- const renderPrimary = fontManager.renderFamily(
+ const renderPrimary = renderFamilies(
primary,
drawn ? weightToStyle(drawn.weight, drawn.italic) : style
)
- const renderArabicFallbacks = arabicFallbacks.map((family) =>
- fontManager.renderFamily(family, 'Regular')
- )
- const renderCJKFallbacks = cjkFallbacks.map((family) =>
- fontManager.renderFamily(family, 'Regular')
+ const renderArabicFallbacks = arabicFallbacks.flatMap((family) =>
+ renderFamilies(family, 'Regular')
)
- const key = `${primary}\0${renderPrimary}\0${renderArabicFallbacks.join('\0')}\0${renderCJKFallbacks.join('\0')}`
+ const renderCJKFallbacks = cjkFallbacks.flatMap((family) => renderFamilies(family, 'Regular'))
+ const key = [
+ primary,
+ ...renderPrimary,
+ '',
+ ...renderArabicFallbacks,
+ '',
+ ...renderCJKFallbacks
+ ].join('\0')
const cached = familiesCache.peek(key)
if (cached) return cached
const resolved = uniq([
- renderPrimary,
+ ...renderPrimary,
...(primary === DEFAULT_FONT_FAMILY ? [] : [DEFAULT_FONT_FAMILY]),
...renderArabicFallbacks,
...renderCJKFallbacks,
diff --git a/packages/core/src/io/formats/pdf/dom.ts b/packages/core/src/io/formats/pdf/dom.ts
new file mode 100644
index 000000000..fafc5acbb
--- /dev/null
+++ b/packages/core/src/io/formats/pdf/dom.ts
@@ -0,0 +1,101 @@
+import type * as HappyDOM from 'happy-dom'
+
+import { IS_BROWSER } from '#core/constants'
+
+/** A page's SVG markup as the element svg2pdf draws, or null when it does not parse. */
+export type SVGPageParser = (svg: string) => Element | null
+
+interface SVGParser {
+ parseFromString(
+ svg: string,
+ type: 'image/svg+xml'
+ ): {
+ querySelector(selectors: string): unknown
+ documentElement: unknown
+ }
+}
+
+/**
+ * The globals svg2pdf reads: it parses a page's stylesheets in a document it makes, and keeps the
+ * rules that are instances of the CSSOM classes.
+ */
+interface SVG2PDFGlobals {
+ document?: unknown
+ CSSStyleSheet?: unknown
+ CSSStyleRule?: unknown
+}
+
+const SVG2PDF_GLOBALS = ['document', 'CSSStyleSheet', 'CSSStyleRule'] as const
+
+type SVG2PDFGlobal = (typeof SVG2PDF_GLOBALS)[number]
+
+function removeGlobal(scope: SVG2PDFGlobals, name: SVG2PDFGlobal): void {
+ if (name === 'document') delete scope.document
+ else if (name === 'CSSStyleSheet') delete scope.CSSStyleSheet
+ else delete scope.CSSStyleRule
+}
+
+/**
+ * Kept out of the browser bundle: a browser has a DOM of its own, and happy-dom is only loaded
+ * where there is none.
+ */
+const HAPPY_DOM = 'happy-dom'
+
+let exporting: Promise<unknown> = Promise.resolve()
+
+function isElement(value: unknown): value is Element {
+ return typeof value === 'object' && value !== null && 'tagName' in value
+}
+
+function parseSVGPage(parser: SVGParser): SVGPageParser {
+ return (svg) => {
+ const parsed = parser.parseFromString(svg, 'image/svg+xml')
+ if (parsed.querySelector('parsererror')) return null
+ return isElement(parsed.documentElement) ? parsed.documentElement : null
+ }
+}
+
+/**
+ * Runs `draw` with a parser for page SVG and the DOM svg2pdf draws it through. A browser has both.
+ * Elsewhere, as in the CLI, happy-dom stands in: svg2pdf reads its DOM as globals, so they are set
+ * only while `draw` runs, one export at a time, and restored after.
+ */
+export function withPDFDOM<T>(draw: (parse: SVGPageParser) => Promise<T>): Promise<T> {
+ if (IS_BROWSER) return draw(parseSVGPage(new DOMParser()))
+ const run = exporting.then(() => withHappyDOM(draw))
+ exporting = run.catch(() => undefined)
+ return run
+}
+
+async function withHappyDOM<T>(draw: (parse: SVGPageParser) => Promise<T>): Promise<T> {
+ const { Window } = (await import(/* @vite-ignore */ HAPPY_DOM)) as typeof HappyDOM
+ const dom = new Window()
+ const scope: SVG2PDFGlobals = globalThis
+ const values: Required<SVG2PDFGlobals> = {
+ document: dom.document,
+ CSSStyleSheet: dom.CSSStyleSheet,
+ CSSStyleRule: dom.CSSStyleRule
+ }
+ // Each global replaced, with its descriptor before, so an accessor a host defines comes back as
+ // one and a global that could not be replaced is left as it was.
+ const replaced: Array<[SVG2PDFGlobal, PropertyDescriptor | undefined]> = []
+ try {
+ for (const name of SVG2PDF_GLOBALS) {
+ const previous = Object.getOwnPropertyDescriptor(globalThis, name)
+ Object.defineProperty(globalThis, name, {
+ value: values[name],
+ configurable: true,
+ writable: true
+ })
+ replaced.push([name, previous])
+ }
+ return await draw(parseSVGPage(new dom.DOMParser()))
+ } finally {
+ // What is replaced is configurable, so putting it back does not throw.
+ for (const [name, previous] of replaced) {
+ if (previous) Object.defineProperty(globalThis, name, previous)
+ else removeGlobal(scope, name)
+ }
+ await dom.happyDOM.close()
+ }
+}
diff --git a/packages/core/src/io/formats/pdf/export.ts b/packages/core/src/io/formats/pdf/export.ts
index f14da417c..ea5d7aae9 100644
--- a/packages/core/src/io/formats/pdf/export.ts
+++ b/packages/core/src/io/formats/pdf/export.ts
@@ -3,6 +3,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { computeContentBounds } from '#core/io/formats/raster'
import { renderNodesToSVG, type SVGExportOptions, type SVGTextLayout } from '#core/io/formats/svg'
+import { withPDFDOM, type SVGPageParser } from './dom'
import {
cutFontInstances,
embeddedFontAlias,
@@ -41,7 +42,8 @@ type PageSVGOptions = Pick<SVGExportOptions, 'textLayout' | 'fontAlias'>
function preparePage(
graph: SceneGraph,
spec: PDFPageSpec,
- svgOptions: PageSVGOptions
+ svgOptions: PageSVGOptions,
+ parse: SVGPageParser
): PreparedPage | null {
const svg = renderNodesToSVG(graph, spec.pageId, spec.nodeIds, {
xmlDeclaration: false,
@@ -56,10 +58,8 @@ function preparePage(
const height = bounds.maxY - bounds.minY
if (width <= 0 || height <= 0) return null
- const svgDoc = new DOMParser().parseFromString(svg, 'image/svg+xml')
- if (svgDoc.querySelector('parsererror')) return null
-
- return { spec, svgElement: svgDoc.documentElement, width, height }
+ const svgElement = parse(svg)
+ return svgElement ? { spec, svgElement, width, height } : null
}
const orientationOf = (page: PreparedPage) => (page.width > page.height ? 'landscape' : 'portrait')
@@ -67,10 +67,19 @@ const orientationOf = (page: PreparedPage) => (page.width > page.height ? 'lands
/**
* A PDF with one page per spec, each sized to its content. Null when no page has anything visible.
*/
-export async function renderPagesToPDFDetailed(
+export function renderPagesToPDFDetailed(
graph: SceneGraph,
specs: readonly PDFPageSpec[],
options: PDFExportOptions = {}
+): Promise<PDFExportResult | null> {
+ return withPDFDOM((parse) => renderPages(graph, specs, options, parse))
+}
+
+async function renderPages(
+ graph: SceneGraph,
+ specs: readonly PDFPageSpec[],
+ options: PDFExportOptions,
+ parse: SVGPageParser
): Promise<PDFExportResult | null> {
const embedding = options.fonts ? planFontEmbedding(options.fonts) : null
const svgOptions: PageSVGOptions = {
@@ -79,7 +88,7 @@ export async function renderPagesToPDFDetailed(
}
const preparePages = () =>
specs
- .map((spec) => preparePage(graph, spec, svgOptions))
+ .map((spec) => preparePage(graph, spec, svgOptions, parse))
.filter((page): page is PreparedPage => page !== null)
let prepared = preparePages()
if (prepared.length === 0) return null
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index 1d15d9385..28027f492 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -27,6 +27,7 @@ import { keepsSavedLayout, usesDetachedDerivedLayout } from './layout/derived'
import { applyEffectiveGeneratedTextLayout } from './layout/effective-generated-text'
import { buildGridTree, createGridChildNode } from './layout/grid'
import { sizeAutoResizingText } from './layout/text-auto-resize'
+export { sizeAutoResizingText } from './layout/text-auto-resize'
export {
estimateTextSize,
getTextMeasurer,
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.ts
index 3a2724bc3..83ba7cf74 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/fonts.ts
@@ -75,6 +75,16 @@ export type BundledFontLocator = (file: string) => string
const defaultBundledFontLocator: BundledFontLocator = (file) => `/${file}`
+/** Whether two font files hold the same bytes, as one downloaded or read again does. */
+function sameFontFile(a: ArrayBuffer, b: ArrayBuffer): boolean {
+ if (a === b) return true
+ if (a.byteLength !== b.byteLength) return false
+ const left = new Uint8Array(a)
+ const right = new Uint8Array(b)
+ for (let index = 0; index < left.length; index++) if (left[index] !== right[index]) return false
+ return true
+}
+
/** `load`'s answer once HarfBuzz has loaded too, the two loading side by side. */
async function withHarfBuzz<T>(load: Promise<T>): Promise<T> {
const [answer] = await Promise.all([load, loadHarfBuzz()])
@@ -88,6 +98,12 @@ export class FontManager {
private supplementalFamilyData = new Map<string, ArrayBuffer[]>()
/** The name each file of a family loaded from several files is registered under. */
private fileFamilies = new Map<ArrayBuffer, string>()
+ /**
+ * Families a style's file was replaced in, such as a web font fetched again for more characters.
+ * The old file stays registered first under the family's name, and CanvasKit draws with the
+ * first file it has for a style, so these draw from each file's own name.
+ */
+ private replacedFamilies = new Set<string>()
private remoteCoverage = new Map<string, Set<string>>()
private instanceVariations = new WeakMap<ArrayBuffer, Map<string, FontVariation[] | null>>()
private variations = new WeakMap<
@@ -631,19 +647,38 @@ export class FontManager {
* paint. Loaded from several files, such as a bundled static face beside a downloaded variable
* one, CanvasKit would pick among them by the weight each file declares, which can tie; each
* style then draws from the file loaded for it, registered with its shards under a name of the
- * file's own.
+ * file's own. So does a family a style's file was replaced in, whose old file CanvasKit would
+ * keep drawing under the family's name.
*/
renderFamily(family: string, style: string): string {
const data = this.loadedData(family, style)
- if (!data || this.familyFileCount(family) < 2) return family
+ if (!data || (this.familyFileCount(family) < 2 && !this.replacedFamilies.has(family)))
+ return family
+ const name = this.fileFamily(family, data)
+ for (const shard of this.supplementalFamilyData.get(`${family}|${style}`) ?? [])
+ this.registerFontInCanvasKit(name, shard)
+ return name
+ }
+
+ /**
+ * The names CanvasKit draws the other files of `style` of `family` under, such as the coverage
+ * shards of a web font split by unicode-range. CanvasKit draws a character only from the first
+ * file registered under a name, so each shard is a family of its own that text falls back to.
+ */
+ renderShardFamilies(family: string, style: string): string[] {
+ return (this.supplementalFamilyData.get(`${family}|${style}`) ?? []).map((data) =>
+ this.fileFamily(family, data)
+ )
+ }
+
+ /** The name one file of `family` is registered under on its own. */
+ private fileFamily(family: string, data: ArrayBuffer): string {
let name = this.fileFamilies.get(data)
if (!name) {
name = fontFaceRenderFamily(family, `file ${this.fileFamilies.size + 1}`)
this.fileFamilies.set(data, name)
}
this.registerFontInCanvasKit(name, data)
- for (const shard of this.supplementalFamilyData.get(`${family}|${style}`) ?? [])
- this.registerFontInCanvasKit(name, shard)
return name
}
@@ -836,7 +871,7 @@ export class FontManager {
private registerSupplemental(family: string, style: string, buffer: ArrayBuffer): void {
const key = `${family}|${style}`
const supplemental = this.supplementalFamilyData.get(key) ?? []
- if (supplemental.includes(buffer)) return
+ if (supplemental.some((file) => sameFontFile(file, buffer))) return
supplemental.push(buffer)
this.supplementalFamilyData.set(key, supplemental)
this.registerFontInCanvasKit(family, buffer)
@@ -851,12 +886,15 @@ export class FontManager {
): ArrayBuffer | null {
const key = `${family}|${style}`
const existing = this.loadedFamilies.get(key)
- if (existing === buffer) {
+ if (existing && sameFontFile(existing, buffer)) {
if (source) this.loadedFamilySources.set(key, source)
- this.registerFontInCanvasKit(family, buffer)
- return buffer
+ this.registerFontInCanvasKit(family, existing)
+ return existing
+ }
+ if (existing) {
+ this.registerSupplemental(family, style, existing)
+ this.replacedFamilies.add(family)
}
- if (existing) this.registerSupplemental(family, style, existing)
this.loadedFamilies.set(key, buffer)
if (source) this.loadedFamilySources.set(key, source)
this.registerFontInCanvasKit(family, buffer)
diff --git a/packages/core/src/text/web-fonts.ts b/packages/core/src/text/web-fonts.ts
index 17a80b099..83154a63b 100644
--- a/packages/core/src/text/web-fonts.ts
+++ b/packages/core/src/text/web-fonts.ts
@@ -120,11 +120,41 @@ function familyFacesOf(result: ResolveFontResult): FamilyFace[] {
return [...faces.values()]
}
-function resolvedRemoteFaces(result: ResolveFontResult): Array<{
+/** Whether a face's `unicode-range` (`U+3000-303F`, `U+4E??`) holds `codePoint`. */
+function inUnicodeRange(range: readonly string[], codePoint: number): boolean {
+ return range.some((part) => {
+ const [start = '', end = start] = part.trim().replace(/^U\+/iu, '').split('-')
+ const low = Number.parseInt(start.replaceAll('?', '0'), 16)
+ const high = Number.parseInt(end.replaceAll('?', 'F'), 16)
+ return codePoint >= low && codePoint <= high
+ })
+}
+
+/**
+ * The faces to download for `characters`: those whose `unicode-range` holds one of them, as a
+ * browser picks the files of a split family. A CJK family comes in a hundred or more such shards.
+ * Without characters, every face; when no range holds one, such as an emoji asked of a text
+ * family, only the first face, the provider's default subset, so the family still loads.
+ */
+function facesForCharacters(result: ResolveFontResult, characters: string): FontFaceData[] {
+ const codePoints = Array.from(characters, (character) => character.codePointAt(0) ?? 0)
+ if (codePoints.length === 0) return result.fonts
+ const covering = result.fonts.filter(
+ (face) =>
+ !face.unicodeRange ||
+ codePoints.some((codePoint) => inUnicodeRange(face.unicodeRange ?? [], codePoint))
+ )
+ return covering.length > 0 ? covering : result.fonts.slice(0, 1)
+}
+
+function resolvedRemoteFaces(
+ result: ResolveFontResult,
+ characters: string
+): Array<{
source: RemoteFontSource
init?: RequestInit
}> {
- const candidates = result.fonts.flatMap((face) => {
+ const candidates = facesForCharacters(result, characters).flatMap((face) => {
const source = preferredRemoteSource(face)
return source ? [{ source, init: face.meta?.init, priority: face.meta?.priority ?? 0 }] : []
})
@@ -451,7 +481,7 @@ export class WebFontResolver {
signal
)
signal?.throwIfAborted()
- const faces = resolvedRemoteFaces(result)
+ const faces = resolvedRemoteFaces(result, characters)
const buffers = await Promise.all(
faces.map(async ({ source, init }) => {
const response = await this.fetchRemote(source.url, { ...init, signal })
diff --git a/packages/core/tests/canvas/text/faces.test.ts b/packages/core/tests/canvas/text/faces.test.ts
index ad2d682ee..3b26fea0a 100644
--- a/packages/core/tests/canvas/text/faces.test.ts
+++ b/packages/core/tests/canvas/text/faces.test.ts
@@ -12,6 +12,7 @@ import { buildParagraph } from '#core/canvas/text'
import { withFigExportRuntime } from '#core/canvas/text/shape'
import { getCanvasKit } from '#core/canvaskit'
import { FontManager, fontManager } from '#core/text/fonts'
+import { WEB_FONT_PROVIDER_IDS } from '#core/text/web-fonts'
import { glyphOutlineSourceSync } from '#core/text/font/glyphs'
/** A family only these tests load, so faces other tests load cannot answer for it. */
@@ -58,6 +59,36 @@ function drawn(
}
}
+function fixtureFont(file: string): Promise<ArrayBuffer> {
+ return Bun.file(join(FIXTURES, 'fonts', file)).arrayBuffer()
+}
+
+/** How many characters of `text` the paragraph the canvas draws shapes to the missing glyph. */
+function missingGlyphs(
+ ck: CanvasKit,
+ fontProvider: TypefaceFontProvider,
+ fontFamily: string,
+ text: string
+): number {
+ const node = createDefaultNode(() => 'face-text', 'TEXT', {
+ text,
+ fontFamily,
+ fontSize: 40,
+ width: 600,
+ height: 60
+ })
+ const paragraph = buildParagraph({ ck, fontProvider, fontsLoaded: true }, node, ck.BLACK)
+ try {
+ paragraph.layout(600)
+ return paragraph
+ .getShapedLines()
+ .flatMap((line) => line.runs.flatMap((run) => Array.from(run.glyphs)))
+ .filter((glyph) => glyph === 0).length
+ } finally {
+ paragraph.delete()
+ }
+}
+
/**
* Asked for a face a family has not loaded, CanvasKit would slant or embolden another, which
* neither Figma, a browser, nor a native text stack draws the same. Figma draws a missing face as
@@ -124,6 +155,71 @@ describe('text faces', () => {
expect(light('Faces Test Mixed')).toEqual(light('Faces Test Variable Only'))
})
+ test('draws a style from the file that replaced the one it loaded first', async () => {
+ // A web font fetched again for more characters replaces the file the style loaded first,
+ // which stays registered under the family's name ahead of it.
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ const fontFamily = 'Faces Test Replaced'
+ await fontManager.markLoaded(fontFamily, 'Regular', await fixtureFont('InterVariable-Latin.ttf'))
+ await fontManager.markLoaded(fontFamily, 'Regular', await fixtureFont('NotoSansSC-Regular.ttf'))
+ expect(missingGlyphs(ck, fontProvider, fontFamily, '中文')).toBe(0)
+ })
+
+ test('draws a web font split by unicode-range from each of its files', async () => {
+ // As a CJK family comes: a Latin file, and shards for the rest.
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ const fontFamily = 'Faces Test Shards'
+ const CJK_SHARD = 'https://fonts.gstatic.com/s/test/shards-cjk.ttf'
+ const files = {
+ 'https://fonts.gstatic.com/s/test/shards-latin.ttf': {
+ range: 'U+0000-00FF',
+ data: await fixtureFont('InterVariable-Latin.ttf')
+ },
+ [CJK_SHARD]: {
+ range: 'U+4E00-9FFF',
+ data: await fixtureFont('NotoSansSC-Regular.ttf')
+ }
+ }
+ const providers = fontManager.enabledOnlineFontProviders()
+ fontManager.setOnlineFontProviders({ google: true })
+ fontManager.setWebFontFetch(async (url) => {
+ if (url.startsWith('https://fonts.google.com/metadata/fonts'))
+ return Response.json({ familyMetadataList: [{ family: fontFamily, fonts: { '400': {} }, axes: [] }] })
+ if (url.startsWith('https://fonts.google.com/metadata/icons'))
+ return new Response(`)]}'\n${JSON.stringify({ families: [] })}`)
+ if (url.startsWith('https://fonts.googleapis.com/css2'))
+ return new Response(
+ Object.entries(files)
+ .map(
+ ([src, { range }]) =>
+ `@font-face { font-family: '${fontFamily}'; font-weight: 400; src: url(${src}) format('truetype'); unicode-range: ${range}; }`
+ )
+ .join('\n')
+ )
+ const file = Object.entries(files).find(([src]) => src === url)?.[1]
+ return file ? new Response(file.data.slice(0)) : new Response(null, { status: 404 })
+ })
+ try {
+ await fontManager.loadFont(fontFamily, 'Regular', 'Faces 中文')
+ expect(missingGlyphs(ck, fontProvider, fontFamily, 'Faces 中文')).toBe(0)
+ // And paints them as the CJK file does on its own.
+ await fontManager.markLoaded('Faces Test Han', 'Regular', files[CJK_SHARD].data)
+ const paint = (family: string, text: string) =>
+ drawn(ck, fontProvider, { fontFamily: family, text, fontWeight: 400, italic: false })
+ expect(paint(fontFamily, '中文')).toEqual(paint('Faces Test Han', '中文'))
+ expect(paint(fontFamily, '中文')).not.toEqual(paint(fontFamily, ' '))
+ } finally {
+ fontManager.setWebFontFetch(null)
+ fontManager.setOnlineFontProviders(
+ Object.fromEntries(WEB_FONT_PROVIDER_IDS.map((id) => [id, providers.includes(id)]))
+ )
+ }
+ })
+
/**
* One face for the whole text: a family without the requested face draws its own, and the
* characters it lacks fall back in that same face, which is the outline saved for them.
diff --git a/packages/core/tests/io/formats/pdf/export.test.ts b/packages/core/tests/io/formats/pdf/export.test.ts
new file mode 100644
index 000000000..e95a1f3eb
--- /dev/null
+++ b/packages/core/tests/io/formats/pdf/export.test.ts
@@ -0,0 +1,55 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { exportPDFDocument } from '#core/io/formats/pdf'
+
+/** A page with a red square and a gradient, drawn without a browser DOM, as the CLI exports. */
+function card() {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const frame = graph.createNode('FRAME', pageId, { name: 'Card', width: 120, height: 80 })
+ graph.createNode('RECTANGLE', frame.id, {
+ width: 40,
+ height: 40,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ })
+ graph.createNode('ELLIPSE', frame.id, {
+ x: 60,
+ width: 40,
+ height: 40,
+ fills: [
+ {
+ type: 'GRADIENT_LINEAR',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ gradientStops: [
+ { position: 0, color: { r: 0, g: 0, b: 1, a: 1 } },
+ { position: 1, color: { r: 0, g: 1, b: 0, a: 1 } }
+ ],
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ }
+ ]
+ })
+ return { graph, spec: { pageId, nodeIds: [frame.id], label: 'Card' } }
+}
+
+test('exports a PDF without a browser DOM, and leaves no DOM behind', async () => {
+ const { graph, spec } = card()
+ const result = await exportPDFDocument(graph, [spec], { embedFonts: false })
+ expect(new TextDecoder().decode(result?.data.slice(0, 5))).toBe('%PDF-')
+ expect(result?.pages).toEqual([{ label: 'Card', width: 120, height: 80 }])
+ expect('document' in globalThis).toBe(false)
+ expect('CSSStyleSheet' in globalThis).toBe(false)
+})
+
+test('exports several PDFs at once', async () => {
+ const exports = Array.from({ length: 3 }, () => {
+ const { graph, spec } = card()
+ return exportPDFDocument(graph, [spec], { embedFonts: false })
+ })
+ const results = await Promise.all(exports)
+ expect(results.map((result) => result?.pages.length)).toEqual([1, 1, 1])
+ expect('document' in globalThis).toBe(false)
+})
diff --git a/packages/core/tests/text/fonts.test.ts b/packages/core/tests/text/fonts.test.ts
index 045b8876c..43aff06c1 100644
--- a/packages/core/tests/text/fonts.test.ts
+++ b/packages/core/tests/text/fonts.test.ts
@@ -86,3 +86,15 @@ test('a variable font shared with another weight still fetches the characters it
await manager.loadFont(family, 'Bold', 'xyz')
expect(asked.at(-1)).toContain('xyz')
})
+
+test('keeps the file it has when the same font is read or downloaded again', async () => {
+ const manager = offlineManager()
+ const family = 'Fonts Test Same File'
+ const file = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()
+ await manager.markLoaded(family, 'Regular', file)
+ await manager.markLoaded(family, 'Regular', file.slice(0))
+ expect(manager.loadedData(family, 'Regular')).toBe(file)
+ // Nothing replaced the file, so it draws under the family's own name with nothing else.
+ expect(manager.renderFamily(family, 'Regular')).toBe(family)
+ expect(manager.renderShardFamilies(family, 'Regular')).toEqual([])
+})
diff --git a/packages/core/tests/text/web-fonts.test.ts b/packages/core/tests/text/web-fonts.test.ts
index d8574a9e1..a56326bb9 100644
--- a/packages/core/tests/text/web-fonts.test.ts
+++ b/packages/core/tests/text/web-fonts.test.ts
@@ -45,7 +45,65 @@ async function googleResolver(families: Family[], icons: string[] = []) {
return { resolver, requests }
}
+/**
+ * A resolver whose Fontsource serves `family` as it serves a variable CJK family: a Latin file, and
+ * its Japanese subset in numbered unicode-range shards with no file of the subset's own. It records
+ * the font files downloaded.
+ */
+async function fontsourceResolver(family: string) {
+ const woff2 = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Faces.woff2')).arrayBuffer()
+ const id = family.toLowerCase().replaceAll(' ', '-')
+ const downloads: string[] = []
+ const resolver = new WebFontResolver()
+ resolver.setEnabled({ fontsource: true })
+ resolver.setRemoteFetch(async (input) => {
+ const url = String(input)
+ if (url === 'https://api.fontsource.org/v1/fonts')
+ return Response.json([
+ {
+ id,
+ family,
+ subsets: ['japanese', 'latin'],
+ weights: [100, 400, 900],
+ styles: ['normal'],
+ defSubset: 'latin',
+ variable: true,
+ category: 'sans-serif'
+ }
+ ])
+ if (url === `https://api.fontsource.org/v1/variable/${id}`)
+ return Response.json({ axes: { wght: { default: '400', min: '100', max: '900', step: '1' } } })
+ if (url === `https://api.fontsource.org/v1/fonts/${id}`)
+ return Response.json({
+ unicodeRange: { '[0]': 'U+4e00-4fff', '[1]': 'U+3000-30ff', latin: 'U+0000-00ff' },
+ variants: {}
+ })
+ if (url.startsWith('https://cdn.jsdelivr.net/')) {
+ downloads.push(url.slice(url.lastIndexOf('/') + 1))
+ return new Response(woff2.slice(0))
+ }
+ return new Response(null, { status: 404 })
+ })
+ return { resolver, downloads }
+}
+
describe('web fonts', () => {
+ test('downloads the files of a split family that hold the characters asked for', async () => {
+ const family = 'Web Font Test Shards'
+ const { resolver, downloads } = await fontsourceResolver(family)
+ // ボ is in the second Japanese shard; A in the Latin file.
+ await resolver.fetchFont([family], 'Regular', 'Aボ')
+ expect(downloads.toSorted()).toEqual(['1-wght-normal.woff2', 'latin-wght-normal.woff2'])
+ })
+
+ test('downloads only the default file of a split family for characters no file holds', async () => {
+ const family = 'Web Font Test Shards Uncovered'
+ const { resolver, downloads } = await fontsourceResolver(family)
+ // 語 asks for the Japanese shards, but the ones served stop short of it.
+ await resolver.fetchFont([family], 'Regular', '語')
+ expect(downloads).toEqual(['latin-wght-normal.woff2'])
+ })
+
test('loads a font served as WOFF2 as the TrueType font it holds', async () => {
const family = 'Web Font Test WOFF2'
const { resolver } = await googleResolver([{ family, axes: [] }])
diff --git a/packages/docs/de/overview/comparison.md b/packages/docs/de/overview/comparison.md
index 8f835c214..3e32e803a 100644
--- a/packages/docs/de/overview/comparison.md
+++ b/packages/docs/de/overview/comparison.md
@@ -181,12 +181,11 @@ Serialisierbare Änderungen passen gut zu Penpots serverbasierter Zusammenarbeit
## 10. Stärken von Penpot
1. **Serverbasierte Zusammenarbeit:** Konten, Zugriffskontrolle und zentrale Speicherung über WebSockets.
-2. **PDF export:** eigener Chromium exporter.
-3. **Plugin system:** Sandboxed execution und Plugin API.
-4. **Design tokens:** integrierte Unterstützung.
-5. **CSS Grid:** eigene Implementation; OpenPencil verwendet einen Yoga fork mit Grid.
-6. **Self-hosting:** Team platform über Docker deploybar.
-7. **Reife:** mehrjährige Verwendung in Production.
+2. **Plugin system:** Sandboxed execution und Plugin API.
+3. **Design tokens:** integrierte Unterstützung.
+4. **CSS Grid:** eigene Implementation; OpenPencil verwendet einen Yoga fork mit Grid.
+5. **Self-hosting:** Team platform über Docker deploybar.
+6. **Reife:** mehrjährige Verwendung in Production.
## 11. Scripts und Erweiterbarkeit
@@ -209,4 +208,4 @@ Penpot besitzt isoliert ausgeführte Plugins, aber keine vergleichbare Skript-AP
| Selbsthosting | Penpot | Docker-Bereitstellung |
| Ökosystemreife | Penpot | Mehrjährige Produktionserfahrung |
-OpenPencil ist ein kompakter Editor in einem Prozess mit CanvasKit-Renderer und nativer `.fig`-Unterstützung. Penpot ist eine vollständige Client-Server-Plattform mit Clojure, ClojureScript, Rust, Datenbanken und Docker-Diensten. Beide unterstützen Zusammenarbeit mit unterschiedlichen Modellen. Penpot bietet ein Plugin-Ökosystem und PDF-Export; OpenPencil eine Figma-kompatible API ohne Oberfläche, 90 AI/MCP-Werkzeuge, SVG-Export und eine Desktop-App.
+OpenPencil ist ein kompakter Editor in einem Prozess mit CanvasKit-Renderer und nativer `.fig`-Unterstützung. Penpot ist eine vollständige Client-Server-Plattform mit Clojure, ClojureScript, Rust, Datenbanken und Docker-Diensten. Beide unterstützen Zusammenarbeit mit unterschiedlichen Modellen. Penpot bietet ein Plugin-Ökosystem; OpenPencil eine Figma-kompatible API ohne Oberfläche, 90 AI/MCP-Werkzeuge, SVG- und PDF-Export und eine Desktop-App.
diff --git a/packages/docs/de/reference/figma-compatibility.md b/packages/docs/de/reference/figma-compatibility.md
index 70c2ee1a1..99ad4acae 100644
--- a/packages/docs/de/reference/figma-compatibility.md
+++ b/packages/docs/de/reference/figma-compatibility.md
@@ -89,7 +89,7 @@ Verbindungen, Auslöser, Aktionen, Animationen, Overlays, Scrollverhalten, Ablä
## Import und Export
-`.fig`-Import/-Export, Speichern, Figma-Zwischenablage und Bild-/SVG-Export funktionieren. Sketch-Import, PDF-Export und Versionsverlauf fehlen.
+`.fig`-Import/-Export, Speichern, Figma-Zwischenablage sowie Bild-, SVG- und PDF-Export funktionieren. Sketch-Import und Versionsverlauf fehlen.
## Plugin API, Zusammenarbeit und Entwicklermodus
diff --git a/packages/docs/es/overview/comparison.md b/packages/docs/es/overview/comparison.md
index b8ec8dbb3..f652e6fb7 100644
--- a/packages/docs/es/overview/comparison.md
+++ b/packages/docs/es/overview/comparison.md
@@ -181,12 +181,11 @@ Los cambios serializables encajan con la colaboración basada en servidor, pero
## 10. Ventajas de Penpot
1. **Colaboración mediante servidor:** cuentas, control de acceso y almacenamiento central a través de WebSockets.
-2. **Exportación PDF:** exportador independiente basado en Chromium.
-3. **Sistema de plugins:** ejecución aislada y API de plugins.
-4. **Variables de diseño:** compatibilidad integrada.
-5. **CSS Grid:** implementación propia; OpenPencil usa una variante de Yoga con Grid.
-6. **Alojamiento propio:** despliegue de una plataforma de equipo mediante Docker.
-7. **Madurez:** varios años de uso en producción.
+2. **Sistema de plugins:** ejecución aislada y API de plugins.
+3. **Variables de diseño:** compatibilidad integrada.
+4. **CSS Grid:** implementación propia; OpenPencil usa una variante de Yoga con Grid.
+5. **Alojamiento propio:** despliegue de una plataforma de equipo mediante Docker.
+6. **Madurez:** varios años de uso en producción.
## 11. Scripts y extensibilidad
@@ -209,4 +208,4 @@ Penpot ofrece plugins aislados, pero no una API equivalente para scripting sin i
| Alojamiento propio | Penpot | Despliegue con Docker |
| Madurez del ecosistema | Penpot | Años de uso en producción |
-OpenPencil es un editor compacto de un solo proceso con renderizador CanvasKit y compatibilidad nativa con `.fig`. Penpot es una plataforma cliente-servidor completa con Clojure, ClojureScript, Rust, bases de datos y servicios Docker. Ambos ofrecen colaboración con modelos diferentes. Penpot tiene un ecosistema de plugins y exportación PDF; OpenPencil ofrece scripting sin interfaz compatible con Figma, 90 herramientas AI/MCP, exportación SVG y una aplicación de escritorio.
+OpenPencil es un editor compacto de un solo proceso con renderizador CanvasKit y compatibilidad nativa con `.fig`. Penpot es una plataforma cliente-servidor completa con Clojure, ClojureScript, Rust, bases de datos y servicios Docker. Ambos ofrecen colaboración con modelos diferentes. Penpot tiene un ecosistema de plugins; OpenPencil ofrece scripting sin interfaz compatible con Figma, 90 herramientas AI/MCP, exportación SVG y PDF, y una aplicación de escritorio.
diff --git a/packages/docs/es/reference/figma-compatibility.md b/packages/docs/es/reference/figma-compatibility.md
index d96bcc5c6..e5a9bf44d 100644
--- a/packages/docs/es/reference/figma-compatibility.md
+++ b/packages/docs/es/reference/figma-compatibility.md
@@ -91,7 +91,7 @@ Comparación entre las funciones de Figma Design y el estado actual de OpenPenci
| Enlaces | 🔲 | No hay hipervínculos |
| Emoji y símbolos | 🔲 | Compatibilidad incompleta |
| OpenType | 🔲 | Sin ligaduras, alternativas estilísticas ni cifras tabulares |
-| Fuentes variables | 🔲 | No permite ajustar peso, anchura o inclinación |
+| Fuentes variables | 🟡 | Los estilos con nombre usan sus valores de eje y el tamaño óptico sigue al tamaño de fuente, como en Figma; la API de plugins ajusta cualquier eje, pero el panel aún no tiene controles de ejes |
| CJK | 🔲 | Compatibilidad incompleta con chino, japonés y coreano |
| RTL | 🔲 | No hay disposición de derecha a izquierda |
| Fuentes de iconos | 🔲 | Sin tratamiento especial |
@@ -183,7 +183,7 @@ Conexiones, activadores, acciones, animaciones, transiciones, superposiciones, d
| Pegar desde Figma | ✅ | Decodifica el binario Kiwi del portapapeles |
| Copiar a Figma | ✅ | Genera binario Kiwi legible por Figma |
| Importar Sketch | 🔲 | No hay analizador `.sketch` |
-| Exportar imagen/SVG/PDF | 🟡 | PNG, JPG, WEBP y SVG ✅; PDF 🔲 |
+| Exportar imagen/SVG/PDF | ✅ | PNG, JPG, WEBP, SVG y PDF; el PDF incrusta las fuentes de su texto cuando sus archivos se pueden incrustar |
| Historial de versiones | 🔲 | No consulta ni restaura versiones anteriores |
| Recursos entre herramientas | ✅ | Portapapeles de Figma y copiar como texto/SVG/PNG/JSX |
diff --git a/packages/docs/fr/overview/comparison.md b/packages/docs/fr/overview/comparison.md
index 37375b2d5..2f07ef42c 100644
--- a/packages/docs/fr/overview/comparison.md
+++ b/packages/docs/fr/overview/comparison.md
@@ -181,12 +181,11 @@ Les changements sérialisables conviennent à la collaboration via serveur, mais
## 10. Avantages de Penpot
1. **Collaboration via serveur :** comptes, contrôle d’accès et stockage central avec WebSockets.
-2. **Export PDF :** exportateur Chromium dédié.
-3. **Système de plugins :** exécution isolée et API de plugins.
-4. **Variables de design :** prise en charge intégrée.
-5. **CSS Grid :** implémentation propre ; OpenPencil utilise une variante de Yoga avec Grid.
-6. **Auto-hébergement :** déploiement d’une plateforme d’équipe avec Docker.
-7. **Maturité :** plusieurs années d’utilisation en production.
+2. **Système de plugins :** exécution isolée et API de plugins.
+3. **Variables de design :** prise en charge intégrée.
+4. **CSS Grid :** implémentation propre ; OpenPencil utilise une variante de Yoga avec Grid.
+5. **Auto-hébergement :** déploiement d’une plateforme d’équipe avec Docker.
+6. **Maturité :** plusieurs années d’utilisation en production.
## 11. Scripts et extensibilité
@@ -209,4 +208,4 @@ Penpot propose des plugins isolés, mais pas d’API équivalente pour les scrip
| Auto-hébergement | Penpot | Déploiement Docker |
| Maturité de l’écosystème | Penpot | Plusieurs années en production |
-OpenPencil est un éditeur compact à processus unique avec moteur CanvasKit et prise en charge native de `.fig`. Penpot est une plateforme client-serveur complète utilisant Clojure, ClojureScript, Rust, des bases de données et des services Docker. Les deux offrent la collaboration selon des modèles différents. Penpot propose un écosystème de plugins et l’export PDF ; OpenPencil fournit des scripts sans interface compatibles Figma, 90 outils AI/MCP, l’export SVG et une application de bureau.
+OpenPencil est un éditeur compact à processus unique avec moteur CanvasKit et prise en charge native de `.fig`. Penpot est une plateforme client-serveur complète utilisant Clojure, ClojureScript, Rust, des bases de données et des services Docker. Les deux offrent la collaboration selon des modèles différents. Penpot propose un écosystème de plugins ; OpenPencil fournit des scripts sans interface compatibles Figma, 90 outils AI/MCP, l’export SVG et PDF, et une application de bureau.
diff --git a/packages/docs/fr/reference/figma-compatibility.md b/packages/docs/fr/reference/figma-compatibility.md
index aeb301385..0eb2d6590 100644
--- a/packages/docs/fr/reference/figma-compatibility.md
+++ b/packages/docs/fr/reference/figma-compatibility.md
@@ -72,7 +72,7 @@ Connexions, déclencheurs, actions, animations, superpositions, défilement, par
| Coller depuis Figma | ✅ | Décode le binaire Kiwi du presse-papiers |
| Copier vers Figma | ✅ | Produit un binaire Kiwi lisible par Figma |
| Importer Sketch | 🔲 | Pas d’analyseur `.sketch` |
-| Export image/SVG/PDF | 🟡 | PNG, JPG, WEBP et SVG ✅ ; PDF 🔲 |
+| Export image/SVG/PDF | ✅ | PNG, JPG, WEBP, SVG et PDF ; le PDF intègre les polices de son texte lorsque leurs fichiers peuvent l’être |
| Historique des versions | 🔲 | Pas de consultation ni restauration |
| Ressources entre outils | ✅ | Presse-papiers Figma et copie en texte/SVG/PNG/JSX |
diff --git a/packages/docs/it/overview/comparison.md b/packages/docs/it/overview/comparison.md
index 2610fd7e1..3500080ca 100644
--- a/packages/docs/it/overview/comparison.md
+++ b/packages/docs/it/overview/comparison.md
@@ -151,12 +151,11 @@ Penpot usa Potok. `UpdateEvent` cambia lo stato, `WatchEvent` esegue gli effetti
## 10. Vantaggi di Penpot
1. **Collaborazione tramite server:** account, controllo degli accessi e archiviazione centrale.
-2. **Export PDF:** esportatore Chromium dedicato.
-3. **Sistema di plugin:** esecuzione isolata e API dei plugin.
-4. **Token di design:** supporto integrato.
-5. **CSS Grid:** implementazione propria; OpenPencil usa una variante di Yoga con Grid.
-6. **Installazione autonoma:** piattaforma di gruppo distribuibile con Docker.
-7. **Maturità:** diversi anni di uso in produzione.
+2. **Sistema di plugin:** esecuzione isolata e API dei plugin.
+3. **Token di design:** supporto integrato.
+4. **CSS Grid:** implementazione propria; OpenPencil usa una variante di Yoga con Grid.
+5. **Installazione autonoma:** piattaforma di gruppo distribuibile con Docker.
+6. **Maturità:** diversi anni di uso in produzione.
## 11. Script ed estensibilità
diff --git a/packages/docs/it/reference/figma-compatibility.md b/packages/docs/it/reference/figma-compatibility.md
index 2d41bf8e0..9f9a7388b 100644
--- a/packages/docs/it/reference/figma-compatibility.md
+++ b/packages/docs/it/reference/figma-compatibility.md
@@ -46,7 +46,7 @@ Collegamenti, trigger, azioni, animazioni, sovrapposizioni, scorrimento, flussi,
## Importazione ed esportazione
-Importazione/esportazione `.fig`, salvataggio, appunti Figma ed esportazione immagini/SVG funzionano. Importazione Sketch, PDF e cronologia delle versioni mancano.
+Importazione/esportazione `.fig`, salvataggio, appunti Figma ed esportazione di immagini, SVG e PDF funzionano. Importazione Sketch e cronologia delle versioni mancano.
## API dei plugin e scripting
diff --git a/packages/docs/overview/comparison.md b/packages/docs/overview/comparison.md
index f297074ba..95aa3a1cc 100644
--- a/packages/docs/overview/comparison.md
+++ b/packages/docs/overview/comparison.md
@@ -263,12 +263,11 @@ Open Pencil's approach is simpler and lower overhead. Penpot's approach is more
## 10. What Penpot Does Better
1. **Server-side collaboration** — centralized multi-user editing with WebSockets, user accounts, and access control (Open Pencil uses P2P via Trystero + Yjs — no server, but also no access control or persistence beyond the session)
-2. **PDF export** — headless Chromium export service for PDF rendering (OpenPencil exports SVG but not PDF yet)
-3. **Plugin system** — full plugin API with sandboxed execution
-4. **Design tokens** — native design token support
-5. **CSS Grid layout** — custom implementation (Open Pencil uses Yoga fork with grid support)
-6. **Self-hosting** — Docker-based deployment for teams
-7. **Maturity** — years of production usage, battle-tested at scale
+2. **Plugin system** — full plugin API with sandboxed execution
+3. **Design tokens** — native design token support
+4. **CSS Grid layout** — custom implementation (Open Pencil uses Yoga fork with grid support)
+5. **Self-hosting** — Docker-based deployment for teams
+6. **Maturity** — years of production usage, battle-tested at scale
## 11. Scripting & Extensibility
@@ -289,4 +288,4 @@ OpenPencil ships with an [`eval` command](/programmable/cli/scripting) that prov
| **Self-hosting** | Penpot | Docker-ready vs desktop-only |
| **Ecosystem maturity** | Penpot | Years of production vs early stage |
-Open Pencil is architecturally leaner — a single-process CanvasKit renderer in ~26K LOC of TypeScript, Figma-compatible by design. Penpot is a full-stack platform with ~299K LOC across Clojure, ClojureScript, Rust, and SCSS, plus a Docker service fleet. Both now offer real-time collaboration (different architectures: P2P vs server). Penpot has a plugin ecosystem and server-side PDF export; Open Pencil has Figma-compatible headless scripting, **90 AI/MCP tools**, SVG export, and a native desktop app.
+Open Pencil is architecturally leaner — a single-process CanvasKit renderer in ~26K LOC of TypeScript, Figma-compatible by design. Penpot is a full-stack platform with ~299K LOC across Clojure, ClojureScript, Rust, and SCSS, plus a Docker service fleet. Both now offer real-time collaboration (different architectures: P2P vs server). Penpot has a plugin ecosystem; Open Pencil has Figma-compatible headless scripting, **90 AI/MCP tools**, SVG and PDF export, and a native desktop app.
diff --git a/packages/docs/pl/overview/comparison.md b/packages/docs/pl/overview/comparison.md
index 67c26369b..1ea2e88aa 100644
--- a/packages/docs/pl/overview/comparison.md
+++ b/packages/docs/pl/overview/comparison.md
@@ -151,12 +151,11 @@ Penpot korzysta z Potok. `UpdateEvent` zmienia stan, `WatchEvent` wykonuje skutk
## 10. Zalety Penpota
1. **Współpraca przez serwer:** konta, kontrola dostępu i centralne przechowywanie.
-2. **Eksport PDF:** oddzielny eksporter Chromium.
-3. **System wtyczek:** wykonanie w izolacji i API wtyczek.
-4. **Tokeny projektu:** wbudowana obsługa.
-5. **CSS Grid:** własna implementacja; OpenPencil używa odmiany Yoga z Grid.
-6. **Samodzielne wdrożenie:** platforma zespołowa uruchamiana przez Docker.
-7. **Dojrzałość:** wiele lat użycia produkcyjnego.
+2. **System wtyczek:** wykonanie w izolacji i API wtyczek.
+3. **Tokeny projektu:** wbudowana obsługa.
+4. **CSS Grid:** własna implementacja; OpenPencil używa odmiany Yoga z Grid.
+5. **Samodzielne wdrożenie:** platforma zespołowa uruchamiana przez Docker.
+6. **Dojrzałość:** wiele lat użycia produkcyjnego.
## 11. Skrypty i rozszerzanie
diff --git a/packages/docs/pl/reference/figma-compatibility.md b/packages/docs/pl/reference/figma-compatibility.md
index 289103b2c..ee81ce72b 100644
--- a/packages/docs/pl/reference/figma-compatibility.md
+++ b/packages/docs/pl/reference/figma-compatibility.md
@@ -91,7 +91,7 @@ Porównanie funkcji Figma Design z obecnymi możliwościami OpenPencil.
| Łącza | 🔲 | Brak odnośników w tekście |
| Emoji i symbole | 🔲 | Obsługa niepełna |
| OpenType | 🔲 | Brak ligatur i wariantów stylistycznych |
-| Czcionki zmienne | 🔲 | Brak regulacji osi |
+| Czcionki zmienne | 🟡 | Style nazwane są rysowane w swoich wartościach osi, a rozmiar optyczny podąża za rozmiarem czcionki, jak w Figmie; API wtyczek ustawia dowolną oś, ale panel nie ma jeszcze kontrolek osi |
| CJK | 🔲 | Brak pełnej obsługi chińskiego, japońskiego i koreańskiego |
| RTL | 🔲 | Brak układu od prawej do lewej |
| Czcionki ikon | 🔲 | Brak specjalnej obsługi glifów |
@@ -166,7 +166,7 @@ Połączenia, wyzwalacze, działania, animacje, nakładki, przewijanie, przepły
| Zapis | ✅ | Okna systemowe, File System Access API i pobieranie w Safari |
| Schowek Figmy | ✅ | Kopiowanie i wklejanie binarnego Kiwi |
| Import Sketch | 🔲 | Brak odczytu `.sketch` |
-| Obrazy, SVG i PDF | 🟡 | PNG, JPG, WEBP i SVG działają; PDF nie |
+| Obrazy, SVG i PDF | ✅ | PNG, JPG, WEBP, SVG i PDF; PDF osadza czcionki tekstu, gdy ich pliki da się osadzić |
| Historia wersji | 🔲 | Brak przeglądania i przywracania |
| Kopiowanie zasobów | ✅ | Tekst, SVG, PNG, JSX i schowek Figmy |
diff --git a/packages/docs/reference/figma-compatibility.md b/packages/docs/reference/figma-compatibility.md
index 4bfa4bc12..1e6d7f90a 100644
--- a/packages/docs/reference/figma-compatibility.md
+++ b/packages/docs/reference/figma-compatibility.md
@@ -93,7 +93,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu
| Links in text | 🔲 | Hyperlinks within text content |
| Emojis & smart symbols | 🔲 | Emoji rendering and special characters |
| OpenType features | 🔲 | Ligatures, stylistic alternates, tabular figures |
-| Variable fonts | 🔲 | Adjustable font axes (weight, width, slant) |
+| Variable fonts | 🟡 | Named styles draw at their axis values and optical size follows the font size, as in Figma; the plugin API sets any axis, but the panel has no axis controls yet |
| CJK text support | 🔲 | Chinese, Japanese, Korean text rendering |
| RTL text support | 🔲 | Right-to-left text layout |
| Icon fonts | 🔲 | Special handling for icon font glyphs |
@@ -197,7 +197,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu
| Figma clipboard (paste) | ✅ | Decode Kiwi binary from Figma clipboard |
| Figma clipboard (copy) | ✅ | Encode Kiwi binary that Figma can read |
| Sketch file import | 🔲 | .sketch file parsing |
-| Image/SVG/PDF export | 🟡 | PNG/JPG/WEBP/SVG export ✅; PDF export 🔲 |
+| Image/SVG/PDF export | ✅ | PNG, JPG, WEBP, SVG, and PDF; PDF embeds the fonts its text uses where their files can be embedded |
| Version history | 🔲 | Browse and restore previous versions |
| Copy assets between tools | ✅ | Figma clipboard (Kiwi binary), Copy as text/SVG/PNG/JSX |
diff --git a/packages/docs/ru/overview/comparison.md b/packages/docs/ru/overview/comparison.md
index 5b6269309..0e94feb44 100644
--- a/packages/docs/ru/overview/comparison.md
+++ b/packages/docs/ru/overview/comparison.md
@@ -151,12 +151,11 @@ Penpot использует Potok. `UpdateEvent` меняет состояние
## 10. Преимущества Penpot
1. **Серверная совместная работа:** учётные записи, контроль доступа и центральное хранение через WebSockets.
-2. **Экспорт PDF:** отдельный экспортёр Chromium.
-3. **Система плагинов:** изолированное выполнение и API плагинов.
-4. **Токены дизайна:** встроенная поддержка.
-5. **CSS Grid:** собственная реализация; OpenPencil использует ответвление Yoga с Grid.
-6. **Самостоятельное размещение:** развёртывание для команды через Docker.
-7. **Зрелость:** несколько лет эксплуатации.
+2. **Система плагинов:** изолированное выполнение и API плагинов.
+3. **Токены дизайна:** встроенная поддержка.
+4. **CSS Grid:** собственная реализация; OpenPencil использует ответвление Yoga с Grid.
+5. **Самостоятельное размещение:** развёртывание для команды через Docker.
+6. **Зрелость:** несколько лет эксплуатации.
## 11. Сценарии и расширяемость
diff --git a/packages/docs/ru/reference/figma-compatibility.md b/packages/docs/ru/reference/figma-compatibility.md
index a623ba793..b3ed2e77a 100644
--- a/packages/docs/ru/reference/figma-compatibility.md
+++ b/packages/docs/ru/reference/figma-compatibility.md
@@ -91,7 +91,7 @@
| Ссылки | 🔲 | Нет гиперссылок внутри текста |
| Эмодзи и специальные символы | 🔲 | Поддержка неполная |
| OpenType | 🔲 | Нет лигатур, стилистических вариантов и табличных цифр |
-| Вариативные шрифты | 🔲 | Нет настройки осей |
+| Вариативные шрифты | 🟡 | Именованные начертания рисуются со своими значениями осей, а оптический размер следует за размером шрифта, как в Figma; API плагинов задаёт любую ось, но в панели пока нет управления осями |
| CJK | 🔲 | Нет полной поддержки китайского, японского и корейского текста |
| RTL | 🔲 | Нет компоновки справа налево |
| Иконочные шрифты | 🔲 | Нет специальной обработки глифов |
@@ -195,7 +195,7 @@
| Вставка из Figma | ✅ | Декодирование бинарного Kiwi из буфера обмена Figma |
| Копирование в Figma | ✅ | Создание бинарного Kiwi, читаемого Figma |
| Импорт Sketch | 🔲 | Нет разбора `.sketch` |
-| Экспорт изображений, SVG и PDF | 🟡 | PNG, JPG, WEBP и SVG поддерживаются; PDF отсутствует |
+| Экспорт изображений, SVG и PDF | ✅ | PNG, JPG, WEBP, SVG и PDF; PDF встраивает шрифты текста, если их файлы можно встроить |
| История версий | 🔲 | Нет просмотра и восстановления версий |
| Обмен ресурсами | ✅ | Буфер обмена Figma и копирование как текст, SVG, PNG или JSX |
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 000000000..dd2b0e061
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,49 @@
+diff --git a/dist/index.mjs b/dist/index.mjs
+index 4025303a697d83850dee843310084bfec0398426..2646c9cf1cea7ffd68acb16bbd24a25344e885cc 100644
+--- a/dist/index.mjs
++++ b/dist/index.mjs
+@@ -746,6 +746,17 @@ function pickFontsourceAxisSlug(axes) {
+ async function getVariableAxes(ctx, font) {
+ return await ctx.storage.getItem(`fontsource:${font.family}-axes.json`, () => ctx.fetch(`${BASE_URL}/variable/${font.id}`).then((res) => res.json()));
+ }
++function getVariableFiles(fontDetail, subset) {
++ const shards = Object.keys(fontDetail.unicodeRange).filter((key) => /^\[\d+\]$/.test(key));
++ if (fontDetail.unicodeRange[subset] || shards.length === 0) return [{
++ file: subset,
++ range: subset
++ }];
++ return shards.map((range) => ({
++ file: range.slice(1, -1),
++ range
++ }));
++}
+ const VALID_FALLBACKS$1 = [
+ "sans-serif",
+ "serif",
+@@ -776,16 +787,16 @@ var fontsource_default = defineFontProvider("fontsource", async (_options, ctx)
+ const variableAxes = await getVariableAxes(ctx, font);
+ if (variableAxes?.axes.wght) {
+ const axisSlug = pickFontsourceAxisSlug(Object.keys(variableAxes.axes));
+- fontFaceData.push({
+- style,
+- weight: [Number(variableAxes.axes.wght.min), Number(variableAxes.axes.wght.max)],
+- src: [{
+- url: `https://cdn.jsdelivr.net/fontsource/fonts/${font.id}:vf@latest/${subset}-${axisSlug}-${style}.woff2`,
+- format: "woff2"
+- }],
+- unicodeRange: fontDetail.unicodeRange[subset]?.split(","),
+- meta: { subset }
+- });
++ for (const { file, range } of getVariableFiles(fontDetail, subset)) fontFaceData.push({
++ style,
++ weight: [Number(variableAxes.axes.wght.min), Number(variableAxes.axes.wght.max)],
++ src: [{
++ url: `https://cdn.jsdelivr.net/fontsource/fonts/${font.id}:vf@latest/${file}-${axisSlug}-${style}.woff2`,
++ format: "woff2"
++ }],
++ unicodeRange: fontDetail.unicodeRange[range]?.split(","),
++ meta: { subset }
++ });
+ }
+ } catch {
+ console.error(`Could not download variable axes metadata for \`${font.family}\` from \`fontsource\`. \`unifont\` will not be able to inject variable axes for ${font.family}.`);
diff --git a/tests/engine/text/fonts/lifecycle.test.ts b/tests/engine/text/fonts/lifecycle.test.ts
index 620f1c9cc..c6d7c00a9 100644
--- a/tests/engine/text/fonts/lifecycle.test.ts
+++ b/tests/engine/text/fonts/lifecycle.test.ts
@@ -37,7 +37,7 @@ describe('font lifecycle', () => {
expect(registrations).toEqual(['Generation Test'])
})
- test('keeps cumulative subset registrations under the source family', async () => {
+ test('draws a style from the cumulative subset that replaced its file', async () => {
const manager = new FontManager()
const registrations: string[] = []
const provider = {
@@ -51,9 +51,11 @@ describe('font lifecycle', () => {
const firstGeneration = manager.generation()
await manager.markLoaded('Subset Font', 'Regular', new ArrayBuffer(12))
- expect(manager.renderFamily('Subset Font', 'Regular')).toBe('Subset Font')
+ // CanvasKit draws from the first file registered under a name, which is the replaced one.
+ const drawn = manager.renderFamily('Subset Font', 'Regular')
+ expect(drawn).not.toBe('Subset Font')
expect(manager.generation()).toBeGreaterThan(firstGeneration)
- expect(registrations).toEqual(['Subset Font', 'Subset Font'])
+ expect(registrations).toEqual(['Subset Font', 'Subset Font', drawn, drawn])
})
test('tracks nodes gated by pre-render font resolution', () => {
diff --git a/tools/checks/lint/src/rules/runtime.ts b/tools/checks/lint/src/rules/runtime.ts
index 8f4a869cc..b3b5cb11e 100644
--- a/tools/checks/lint/src/rules/runtime.ts
+++ b/tools/checks/lint/src/rules/runtime.ts
@@ -199,7 +199,8 @@ const noCoreBrowserGlobals = {
'/packages/core/src/canvas/renderer.ts',
'/packages/core/src/text/fonts.ts',
'/packages/core/src/profiler/render-profiler.ts',
- '/packages/core/src/figma-api/index.ts'
+ '/packages/core/src/figma-api/index.ts',
+ '/packages/core/src/io/formats/pdf/dom.ts'
]
if (allowedFiles.some((suffix) => file.endsWith(suffix))) return {}