Skip to content

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

feat: draw variable fonts at the axes Figma draws them (#1453)

Danila Poyarkovfde085c5399b
diff --git a/changes/1453/added.md b/changes/1453/added.md
new file mode 100644
index 000000000..cf5f76058
--- /dev/null
+++ b/changes/1453/added.md
@@ -0,0 +1 @@
+- Variable fonts draw every style they cover from one file, fonts installed locally included, at the axes Figma draws them: a style's named instance, the axes the text sets, and an optical size that follows the font size unless the text detaches it, which `.fig` files keep. Inter ships as its variable files, so every weight and italic draws offline.
diff --git a/packages/core/assets/Inter-Bold.ttf b/packages/core/assets/Inter-Bold.ttf
deleted file mode 100644
index ae2c2d436..000000000
Binary files a/packages/core/assets/Inter-Bold.ttf and /dev/null differ
diff --git a/packages/core/assets/Inter-ExtraBold.ttf b/packages/core/assets/Inter-ExtraBold.ttf
deleted file mode 100644
index 8a9a1bcb9..000000000
Binary files a/packages/core/assets/Inter-ExtraBold.ttf and /dev/null differ
diff --git a/packages/core/assets/Inter-Medium.ttf b/packages/core/assets/Inter-Medium.ttf
deleted file mode 100644
index 4a57a1a72..000000000
Binary files a/packages/core/assets/Inter-Medium.ttf and /dev/null differ
diff --git a/packages/core/assets/Inter-OFL.txt b/packages/core/assets/Inter-OFL.txt
new file mode 100644
index 000000000..9b2ca37b3
--- /dev/null
+++ b/packages/core/assets/Inter-OFL.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/packages/core/assets/Inter-Regular.ttf b/packages/core/assets/Inter-Regular.ttf
deleted file mode 100644
index 9a53a64e5..000000000
Binary files a/packages/core/assets/Inter-Regular.ttf and /dev/null differ
diff --git a/packages/core/assets/InterVariable-Italic.ttf b/packages/core/assets/InterVariable-Italic.ttf
new file mode 100644
index 000000000..5b358cdd5
Binary files /dev/null and b/packages/core/assets/InterVariable-Italic.ttf differ
diff --git a/packages/core/assets/InterVariable.ttf b/packages/core/assets/InterVariable.ttf
new file mode 100644
index 000000000..4ab79e010
Binary files /dev/null and b/packages/core/assets/InterVariable.ttf differ
diff --git a/packages/core/src/canvas/text/font-families.ts b/packages/core/src/canvas/text/font-families.ts
index 67afc5121..344f68b1f 100644
--- a/packages/core/src/canvas/text/font-families.ts
+++ b/packages/core/src/canvas/text/font-families.ts
@@ -1,6 +1,7 @@
import { uniq } from 'es-toolkit/array'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import type { FontVariation } from '@open-pencil/scene-graph'
+import { parseFontStyle, weightToStyle } from '@open-pencil/scene-graph/font-style'
import { ResourceCache } from '#core/cache/resource'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
@@ -10,6 +11,35 @@ import { fontManager, fontWeightMatchOrder } from '#core/text/fonts'
const familiesCache = new ResourceCache<string, string[]>({ maxEntries: 256 })
+/** What decides the axis values of a variable font text is drawn in. */
+export interface DrawnFontAxes {
+ family: string
+ weight: number
+ italic: boolean
+ fontSize: number
+ /** The axes the text sets. */
+ variations: readonly FontVariation[]
+ opticalSizeFromFontSize: boolean
+}
+
+/**
+ * The axis values text is drawn at, as Figma draws a variable font: its style's named instance,
+ * then the axes it sets. While the optical size follows the font size, `opsz` is the font size and
+ * a stored `opsz` is ignored. Fonts without an axis ignore its value.
+ */
+export function drawnFontVariations(font: DrawnFontAxes): FontVariation[] {
+ const named =
+ fontManager.namedInstanceVariations(font.family, weightToStyle(font.weight, font.italic)) ?? []
+ const set = font.opticalSizeFromFontSize
+ ? [
+ ...font.variations.filter((variation) => variation.axis !== 'opsz'),
+ { axis: 'opsz', value: font.fontSize }
+ ]
+ : font.variations
+ const axes = new Map([...named, ...set].map(({ axis, value }) => [axis, value]))
+ return [...axes].map(([axis, value]) => ({ axis, value }))
+}
+
/**
* The loaded face of a family that text asking for a style is drawn in: that style, or the
* nearest loaded weight in the same slant, then the other, as font matching picks it; `null`
@@ -25,27 +55,59 @@ export function loadedFace(family: string, weight: number, italic: boolean): Fam
return null
}
+/**
+ * The families a paragraph's text falls back through, by their own names: its family, the
+ * default family, the Arabic and CJK fallbacks, then emoji, so a character a script's font has
+ * stays in that font. Fonts are read by these names; CanvasKit is asked for them as
+ * {@link resolveParagraphFontFamilies} names them.
+ */
+export function paragraphSourceFamilies(
+ primary: string,
+ arabicFallbacks: readonly string[] = fontManager.getArabicFallbackFamilies(),
+ cjkFallbacks: readonly string[] = fontManager.getCJKFallbackFamilies()
+): string[] {
+ return uniq([
+ primary,
+ ...(primary === DEFAULT_FONT_FAMILY ? [] : [DEFAULT_FONT_FAMILY]),
+ ...arabicFallbacks,
+ ...cjkFallbacks,
+ EMOJI_METRICS_FAMILY
+ ])
+}
+
+/**
+ * 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.
+ */
export function resolveParagraphFontFamilies(
primary: string,
style: string,
arabicFallbacks: readonly string[] = fontManager.getArabicFallbackFamilies(),
cjkFallbacks: readonly string[] = fontManager.getCJKFallbackFamilies()
): string[] {
- const renderPrimary = fontManager.renderFamily(primary, style)
+ // 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(
+ 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 key = `${renderPrimary}\0${renderArabicFallbacks.join('\0')}\0${renderCJKFallbacks.join('\0')}`
+ const key = `${primary}\0${renderPrimary}\0${renderArabicFallbacks.join('\0')}\0${renderCJKFallbacks.join('\0')}`
const cached = familiesCache.peek(key)
if (cached) return cached
- const families = [renderPrimary]
- if (primary !== DEFAULT_FONT_FAMILY) families.push(DEFAULT_FONT_FAMILY)
- // Emoji come last, so a character a script's font has stays in that font.
- families.push(...renderArabicFallbacks, ...renderCJKFallbacks, EMOJI_METRICS_FAMILY)
- const resolved = uniq(families)
+ const resolved = uniq([
+ renderPrimary,
+ ...(primary === DEFAULT_FONT_FAMILY ? [] : [DEFAULT_FONT_FAMILY]),
+ ...renderArabicFallbacks,
+ ...renderCJKFallbacks,
+ EMOJI_METRICS_FAMILY
+ ])
familiesCache.set(key, resolved)
return resolved
}
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
index ffba61854..da73f0f36 100644
--- a/packages/core/src/canvas/text/paragraph/index.ts
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -15,7 +15,11 @@ import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
import { weightToStyle } from '@open-pencil/scene-graph/font-style'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
-import { loadedFace, resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
+import {
+ drawnFontVariations,
+ loadedFace,
+ resolveParagraphFontFamilies
+} from '#core/canvas/text/font-families'
import { laidOutText } from '#core/canvas/text/keycap'
import {
pushParagraphStyle,
@@ -179,8 +183,14 @@ function pushStyleRun(
locale: styleRunLanguage(style, node),
fontStyle: drawnFontStyle(ck, runFamily, runWeight, runItalic),
fontVariations: textFontVariations(
- style.fontVariations ?? node.fontVariations,
- fontManager.namedInstanceVariations(runFamily, weightToStyle(runWeight, runItalic))
+ drawnFontVariations({
+ family: runFamily,
+ weight: runWeight,
+ italic: runItalic,
+ fontSize: runFontSize,
+ variations: style.fontVariations ?? node.fontVariations,
+ opticalSizeFromFontSize: node.opticalSizeFromFontSize
+ })
),
fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),
letterSpacing: style.letterSpacing ?? (node.letterSpacing || 0),
@@ -292,11 +302,14 @@ export function buildSkParagraph(
node.italic
),
fontVariations: textFontVariations(
- node.fontVariations,
- fontManager.namedInstanceVariations(
- node.fontFamily || DEFAULT_FONT_FAMILY,
- weightToStyle(node.fontWeight, node.italic)
- )
+ drawnFontVariations({
+ family: node.fontFamily || DEFAULT_FONT_FAMILY,
+ weight: node.fontWeight,
+ italic: node.italic,
+ fontSize: baseFontSize,
+ variations: node.fontVariations,
+ opticalSizeFromFontSize: node.opticalSizeFromFontSize
+ })
),
fontFeatures: textFontFeatures(node.fontFeatures),
letterSpacing: node.letterSpacing || 0,
diff --git a/packages/core/src/canvas/text/paragraph/inputs.ts b/packages/core/src/canvas/text/paragraph/inputs.ts
index 32677855b..f46ee418b 100644
--- a/packages/core/src/canvas/text/paragraph/inputs.ts
+++ b/packages/core/src/canvas/text/paragraph/inputs.ts
@@ -12,6 +12,7 @@ export const PARAGRAPH_INPUT_KEYS = [
'italic',
'styleRuns',
'fontVariations',
+ 'opticalSizeFromFontSize',
'fontFeatures',
'textLanguage',
'textDirection',
diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.ts
index 1e4e3250e..1b4f85232 100644
--- a/packages/core/src/canvas/text/placed.ts
+++ b/packages/core/src/canvas/text/placed.ts
@@ -4,14 +4,16 @@ import { uniq } from 'es-toolkit/array'
import type { SceneNode } from '@open-pencil/scene-graph'
import { weightToStyle } from '@open-pencil/scene-graph/font-style'
-import { loadedFace, resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
+import {
+ drawnFontVariations,
+ loadedFace,
+ paragraphSourceFamilies
+} from '#core/canvas/text/font-families'
import { laidOutText } from '#core/canvas/text/keycap'
import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'
-import { textFontVariations } from '#core/canvas/text/paragraph'
import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { ELLIPSIS } from '#core/text/ellipsis'
-import { fontManager } from '#core/text/fonts'
import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/opentype'
type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]
@@ -50,18 +52,21 @@ function fontAt(node: SceneNode, index: number) {
const weight = run?.style.fontWeight ?? node.fontWeight
const italic = run?.style.italic ?? node.italic
const style = weightToStyle(weight, italic)
- const variations =
- textFontVariations(
- run?.style.fontVariations ?? node.fontVariations,
- fontManager.namedInstanceVariations(family, style)
- ) ?? []
+ const variations = drawnFontVariations({
+ family,
+ weight,
+ italic,
+ fontSize: run?.style.fontSize ?? node.fontSize,
+ variations: run?.style.fontVariations ?? node.fontVariations,
+ opticalSizeFromFontSize: node.opticalSizeFromFontSize
+ })
const drawn = loadedFace(family, weight, italic) ?? { weight, italic }
return { family, weight, italic, style, variations, drawn }
}
/** The outline source of each font the paragraph may have drawn a character in, in its order. */
function* candidateSources(font: ReturnType<typeof fontAt>) {
- for (const family of resolveParagraphFontFamilies(font.family, font.style)) {
+ for (const family of paragraphSourceFamilies(font.family)) {
const style = loadedStyle(family, font.drawn.weight, font.drawn.italic)
const source = style ? glyphOutlineSourceSync(family, style, font.variations) : null
if (source) yield source
@@ -77,7 +82,7 @@ export function characterFamily(node: SceneNode, text: string, index: number): s
if (codePoint === undefined) return null
const character = String.fromCodePoint(codePoint)
const font = fontAt(node, index)
- for (const family of resolveParagraphFontFamilies(font.family, font.style)) {
+ for (const family of paragraphSourceFamilies(font.family)) {
const style = loadedStyle(family, font.drawn.weight, font.drawn.italic)
if (style && glyphOutlineSourceSync(family, style, font.variations)?.covers(character))
return family
diff --git a/packages/core/src/text/font/variation.ts b/packages/core/src/text/font/variation.ts
index 3af5e3ce6..68dc9b4cc 100644
--- a/packages/core/src/text/font/variation.ts
+++ b/packages/core/src/text/font/variation.ts
@@ -79,12 +79,24 @@ function fontName(view: DataView, name: TableRange, nameId: number): string | nu
return fallback
}
-/**
- * Returns the axis coordinates a variable font needs to render `style`, preferring the named
- * instance with that name (for example SF Pro `Medium` is `wght` 510) and otherwise clamping the
- * style's weight to the `wght` axis. Returns `null` for static fonts.
- */
-export function namedInstanceVariations(data: ArrayBuffer, style: string): FontVariation[] | null {
+/** A variation axis of a font: its tag, its range and default, and the name the font gives it. */
+export interface FontAxis {
+ tag: string
+ min: number
+ default: number
+ max: number
+ name: string
+}
+
+interface VariationTable {
+ view: DataView
+ axes: FontAxis[]
+ /** Where each named instance's record starts. */
+ instances: number[]
+ name: TableRange | null
+}
+
+function variationTable(data: ArrayBuffer): VariationTable | null {
const view = new DataView(data)
const fvar = sfntTable(view, 'fvar')
if (!fvar || fvar.length < FVAR_HEADER_SIZE) return null
@@ -102,21 +114,44 @@ export function namedInstanceVariations(data: ArrayBuffer, style: string): FontV
return null
}
+ const name = sfntTable(view, 'name')
const axes = Array.from({ length: axisCount }, (_, index) => {
const axis = axesOffset + index * axisSize
let tag = ''
for (let c = 0; c < 4; c++) tag += String.fromCharCode(view.getUint8(axis + c))
- return { tag, min: fixed(view, axis + 4), max: fixed(view, axis + 12) }
+ return {
+ tag,
+ min: fixed(view, axis + 4),
+ default: fixed(view, axis + 8),
+ max: fixed(view, axis + 12),
+ name: (name && fontName(view, name, view.getUint16(axis + 18))) ?? tag
+ }
})
+ const instancesOffset = axesOffset + axisCount * axisSize
+ const instances = Array.from(
+ { length: instanceCount },
+ (_, index) => instancesOffset + index * instanceSize
+ )
+ return { view, axes, instances, name }
+}
- const name = sfntTable(view, 'name')
+/** The variation axes of a font, in its order, or `null` for a static font. */
+export function fontAxes(data: ArrayBuffer): FontAxis[] | null {
+ return variationTable(data)?.axes ?? null
+}
+
+/**
+ * Returns the axis coordinates a variable font needs to render `style`, preferring the named
+ * instance with that name (for example SF Pro `Medium` is `wght` 510) and otherwise clamping the
+ * style's weight to the `wght` axis. Returns `null` for static fonts.
+ */
+export function namedInstanceVariations(data: ArrayBuffer, style: string): FontVariation[] | null {
+ const table = variationTable(data)
+ if (!table) return null
+ const { view, axes, instances, name } = table
const requested = normalizeStyleName(style)
- const instancesOffset = axesOffset + axisCount * axisSize
const instance = name
- ? Array.from(
- { length: instanceCount },
- (_, index) => instancesOffset + index * instanceSize
- ).find((offset) => {
+ ? instances.find((offset) => {
const instanceName = fontName(view, name, view.getUint16(offset))
return instanceName !== null && normalizeStyleName(instanceName) === requested
})
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.ts
index b23da4549..7abca1904 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/fonts.ts
@@ -5,9 +5,10 @@ import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
import type { FontVariation, SceneGraph } from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY, IS_BROWSER } from '#core/constants'
+import { fontFaceRenderFamily } from '#core/text/face'
import { facesFromStyles, hasFamilyFace, type FamilyFace } from '#core/text/font/faces'
import { chooseLocalFontMatch } from '#core/text/font/style'
-import { isVariableFont, namedInstanceVariations } from '#core/text/font/variation'
+import { fontAxes, namedInstanceVariations } from '#core/text/font/variation'
export * from '#core/text/font/sources'
export * from '#core/text/font/style'
@@ -15,6 +16,7 @@ export * from '#core/text/font/variation'
export * from '#core/text/font/woff2'
import {
normalizeFontFamily,
+ parseFontStyle,
styleToWeight,
weightToStyle
} from '@open-pencil/scene-graph/font-style'
@@ -35,20 +37,30 @@ import { collectGraphFontKeys } from '#core/text/requirements'
import { normalizedCoverageText, WebFontResolver } from '#core/text/web-fonts'
import type { WebFontFetch, WebFontProviderId } from '#core/text/web-fonts'
-type FindLocalFontOptions = { allowVariable?: boolean }
+/** Inter's weights, each drawn from Inter's variable files at its named instance. */
+const INTER_WEIGHTS = [
+ 'Thin',
+ 'ExtraLight',
+ 'Light',
+ 'Regular',
+ 'Medium',
+ 'SemiBold',
+ 'Bold',
+ 'ExtraBold',
+ 'Black'
+]
const BUNDLED_FONTS: Record<string, string> = {
- 'Inter|Regular': '/Inter-Regular.ttf',
- 'Inter|Medium': '/Inter-Medium.ttf',
- 'Inter|SemiBold': '/Inter-SemiBold.ttf',
- 'Inter|Bold': '/Inter-Bold.ttf',
- 'Inter|ExtraBold': '/Inter-ExtraBold.ttf',
+ ...Object.fromEntries(INTER_WEIGHTS.map((weight) => [`Inter|${weight}`, '/InterVariable.ttf'])),
+ ...Object.fromEntries(
+ INTER_WEIGHTS.map((weight) => [`Inter|${weight} Italic`, '/InterVariable-Italic.ttf'])
+ ),
'Noto Naskh Arabic|Regular': '/NotoNaskhArabic-Regular.ttf',
'OpenPencil Emoji Metrics|Regular': '/OpenPencilEmojiMetrics-Regular.ttf'
}
/**
- * Maps a bundled font's file name (`Inter-Regular.ttf`) to the URL a browser fetches it from.
+ * Maps a bundled font's file name (`InterVariable.ttf`) to the URL a browser fetches it from.
* Mirrors CanvasKit's `locateFile`; the default expects the host to serve
* `@open-pencil/core/assets` at the site root.
*/
@@ -61,6 +73,8 @@ export class FontManager {
private loadedFamilySources = new Map<string, FontLoadedSource>()
private unavailableFaces = new Map<string, FontUnavailableReason>()
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>()
private remoteCoverage = new Map<string, Set<string>>()
private instanceVariations = new WeakMap<ArrayBuffer, Map<string, FontVariation[] | null>>()
private blockedNodeIds = new Set<string>()
@@ -346,25 +360,30 @@ export class FontManager {
}
async loadLocalFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {
- const cacheKey = `${family}|${style}`
- const loaded = this.loadedFamilies.get(cacheKey)
+ const loaded = this.loadedFamilies.get(`${family}|${style}`)
if (loaded) {
this.registerFontInCanvasKit(family, loaded)
return loaded
}
+ return (
+ (await this.loadInstalledFont(family, style)) ?? (await this.loadBundledFont(family, style))
+ )
+ }
+ /** The face installed on this machine, from the host or the browser's local fonts. */
+ private async loadInstalledFont(family: string, style: string): Promise<ArrayBuffer | null> {
const hostBuffer = await this.loadHostFont(family, style)
if (hostBuffer) return this.registerAndCache(family, style, hostBuffer, 'local')
const localBuffer = await this.findLocalFont(family, style)
- if (localBuffer) return this.registerAndCache(family, style, localBuffer, 'local')
+ return localBuffer ? this.registerAndCache(family, style, localBuffer, 'local') : null
+ }
- const bundledURL = BUNDLED_FONTS[cacheKey]
+ private async loadBundledFont(family: string, style: string): Promise<ArrayBuffer | null> {
+ const bundledURL = BUNDLED_FONTS[`${family}|${style}`]
if (!bundledURL) return null
try {
const buffer = await this.fetchBundledFont(bundledURL)
- return buffer && !isVariableFont(buffer)
- ? this.registerAndCache(family, style, buffer, 'bundled')
- : null
+ return buffer ? this.registerAndCache(family, style, buffer, 'bundled') : null
} catch (e) {
console.warn(`Bundled font load failed for "${family}" ${style}:`, e)
return null
@@ -422,24 +441,62 @@ export class FontManager {
const loaded = this.loadedData(family, style)
if (loaded) {
this.registerFontInCanvasKit(family, loaded)
- const remoteCoverage = this.remoteCoverage.get(`${family}|${style}`)
- const missingRemoteCoverage = Boolean(
- characters &&
- remoteCoverage &&
- Array.from(characters).some((character) => !remoteCoverage.has(character))
- )
- return missingRemoteCoverage
- ? ((await this.loadRemoteFont(family, style, characters, signal)) ?? loaded)
- : loaded
+ return this.withRemoteCoverage(family, style, loaded, characters, signal)
}
+ // An installed face of the style comes first; otherwise a variable file the family already
+ // loaded draws it.
+ const installed = await this.loadInstalledFont(family, style)
+ if (installed) return installed
+ const shared = this.sharedVariableFace(family, style)
+ if (shared) return this.withRemoteCoverage(family, style, shared, characters, signal)
return (
- (await this.loadLocalFont(family, style)) ??
+ (await this.loadBundledFont(family, style)) ??
(await this.loadCachedFont(family, style, characters)) ??
(await this.loadRemoteFont(family, style, characters, signal))
)
}
+ /**
+ * `data`, or a web font fetched again with `characters` when it came from the web without them,
+ * as a provider cuts a font down to the text it is asked for.
+ */
+ private async withRemoteCoverage(
+ family: string,
+ style: string,
+ data: ArrayBuffer,
+ characters: string,
+ signal?: AbortSignal
+ ): Promise<ArrayBuffer> {
+ const remoteCoverage = this.remoteCoverage.get(`${family}|${style}`)
+ const missingRemoteCoverage = Boolean(
+ characters &&
+ remoteCoverage &&
+ Array.from(characters).some((character) => !remoteCoverage.has(character))
+ )
+ return missingRemoteCoverage
+ ? ((await this.loadRemoteFont(family, style, characters, signal)) ?? data)
+ : data
+ }
+
+ /**
+ * A variable font the family loaded for another style in the same slant whose weight axis
+ * reaches this style's weight, registered for this style too: one file draws every weight.
+ */
+ private sharedVariableFace(family: string, style: string): ArrayBuffer | null {
+ const { weight, italic } = parseFontStyle(style)
+ for (const [key, data] of this.loadedFamilies) {
+ if (!key.startsWith(`${family}|`)) continue
+ if (parseFontStyle(key.slice(family.length + 1)).italic !== italic) continue
+ const wght = fontAxes(data)?.find((axis) => axis.tag === 'wght')
+ if (!wght || weight < wght.min || weight > wght.max) continue
+ const coverage = this.remoteCoverage.get(key)
+ if (coverage) this.remoteCoverage.set(`${family}|${style}`, new Set(coverage))
+ return this.registerAndCache(family, style, data, this.loadedFamilySources.get(key))
+ }
+ return null
+ }
+
async ensureNodeFont(family: string, weight: number): Promise<void> {
await this.loadFont(family, weightToStyle(weight))
}
@@ -492,11 +549,33 @@ export class FontManager {
return byStyle.get(style) ?? null
}
- renderFamily(family: string, _style: string): string {
- // CanvasKit can shape metrics but paint no glyphs for some CJK/Arabic faces registered under a
- // synthetic alias. Keep every shard under the font's source family; character-aware remote
- // requests already fetch cumulative coverage before replacing the primary buffer.
- return family
+ /**
+ * The family CanvasKit is asked for to draw `style` of `family`. A family loaded from one file
+ * draws under its own name, with every coverage shard, as some CJK and Arabic faces need to
+ * 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.
+ */
+ renderFamily(family: string, style: string): string {
+ const data = this.loadedData(family, style)
+ if (!data || this.familyFileCount(family) < 2) return family
+ 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
+ }
+
+ /** How many files the family's loaded styles come from. */
+ private familyFileCount(family: string): number {
+ const files = new Set<ArrayBuffer>()
+ for (const [key, data] of this.loadedFamilies) if (key.startsWith(`${family}|`)) files.add(data)
+ return files.size
}
collectFontKeys(graph: SceneGraph, nodeIds: string[]): Array<[string, string]> {
@@ -507,9 +586,7 @@ export class FontManager {
if (this.cjkFallbackFamilies.length > 0) return this.cjkFallbackFamilies
if (this.cjkFallbackPromise) return this.cjkFallbackPromise
- this.cjkFallbackPromise = this.ensureFallbackFamilies('cjk', this.cjkFallbackFamilies, {
- allowVariableLocalFonts: true
- })
+ this.cjkFallbackPromise = this.ensureFallbackFamilies('cjk', this.cjkFallbackFamilies)
return this.cjkFallbackPromise
}
@@ -543,19 +620,13 @@ export class FontManager {
signal?.throwIfAborted()
const target = script === 'arabic' ? this.arabicFallbackFamilies : this.cjkFallbackFamilies
if (signal) {
- result[script] = await this.ensureFallbackFamilies(
- script,
- target,
- { allowVariableLocalFonts: script === 'cjk' },
- characters,
- signal
- )
+ result[script] = await this.ensureFallbackFamilies(script, target, characters, signal)
} else if (script === 'arabic' && !characters) {
result[script] = await this.ensureArabicFallback()
} else if (script === 'cjk' && !characters) {
result[script] = await this.ensureCJKFallback()
} else {
- result[script] = await this.ensureFallbackFamilies(script, target, {}, characters)
+ result[script] = await this.ensureFallbackFamilies(script, target, characters)
}
})
)
@@ -576,7 +647,6 @@ export class FontManager {
private async ensureFallbackFamilies(
script: FontFallbackScript,
targetFamilies: string[],
- options: { allowVariableLocalFonts?: boolean } = {},
characters = '',
signal?: AbortSignal
): Promise<string[]> {
@@ -586,10 +656,7 @@ export class FontManager {
for (const family of manifest.localFamilies) {
signal?.throwIfAborted()
const buffer =
- (await this.loadHostFont(family, 'Regular')) ??
- (await this.findLocalFont(family, undefined, {
- allowVariable: options.allowVariableLocalFonts
- }))
+ (await this.loadHostFont(family, 'Regular')) ?? (await this.findLocalFont(family))
if (
buffer &&
this.registerAndCache(family, 'Regular', buffer, 'fallback') &&
@@ -667,11 +734,7 @@ export class FontManager {
}
}
- private async findLocalFont(
- family: string,
- style?: string,
- options: FindLocalFontOptions = {}
- ): Promise<ArrayBuffer | null> {
+ private async findLocalFont(family: string, style?: string): Promise<ArrayBuffer | null> {
if (!IS_BROWSER || !window.queryLocalFonts) return null
if (this.localFontAccessState !== 'granted') return null
try {
@@ -679,9 +742,7 @@ export class FontManager {
const match = chooseLocalFontMatch(fonts, family, style)
if (!match) return null
const blob: Blob = await match.blob()
- const buffer = await blob.arrayBuffer()
- if (!options.allowVariable && isVariableFont(buffer)) return null
- return buffer
+ return await blob.arrayBuffer()
} catch (e) {
console.warn(`Local font access failed for "${family}" ${style ?? ''}:`, e)
return null
diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.ts
index b4f7a6a82..230d60a90 100644
--- a/packages/core/src/text/opentype.ts
+++ b/packages/core/src/text/opentype.ts
@@ -21,6 +21,11 @@ interface OutlinePath {
interface OutlineGlyph {
path: OutlinePath
advanceWidth?: number
+ /**
+ * The default instance's advance, which opentype.js sets aside when it draws a variable font's
+ * instance and overwrites `advanceWidth` with that instance's.
+ */
+ _advanceWidth?: number
getPath(
x: number,
y: number,
@@ -102,8 +107,9 @@ function glyphsForCodePoints(font: OutlineFont, text: string): OutlineGlyph[] {
return Array.from(text, (character) => font.charToGlyph(character))
}
+/** A glyph's advance in the font's default instance, whatever instance was last drawn. */
function glyphAdvanceWidth(font: OutlineFont, glyph: OutlineGlyph, fontSize: number): number {
- return ((glyph.advanceWidth ?? 0) * fontSize) / font.unitsPerEm
+ return ((glyph._advanceWidth ?? glyph.advanceWidth ?? 0) * fontSize) / font.unitsPerEm
}
export function measureTextWithOpenType(
diff --git a/packages/core/tests/canvas/text/faces.test.ts b/packages/core/tests/canvas/text/faces.test.ts
index 10cc2eebc..a802cb1f9 100644
--- a/packages/core/tests/canvas/text/faces.test.ts
+++ b/packages/core/tests/canvas/text/faces.test.ts
@@ -1,13 +1,13 @@
import { describe, expect, test } from 'bun:test'
-
-import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
+import { join } from 'node:path'
import { expectDefined } from '#core-tests/helpers/assert'
+import { FIXTURES } from '#core-tests/helpers/paths'
+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
-import { SceneGraph } from '@open-pencil/scene-graph'
-
import { buildParagraph } from '#core/canvas/text'
import { withFigExportRuntime } from '#core/canvas/text/shape'
import { getCanvasKit } from '#core/canvaskit'
@@ -25,7 +25,7 @@ async function bundled(file: string): Promise<ArrayBuffer> {
function drawn(
ck: CanvasKit,
fontProvider: TypefaceFontProvider,
- style: { fontWeight: number; italic: boolean }
+ style: Partial<SceneNode> & { fontWeight: number; italic: boolean }
): Uint8Array {
const node = createDefaultNode(() => 'face-text', 'TEXT', {
text: 'Faces',
@@ -44,7 +44,13 @@ function drawn(
paragraph.layout(300)
paragraph.draw(surface.getCanvas(), 0, 0)
return expectDefined(
- surface.getCanvas().readPixels(0, 0, { width: 300, height: 60, colorType: ck.ColorType.RGBA_8888, alphaType: ck.AlphaType.Unpremul, colorSpace: ck.ColorSpace.SRGB }),
+ surface.getCanvas().readPixels(0, 0, {
+ width: 300,
+ height: 60,
+ colorType: ck.ColorType.RGBA_8888,
+ alphaType: ck.AlphaType.Unpremul,
+ colorSpace: ck.ColorSpace.SRGB
+ }),
'pixels'
) as Uint8Array
} finally {
@@ -62,7 +68,7 @@ describe('text faces', () => {
const ck = await getCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
fontManager.attachProvider(ck, fontProvider)
- fontManager.markLoaded(FAMILY, 'Regular', await bundled('/Inter-Regular.ttf'))
+ fontManager.markLoaded(FAMILY, 'Regular', await bundled('/InterVariable.ttf'))
const regular = drawn(ck, fontProvider, { fontWeight: 400, italic: false })
expect(drawn(ck, fontProvider, { fontWeight: 400, italic: true })).toEqual(regular)
expect(drawn(ck, fontProvider, { fontWeight: 700, italic: false })).toEqual(regular)
@@ -72,12 +78,52 @@ describe('text faces', () => {
const ck = await getCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
fontManager.attachProvider(ck, fontProvider)
- fontManager.markLoaded(FAMILY, 'Regular', await bundled('/Inter-Regular.ttf'))
- fontManager.markLoaded(FAMILY, 'Bold', await bundled('/Inter-Bold.ttf'))
+ fontManager.markLoaded(FAMILY, 'Regular', await bundled('/InterVariable.ttf'))
+ fontManager.markLoaded(FAMILY, 'Bold', await bundled('/InterVariable.ttf'))
const regular = drawn(ck, fontProvider, { fontWeight: 400, italic: false })
expect(drawn(ck, fontProvider, { fontWeight: 700, italic: false })).not.toEqual(regular)
})
+ test('draws optical size at the font size unless the text detaches it, as Figma does', async () => {
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ // Inter's optical size axis runs from 14 to 32, so text at 40 follows it to 32.
+ const variable = await Bun.file(
+ join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')
+ ).arrayBuffer()
+ const fontFamily = 'Faces Test Optical'
+ fontManager.markLoaded(fontFamily, 'Regular', variable)
+ const face = (fields: Partial<SceneNode>) =>
+ drawn(ck, fontProvider, { fontFamily, fontWeight: 400, italic: false, ...fields })
+ const automatic = face({})
+ expect(face({ fontVariations: [{ axis: 'opsz', value: 14 }] })).toEqual(automatic)
+ expect(
+ face({ opticalSizeFromFontSize: false, fontVariations: [{ axis: 'opsz', value: 14 }] })
+ ).not.toEqual(automatic)
+ expect(
+ face({ opticalSizeFromFontSize: false, fontVariations: [{ axis: 'opsz', value: 32 }] })
+ ).toEqual(automatic)
+ })
+
+ test('draws each style of a family loaded from several files from its own file', async () => {
+ const ck = await getCanvasKit()
+ const fontProvider = ck.TypefaceFontProvider.Make()
+ fontManager.attachProvider(ck, fontProvider)
+ // A static Regular and a variable file loaded for Light both declare weight 400, which
+ // CanvasKit would tie between.
+ const regular = await Bun.file(join(FIXTURES, 'fonts', 'InterRegular-Faces.ttf')).arrayBuffer()
+ const variable = await Bun.file(
+ join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')
+ ).arrayBuffer()
+ fontManager.markLoaded('Faces Test Mixed', 'Regular', regular)
+ fontManager.markLoaded('Faces Test Mixed', 'Light', variable)
+ fontManager.markLoaded('Faces Test Variable Only', 'Light', variable)
+ const light = (fontFamily: string) =>
+ drawn(ck, fontProvider, { fontFamily, fontWeight: 300, italic: false })
+ expect(light('Faces Test Mixed')).toEqual(light('Faces Test Variable Only'))
+ })
+
/**
* 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.
@@ -85,8 +131,8 @@ describe('text faces', () => {
test('saves fallback characters in the face the text is drawn in', async () => {
const primary = 'Faces Test Naskh'
fontManager.markLoaded(primary, 'Regular', await bundled('/NotoNaskhArabic-Regular.ttf'))
- fontManager.markLoaded('Inter', 'Regular', await bundled('/Inter-Regular.ttf'))
- fontManager.markLoaded('Inter', 'Bold', await bundled('/Inter-Bold.ttf'))
+ fontManager.markLoaded('Inter', 'Regular', await bundled('/InterVariable.ttf'))
+ fontManager.markLoaded('Inter', 'Bold', await bundled('/InterVariable.ttf'))
const graph = new SceneGraph()
const node = graph.createNode('TEXT', graph.getPages()[0].id, {
text: 'F',
diff --git a/packages/core/tests/canvas/text/lines.test.ts b/packages/core/tests/canvas/text/lines.test.ts
index 8fe6bde0c..d0c96db10 100644
--- a/packages/core/tests/canvas/text/lines.test.ts
+++ b/packages/core/tests/canvas/text/lines.test.ts
@@ -92,7 +92,7 @@ describe('lines of mixed sizes', () => {
provider = ck.TypefaceFontProvider.Make()
fontManager.attachProvider(ck, provider)
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
provider.registerFont(inter, 'Inter')
diff --git a/packages/core/tests/canvas/text/lists.test.ts b/packages/core/tests/canvas/text/lists.test.ts
index 175e35431..80bf35c36 100644
--- a/packages/core/tests/canvas/text/lists.test.ts
+++ b/packages/core/tests/canvas/text/lists.test.ts
@@ -45,7 +45,7 @@ function lineStarts(shaped: ShapedText): number[] {
describe('text lists', () => {
beforeAll(async () => {
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
fontManager.markLoaded('Inter', 'Regular', inter)
diff --git a/packages/core/tests/canvas/text/readiness.test.ts b/packages/core/tests/canvas/text/readiness.test.ts
index 2cdfa169f..c4760f9fe 100644
--- a/packages/core/tests/canvas/text/readiness.test.ts
+++ b/packages/core/tests/canvas/text/readiness.test.ts
@@ -15,7 +15,7 @@ import { fontManager } from '#core/text/fonts'
describe('text readiness with characters no font has', () => {
beforeAll(async () => {
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
fontManager.markLoaded('Inter', 'Regular', inter)
diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.ts
index 9cad68d1d..3d7d0fdf5 100644
--- a/packages/core/tests/canvas/text/shape.test.ts
+++ b/packages/core/tests/canvas/text/shape.test.ts
@@ -38,7 +38,7 @@ async function shape(props: Partial<SceneNode>): Promise<ShapedText | null> {
describe('text shaping for saved glyphs', () => {
beforeAll(async () => {
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
fontManager.markLoaded('Inter', 'Regular', inter)
diff --git a/packages/core/tests/editor/structure/flatten.test.ts b/packages/core/tests/editor/structure/flatten.test.ts
index 3e4dcfaa6..4d3d91456 100644
--- a/packages/core/tests/editor/structure/flatten.test.ts
+++ b/packages/core/tests/editor/structure/flatten.test.ts
@@ -31,12 +31,12 @@ async function createEditorWithRenderer() {
}
async function loadInterRegular() {
- const data = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontManager.markLoaded('Inter', 'Regular', data)
}
async function loadInterBold() {
- const data = await Bun.file('packages/core/assets/Inter-Bold.ttf').arrayBuffer()
+ const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontManager.markLoaded('Inter', 'Bold', data)
}
diff --git a/packages/core/tests/figma-api/text/autosize.test.ts b/packages/core/tests/figma-api/text/autosize.test.ts
index 2951e00ab..c8ffebe8a 100644
--- a/packages/core/tests/figma-api/text/autosize.test.ts
+++ b/packages/core/tests/figma-api/text/autosize.test.ts
@@ -14,7 +14,7 @@ beforeAll(async () => {
fontManager.markLoaded(
'Inter',
'Regular',
- expectDefined(await fontManager.fetchBundledFont('/Inter-Regular.ttf'), 'bundled Inter font')
+ expectDefined(await fontManager.fetchBundledFont('/InterVariable.ttf'), 'bundled Inter font')
)
})
diff --git a/packages/core/tests/io/formats/fig/export/live-document.test.ts b/packages/core/tests/io/formats/fig/export/live-document.test.ts
index b64118081..181726d4a 100644
--- a/packages/core/tests/io/formats/fig/export/live-document.test.ts
+++ b/packages/core/tests/io/formats/fig/export/live-document.test.ts
@@ -15,7 +15,7 @@ import { fontManager } from '#core/text/fonts'
// a font an edit brought in while they loaded.
test('font digests cover a font added while they load', async () => {
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
fontManager.markLoaded('Inter', 'Regular', inter)
diff --git a/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.ts
index 945008880..82d244efd 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.ts
@@ -18,7 +18,7 @@ const LIST: TextParagraphStyle[] = [
beforeAll(async () => {
await initCodec()
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
fontManager.markLoaded('Inter', 'Regular', inter)
diff --git a/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.ts
index 9b4c65c5d..bc62a723c 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.ts
@@ -10,7 +10,7 @@ import { SceneGraph } from '@open-pencil/scene-graph'
beforeAll(async () => {
await initCodec()
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
fontManager.markLoaded('Inter', 'Regular', inter)
diff --git a/packages/core/tests/io/formats/pdf/fonts.test.ts b/packages/core/tests/io/formats/pdf/fonts.test.ts
index 1168c4f88..e25cf4612 100644
--- a/packages/core/tests/io/formats/pdf/fonts.test.ts
+++ b/packages/core/tests/io/formats/pdf/fonts.test.ts
@@ -34,7 +34,8 @@ let interVariable: ArrayBuffer
let cff: ArrayBuffer
beforeAll(async () => {
- inter = expectDefined(await fontManager.fetchBundledFont('/Inter-Regular.ttf'), 'Inter')
+ // Static, as jsPDF embeds only static TrueType; the canvas labels' face.
+ inter = expectDefined(await fontManager.fetchBundledFont('/Inter-SemiBold.ttf'), 'Inter')
interVariable = await fixture('InterVariable-Latin.ttf')
cff = await fixture('NotoSansCJK-Test.otf')
})
diff --git a/packages/core/tests/io/formats/pdf/text-layout.test.ts b/packages/core/tests/io/formats/pdf/text-layout.test.ts
index 82cc7db0d..52b6969fa 100644
--- a/packages/core/tests/io/formats/pdf/text-layout.test.ts
+++ b/packages/core/tests/io/formats/pdf/text-layout.test.ts
@@ -11,7 +11,7 @@ import { fontManager } from '#core/text/fonts'
const SENTENCE = 'A sentence long enough that it has to wrap onto a second line.'
beforeAll(async () => {
- const inter = expectDefined(await fontManager.fetchBundledFont('/Inter-Regular.ttf'), 'Inter')
+ const inter = expectDefined(await fontManager.fetchBundledFont('/InterVariable.ttf'), 'Inter')
fontManager.markLoaded('Inter', 'Regular', inter)
})
diff --git a/packages/core/tests/text/fonts.test.ts b/packages/core/tests/text/fonts.test.ts
index cf189ee58..e230bf971 100644
--- a/packages/core/tests/text/fonts.test.ts
+++ b/packages/core/tests/text/fonts.test.ts
@@ -1,4 +1,7 @@
import { expect, test } from 'bun:test'
+import { join } from 'node:path'
+
+import { FIXTURES } from '#core-tests/helpers/paths'
import { FontManager } from '@open-pencil/core/text'
@@ -30,3 +33,56 @@ test('a new catalog tells listeners to ask for their families again', () => {
manager.setHostFontCatalog([])
expect(resets).toBe(1)
})
+
+test('draws every weight its variable font covers from the one file, in the same slant', async () => {
+ const manager = offlineManager()
+ const variable = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()
+ manager.markLoaded('Fonts Test Variable', 'Regular', variable)
+ expect(await manager.loadFont('Fonts Test Variable', 'Bold')).toBe(variable)
+ expect(manager.isStyleLoaded('Fonts Test Variable', 'Bold')).toBe(true)
+ // The file is upright, so it does not stand in for an italic.
+ expect(await manager.loadFont('Fonts Test Variable', 'Bold Italic')).toBeNull()
+})
+
+test('an installed face of the style comes before a variable file loaded for another style', async () => {
+ const manager = offlineManager()
+ const family = 'Fonts Test Installed First'
+ const variable = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()
+ const installed = await Bun.file(join(FIXTURES, 'fonts', 'InterRegular-Faces.ttf')).arrayBuffer()
+ manager.setHostFontLoader(async (name, style) =>
+ name === family && style === 'Regular' ? installed : null
+ )
+ manager.markLoaded(family, 'Light', variable)
+ expect(await manager.loadFont(family, 'Regular')).toBe(installed)
+ // A weight nothing installs draws from the variable file.
+ expect(await manager.loadFont(family, 'Bold')).toBe(variable)
+})
+
+test('a variable font shared with another weight still fetches the characters it lacks', async () => {
+ const manager = new FontManager()
+ manager.setOnlineFontProviders({ google: true })
+ const family = 'Fonts Test Shared Coverage'
+ const fontURL = 'https://fonts.gstatic.com/s/test/shared.ttf'
+ const variable = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()
+ const asked: string[] = []
+ manager.setWebFontFetch(async (url) => {
+ if (url.startsWith('https://fonts.google.com/metadata/fonts'))
+ return Response.json({
+ familyMetadataList: [
+ { family, fonts: { '400': {}, '700': {} }, axes: [{ tag: 'wght', min: 100, max: 900 }] }
+ ]
+ })
+ if (url.startsWith('https://fonts.googleapis.com/css2')) {
+ asked.push(new URL(url).searchParams.get('text') ?? '')
+ return new Response(
+ `@font-face { font-family: '${family}'; font-style: normal; font-weight: 100 900; src: url(${fontURL}) format('truetype'); }`
+ )
+ }
+ if (url === fontURL) return new Response(variable.slice(0))
+ return new Response(null, { status: 404 })
+ })
+
+ await manager.loadFont(family, 'Regular', 'abc')
+ await manager.loadFont(family, 'Bold', 'xyz')
+ expect(asked.at(-1)).toContain('xyz')
+})
diff --git a/packages/core/tests/text/opentype.test.ts b/packages/core/tests/text/opentype.test.ts
new file mode 100644
index 000000000..36860dab6
--- /dev/null
+++ b/packages/core/tests/text/opentype.test.ts
@@ -0,0 +1,23 @@
+import { expect, test } from 'bun:test'
+import { join } from 'node:path'
+
+import { FIXTURES } from '#core-tests/helpers/paths'
+
+import { fontManager } from '@open-pencil/core/text'
+
+import { glyphAdvanceSync, glyphOutlineSourceSync } from '#core/text/opentype'
+
+test('measures default advances whatever instance of a variable font was last outlined', async () => {
+ const family = 'OpenType Test Variable'
+ fontManager.markLoaded(
+ family,
+ 'Regular',
+ await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()
+ )
+ const source = glyphOutlineSourceSync(family, 'Regular', [{ axis: 'wght', value: 900 }])
+ const glyph = source?.glyphOf('H') ?? 0
+ const before = glyphAdvanceSync(family, 'Regular', glyph, 100)
+ // opentype.js writes the instance's advance onto the glyph it outlines.
+ source?.outline(glyph, 100)
+ expect(glyphAdvanceSync(family, 'Regular', glyph, 100)).toBe(before)
+})
diff --git a/packages/core/tests/text/prepare.test.ts b/packages/core/tests/text/prepare.test.ts
index e742dec9b..ebcbfc431 100644
--- a/packages/core/tests/text/prepare.test.ts
+++ b/packages/core/tests/text/prepare.test.ts
@@ -25,7 +25,7 @@ describe('emoji font preparation', () => {
beforeAll(async () => {
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
fontManager.markLoaded('Inter', 'Regular', inter)
diff --git a/packages/fig/src/instance-overrides/fields.ts b/packages/fig/src/instance-overrides/fields.ts
index 2cb1d2d5c..039aca749 100644
--- a/packages/fig/src/instance-overrides/fields.ts
+++ b/packages/fig/src/instance-overrides/fields.ts
@@ -107,6 +107,11 @@ export const OVERRIDE_FIELDS = {
stackPositioning: { scene: ['layoutPositioning'], kind: 'node' },
fontName: { scene: ['fontFamily', 'fontWeight', 'italic'], kind: 'node' },
fontVariations: { scene: ['fontVariations'], kind: 'node', absent: [] },
+ detachOpticalSizeFromFontSize: {
+ scene: ['opticalSizeFromFontSize'],
+ kind: 'node',
+ absent: false
+ },
lineHeight: { scene: ['lineHeight'], kind: 'node', absent: { value: 100, units: 'PERCENT' } },
letterSpacing: { scene: ['letterSpacing'], kind: 'node' },
paragraphSpacing: { scene: ['paragraphSpacing'], kind: 'node', length: true, absent: 0 },
diff --git a/packages/fig/src/instance-overrides/text-provenance.ts b/packages/fig/src/instance-overrides/text-provenance.ts
index 8cca3dbc4..7ddbab613 100644
--- a/packages/fig/src/instance-overrides/text-provenance.ts
+++ b/packages/fig/src/instance-overrides/text-provenance.ts
@@ -6,6 +6,7 @@ const SHAPING_FIELDS = [
'fontSize',
'fontName',
'fontVariations',
+ 'detachOpticalSizeFromFontSize',
'letterSpacing',
'lineHeight',
'textCase',
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index caf024efa..0b056c137 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -365,6 +365,7 @@ type TextProps = Pick<
| 'hangingList'
| 'styleRuns'
| 'fontVariations'
+ | 'opticalSizeFromFontSize'
| 'fontFeatures'
| 'textTruncation'
| 'textDirection'
@@ -452,6 +453,7 @@ function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {
...convertParagraphProps(nc),
styleRuns: importStyleRuns(nc),
fontVariations: convertFontVariations(nc),
+ opticalSizeFromFontSize: nc.detachOpticalSizeFromFontSize !== true,
fontFeatures: convertFontFeatures(nc),
textTruncation: (nc.textTruncation as string) === 'ENDING' ? 'ENDING' : 'DISABLED',
textDirection: readNodeChangePluginData(nc, OPEN_PENCIL_PLUGIN_DATA.textDirection) ?? 'AUTO',
@@ -1207,6 +1209,7 @@ export const FIGMA_RAW_NODE_FIELD_KEYS = [
'textUserLayoutVersion',
'textExplicitLayoutVersion',
'fontVariations',
+ 'detachOpticalSizeFromFontSize',
'fontVariantCommonLigatures',
'fontVariantContextualLigatures',
'toggledOnOTFeatures',
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index a239f7761..6846f9b06 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -101,6 +101,7 @@ function serializeTextProps(
if (node.fontVariations.length > 0) {
nc.fontVariations = node.fontVariations.map(fontVariationToKiwi)
}
+ if (!node.opticalSizeFromFontSize) nc.detachOpticalSizeFromFontSize = true
const autoResize = node.textAutoResize
const rawNodeFields = effectiveFigmaRawNodeFields(node)
if (!node.source.id || autoResize !== 'NONE' || 'textAutoResize' in rawNodeFields) {
diff --git a/packages/fig/src/source-metadata.ts b/packages/fig/src/source-metadata.ts
index 816136c9b..1bef78205 100644
--- a/packages/fig/src/source-metadata.ts
+++ b/packages/fig/src/source-metadata.ts
@@ -78,6 +78,7 @@ const EDITED_RAW_FIELDS: Partial<Record<string, readonly string[]>> = {
paragraphIndent: ['paragraphIndent', ...TEXT_DERIVED_RAW_FIELDS],
hangingList: ['hangingList', ...TEXT_DERIVED_RAW_FIELDS],
fontVariations: ['fontVariations', ...TEXT_DERIVED_RAW_FIELDS],
+ opticalSizeFromFontSize: ['detachOpticalSizeFromFontSize', ...TEXT_DERIVED_RAW_FIELDS],
fontFeatures: [
'fontVariantCommonLigatures',
'fontVariantContextualLigatures',
diff --git a/packages/fig/tests/node-change/font-variations.test.ts b/packages/fig/tests/node-change/font-variations.test.ts
new file mode 100644
index 000000000..b1ae66716
--- /dev/null
+++ b/packages/fig/tests/node-change/font-variations.test.ts
@@ -0,0 +1,32 @@
+import { expect, test } from 'bun:test'
+
+import { nodeChangeToProps, sceneNodeToKiwi } from '@open-pencil/fig/node-change'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+const OPSZ = 0x6f70737a
+
+test('reads an optical size Figma detached from the font size, and follows it otherwise', () => {
+ const detached = nodeChangeToProps(
+ {
+ type: 'TEXT',
+ fontVariations: [{ axisTag: OPSZ, axisName: 'opsz', value: 8 }],
+ detachOpticalSizeFromFontSize: true
+ } as NodeChange,
+ []
+ )
+ expect(detached.opticalSizeFromFontSize).toBe(false)
+ expect(detached.fontVariations).toEqual([{ axis: 'opsz', value: 8 }])
+ expect(nodeChangeToProps({ type: 'TEXT' } as NodeChange, []).opticalSizeFromFontSize).toBe(true)
+})
+
+test('writes the detached optical size only when the text has one', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const write = (opticalSizeFromFontSize: boolean) => {
+ const node = graph.createNode('TEXT', page, { text: 'Faces', opticalSizeFromFontSize })
+ return sceneNodeToKiwi(node, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])[0]
+ }
+ expect(write(false).detachOpticalSizeFromFontSize).toBe(true)
+ expect(write(true).detachOpticalSizeFromFontSize).toBeUndefined()
+})
diff --git a/packages/pen/src/text.ts b/packages/pen/src/text.ts
index 3ce09b930..8b00b8059 100644
--- a/packages/pen/src/text.ts
+++ b/packages/pen/src/text.ts
@@ -72,5 +72,7 @@ export function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext):
node.lineHeight = resolveNumber(pen.lineHeight, ctx) * node.fontSize
if (pen.letterSpacing !== undefined) node.letterSpacing = resolveNumber(pen.letterSpacing, ctx)
node.textAutoResize = TEXT_GROWTH[pen.textGrowth ?? 'auto'] ?? 'WIDTH_AND_HEIGHT'
+ // pen.dev draws every font at its default optical size, whatever the text's size.
+ node.opticalSizeFromFontSize = false
node.strokes = []
}
diff --git a/packages/pen/tests/text.test.ts b/packages/pen/tests/text.test.ts
index a9305addf..bd781cbad 100644
--- a/packages/pen/tests/text.test.ts
+++ b/packages/pen/tests/text.test.ts
@@ -57,6 +57,10 @@ describe('parsePenFile — text', () => {
expect(textOf({ fontSize: 10, lineHeight: 6 }).lineHeight).toBe(60)
})
+ test('keeps every font at its default optical size, as pen.dev draws it', () => {
+ expect(textOf({ fontSize: 96 }).opticalSizeFromFontSize).toBe(false)
+ })
+
test('draws no text stroke, as pen.dev does not', () => {
expect(textOf({ stroke: '#FF0000', strokeWidth: 1 }).strokes).toEqual([])
})
diff --git a/packages/scene-graph/src/fields/text.ts b/packages/scene-graph/src/fields/text.ts
index a2d7b6868..bc77ffd5a 100644
--- a/packages/scene-graph/src/fields/text.ts
+++ b/packages/scene-graph/src/fields/text.ts
@@ -10,6 +10,7 @@ export const TEXT_METRIC_FIELDS = [
'letterSpacing',
'styleRuns',
'fontVariations',
+ 'opticalSizeFromFontSize',
'fontFeatures',
'textParagraphs',
'listSpacing',
@@ -58,5 +59,6 @@ export const TEXT_STYLE_FIELDS = [
'textCase',
...TEXT_DECORATION_FIELDS,
'fontFeatures',
- 'fontVariations'
+ 'fontVariations',
+ 'opticalSizeFromFontSize'
] as const satisfies readonly (keyof SceneNode)[]
diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.ts
index 0ca8b809d..3f7bff660 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -142,6 +142,7 @@ export function createDefaultNode(
hangingList: false,
styleRuns: [],
fontVariations: [],
+ opticalSizeFromFontSize: true,
fontFeatures: [],
horizontalConstraint: 'MIN',
verticalConstraint: 'MIN',
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index d29906264..37e3b4c01 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -669,6 +669,11 @@ export interface SceneNode {
styleRuns: StyleRun[]
fontVariations: FontVariation[]
+ /**
+ * Whether a variable font's optical size follows the font size, as Figma's "Set optical size
+ * automatically" does by default; when it does not, the `opsz` in `fontVariations` applies.
+ */
+ opticalSizeFromFontSize: boolean
fontFeatures: FontFeature[]
horizontalConstraint: ConstraintType
diff --git a/src/app/editor/fonts/bundled.ts b/src/app/editor/fonts/bundled.ts
index 85d6ea9a6..a389b64ef 100644
--- a/src/app/editor/fonts/bundled.ts
+++ b/src/app/editor/fonts/bundled.ts
@@ -1,8 +1,6 @@
-import interBold from '@open-pencil/core/assets/Inter-Bold.ttf?url'
-import interExtraBold from '@open-pencil/core/assets/Inter-ExtraBold.ttf?url'
-import interMedium from '@open-pencil/core/assets/Inter-Medium.ttf?url'
-import interRegular from '@open-pencil/core/assets/Inter-Regular.ttf?url'
import interSemiBold from '@open-pencil/core/assets/Inter-SemiBold.ttf?url'
+import interVariableItalic from '@open-pencil/core/assets/InterVariable-Italic.ttf?url'
+import interVariable from '@open-pencil/core/assets/InterVariable.ttf?url'
import notoNaskhArabic from '@open-pencil/core/assets/NotoNaskhArabic-Regular.ttf?url'
import emojiMetrics from '@open-pencil/core/assets/OpenPencilEmojiMetrics-Regular.ttf?url'
import { fontManager } from '@open-pencil/core/text'
@@ -14,11 +12,9 @@ import { fontManager } from '@open-pencil/core/text'
* in a Vite build, not in the Bun test runner.
*/
const BUNDLED_FONT_URLS: Record<string, string> = {
- 'Inter-Regular.ttf': interRegular,
- 'Inter-Medium.ttf': interMedium,
+ 'InterVariable.ttf': interVariable,
+ 'InterVariable-Italic.ttf': interVariableItalic,
'Inter-SemiBold.ttf': interSemiBold,
- 'Inter-Bold.ttf': interBold,
- 'Inter-ExtraBold.ttf': interExtraBold,
'NotoNaskhArabic-Regular.ttf': notoNaskhArabic,
'OpenPencilEmojiMetrics-Regular.ttf': emojiMetrics
}
diff --git a/tests/e2e/canvas/optical-size-visual.spec.ts b/tests/e2e/canvas/optical-size-visual.spec.ts
new file mode 100644
index 000000000..09a6716c2
--- /dev/null
+++ b/tests/e2e/canvas/optical-size-visual.spec.ts
@@ -0,0 +1,48 @@
+import { expect, test } from '#tests/e2e/fixtures'
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+test('variable text follows its font size on the optical size axis unless detached', async ({
+ page
+}) => {
+ await page.goto('/?test&no-chrome&no-rulers')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ await page.evaluate(async () => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Editor unavailable')
+ const card = store.graph.createNode('FRAME', store.state.currentPageId, {
+ name: 'Card',
+ width: 520,
+ height: 150,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]
+ })
+ // Inter's optical size runs from 14 to 32, so at 32 and 48 the automatic axis leaves the
+ // default the detached text keeps.
+ const rows = [
+ { y: 10, fontSize: 32, opticalSizeFromFontSize: true },
+ { y: 50, fontSize: 32, opticalSizeFromFontSize: false },
+ { y: 90, fontSize: 48, opticalSizeFromFontSize: true }
+ ]
+ for (const row of rows) {
+ store.graph.createNode('TEXT', card.id, {
+ name: row.opticalSizeFromFontSize ? 'Automatic' : 'Detached',
+ text: 'Hamburgefonstiv',
+ x: 10,
+ y: row.y,
+ width: 500,
+ height: row.fontSize * 1.2,
+ fontFamily: 'Inter',
+ fontSize: row.fontSize,
+ opticalSizeFromFontSize: row.opticalSizeFromFontSize,
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ fills: [
+ { type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+ }
+ await store.loadFontsForNodes([card.id])
+ store.requestRender()
+ })
+ await canvas.waitForRender()
+ expect(await canvas.screenshotCanvasRegion(520, 150)).toMatchSnapshot('optical-size.png')
+})
diff --git a/tests/e2e/canvas/optical-size-visual.spec.ts-snapshots/optical-size-openpencil-darwin.png b/tests/e2e/canvas/optical-size-visual.spec.ts-snapshots/optical-size-openpencil-darwin.png
new file mode 100644
index 000000000..6175695b2
Binary files /dev/null and b/tests/e2e/canvas/optical-size-visual.spec.ts-snapshots/optical-size-openpencil-darwin.png differ
diff --git a/tests/engine/app/font-loading.test.ts b/tests/engine/app/font-loading.test.ts
index b94c8ff71..2a11beb91 100644
--- a/tests/engine/app/font-loading.test.ts
+++ b/tests/engine/app/font-loading.test.ts
@@ -31,7 +31,7 @@ describe('app font loading', () => {
test('ensureGraphFonts loads fallback packs when loaded primary font misses CJK glyphs', async () => {
const interData = await Bun.file(
- repoPath('packages/core/assets/Inter-Regular.ttf')
+ repoPath('packages/core/assets/InterVariable.ttf')
).arrayBuffer()
fontManager.markLoaded('Inter', 'Regular', interData)
diff --git a/tests/engine/clipboard/figma/html.test.ts b/tests/engine/clipboard/figma/html.test.ts
index 66252c87a..470896a1a 100644
--- a/tests/engine/clipboard/figma/html.test.ts
+++ b/tests/engine/clipboard/figma/html.test.ts
@@ -27,7 +27,7 @@ describe('buildFigmaClipboardHTML', () => {
beforeAll(async () => {
await initCodec()
const inter = expectDefined(
- await fontManager.fetchBundledFont('/Inter-Regular.ttf'),
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
'bundled Inter font'
)
fontManager.markLoaded('Inter', 'Regular', inter)
diff --git a/tests/engine/core/editor/text/path-edit.test.ts b/tests/engine/core/editor/text/path-edit.test.ts
index e2025bc41..abeff0c5a 100644
--- a/tests/engine/core/editor/text/path-edit.test.ts
+++ b/tests/engine/core/editor/text/path-edit.test.ts
@@ -23,7 +23,7 @@ function straightLineNetwork() {
describe('pathTextEditChanges — reflow on character edit', () => {
test('re-lays out glyphs along the path instead of clearing them', async () => {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(font).toBeTruthy()
if (!font) return
fontManager.markLoaded('Inter', 'Regular', font)
@@ -69,7 +69,7 @@ describe('pathTextEditChanges — reflow on character edit', () => {
})
test('uses opentype.js glyph positioning when the font supports its shaping pipeline', async () => {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(font).toBeTruthy()
if (!font) return
fontManager.markLoaded('Inter', 'Regular', font)
@@ -83,7 +83,7 @@ describe('pathTextEditChanges — reflow on character edit', () => {
})
test('folds letterSpacing into the pen-walk advance', async () => {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(font).toBeTruthy()
if (!font) return
fontManager.markLoaded('Inter', 'Regular', font)
@@ -156,7 +156,7 @@ describe('pathTextEditChanges — reflow on character edit', () => {
})
test('uses pending fontSize from the same update batch', async () => {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(font).toBeTruthy()
if (!font) return
fontManager.markLoaded('Inter', 'Regular', font)
@@ -199,7 +199,7 @@ describe('pathTextEditChanges — reflow on character edit', () => {
describe('pathTextEditChanges — alignment', () => {
/** "OO" at 40px on a 400-long straight path, glyph 0 at x = 150, aligned as given. */
async function alignedText(align: 'LEFT' | 'CENTER' | 'RIGHT', forward = true) {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
if (!font) throw new Error('missing bundled font')
fontManager.markLoaded('Inter', 'Regular', font)
const graph = new SceneGraph()
@@ -320,7 +320,7 @@ describe('aligned path text is laid out from the text path start, as in Figma',
}
async function edited(align: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED', forward = true) {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
if (!font) throw new Error('bundled font missing')
fontManager.markLoaded('Inter', 'Regular', font)
const text = 'Hello'
@@ -383,7 +383,7 @@ describe('path text that overflows its alignment’s part of the path, as in Fig
/** A straight 400-wide line in two segments; the text starts at x = 300. */
async function overflowing(align: 'LEFT' | 'CENTER' | 'RIGHT', tValue = 0.5) {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
if (!font) throw new Error('bundled font missing')
fontManager.markLoaded('Inter', 'Regular', font)
const graph = new SceneGraph()
@@ -464,7 +464,7 @@ describe('path text that overflows its alignment’s part of the path, as in Fig
})
test('overflowing text on a closed path keeps what fits one loop', async () => {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
if (!font) throw new Error('bundled font missing')
fontManager.markLoaded('Inter', 'Regular', font)
const graph = new SceneGraph()
@@ -527,7 +527,7 @@ test('overflowing text on a closed path keeps what fits one loop', async () => {
// wrong side and scrambled the run once the sides changed length.
describe('resizedPathTextGlyphs — resize lays the text out again', () => {
test('a squashed or stretched square keeps every letter on the path, in order', async () => {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
if (!font) throw new Error('expected the bundled Inter font')
fontManager.markLoaded('Inter', 'Regular', font)
diff --git a/tests/engine/core/editor/text/start-editing-gate.test.ts b/tests/engine/core/editor/text/start-editing-gate.test.ts
index 9db33b353..de3dab1bb 100644
--- a/tests/engine/core/editor/text/start-editing-gate.test.ts
+++ b/tests/engine/core/editor/text/start-editing-gate.test.ts
@@ -12,7 +12,7 @@ import { fontManager } from '#core/text/fonts'
*/
describe('startTextEditing — path-text font gate', () => {
test('blocks unavailable-font path text, allows available-font + normal text', async () => {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(font).toBeTruthy()
if (!font) return
fontManager.markLoaded('Inter', 'Regular', font)
diff --git a/tests/engine/io/fig/import/raw-field-coverage.test.ts b/tests/engine/io/fig/import/raw-field-coverage.test.ts
index 37aea6bef..2d473d5c5 100644
--- a/tests/engine/io/fig/import/raw-field-coverage.test.ts
+++ b/tests/engine/io/fig/import/raw-field-coverage.test.ts
@@ -11,6 +11,7 @@ const RAW_FIELD_COVERAGE = {
'borderStrokeWeightsIndependent',
'borderTopWeight',
'derivedTextData',
+ 'detachOpticalSizeFromFontSize',
'backgroundPaints',
'effects',
'fillGeometry',
diff --git a/tests/engine/io/fig/import/schema-coverage.test.ts b/tests/engine/io/fig/import/schema-coverage.test.ts
index 6829d6654..558c95b27 100644
--- a/tests/engine/io/fig/import/schema-coverage.test.ts
+++ b/tests/engine/io/fig/import/schema-coverage.test.ts
@@ -376,10 +376,10 @@ describe('Figma Kiwi schema coverage', () => {
modeled: 128,
schemaTag: 60,
internalBookkeeping: 16,
- rawPreserved: 45,
+ rawPreserved: 46,
styleLibraryMetadata: 38,
componentInstanceMetadata: 32,
- textMetadata: 19,
+ textMetadata: 18,
slideFigjamMetadata: 39,
visualGeometryMetadata: 37,
layoutMetadata: 29,
diff --git a/tests/engine/render/canvas/labels/fonts.test.ts b/tests/engine/render/canvas/labels/fonts.test.ts
index 3ac424e61..0978a6412 100644
--- a/tests/engine/render/canvas/labels/fonts.test.ts
+++ b/tests/engine/render/canvas/labels/fonts.test.ts
@@ -5,6 +5,7 @@ import { initCanvasKit } from '#cli/headless'
import { LabelParagraphCache } from '#core/canvas/labels/paragraph-cache'
import { resolveLabelFontCoverage } from '#core/canvas/renderer/fonts'
import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
+import { fontManager } from '#core/text/fonts'
import { FontResolver, missingGlyphOccurrences } from '#core/text/resolver'
import { expectDefined } from '#tests/helpers/assert'
@@ -30,7 +31,9 @@ test.each([
}
])('labels reuse shared fallback loading and render real $family glyphs', async (fixture) => {
const provider = ck.TypefaceFontProvider.Make()
- provider.registerFont(readFileSync(repoPath('packages/core/assets/Inter-Regular.ttf')), 'Inter')
+ // Attached, as the renderer's provider is, so faces the font manager names are registered in it.
+ fontManager.attachProvider(ck, provider)
+ provider.registerFont(readFileSync(repoPath('packages/core/assets/InterVariable.ttf')), 'Inter')
const release = Promise.withResolvers<undefined>()
const settled = Promise.withResolvers<undefined>()
let generation = 1
@@ -142,6 +145,7 @@ test.each([
cache.clear()
fresh.clear()
surface.delete()
+ fontManager.detachProvider(provider)
provider.delete()
}
})
diff --git a/tests/engine/render/canvas/labels/paragraph-cache.test.ts b/tests/engine/render/canvas/labels/paragraph-cache.test.ts
index 97df39c92..adba18693 100644
--- a/tests/engine/render/canvas/labels/paragraph-cache.test.ts
+++ b/tests/engine/render/canvas/labels/paragraph-cache.test.ts
@@ -14,7 +14,7 @@ beforeAll(async () => {
describe('label paragraph cache', () => {
test('shapes labels with Inter and invalidates native paragraphs by font generation', () => {
- const bytes = readFileSync(repoPath('packages/core/assets/Inter-Regular.ttf'))
+ const bytes = readFileSync(repoPath('packages/core/assets/InterVariable.ttf'))
const data = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
const provider = ck.TypefaceFontProvider.Make()
provider.registerFont(data, 'Inter')
diff --git a/tests/engine/render/canvas/labels/paragraph-reuse.test.ts b/tests/engine/render/canvas/labels/paragraph-reuse.test.ts
index db15eab65..00a26c95a 100644
--- a/tests/engine/render/canvas/labels/paragraph-reuse.test.ts
+++ b/tests/engine/render/canvas/labels/paragraph-reuse.test.ts
@@ -14,7 +14,7 @@ let provider: TypefaceFontProvider
beforeAll(async () => {
ck = await initCanvasKit()
provider = ck.TypefaceFontProvider.Make()
- provider.registerFont(readFileSync(repoPath('packages/core/assets/Inter-Regular.ttf')), 'Inter')
+ provider.registerFont(readFileSync(repoPath('packages/core/assets/InterVariable.ttf')), 'Inter')
provider.registerFont(readFileSync(repoPath('packages/core/assets/Inter-SemiBold.ttf')), 'Inter')
})
afterAll(() => provider.delete())
diff --git a/tests/engine/render/canvas/painted-text.test.ts b/tests/engine/render/canvas/painted-text.test.ts
index 2f4518bc9..2c7737d86 100644
--- a/tests/engine/render/canvas/painted-text.test.ts
+++ b/tests/engine/render/canvas/painted-text.test.ts
@@ -13,10 +13,9 @@ import { repoPath } from '#tests/helpers/paths'
const FONT_FAMILY = 'Painted text fixture'
beforeAll(async () => {
- for (const style of ['Regular', 'SemiBold']) {
- const data = await Bun.file(repoPath(`packages/core/assets/Inter-${style}.ttf`)).arrayBuffer()
- fontManager.markLoaded(FONT_FAMILY, style, data)
- }
+ // Inter's variable file draws both styles, as the bundled Inter does.
+ const data = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()
+ for (const style of ['Regular', 'SemiBold']) fontManager.markLoaded(FONT_FAMILY, style, data)
})
const solid: Fill = { type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }
diff --git a/tests/engine/render/canvas/text/preparation-cache.test.ts b/tests/engine/render/canvas/text/preparation-cache.test.ts
index 03250ef01..8c618692a 100644
--- a/tests/engine/render/canvas/text/preparation-cache.test.ts
+++ b/tests/engine/render/canvas/text/preparation-cache.test.ts
@@ -60,7 +60,7 @@ async function fixture(maxEntries = 8, maxUnits = 1000) {
describe('text preparation cache', () => {
test('does not repeatedly shape coverage when a dense scan exceeds paragraph capacity', async () => {
const f = await fixture(8)
- const data = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
f.provider.registerFont(data, 'Inter')
fontManager.markLoaded('Inter', 'Regular', data)
let builds = 0
@@ -248,6 +248,7 @@ describe('text preparation cache', () => {
italic: true,
fontFeatures: [{ tag: 'liga', enabled: false }],
fontVariations: [{ axis: 'wght', value: 700 }],
+ opticalSizeFromFontSize: false,
textLanguage: 'ar',
textDirection: 'RTL',
textCase: 'UPPER',
diff --git a/tests/engine/render/canvas/text/render.test.ts b/tests/engine/render/canvas/text/render.test.ts
index 3340626eb..e9f0fa487 100644
--- a/tests/engine/render/canvas/text/render.test.ts
+++ b/tests/engine/render/canvas/text/render.test.ts
@@ -195,7 +195,7 @@ describe('renderText', () => {
test('keeps native paragraph layout even when outline font data is available', async () => {
const interData = await Bun.file(
- repoPath('packages/core/assets/Inter-Regular.ttf')
+ repoPath('packages/core/assets/InterVariable.ttf')
).arrayBuffer()
fontManager.markLoaded('Inter', 'Regular', interData)
const r = createMockRenderer()
@@ -317,8 +317,8 @@ describe('paragraph font weights', () => {
test('bold Inter paragraph is wider than regular Inter', async () => {
const { renderer, surface } = await createTextRenderer()
await renderer.loadFonts()
- const regular = await Bun.file(repoPath('packages/core/assets/Inter-Regular.ttf')).arrayBuffer()
- const bold = await Bun.file(repoPath('packages/core/assets/Inter-Bold.ttf')).arrayBuffer()
+ const regular = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()
+ const bold = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()
fontManager.markLoaded('Inter', 'Regular', regular)
fontManager.markLoaded('Inter', 'Bold', bold)
@@ -343,7 +343,7 @@ describe('paragraph font weights', () => {
test('shapes italic text when only the regular family face is available', async () => {
const { renderer, surface } = await createTextRenderer()
await renderer.loadFonts()
- const regular = await Bun.file(repoPath('packages/core/assets/Inter-Regular.ttf')).arrayBuffer()
+ const regular = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()
fontManager.markLoaded('Inter', 'Regular', regular)
const demand = fontFaceDemand('Inter', 'Regular Italic', 'Synthetic italic')
fontResolver.reset(demand)
@@ -379,7 +379,7 @@ describe('renderText headless visual', () => {
const ck = await initCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
fontManager.attachProvider(ck, fontProvider)
- const interData = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontProvider.registerFont(interData, 'Inter')
fontManager.markLoaded('Inter', 'Regular', interData)
const fallbackFamilies = fontManager.getCJKFallbackFamilies()
@@ -409,7 +409,7 @@ describe('renderText headless visual', () => {
const ck = await initCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
fontManager.attachProvider(ck, fontProvider)
- const interData = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontManager.markLoaded('Inter', 'Regular', interData)
const fallbackFamilies = fontManager.getCJKFallbackFamilies()
const originalFallbacks = [...fallbackFamilies]
@@ -462,7 +462,7 @@ describe('renderText headless visual', () => {
const fontProvider = ck.TypefaceFontProvider.Make()
fontManager.attachProvider(ck, fontProvider)
- const interData = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontManager.markLoaded('Inter', 'Regular', interData)
const notoPath = repoPath('tests/fixtures/fonts/NotoSansSC-Regular.ttf')
@@ -534,7 +534,7 @@ describe('renderText headless visual', () => {
const fontProvider = ck.TypefaceFontProvider.Make()
fontManager.attachProvider(ck, fontProvider)
- const interData = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontProvider.registerFont(interData, 'Inter')
fontManager.markLoaded('Inter', 'Regular', interData)
@@ -613,7 +613,7 @@ describe('renderText headless visual', () => {
const fontProvider = ck.TypefaceFontProvider.Make()
fontManager.attachProvider(ck, fontProvider)
- const interData = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const interData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontProvider.registerFont(interData, 'Inter')
fontManager.markLoaded('Inter', 'Regular', interData)
diff --git a/tests/engine/text/coverage.test.ts b/tests/engine/text/coverage.test.ts
index bd664e6a2..5af52fc7e 100644
--- a/tests/engine/text/coverage.test.ts
+++ b/tests/engine/text/coverage.test.ts
@@ -20,7 +20,7 @@ describe('font fallback coverage indexing', () => {
test('detects supplementary-plane Han code points', async () => {
const family = `SupplementaryHan_${Date.now()}`
- const data = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontManager.markLoaded(family, 'Regular', data)
const graph = new SceneGraph()
const node = graph.createNode('TEXT', pageId(graph), {
@@ -34,7 +34,7 @@ describe('font fallback coverage indexing', () => {
test('uses BCP-47 language hints for Han fallback selection', async () => {
const family = `LanguageHint_${Date.now()}`
- const data = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const data = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
fontManager.markLoaded(family, 'Regular', data)
const graph = new SceneGraph()
const node = graph.createNode('TEXT', pageId(graph), {
@@ -56,7 +56,7 @@ describe('font fallback coverage indexing', () => {
test('uses UTF-16 style-run indices after a surrogate pair', async () => {
const cjkData = await Bun.file('tests/fixtures/fonts/NotoSansSC-Regular.ttf').arrayBuffer()
- const latinData = await Bun.file('packages/core/assets/Inter-Regular.ttf').arrayBuffer()
+ const latinData = await Bun.file('packages/core/assets/InterVariable.ttf').arrayBuffer()
const cjkFamily = `CJKRunBase_${Date.now()}`
const latinFamily = `CJKRunOverride_${Date.now()}`
fontManager.markLoaded(cjkFamily, 'Regular', cjkData)
diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.ts
index 3e8f25f47..c51010835 100644
--- a/tests/engine/text/edit-undo.test.ts
+++ b/tests/engine/text/edit-undo.test.ts
@@ -85,7 +85,7 @@ function straightTextPathNetwork() {
}
async function setupPathText() {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(font).toBeTruthy()
if (!font) return null
fontManager.markLoaded('Inter', 'Regular', font)
diff --git a/tests/engine/text/fonts/coverage.test.ts b/tests/engine/text/fonts/coverage.test.ts
index 7b27a7363..121302380 100644
--- a/tests/engine/text/fonts/coverage.test.ts
+++ b/tests/engine/text/fonts/coverage.test.ts
@@ -6,7 +6,7 @@ import { SceneGraph } from '@open-pencil/scene-graph'
import { repoPath } from '#tests/helpers/paths'
async function loadInter() {
- const interData = await Bun.file(repoPath('packages/core/assets/Inter-Regular.ttf')).arrayBuffer()
+ const interData = await Bun.file(repoPath('packages/core/assets/InterVariable.ttf')).arrayBuffer()
fontManager.markLoaded('Inter', 'Regular', interData)
}
diff --git a/tests/engine/text/fonts/lifecycle.test.ts b/tests/engine/text/fonts/lifecycle.test.ts
index 9cd472540..9bf8c97c4 100644
--- a/tests/engine/text/fonts/lifecycle.test.ts
+++ b/tests/engine/text/fonts/lifecycle.test.ts
@@ -114,14 +114,14 @@ describe('font lifecycle', () => {
const manager = new FontManager()
const [first, second] = await Promise.all([
- manager.fetchBundledFont('/Inter-Regular.ttf'),
- manager.fetchBundledFont('/Inter-Regular.ttf')
+ manager.fetchBundledFont('/InterVariable.ttf'),
+ manager.fetchBundledFont('/InterVariable.ttf')
])
expect(first).not.toBeNull()
expect(second).toBe(first)
// A settled request is not kept, so a later load (or a retry after a failure) reads again.
- const later = await manager.fetchBundledFont('/Inter-Regular.ttf')
+ const later = await manager.fetchBundledFont('/InterVariable.ttf')
expect(later).not.toBe(first)
expect(later?.byteLength).toBe(first?.byteLength)
})
diff --git a/tests/engine/text/fonts/loading.test.ts b/tests/engine/text/fonts/loading.test.ts
index 7276a2328..49c5ebc43 100644
--- a/tests/engine/text/fonts/loading.test.ts
+++ b/tests/engine/text/fonts/loading.test.ts
@@ -649,20 +649,20 @@ describe('isVariableFont', () => {
})
describe('fetchBundledFont', () => {
- test('loads Inter-Regular.ttf from assets in headless', async () => {
- const buffer = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ test('loads InterVariable.ttf from assets in headless', async () => {
+ const buffer = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(buffer).toBeInstanceOf(ArrayBuffer)
expect(expectDefined(buffer, 'Inter font buffer').byteLength).toBeGreaterThan(100_000)
})
- test('loads Inter-Bold.ttf from assets in headless', async () => {
- const buffer = await fontManager.fetchBundledFont('/Inter-Bold.ttf')
+ test('loads InterVariable.ttf from assets in headless', async () => {
+ const buffer = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(buffer).toBeInstanceOf(ArrayBuffer)
expect(expectDefined(buffer, 'Inter bold font buffer').byteLength).toBeGreaterThan(100_000)
})
test('returns valid TTF data', async () => {
- const buffer = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const buffer = await fontManager.fetchBundledFont('/InterVariable.ttf')
const view = new DataView(expectDefined(buffer, 'Inter font buffer'))
// TrueType magic: 0x00010000
expect(view.getUint32(0)).toBe(0x00010000)
diff --git a/tests/engine/text/opentype/outlines.test.ts b/tests/engine/text/opentype/outlines.test.ts
index 03a186f29..983db1d21 100644
--- a/tests/engine/text/opentype/outlines.test.ts
+++ b/tests/engine/text/opentype/outlines.test.ts
@@ -4,7 +4,7 @@ import { fontManager, probeGlyphOutlineCommands } from '@open-pencil/core/text'
describe('clipboard text outline probe', () => {
test('lazy-loads opentype.js and extracts glyph commands from a loaded font', async () => {
- const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/InterVariable.ttf')
expect(font).toBeTruthy()
if (!font) return
diff --git a/tests/fixtures/fonts/InterRegular-Faces.ttf b/tests/fixtures/fonts/InterRegular-Faces.ttf
new file mode 100644
index 000000000..a2940a522
--- /dev/null
+++ b/tests/fixtures/fonts/InterRegular-Faces.ttf
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a281ce01b1d238472e73a8d0bab87d6c821f48e0f7a032e3058c0032dadadd0f
+size 2072
diff --git a/tests/fixtures/pen-oracles/fonts/Inter--Light.font b/tests/fixtures/pen-oracles/fonts/Inter--Light.font
deleted file mode 100644
index f6f160841..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Inter--Light.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Inter--Regular Italic.font b/tests/fixtures/pen-oracles/fonts/Inter--Regular Italic.font
deleted file mode 100644
index 42757216c..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Inter--Regular Italic.font and /dev/null differ
diff --git a/tools/generate/visual-oracles/src/operations/compare/pen.ts b/tools/generate/visual-oracles/src/operations/compare/pen.ts
index 41462e317..a1f056d45 100644
--- a/tools/generate/visual-oracles/src/operations/compare/pen.ts
+++ b/tools/generate/visual-oracles/src/operations/compare/pen.ts
@@ -17,7 +17,8 @@
* to --output.
*/
-import { copyFileSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
+import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { parseArgs } from 'node:util'
@@ -49,6 +50,7 @@ import { styleToWeight } from '@open-pencil/scene-graph/font-style'
const PEN_MCP_SERVER =
'/Applications/Pen.app/Contents/Resources/app.asar.unpacked/out/mcp-server-darwin-arm64'
const ICONIFY_API = 'https://api.iconify.design'
+const EXPORT_TIMEOUT_MS = 300_000
const GOOGLE_FONTS_CSS = 'https://fonts.googleapis.com/css2'
const iconSetSchema = v.pipe(
@@ -109,17 +111,27 @@ const missing = [...wanted].filter((id) => !frames.some((frame) => frame.id ===
if (missing.length > 0) throw new Error(`The document has no top-level ${missing.join(', ')}`)
const assets = penAssets(doc)
-clearFixtures()
-writeFileSync(join(fixtures, 'probes.pen'), text)
-for (const image of assets.images.filter(isDocumentAssetPath)) {
- mkdirSync(dirname(join(fixtures, image)), { recursive: true })
- copyFileSync(join(dirname(source), image), join(fixtures, image))
+// pen.dev exports first, so a failed export leaves the fixtures as they were, and into a
+// directory of its own, which clearing the fixtures cannot reach.
+const exported = mkdtempSync(join(tmpdir(), 'pen-export-'))
+try {
+ await exportFromPen(
+ source,
+ frames.map((frame) => frame.id),
+ exported
+ )
+ clearFixtures()
+ writeFileSync(join(fixtures, 'probes.pen'), text)
+ for (const image of assets.images.filter(isDocumentAssetPath)) {
+ mkdirSync(dirname(join(fixtures, image)), { recursive: true })
+ copyFileSync(join(dirname(source), image), join(fixtures, image))
+ }
+ for (const frame of frames) {
+ copyFileSync(join(exported, `${frame.id}.png`), join(fixtures, `${frame.id}.png`))
+ }
+} finally {
+ rmSync(exported, { recursive: true, force: true })
}
-await exportFromPen(
- source,
- frames.map((frame) => frame.id),
- fixtures
-)
const iconSets = await fetchIconSets(assets.icons)
for (const set of iconSets.values()) {
@@ -248,13 +260,17 @@ async function exportFromPen(document: string, frameIds: string[], directory: st
new StdioClientTransport({ command: values.server, args: ['--app', 'desktop'] })
)
try {
- const result = await client.callTool({
- name: 'execute',
- arguments: {
- filePath: document,
- input: `Export(${JSON.stringify(frameIds)}, "png", ${JSON.stringify(directory)}, { scale: 1 })`
- }
- })
+ const result = await client.callTool(
+ {
+ name: 'execute',
+ arguments: {
+ filePath: document,
+ input: `Export(${JSON.stringify(frameIds)}, "png", ${JSON.stringify(directory)}, { scale: 1 })`
+ }
+ },
+ // Exporting every frame takes pen.dev a while.
+ { timeout: EXPORT_TIMEOUT_MS }
+ )
if (result.isError) throw new Error(`pen.dev export failed: ${JSON.stringify(result.content)}`)
} finally {
await client.close()