Skip to content

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

fix!: refuse text edits in unloaded fonts as Figma does, and size text once its font loads (#1575)

Danila Poyarkov22d9d9f21225
diff --git a/changes/1570/fixed.md b/changes/1570/fixed.md
index 0896f435b..795a0502c 100644
--- a/changes/1570/fixed.md
+++ b/changes/1570/fixed.md
@@ -1 +1 @@
-- Claude models used through OpenRouter cache the chat's prompt, also with a thinking level set, so repeated turns are billed at the cached-input rate.
+- Claude models used through OpenRouter mark the chat's prompt for caching, also with a thinking level set, so repeated turns can be billed at the cached-input rate when the provider has the prompt cached.
diff --git a/changes/1575/breaking.md b/changes/1575/breaking.md
new file mode 100644
index 000000000..7b505e0fa
--- /dev/null
+++ b/changes/1575/breaking.md
@@ -0,0 +1 @@
+- Plugin scripts run through `eval`, the CLI, and MCP follow Figma's font rule: an edit that lays text out again (characters, size, font, spacing, case, alignment, auto-resize, and the matching `setRange…` methods) throws `Cannot write to node with unloaded font` until `figma.loadFontAsync` has loaded every font the text uses, a new font has to be loaded before it is set, and `loadFontAsync` rejects a font that cannot load. Text in a missing font can still take a loaded font for all of its characters.
diff --git a/changes/1575/fixed.md b/changes/1575/fixed.md
new file mode 100644
index 000000000..06dc5df4a
--- /dev/null
+++ b/changes/1575/fixed.md
@@ -0,0 +1 @@
+- Text changed by AI agents, MCP tools, or scripts to a font that had not loaded yet takes its real size, including text outside auto layout, so exported images match the sizes the agent reads back.
diff --git a/packages/cli/src/tool-data.ts b/packages/cli/src/tool-data.ts
index 7797e541c..9339d044c 100644
--- a/packages/cli/src/tool-data.ts
+++ b/packages/cli/src/tool-data.ts
@@ -45,5 +45,6 @@ export async function runToolData(
populateWholeDocument(graph)
await measureDocumentText(graph)
const figma = await createHeadlessFigma(graph)
+ await tool.loadFonts(figma, args)
return { result: await editDocument(graph, () => tool.execute(figma, args)), graph }
}
diff --git a/packages/core/src/editor/text/pending-layout.ts b/packages/core/src/editor/text/pending-layout.ts
index 45b587e4e..bf7971c6d 100644
--- a/packages/core/src/editor/text/pending-layout.ts
+++ b/packages/core/src/editor/text/pending-layout.ts
@@ -2,6 +2,7 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { isNodeFontLoaded } from '#core/canvas/text'
+import { sizeAutoResizingText } from '#core/layout/text-auto-resize'
export type PendingLayoutRenderer = Pick<SkiaRenderer, 'measureTextNode' | 'fontsLoaded'> &
Parameters<typeof isNodeFontLoaded>[0]
@@ -19,10 +20,10 @@ function facesLoaded(renderer: PendingLayoutRenderer, node: SceneNode): boolean
}
/**
- * Text measured before its face loaded is laid out with an estimate. Remember those layers and
- * lay them out again once their faces settle, so auto-sized text and the Hug frames around it
- * take their real size without adding an undo step. Layout of the document's own state stays
- * derived.
+ * Text measured before its face loaded is laid out with an estimate. Remember those layers and,
+ * once their faces settle, measure them again and lay out the frames around them, so auto-sized
+ * text takes its real size wherever it sits, without adding an undo step. Layout of the
+ * document's own state stays derived.
*/
export function createPendingTextLayout(ctx: PendingTextLayoutContext) {
/** Layer id → whether it was measured while laying out the document's own state. */
@@ -50,11 +51,14 @@ export function createPendingTextLayout(ctx: PendingTextLayoutContext) {
if (node) (isDerived ? derived : edited).push(id)
}
if (edited.length === 0 && derived.length === 0) return
- if (derived.length > 0)
- graph.applyDerivedLayoutDuring(() => {
- for (const id of derived) ctx.runLayoutForNode(id)
- })
- for (const id of edited) ctx.runLayoutForNode(id)
+ // Layout measures text only in auto layout; text that sizes itself is measured here,
+ // unless it keeps the glyphs its file saved, whose size is the file's.
+ const relayout = (id: string) => {
+ if (!graph.getNode(id)?.derivedTextGlyphs?.length) sizeAutoResizingText(graph, id)
+ ctx.runLayoutForNode(id)
+ }
+ if (derived.length > 0) graph.applyDerivedLayoutDuring(() => derived.forEach(relayout))
+ edited.forEach(relayout)
ctx.requestRender()
}
diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.ts
index c6d798d63..1e2635db0 100644
--- a/packages/core/src/figma-api/accessors/text/index.ts
+++ b/packages/core/src/figma-api/accessors/text/index.ts
@@ -23,8 +23,10 @@ import {
type FigmaLetterSpacing,
type FigmaLineHeight
} from '#core/figma-api/text'
+import { assertFontLoaded, assertTextFontsLoaded } from '#core/figma-api/text/loaded-fonts'
import { getTextStyle, type TextSegmentField } from '#core/figma-api/text/style'
import { styleRunsWithPatch, textStyleChanges } from '#core/text/character-style'
+import { textFontFace } from '#core/text/requirements'
import { hyperlinkTarget } from './hyperlink'
import { fontNameStyle } from './ranges'
@@ -43,6 +45,7 @@ function spacing(internals: NodeProxyInternals, name: TextParagraphSpacingField,
if (invalid) {
throw new Error(`in set_${name}: Property "${name}" failed validation: ${invalid}`)
}
+ assertTextFontsLoaded(`set_${name}`, raw(this, internals))
updateNode(this, internals, { [name]: value })
}
}
@@ -50,13 +53,15 @@ function spacing(internals: NodeProxyInternals, name: TextParagraphSpacingField,
/**
* Getter/setter pair for a style characters can override: it reads `mixed` while they differ,
- * and setting it gives every character the value, as Figma's node setters do.
+ * and setting it gives every character the value, as Figma's node setters do. Setting one that
+ * lays the text out again needs the text's fonts loaded, as in Figma.
*/
function characterStyle<T>(
internals: NodeProxyInternals,
field: TextSegmentField,
mixed: symbol,
- changes: (node: SceneNode, value: T) => Partial<SceneNode>
+ changes: (node: SceneNode, value: T) => Partial<SceneNode>,
+ needsFonts = true
) {
return {
get(this: ProxyThis): unknown {
@@ -64,18 +69,28 @@ function characterStyle<T>(
},
set(this: ProxyThis, value: T) {
const node = raw(this, internals)
- updateNode(this, internals, textStyleChanges(node, changes(node, value)))
+ const patch = changes(node, value)
+ if (needsFonts) assertTextFontsLoaded(`set_${field}`, node)
+ updateNode(this, internals, textStyleChanges(node, patch))
}
}
}
-/** Getter/setter pair for a text property stored verbatim on the node. */
-function field<Field extends keyof SceneNode>(internals: NodeProxyInternals, name: Field) {
+/**
+ * Getter/setter pair for a text property stored verbatim on the node; one that lays the text out
+ * again needs its fonts loaded, as in Figma.
+ */
+function field<Field extends keyof SceneNode>(
+ internals: NodeProxyInternals,
+ name: Field,
+ needsFonts = true
+) {
return {
get(this: ProxyThis): SceneNode[Field] {
return raw(this, internals)[name]
},
set(this: ProxyThis, value: SceneNode[Field]) {
+ if (needsFonts) assertTextFontsLoaded(`set_${name}`, raw(this, internals))
updateNode(this, internals, { [name]: value } as Partial<SceneNode>)
}
}
@@ -92,23 +107,39 @@ export function installTextNodeProxyAccessors(
return raw(this, internals).text
},
set(this: ProxyThis, value: string) {
+ assertTextFontsLoaded('set_characters', raw(this, internals))
const textParagraphs = paragraphStylesForCharacters(raw(this, internals), value)
const styleRuns = styleRunsForCharacters(raw(this, internals), value)
updateNode(this, internals, { text: value, textParagraphs, styleRuns })
}
},
- fontName: characterStyle<FigmaFontNameInput>(internals, 'fontName', mixed, (node, value) =>
- fontNameStyle('set_fontName', node, 0, value)
+ // The new font replaces every character's, so only it has to be loaded, as in Figma.
+ fontName: characterStyle<FigmaFontNameInput>(
+ internals,
+ 'fontName',
+ mixed,
+ (node, value) => {
+ const style = fontNameStyle('set_fontName', node, 0, value)
+ assertFontLoaded('set_fontName', textFontFace(node, style))
+ return style
+ },
+ false
),
fontSize: characterStyle<number>(internals, 'fontSize', mixed, (_node, fontSize) => ({
fontSize
})),
- textStyleId: characterStyle<string>(internals, 'textStyleId', mixed, (_node, value) => ({
- textStyleId: value || null
- })),
- fontWeight: characterStyle<number>(internals, 'fontWeight', mixed, (_node, fontWeight) => ({
- fontWeight
- })),
+ textStyleId: characterStyle<string>(
+ internals,
+ 'textStyleId',
+ mixed,
+ (_node, value) => ({ textStyleId: value || null }),
+ false
+ ),
+ // A weight is a face of its own, which has to be loaded as a new font does.
+ fontWeight: characterStyle<number>(internals, 'fontWeight', mixed, (node, fontWeight) => {
+ assertFontLoaded('set_fontWeight', textFontFace(node, { fontWeight }))
+ return { fontWeight }
+ }),
textAlignHorizontal: field(internals, 'textAlignHorizontal'),
textAlignVertical: field(internals, 'textAlignVertical'),
textAutoResize: field(internals, 'textAutoResize'),
@@ -152,6 +183,6 @@ export function installTextNodeProxyAccessors(
paragraphIndent: spacing(internals, 'paragraphIndent', mixed),
hangingList: field(internals, 'hangingList'),
textTruncation: field(internals, 'textTruncation'),
- autoRename: field(internals, 'autoRename')
+ autoRename: field(internals, 'autoRename', false)
})
}
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index 9859ddb48..78b31a370 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -41,6 +41,7 @@ import {
setRangeParagraphSpacing,
type FigmaLetterSpacing
} from '#core/figma-api/text'
+import { assertFontLoaded, assertTextFontsLoaded } from '#core/figma-api/text/loaded-fonts'
import {
assertTextRange,
getRangeTextStyle,
@@ -58,6 +59,7 @@ import {
styleRunsWithPatch,
type TextStylePatch
} from '#core/text/character-style'
+import { textFontFace } from '#core/text/requirements'
import { hyperlinkTarget } from './hyperlink'
import { invalid, received } from './messages'
@@ -345,7 +347,11 @@ const RANGE_SETTERS: Record<string, RangeSetter> = {
if ((value as number) < 1) throw invalid(method, 'Number must be greater than or equal to 1')
return { fontSize: value as number }
},
- setRangeFontName: (method, node, start, _end, value) => fontNameStyle(method, node, start, value),
+ setRangeFontName: (method, node, start, _end, value) => {
+ const style = fontNameStyle(method, node, start, value)
+ assertFontLoaded(method, textFontFace(node, style))
+ return style
+ },
setRangeFills: (method, _node, _start, _end, value) => ({
fills: fillsFromPaints(method, value)
}),
@@ -395,6 +401,13 @@ const RANGE_SETTERS: Record<string, RangeSetter> = {
})
}
+/** Range setters Figma takes with the text's fonts unloaded: paints and links, measured live. */
+const RANGE_SETTERS_WITHOUT_FONTS = new Set([
+ 'setRangeFills',
+ 'setRangeHyperlink',
+ 'setRangeTextDecorationColor'
+])
+
/** Range getters by method and the segment field each reads. */
const RANGE_GETTERS: Record<string, TextSegmentField> = {
getRangeFontSize: 'fontSize',
@@ -510,6 +523,7 @@ export function installTextRangeMethods(
const node = raw(this, internals)
assertTextRange(method, node, start, end)
const patch = setter(method, node, start, end, value, graph(this, internals))
+ if (!RANGE_SETTERS_WITHOUT_FONTS.has(method)) assertTextFontsLoaded(method, node)
updateNode(this, internals, { styleRuns: styleRunsWithPatch(node, start, end, patch) })
}
}
diff --git a/packages/core/src/figma-api/fonts.ts b/packages/core/src/figma-api/fonts.ts
index 797a43467..6afc01479 100644
--- a/packages/core/src/figma-api/fonts.ts
+++ b/packages/core/src/figma-api/fonts.ts
@@ -1,6 +1,12 @@
+import { uniq, uniqBy } from 'es-toolkit/array'
+
import type { FontVariation } from '@open-pencil/scene-graph'
import type { FontFamilyStyle } from '@open-pencil/scene-graph/font-style'
-import { FONT_WEIGHT_NAMES, parseFontStyle } from '@open-pencil/scene-graph/font-style'
+import {
+ FONT_WEIGHT_NAMES,
+ parseFontStyle,
+ weightToStyle
+} from '@open-pencil/scene-graph/font-style'
import {
namedInstanceVariations,
@@ -18,6 +24,53 @@ export function weightToStyleName(weight: number, italic: boolean): string {
return italic ? `${base} Italic` : base
}
+/**
+ * The style name text asks the font manager for, whichever way a script spells it ("Italic",
+ * "Semi Bold"), so a font a script loaded is the one its text edits find loaded.
+ */
+function textFaceStyle(style: string): string {
+ const { weight, italic } = parseFontStyle(style)
+ return weightToStyle(weight, italic)
+}
+
+/** Figma's rejection for a font it cannot load. */
+function fontLoadError(family: string, style: string): Error {
+ return new Error(`The font "${family} ${style}" could not be loaded`)
+}
+
+/**
+ * Loads a font as Figma's `loadFontAsync` does, so text measures and draws with it from then on,
+ * and rejects when it cannot load. A family named alone loads every style it has: one style of
+ * each slant first, so the rest reuse its file where one variable file draws the whole slant, and
+ * then the named styles a variable file draws, which text set by its axes alone takes.
+ */
+export async function loadFigmaFont({ family, style }: FigmaFontNameInput): Promise<void> {
+ if (style !== undefined) {
+ const face = textFaceStyle(style)
+ await fontManager.loadFont(family, face).catch(() => null)
+ if (!fontManager.isStyleLoaded(family, face)) throw fontLoadError(family, style)
+ return
+ }
+ const faces = (await fontManager.familyFaces(family).catch(() => null)) ?? [
+ { weight: 400, italic: false }
+ ]
+ const load = (face: string) => fontManager.loadFont(family, face).catch(() => null)
+ const first = uniqBy(faces, (face) => face.italic)
+ await Promise.all(first.map((face) => load(weightToStyle(face.weight, face.italic))))
+ await Promise.all(
+ faces
+ .filter((face) => !first.includes(face))
+ .map((face) => load(weightToStyle(face.weight, face.italic)))
+ )
+ if (!fontManager.isLoaded(family)) throw fontLoadError(family, 'Regular')
+ const named = [false, true].flatMap((italic) =>
+ (fontManager.familyVariation(family, italic)?.instances ?? []).map((instance) =>
+ weightToStyle(parseFontStyle(instance.name).weight, italic)
+ )
+ )
+ await Promise.all(uniq(named).map(load))
+}
+
/** Variable font axis values by axis tag, as `FontName.variationSettings` holds them. */
export type FigmaVariationSettings = Record<string, number>
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 1b939f3d2..d23a6674d 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -1,4 +1,3 @@
-import { uniqBy } from 'es-toolkit/array'
import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
import type { SceneGraph, SceneNode as CoreSceneNode, NodeType } from '@open-pencil/scene-graph'
@@ -23,7 +22,7 @@ import { fontManager } from '#core/text/fonts'
import { componentFromNode } from './components'
import { flattenSceneNodes } from './flatten'
-import { variationAxisTags, weightToStyleName, type FigmaFontNameInput } from './fonts'
+import { loadFigmaFont, variationAxisTags, type FigmaFontNameInput } from './fonts'
import * as images from './images'
import type {
FigmaBooleanOperationNode,
@@ -532,25 +531,9 @@ export class FigmaAPI implements NodeProxyHost {
// --- Stubs ---
- /**
- * Loads the font so text measures and draws with it from then on. Hosts with their own font
- * sources replace this; a font that cannot load is skipped, where Figma would reject.
- */
+ /** Loads the font so text measures and draws with it from then on; rejects as Figma does. */
async loadFontAsync(fontName: FigmaFontNameInput): Promise<void> {
- if (fontName.style !== undefined) {
- await fontManager.loadFont(fontName.family, fontName.style).catch(() => null)
- return
- }
- // A family named alone loads every style it has. One style of each slant loads first, so the
- // rest reuse its file where one variable file draws the whole slant.
- const faces = (await fontManager.familyFaces(fontName.family).catch(() => null)) ?? [
- { weight: 400, italic: false }
- ]
- const load = ({ weight, italic }: { weight: number; italic: boolean }) =>
- fontManager.loadFont(fontName.family, weightToStyleName(weight, italic)).catch(() => null)
- const first = uniqBy(faces, (face) => face.italic)
- await Promise.all(first.map(load))
- await Promise.all(faces.filter((face) => !first.includes(face)).map(load))
+ await loadFigmaFont(fontName)
}
/**
diff --git a/packages/core/src/figma-api/text/index.ts b/packages/core/src/figma-api/text/index.ts
index fc0ae5579..ce8496fe3 100644
--- a/packages/core/src/figma-api/text/index.ts
+++ b/packages/core/src/figma-api/text/index.ts
@@ -28,6 +28,7 @@ import {
import { invalid, received } from '#core/figma-api/accessors/text/messages'
import { adjustRunsForDelete, getStyleAt, insertRunsWithStyle } from '#core/text/style-runs'
+import { assertTextFontsLoaded } from './loaded-fonts'
import { assertTextRange } from './style'
/** Figma's plugin API line height: automatic, or a size in pixels or percent of the font size. */
@@ -134,6 +135,7 @@ export function insertCharacters(
)
}
assertEditPosition('insertCharacters', node, 'start', start)
+ assertTextFontsLoaded('insertCharacters', node)
const text = node.text.slice(0, start) + characters + node.text.slice(start)
const textParagraphs = paragraphStylesAfterEdit(
node.textParagraphs,
@@ -183,6 +185,7 @@ export function deleteCharacters(
if (end < start) {
throw new Error('in deleteCharacters: deleteCharacters must have (start <= end)')
}
+ assertTextFontsLoaded('deleteCharacters', node)
const text = node.text.slice(0, start) + node.text.slice(end)
const textParagraphs = paragraphStylesAfterEdit(node.textParagraphs, node.text, start, end, '')
const styleRuns = adjustRunsForDelete(node.styleRuns, start, end - start)
@@ -240,6 +243,7 @@ export function setRangeListOptions(
)
}
assertTextRange('setRangeListOptions', node, start, end)
+ assertTextFontsLoaded('setRangeListOptions', node)
updateParagraphs(graph, node, start, end, (style) => withListType(style, options.type))
}
@@ -276,6 +280,7 @@ export function setRangeIndentation(
throw new Error(`in setRangeIndentation: Property "indentation" failed validation: ${invalid}`)
}
assertTextRange('setRangeIndentation', node, start, end)
+ assertTextFontsLoaded('setRangeIndentation', node)
updateParagraphs(graph, node, start, end, (style) => withIndentation(style, level))
}
@@ -315,6 +320,7 @@ export function setRangeParagraphSpacing(
const invalid = spacingProblem(value)
if (invalid) throw new Error(`in ${method}: Property "value" failed validation: ${invalid}`)
assertTextRange(method, node, start, end)
+ assertTextFontsLoaded(method, node)
// Ranges change the paragraphs of their characters; one more reaches the end position's.
updateParagraphs(graph, node, start, end + 1, (style) =>
withParagraphSpacing(style, field, value)
diff --git a/packages/core/src/figma-api/text/loaded-fonts.ts b/packages/core/src/figma-api/text/loaded-fonts.ts
new file mode 100644
index 000000000..6f12f6eec
--- /dev/null
+++ b/packages/core/src/figma-api/text/loaded-fonts.ts
@@ -0,0 +1,54 @@
+import { uniqBy } from 'es-toolkit/array'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import { weightToStyleName } from '#core/figma-api/fonts'
+import type { FontFaceRef } from '#core/text/face'
+import { fontManager } from '#core/text/fonts'
+import { textFontFace } from '#core/text/requirements'
+
+/**
+ * A face as Figma names it in its messages, as `fontName` reads it: "Semi Bold", not "SemiBold",
+ * and a weight between named ones by the nearest, as the font manager loads it.
+ */
+function described(face: FontFaceRef): { family: string; style: string } {
+ const weight = Math.round(face.weight / 100) * 100
+ return { family: face.family, style: weightToStyleName(weight, face.italic) }
+}
+
+function loadHint({ family, style }: { family: string; style: string }): string {
+ return `Please call figma.loadFontAsync({ family: "${family}", style: "${style}" }) and await the returned promise first.`
+}
+
+function isLoaded(face: FontFaceRef): boolean {
+ return fontManager.isStyleLoaded(face.family, face.style)
+}
+
+/** Every face the text draws in: its own and each style run's. */
+function textFaces(node: SceneNode): FontFaceRef[] {
+ const faces = [textFontFace(node), ...node.styleRuns.map((run) => textFontFace(node, run.style))]
+ return uniqBy(faces, (face) => `${face.family}\0${face.style}`)
+}
+
+/**
+ * Figma refuses an edit that lays text out again until every font the text uses is loaded, so
+ * the text is never measured in a stand-in font. Paints and links need no font. Callers check
+ * the edit's own arguments first, as Figma does.
+ */
+export function assertTextFontsLoaded(method: string, node: SceneNode): void {
+ const unloaded = textFaces(node).find((face) => !isLoaded(face))
+ if (!unloaded) return
+ const font = described(unloaded)
+ throw new Error(
+ `in ${method}: Cannot write to node with unloaded font "${font.family} ${font.style}". ${loadHint(font)}`
+ )
+}
+
+/** Figma refuses a font that is not loaded yet, before it checks the text's own. */
+export function assertFontLoaded(method: string, face: FontFaceRef): void {
+ if (isLoaded(face)) return
+ const font = described(face)
+ throw new Error(
+ `in ${method}: Cannot use unloaded font "${font.family} ${font.style}". ${loadHint(font)}`
+ )
+}
diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.ts
index 8e50dde24..16f58f317 100644
--- a/packages/core/src/tools/ai-adapter.ts
+++ b/packages/core/src/tools/ai-adapter.ts
@@ -190,7 +190,7 @@ export function toolsToAI(
try {
let execResult = options.executeTool
? await options.executeTool(def, figma, args, { toolCallId })
- : await def.execute(figma, args)
+ : await def.loadFonts(figma, args).then(() => def.execute(figma, args))
if (def.mutates && options.onFlashNodes) {
const ids = extractNodeIds(execResult)
if (ids.length > 0) options.onFlashNodes(ids)
diff --git a/packages/core/src/tools/analyze/eval/index.ts b/packages/core/src/tools/analyze/eval/index.ts
index fd7ec841a..52ee2beb8 100644
--- a/packages/core/src/tools/analyze/eval/index.ts
+++ b/packages/core/src/tools/analyze/eval/index.ts
@@ -7,7 +7,7 @@ import { compileScript } from './wrap'
export const evalCode = defineTool({
name: 'eval',
description:
- 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is the Figma Plugin API; the `openpencil` global adds what Figma has no API for, such as component behaviours (`openpencil.setBehaviour`, `openpencil.getBehaviour`, `openpencil.behaviourKinds`), slots (`openpencil.createSlot`), comments (`openpencil.getComments`, `openpencil.getComment`, `openpencil.addComment`, and each comment’s `reply` and `resolve`), statuses (`openpencil.statuses`, `openpencil.getStatus`, `openpencil.setStatus`), variable bindings as the layer panel makes them (`openpencil.bindVariable(node, field, variable)`, `openpencil.unbindVariable(node, field)`), layout and text direction (`openpencil.getLayoutDirection`, `setLayoutDirection`, `getTextDirection`, `setTextDirection`), OkHCL paint colors (`openpencil.getFillOkHCL`, `setFillOkHCL`, `getStrokeOkHCL`, `setStrokeOkHCL`), `openpencil.exposeInstanceSwap(instances, candidates, name)`, and `openpencil.getFontStatus()`.',
+ 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is the Figma Plugin API; as in Figma, `await figma.loadFontAsync(fontName)` every font a text uses, and any new font, before editing its characters, size, font, or layout; the `openpencil` global adds what Figma has no API for, such as component behaviours (`openpencil.setBehaviour`, `openpencil.getBehaviour`, `openpencil.behaviourKinds`), slots (`openpencil.createSlot`), comments (`openpencil.getComments`, `openpencil.getComment`, `openpencil.addComment`, and each comment’s `reply` and `resolve`), statuses (`openpencil.statuses`, `openpencil.getStatus`, `openpencil.setStatus`), variable bindings as the layer panel makes them (`openpencil.bindVariable(node, field, variable)`, `openpencil.unbindVariable(node, field)`), layout and text direction (`openpencil.getLayoutDirection`, `setLayoutDirection`, `getTextDirection`, `setTextDirection`), OkHCL paint colors (`openpencil.getFillOkHCL`, `setFillOkHCL`, `getStrokeOkHCL`, `setStrokeOkHCL`), `openpencil.exposeInstanceSwap(instances, candidates, name)`, and `openpencil.getFontStatus()`.',
execution: { kind: 'async', mutation: 'document' },
capabilities: ['document:read', 'document:write', 'code:execute'],
availability: 'eval',
diff --git a/packages/core/src/tools/create/connector.ts b/packages/core/src/tools/create/connector.ts
index 3ab0f2d62..1ff3f39a6 100644
--- a/packages/core/src/tools/create/connector.ts
+++ b/packages/core/src/tools/create/connector.ts
@@ -1,5 +1,8 @@
import * as v from 'valibot'
+import { CONNECTOR_LABEL_FONT } from '@open-pencil/scene-graph/connectors'
+import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+
import { toolNumber, defineTool, nodeSummary } from '#core/tools/schema'
const MAGNETS = ['AUTO', 'TOP', 'RIGHT', 'BOTTOM', 'LEFT', 'CENTER'] as const
@@ -47,6 +50,15 @@ export const createConnectorTool = defineTool({
label: v.optional(v.pipe(v.string(), v.description('Text on the line'))),
name: v.optional(v.pipe(v.string(), v.description('Layer name')))
}),
+ fonts: (_figma, args) =>
+ args.label
+ ? [
+ {
+ family: CONNECTOR_LABEL_FONT.family,
+ style: weightToStyle(CONNECTOR_LABEL_FONT.weight)
+ }
+ ]
+ : [],
execute: (figma, args) => {
const connector = figma.createConnector()
const straight = args.line_type === 'STRAIGHT'
diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.ts
index 24363971d..586188e21 100644
--- a/packages/core/src/tools/index.ts
+++ b/packages/core/src/tools/index.ts
@@ -14,7 +14,8 @@ export {
nodeSummary,
requireNode,
NodeNotFoundError,
- toolChangesDocument
+ toolChangesDocument,
+ toolFailure
} from './schema'
export type { ToolDef, ToolExecution, ToolCapability } from './schema'
export {
diff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.ts
index 02b39c094..b2be027cd 100644
--- a/packages/core/src/tools/modify/text.ts
+++ b/packages/core/src/tools/modify/text.ts
@@ -2,12 +2,14 @@ import * as v from 'valibot'
import { parseColor } from '@open-pencil/scene-graph/color'
+import type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'
import type {
FigmaFontName,
FigmaFontNameInput,
FigmaVariationSettings
} from '#core/figma-api/fonts'
import { OpenPencilAPI } from '#core/openpencil-api'
+import { collectNodeFontFaces } from '#core/text/requirements'
import {
toolNumber,
nodeIdInputSchema,
@@ -16,6 +18,12 @@ import {
toolFailure
} from '#core/tools/schema'
+/** The fonts a text layer uses, which an edit that lays it out again needs loaded. */
+export function textFonts(figma: FigmaAPI, id: string): FigmaFontNameInput[] {
+ const node = figma.graph.getNode(id)
+ return node ? collectNodeFontFaces(node) : []
+}
+
export const setText = defineTool({
name: 'set_text',
@@ -25,6 +33,7 @@ export const setText = defineTool({
id: nodeIdInputSchema,
text: v.pipe(v.string(), v.description('Text content'))
}),
+ fonts: (figma, { id }) => textFonts(figma, id),
execute: (figma, { id, text }) => {
const node = figma.getNodeById(id)
if (!node) return { error: `Node "${id}" not found` }
@@ -58,6 +67,29 @@ function fontNameInput(
}
}
+/**
+ * The font `set_font` gives the text, or null when it keeps the text's. Text set in several fonts
+ * takes the given family or style for all of it, keeping the rest from its first character. Axes
+ * without a style are set per range, each range taking its nearest named style, as in Figma.
+ */
+function requestedFont(
+ node: FigmaNodeProxy,
+ args: { family?: string; style?: string; variations?: FigmaVariationSettings }
+): { whole: FigmaFontName } | { perRange: FigmaFontNameInput } | null {
+ if (!args.family && !args.style && !args.variations) return null
+ const fontName =
+ typeof node.fontName === 'symbol' && node.characters.length > 0
+ ? node.getRangeFontName(0, 1)
+ : node.fontName
+ const current = typeof fontName === 'symbol' ? null : fontName
+ const family = args.family ?? current?.family ?? ''
+ if (args.variations && !args.style && node.characters.length > 0) {
+ return { perRange: { family, variationSettings: args.variations } }
+ }
+ const style = args.style ?? current?.style ?? 'Regular'
+ return { whole: { family, style, variationSettings: args.variations } }
+}
+
export const setFont = defineTool({
name: 'set_font',
@@ -72,41 +104,40 @@ export const setFont = defineTool({
),
variations: variationsInputSchema
}),
+ // A new font replaces the text's, which then need not be loaded, so a missing font can be
+ // replaced; a size or per-range axes lay out the text in its own fonts.
+ fonts: (figma, args) => {
+ const node = figma.getNodeById(args.id)
+ const font = node && requestedFont(node, args)
+ if (font && 'whole' in font) return [font.whole]
+ return [...(font ? [font.perRange] : []), ...textFonts(figma, args.id)]
+ },
execute: (figma, args) => {
const node = figma.getNodeById(args.id)
if (!node) return nodeNotFound(args.id)
- if (args.size !== undefined) node.fontSize = args.size
- if (args.family || args.style || args.variations) {
- // Text set in several fonts takes the given family or style for all of it, keeping the
- // rest from its first character.
- const fontName =
- typeof node.fontName === 'symbol' && node.characters.length > 0
- ? node.getRangeFontName(0, 1)
- : node.fontName
- const current = typeof fontName === 'symbol' ? null : fontName
- const family = args.family ?? current?.family ?? ''
- try {
- // Axes without a style pick the nearest named style, which a range takes, as in Figma.
- if (args.variations && !args.style && node.characters.length > 0) {
- node.setRangeFontName(0, node.characters.length, {
- family,
- variationSettings: args.variations
- })
- } else {
- node.fontName = {
- family,
- style: args.style ?? current?.style ?? 'Regular',
- variationSettings: args.variations
- }
- }
- } catch (error) {
- return toolFailure(error)
- }
+ const font = requestedFont(node, args)
+ try {
+ if (font && 'whole' in font) node.fontName = font.whole
+ else if (font) node.setRangeFontName(0, node.characters.length, font.perRange)
+ // The size comes after the font, so it lays the text out in the font it ends up in.
+ if (args.size !== undefined) node.fontSize = args.size
+ } catch (error) {
+ return toolFailure(error)
}
return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }
}
})
+/** The font `set_font_range` gives its range: what it names, the rest from the range's start. */
+function rangeFont(
+ node: FigmaNodeProxy,
+ args: { start: number; family?: string; style?: string; variations?: FigmaVariationSettings }
+): FigmaFontNameInput {
+ const inText = args.start < node.characters.length
+ const current = inText ? node.getRangeFontName(args.start, args.start + 1) : node.fontName
+ return fontNameInput(args, typeof current === 'symbol' ? null : current)
+}
+
export const setFontRange = defineTool({
name: 'set_font_range',
@@ -122,6 +153,14 @@ export const setFontRange = defineTool({
variations: variationsInputSchema,
color: v.optional(v.pipe(v.string(), v.description('Text color (hex)')))
}),
+ fonts: (figma, args) => {
+ const node = figma.getNodeById(args.id)
+ if (!node) return []
+ const font = args.family || args.style || args.variations ? rangeFont(node, args) : null
+ // A colour alone is a paint and lays nothing out, so text in a missing font can still take it.
+ const laysOut = font !== null || args.size !== undefined
+ return [...(font ? [font] : []), ...(laysOut ? textFonts(figma, args.id) : [])]
+ },
execute: (figma, args) => {
const node = figma.getNodeById(args.id)
if (!node) return nodeNotFound(args.id)
@@ -135,12 +174,7 @@ export const setFontRange = defineTool({
try {
if (args.size) node.setRangeFontSize(start, end, args.size)
if (args.family || args.style || args.variations) {
- const current = node.getRangeFontName(start, start + 1)
- node.setRangeFontName(
- start,
- end,
- fontNameInput(args, typeof current === 'symbol' ? null : current)
- )
+ node.setRangeFontName(start, end, rangeFont(node, args))
}
if (args.color) {
node.setRangeFills(start, end, [{ type: 'SOLID', color: parseColor(args.color) }])
@@ -164,6 +198,7 @@ export const setTextResize = defineTool({
v.description('Resize mode')
)
}),
+ fonts: (figma, { id }) => textFonts(figma, id),
execute: (figma, { id, mode }) => {
const node = figma.getNodeById(id)
if (!node) return { error: `Node "${id}" not found` }
@@ -202,6 +237,7 @@ export const setTextProperties = defineTool({
v.pipe(v.picklist(['NONE', 'UNDERLINE', 'STRIKETHROUGH']), v.description('Text decoration'))
)
}),
+ fonts: (figma, { id }) => textFonts(figma, id),
execute: (figma, args) => {
const node = figma.getNodeById(args.id)
if (!node) return nodeNotFound(args.id)
diff --git a/packages/core/src/tools/schema.ts b/packages/core/src/tools/schema.ts
index 86ff92197..445c611e0 100644
--- a/packages/core/src/tools/schema.ts
+++ b/packages/core/src/tools/schema.ts
@@ -10,6 +10,7 @@ import * as v from 'valibot'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'
+import type { FigmaFontNameInput } from '#core/figma-api/fonts'
export type ToolCapability =
| 'document:read'
@@ -42,6 +43,12 @@ export interface ToolDef extends ToolMetadata {
input: v.StrictObjectSchema<v.ObjectEntries, undefined>
/** Derived from execution metadata, never declared independently by a tool. */
readonly mutates: boolean
+ /**
+ * Loads the fonts the call's text edits need, as a Figma plugin loads them before it edits
+ * text; rejects when one cannot load. Every executor awaits it before `execute`, so a
+ * synchronous tool still edits in one step.
+ */
+ loadFonts: (figma: FigmaAPI, args: Record<string, unknown>) => Promise<void>
execute: (figma: FigmaAPI, args: Record<string, unknown>) => unknown
}
@@ -52,9 +59,15 @@ export function defineTool<P extends v.ObjectEntries, R>(
def: ToolDefinitionMetadata & {
input: v.StrictObjectSchema<P, undefined>
execution: ToolExecution & (R extends PromiseLike<unknown> ? { kind: 'async' } : unknown)
+ /** The fonts a call's text edits need loaded first; text edits refuse unloaded fonts. */
+ fonts?: (
+ figma: FigmaAPI,
+ args: v.InferOutput<v.StrictObjectSchema<P, undefined>>
+ ) => FigmaFontNameInput[]
execute: (figma: FigmaAPI, args: v.InferOutput<v.StrictObjectSchema<P, undefined>>) => R
}
): ToolDef {
+ const { fonts } = def
return {
...def,
exposure: def.exposure ?? {},
@@ -65,6 +78,13 @@ export function defineTool<P extends v.ObjectEntries, R>(
get mutates() {
return def.execution.mutation !== 'none'
},
+ async loadFonts(figma, args) {
+ if (!fonts) return
+ // Wrong arguments are for `execute` to report.
+ const parsed = v.safeParse(def.input, args)
+ if (!parsed.success) return
+ for (const font of fonts(figma, parsed.output)) await figma.loadFontAsync(font)
+ },
execute: (figma, args) => def.execute(figma, parseToolArgs(def.name, def.input, args))
}
}
diff --git a/packages/core/src/tools/structure/batch.ts b/packages/core/src/tools/structure/batch.ts
index 490feffcb..c3cebc656 100644
--- a/packages/core/src/tools/structure/batch.ts
+++ b/packages/core/src/tools/structure/batch.ts
@@ -1,12 +1,21 @@
-import { safeDestr } from 'destr'
import * as v from 'valibot'
import type { FigmaNodeProxy } from '#core/figma-api'
+import { textFonts } from '#core/tools/modify/text'
import { defineTool } from '#core/tools/schema'
-interface BatchOp {
- id: string
- props: Record<string, unknown>
+const batchOpsSchema = v.array(
+ v.object({ id: v.string(), props: v.record(v.string(), v.unknown()) })
+)
+type BatchOp = v.InferOutput<typeof batchOpsSchema>[number]
+
+/** The operations a call names, or why they cannot be read. */
+function parseOperations(operations: string): BatchOp[] | { error: string } {
+ const json = v.safeParse(v.pipe(v.string(), v.parseJson()), operations)
+ if (!json.success) return { error: 'Invalid JSON in operations' }
+ const ops = v.safeParse(batchOpsSchema, json.output)
+ if (!ops.success) return { error: 'operations must be a JSON array of {id, props}' }
+ return ops.output
}
function str(value: unknown): string {
@@ -104,14 +113,15 @@ export const batchUpdate = defineTool({
)
)
}),
+ // Text that resizes itself lays out again, so its fonts load first.
+ fonts: (figma, { operations }) => {
+ const ops = parseOperations(operations)
+ if (!Array.isArray(ops)) return []
+ return ops.flatMap((op) => (op.props.auto_resize === undefined ? [] : textFonts(figma, op.id)))
+ },
execute: (figma, { operations }) => {
- let ops: BatchOp[]
- try {
- ops = safeDestr<BatchOp[]>(String(operations))
- } catch {
- return { error: 'Invalid JSON in operations' }
- }
- if (!Array.isArray(ops)) return { error: 'operations must be a JSON array' }
+ const ops = parseOperations(operations)
+ if (!Array.isArray(ops)) return ops
const results: Array<{ id: string; updated: string[] }> = []
const errors: string[] = []
diff --git a/packages/core/tests/editor/text/pending-layout.test.ts b/packages/core/tests/editor/text/pending-layout.test.ts
index 244df6d01..17e27dd29 100644
--- a/packages/core/tests/editor/text/pending-layout.test.ts
+++ b/packages/core/tests/editor/text/pending-layout.test.ts
@@ -2,19 +2,24 @@ import { afterEach, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
import { setTextMeasurer } from '@open-pencil/core/layout'
+import type { SceneNode } from '@open-pencil/scene-graph'
import {
createPendingTextLayout,
type PendingLayoutRenderer
} from '#core/editor/text/pending-layout'
import { createLayoutRunner } from '#core/layout/mutations'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
afterEach(() => {
setTextMeasurer(null)
})
-/** A Hug row around auto-width text whose face loads after the first layout. */
-function setup() {
+/**
+ * A Hug row around auto-width text whose face loads after the first layout; `outside` puts the
+ * text on the page instead, where only its own measurement sizes it.
+ */
+function setup({ outside = false, text: values = {} }: { outside?: boolean; text?: Partial<SceneNode> } = {}) {
const editor = createEditor()
const graph = editor.graph
const frame = graph.createNode('FRAME', editor.state.currentPageId, {
@@ -26,10 +31,11 @@ function setup() {
paddingTop: 12,
paddingBottom: 12
})
- const text = graph.createNode('TEXT', frame.id, {
+ const text = graph.createNode('TEXT', outside ? editor.state.currentPageId : frame.id, {
text: 'Weighted label',
fontWeight: 900,
- textAutoResize: 'WIDTH_AND_HEIGHT'
+ textAutoResize: 'WIDTH_AND_HEIGHT',
+ ...values
})
let loaded = false
const renderer: PendingLayoutRenderer = {
@@ -99,3 +105,41 @@ test('layers whose faces are still loading or that were removed are left alone',
pending.relayoutReady(renderer)
expect(renders()).toBe(0)
})
+
+/** Edits the text as the editor and the plugin API do, measuring it as it changes. */
+function edit(graph: ReturnType<typeof setup>['graph'], text: SceneNode, changes: Partial<SceneNode>) {
+ graph.updateNode(text.id, { ...changes, ...textAutoResizeChanges(text, changes) })
+}
+
+test('text outside auto layout edited before its face loads takes its size when it loads', () => {
+ const { graph, text, load, editor } = setup({ outside: true })
+ edit(graph, text, { text: 'Heavier label' })
+ expect(text.width).not.toBe(234)
+
+ load()
+ expect([text.width, text.height]).toEqual([234, 29])
+ expect(editor.undo.canUndo).toBe(false)
+})
+
+test('wrapping text outside auto layout takes its height when its face loads', () => {
+ const { graph, text, load } = setup({ outside: true, text: { textAutoResize: 'HEIGHT', width: 200 } })
+ edit(graph, text, { text: 'Heavier label' })
+ load()
+ expect([text.width, text.height]).toEqual([200, 29])
+})
+
+test('text that keeps the glyphs its file saved keeps the size the file gave it', () => {
+ const { graph, text, runLayoutForNode, load } = setup({
+ outside: true,
+ text: {
+ width: 120,
+ height: 20,
+ derivedTextGlyphs: [{ commandsBlob: new Uint8Array(), x: 0, y: 16, fontSize: 16, firstCharacter: 0 }]
+ }
+ })
+ graph.applyDerivedLayoutDuring(() => runLayoutForNode(text.id))
+ // Measured while it loads, as layout measures text in a flow, without changing it.
+ graph.applyDerivedLayoutDuring(() => textAutoResizeChanges(text, { text: text.text }))
+ load()
+ expect([text.width, text.height]).toEqual([120, 20])
+})
diff --git a/packages/core/tests/figma-api/accessors/basic/rescale.test.ts b/packages/core/tests/figma-api/accessors/basic/rescale.test.ts
index 7f5470850..966fada75 100644
--- a/packages/core/tests/figma-api/accessors/basic/rescale.test.ts
+++ b/packages/core/tests/figma-api/accessors/basic/rescale.test.ts
@@ -1,11 +1,14 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { solidFill } from '#core-tests/helpers/figma-api'
+import { registerTestFont, solidFill } from '#core-tests/helpers/figma-api'
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
+
+beforeAll(() => registerTestFont())
+
function setup() {
const graph = new SceneGraph()
return { graph, api: new FigmaAPI(graph) }
diff --git a/packages/core/tests/figma-api/accessors/connector.test.ts b/packages/core/tests/figma-api/accessors/connector.test.ts
index 5991fa3d8..9509861a7 100644
--- a/packages/core/tests/figma-api/accessors/connector.test.ts
+++ b/packages/core/tests/figma-api/accessors/connector.test.ts
@@ -1,12 +1,18 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { getNodeOrThrow } from '#core-tests/helpers/assert'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
import { pick } from 'es-toolkit'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
import { connectorSublayers } from '@open-pencil/scene-graph/connectors'
+beforeAll(async () => {
+ await registerTestFont()
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Inter', style: 'Medium' })
+})
+
function setup() {
const graph = new SceneGraph()
const api = new FigmaAPI(graph)
diff --git a/packages/core/tests/figma-api/accessors/layout/sizing.test.ts b/packages/core/tests/figma-api/accessors/layout/sizing.test.ts
index 46b184b26..d67143bb9 100644
--- a/packages/core/tests/figma-api/accessors/layout/sizing.test.ts
+++ b/packages/core/tests/figma-api/accessors/layout/sizing.test.ts
@@ -1,7 +1,10 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { getNodeOrThrow } from '#core-tests/helpers/assert'
-import { asTextNode, createAPI } from '#core-tests/helpers/figma-api'
+import { asTextNode, createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
+
+
+beforeAll(() => registerTestFont())
// Expected values were observed by running the same scripts in live Figma on 2026-10-06.
diff --git a/packages/core/tests/figma-api/accessors/text/properties.test.ts b/packages/core/tests/figma-api/accessors/text/properties.test.ts
index f0f8f2e50..2d43aaa44 100644
--- a/packages/core/tests/figma-api/accessors/text/properties.test.ts
+++ b/packages/core/tests/figma-api/accessors/text/properties.test.ts
@@ -1,6 +1,11 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
-import { createAPI } from '#core-tests/helpers/figma-api'
+import { createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(async () => {
+ await registerTestFont('Inter')
+ await registerTestFont('Roboto')
+})
describe('text', () => {
test('characters maps to text content', () => {
@@ -17,17 +22,19 @@ describe('text', () => {
expect(text.fontSize).toBe(24)
})
- test('fontName get/set', () => {
+ test('fontName get/set', async () => {
const api = createAPI()
const text = api.createText()
+ await api.loadFontAsync({ family: 'Roboto', style: 'Bold' })
text.fontName = { family: 'Roboto', style: 'Bold' }
expect(text.fontName.family).toBe('Roboto')
expect(text.fontWeight).toBe(700)
})
- test('fontName italic', () => {
+ test('fontName italic', async () => {
const api = createAPI()
const text = api.createText()
+ await api.loadFontAsync({ family: 'Inter', style: 'Bold Italic' })
text.fontName = { family: 'Inter', style: 'Bold Italic' }
expect(text.fontName.family).toBe('Inter')
expect(text.fontWeight).toBe(700)
diff --git a/packages/core/tests/figma-api/components/instances.test.ts b/packages/core/tests/figma-api/components/instances.test.ts
index ee7ba5fb6..80d4036d8 100644
--- a/packages/core/tests/figma-api/components/instances.test.ts
+++ b/packages/core/tests/figma-api/components/instances.test.ts
@@ -1,10 +1,13 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { asTextNode, createAPI } from '#core-tests/helpers/figma-api'
+import { asTextNode, createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
import { hasInstanceOverride } from '@open-pencil/scene-graph/instances'
+
+beforeAll(() => registerTestFont())
+
describe('components', () => {
test('exposes component property accessors and applies instance properties', () => {
const api = createAPI()
diff --git a/packages/core/tests/figma-api/load-font.test.ts b/packages/core/tests/figma-api/load-font.test.ts
index 97fb366c5..c94b5ab7d 100644
--- a/packages/core/tests/figma-api/load-font.test.ts
+++ b/packages/core/tests/figma-api/load-font.test.ts
@@ -1,25 +1,33 @@
-import { expect, spyOn, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
+
+import { registerTestFont } from '#core-tests/helpers/figma-api'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { fontManager } from '@open-pencil/core/text'
import { SceneGraph } from '@open-pencil/scene-graph'
-test('figma.loadFontAsync loads the font, and goes on when it cannot', async () => {
- const load = spyOn(fontManager, 'loadFont').mockImplementation(async (family) => {
- if (family === 'Missing') throw new Error('not found')
- return null
- })
- try {
- const figma = new FigmaAPI(new SceneGraph())
+beforeAll(() => registerTestFont('Load Test'))
+
+test('figma.loadFontAsync loads a style however a script spells it', async () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ await figma.loadFontAsync({ family: 'Load Test', style: 'Semi Bold' })
+ await figma.loadFontAsync({ family: 'Load Test', style: 'Italic' })
+ expect(fontManager.isStyleLoaded('Load Test', 'SemiBold')).toBe(true)
+ expect(fontManager.isStyleLoaded('Load Test', 'Regular Italic')).toBe(true)
+})
- await figma.loadFontAsync({ family: 'Inter', style: 'Bold' })
- await figma.loadFontAsync({ family: 'Missing', style: 'Regular' })
+test('figma.loadFontAsync loads every named style of a family named alone', async () => {
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Load Test' })
+ expect(fontManager.isStyleLoaded('Load Test', 'Black')).toBe(true)
+ expect(fontManager.isStyleLoaded('Load Test', 'Thin Italic')).toBe(true)
+})
- expect(load.mock.calls.map(([family, style]) => [family, style])).toEqual([
- ['Inter', 'Bold'],
- ['Missing', 'Regular']
- ])
- } finally {
- load.mockRestore()
- }
+test('figma.loadFontAsync rejects a font that cannot load, as Figma does', async () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ await expect(figma.loadFontAsync({ family: 'Missing', style: 'Regular' })).rejects.toThrow(
+ 'The font "Missing Regular" could not be loaded'
+ )
+ await expect(figma.loadFontAsync({ family: 'Missing' })).rejects.toThrow(
+ 'The font "Missing Regular" could not be loaded'
+ )
})
diff --git a/packages/core/tests/figma-api/overrides/edits.test.ts b/packages/core/tests/figma-api/overrides/edits.test.ts
index 243ee361f..94b5e19d9 100644
--- a/packages/core/tests/figma-api/overrides/edits.test.ts
+++ b/packages/core/tests/figma-api/overrides/edits.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { createAPI, solidFill } from '#core-tests/helpers/figma-api'
+import { createAPI, registerTestFont, solidFill } from '#core-tests/helpers/figma-api'
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
@@ -9,6 +9,9 @@ import { createComponentPropertyId } from '@open-pencil/scene-graph/components'
import { hasInstanceOverride } from '@open-pencil/scene-graph/instances'
import { getInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'
+
+beforeAll(() => registerTestFont())
+
// Recorded with the same script in Figma desktop 126.
function setup() {
diff --git a/packages/core/tests/figma-api/overrides/instance.test.ts b/packages/core/tests/figma-api/overrides/instance.test.ts
index c404bf1db..88cfc9915 100644
--- a/packages/core/tests/figma-api/overrides/instance.test.ts
+++ b/packages/core/tests/figma-api/overrides/instance.test.ts
@@ -1,8 +1,12 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
// Each case repeats a script run in Figma desktop 126; the lists are what Figma returned.
const solid = (r: number, g: number, b: number) => ({
diff --git a/packages/core/tests/figma-api/shape-with-text.test.ts b/packages/core/tests/figma-api/shape-with-text.test.ts
index b8d0c8bfc..6d5254a6a 100644
--- a/packages/core/tests/figma-api/shape-with-text.test.ts
+++ b/packages/core/tests/figma-api/shape-with-text.test.ts
@@ -1,12 +1,19 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { pick } from 'es-toolkit'
import { SceneGraph } from '@open-pencil/scene-graph'
import { shapeWithTextFrameFields } from '@open-pencil/scene-graph/generated'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
import { FigmaAPI } from '#core/figma-api'
+beforeAll(async () => {
+ await registerTestFont()
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Inter', style: 'Medium' })
+})
+
const RED = [
{ type: 'SOLID' as const, color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }
]
diff --git a/packages/core/tests/figma-api/text/edit-keeps-colour.test.ts b/packages/core/tests/figma-api/text/edit-keeps-colour.test.ts
index bba06d642..0e8b633d4 100644
--- a/packages/core/tests/figma-api/text/edit-keeps-colour.test.ts
+++ b/packages/core/tests/figma-api/text/edit-keeps-colour.test.ts
@@ -1,6 +1,9 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
-import { createAPI } from '#core-tests/helpers/figma-api'
+import { createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
+
+
+beforeAll(() => registerTestFont())
const RED = [{ type: 'SOLID' as const, color: { r: 1, g: 0, b: 0 } }]
diff --git a/packages/core/tests/figma-api/text/lists.test.ts b/packages/core/tests/figma-api/text/lists.test.ts
index 47f1fd3c1..8e0205a35 100644
--- a/packages/core/tests/figma-api/text/lists.test.ts
+++ b/packages/core/tests/figma-api/text/lists.test.ts
@@ -1,8 +1,12 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
// Results recorded from the same scripts run in live Figma (2026-10-09).
function listText(characters: string) {
const api = new FigmaAPI(new SceneGraph())
diff --git a/packages/core/tests/figma-api/text/paragraph-spacing.test.ts b/packages/core/tests/figma-api/text/paragraph-spacing.test.ts
index 5c6160663..394c3cc62 100644
--- a/packages/core/tests/figma-api/text/paragraph-spacing.test.ts
+++ b/packages/core/tests/figma-api/text/paragraph-spacing.test.ts
@@ -1,8 +1,12 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
// Results recorded from the same scripts run in live Figma (2026-10-10).
function spacedText(characters = 'A\nB\nC') {
const api = new FigmaAPI(new SceneGraph())
diff --git a/packages/core/tests/figma-api/text/references.test.ts b/packages/core/tests/figma-api/text/references.test.ts
index ab7156f70..c17c8b7eb 100644
--- a/packages/core/tests/figma-api/text/references.test.ts
+++ b/packages/core/tests/figma-api/text/references.test.ts
@@ -1,9 +1,16 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(async () => {
+ await registerTestFont()
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Inter', style: 'Bold' })
+})
+
// Shapes and messages follow `@figma/plugin-typings` and the Plugin API documentation for the
// range methods; validation messages follow those Figma reports for the other range setters.
function styledText(characters = 'Hello world') {
diff --git a/packages/core/tests/figma-api/text/styles.test.ts b/packages/core/tests/figma-api/text/styles.test.ts
index 4bc573b51..ebe22e232 100644
--- a/packages/core/tests/figma-api/text/styles.test.ts
+++ b/packages/core/tests/figma-api/text/styles.test.ts
@@ -29,6 +29,7 @@ beforeAll(async () => {
'bundled Inter font'
)
await fontManager.markLoaded('Inter', 'Regular', inter)
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Inter', style: 'Bold' })
})
describe('styled text segments', () => {
diff --git a/packages/core/tests/figma-api/text/units.test.ts b/packages/core/tests/figma-api/text/units.test.ts
index 43753aa57..81df6a278 100644
--- a/packages/core/tests/figma-api/text/units.test.ts
+++ b/packages/core/tests/figma-api/text/units.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
@@ -6,6 +6,10 @@ import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
import { lineHeightPixels, percentLength, pixelLength } from '@open-pencil/scene-graph/text'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
function text() {
const graph = new SceneGraph()
const node = new FigmaAPI(graph).createText()
diff --git a/packages/core/tests/figma-api/text/unloaded-fonts.test.ts b/packages/core/tests/figma-api/text/unloaded-fonts.test.ts
new file mode 100644
index 000000000..85f529f64
--- /dev/null
+++ b/packages/core/tests/figma-api/text/unloaded-fonts.test.ts
@@ -0,0 +1,134 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { asTextNode, registerTestFont, solidFill } from '#core-tests/helpers/figma-api'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Measured in live Figma (2026-10-27) on text whose font no script had loaded.
+const UNLOADED = 'Unloaded Sans'
+const unloadedWrite = (method: string) =>
+ `in ${method}: Cannot write to node with unloaded font "${UNLOADED} Regular". Please call figma.loadFontAsync({ family: "${UNLOADED}", style: "Regular" }) and await the returned promise first.`
+
+beforeAll(async () => {
+ await registerTestFont()
+ await registerTestFont('Weight Test')
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Inter', style: 'Bold' })
+})
+
+/** Text a file set in a font this run has not loaded, as a document can name one. */
+function unloadedText() {
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const node = asTextNode(api.createText())
+ graph.updateNode(node.id, { text: 'Hello world', fontFamily: UNLOADED })
+ return { graph, node, raw: () => graph.getNode(node.id) }
+}
+
+describe('text in a font that is not loaded', () => {
+ test('refuses every edit that lays it out again, and changes nothing', () => {
+ const { node, raw } = unloadedText()
+ const before = structuredClone(raw())
+ const edits: [string, () => void][] = [
+ ['set_characters', () => (node.characters = 'Changed')],
+ ['set_fontSize', () => (node.fontSize = 20)],
+ ['set_letterSpacing', () => (node.letterSpacing = { unit: 'PIXELS', value: 1 })],
+ ['set_lineHeight', () => (node.lineHeight = { unit: 'PIXELS', value: 30 })],
+ ['set_textCase', () => (node.textCase = 'UPPER')],
+ ['set_textDecoration', () => (node.textDecoration = 'UNDERLINE')],
+ ['set_paragraphSpacing', () => (node.paragraphSpacing = 4)],
+ ['set_textAutoResize', () => (node.textAutoResize = 'HEIGHT')],
+ ['set_textAlignHorizontal', () => (node.textAlignHorizontal = 'CENTER')],
+ ['set_textTruncation', () => (node.textTruncation = 'ENDING')],
+ ['insertCharacters', () => node.insertCharacters(0, 'A')],
+ ['deleteCharacters', () => node.deleteCharacters(0, 1)],
+ ['setRangeFontSize', () => node.setRangeFontSize(0, 2, 30)],
+ ['setRangeTextCase', () => node.setRangeTextCase(0, 2, 'UPPER')],
+ ['setRangeListOptions', () => node.setRangeListOptions(0, 2, { type: 'ORDERED' })],
+ ['setRangeIndentation', () => node.setRangeIndentation(0, 2, 1)],
+ ['setRangeParagraphSpacing', () => node.setRangeParagraphSpacing(0, 2, 4)]
+ ]
+ for (const [method, edit] of edits) expect(edit).toThrow(unloadedWrite(method))
+ expect(raw()).toEqual(before)
+ })
+
+ test('reports a wrong argument before the font', () => {
+ const { node } = unloadedText()
+ expect(() => node.setRangeFontSize(0, 99, 20)).toThrow('Range outside of available characters')
+ expect(() => node.setRangeFontSize(2, 2, 20)).toThrow('Empty range selected')
+ expect(() => node.insertCharacters(99, 'A')).toThrow(
+ 'in insertCharacters: Cannot insert characters at index greater than the length of the text'
+ )
+ expect(() => node.setRangeIndentation(0, 2, 9)).toThrow(
+ 'in setRangeIndentation: Property "indentation" failed validation'
+ )
+ })
+
+ test('refuses underline details but takes the underline colour, a paint', () => {
+ const { graph, node, raw } = unloadedText()
+ graph.updateNode(node.id, { textDecoration: 'UNDERLINE' })
+ const details: [string, () => void][] = [
+ ['setRangeTextDecorationStyle', () => node.setRangeTextDecorationStyle(0, 2, 'WAVY')],
+ [
+ 'setRangeTextDecorationOffset',
+ () => node.setRangeTextDecorationOffset(0, 2, { unit: 'PIXELS', value: 2 })
+ ],
+ [
+ 'setRangeTextDecorationThickness',
+ () => node.setRangeTextDecorationThickness(0, 2, { unit: 'PIXELS', value: 2 })
+ ],
+ ['setRangeTextDecorationSkipInk', () => node.setRangeTextDecorationSkipInk(0, 2, false)]
+ ]
+ for (const [method, edit] of details) expect(edit).toThrow(unloadedWrite(method))
+ node.setRangeTextDecorationColor(0, 2, { value: 'AUTO' })
+ expect(raw()?.textDecoration).toBe('UNDERLINE')
+ })
+
+ test('names fonts in its messages as Figma does', () => {
+ const { graph, node } = unloadedText()
+ graph.updateNode(node.id, { fontWeight: 600 })
+ expect(() => (node.fontSize = 20)).toThrow(`unloaded font "${UNLOADED} Semi Bold"`)
+ })
+
+ test('takes paints, links, a size, and a name, which need no font', () => {
+ const { node, raw } = unloadedText()
+ node.fills = [solidFill({ r: 1, g: 0, b: 0, a: 1 })]
+ node.setRangeFills(0, 2, [solidFill({ r: 0, g: 1, b: 0, a: 1 })])
+ node.setRangeHyperlink(0, 2, { type: 'URL', value: 'https://openpencil.dev' })
+ node.resize(100, 40)
+ node.name = 'Renamed'
+ expect(raw()).toMatchObject({ name: 'Renamed', width: 100, height: 40 })
+ })
+
+ test('takes a loaded font for all of it, so a missing font can be replaced', () => {
+ const { node, raw } = unloadedText()
+ node.fontName = { family: 'Inter', style: 'Bold' }
+ expect(raw()).toMatchObject({ fontFamily: 'Inter', fontWeight: 700 })
+ node.characters = 'Now editable'
+ expect(node.characters).toBe('Now editable')
+ })
+
+ test('refuses a new font that is not loaded before checking the text’s own', () => {
+ const { node } = unloadedText()
+ const unloadedUse = (method: string) =>
+ `in ${method}: Cannot use unloaded font "Other Sans Regular". Please call figma.loadFontAsync({ family: "Other Sans", style: "Regular" }) and await the returned promise first.`
+ const other = { family: 'Other Sans', style: 'Regular' }
+ expect(() => (node.fontName = other)).toThrow(unloadedUse('set_fontName'))
+ expect(() => node.setRangeFontName(0, 2, other)).toThrow(unloadedUse('setRangeFontName'))
+ expect(() => node.setRangeFontName(0, 2, { family: 'Inter', style: 'Bold' })).toThrow(
+ unloadedWrite('setRangeFontName')
+ )
+ })
+ test('takes a weight once its face is loaded, as a new font', async () => {
+ const graph = new SceneGraph()
+ const api = new FigmaAPI(graph)
+ const node = asTextNode(api.createText())
+ graph.updateNode(node.id, { fontFamily: 'Weight Test' })
+ expect(() => (node.fontWeight = 900)).toThrow(
+ 'in set_fontWeight: Cannot use unloaded font "Weight Test Black".'
+ )
+ await api.loadFontAsync({ family: 'Weight Test', style: 'Black' })
+ node.fontWeight = 900
+ expect(node.fontName).toMatchObject({ family: 'Weight Test', style: 'Black' })
+ })
+})
diff --git a/packages/core/tests/figma-api/text/variations.test.ts b/packages/core/tests/figma-api/text/variations.test.ts
index b5ac7fdde..381402527 100644
--- a/packages/core/tests/figma-api/text/variations.test.ts
+++ b/packages/core/tests/figma-api/text/variations.test.ts
@@ -17,7 +17,10 @@ beforeAll(async () => {
const variable = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()
const static_ = await Bun.file(join(FIXTURES, 'fonts', 'InterRegular-Faces.ttf')).arrayBuffer()
await fontManager.markLoaded(VARIABLE, 'Regular', variable)
+ await fontManager.markLoaded(VARIABLE, 'Regular Italic', variable)
await fontManager.markLoaded(STATIC, 'Regular', static_)
+ // Text edits need their fonts loaded, as in Figma: the family alone loads its named styles.
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: VARIABLE })
})
function text(family = VARIABLE) {
diff --git a/packages/core/tests/figma-api/traversal/find.test.ts b/packages/core/tests/figma-api/traversal/find.test.ts
index d5d637695..eb0d48a55 100644
--- a/packages/core/tests/figma-api/traversal/find.test.ts
+++ b/packages/core/tests/figma-api/traversal/find.test.ts
@@ -1,7 +1,10 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { createAPI } from '#core-tests/helpers/figma-api'
+import { createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
+
+
+beforeAll(() => registerTestFont())
describe('traversal', () => {
test('findAll finds deep descendants', () => {
diff --git a/packages/core/tests/figma-api/variables/collections.test.ts b/packages/core/tests/figma-api/variables/collections.test.ts
index 4f2dd4c58..3b21af929 100644
--- a/packages/core/tests/figma-api/variables/collections.test.ts
+++ b/packages/core/tests/figma-api/variables/collections.test.ts
@@ -1,7 +1,10 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { createAPI } from '#core-tests/helpers/figma-api'
+import { createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
+
+
+beforeAll(() => registerTestFont())
// Expected values and messages were recorded by running the same calls in Figma desktop.
diff --git a/packages/core/tests/figma-api/variants/set-properties.test.ts b/packages/core/tests/figma-api/variants/set-properties.test.ts
index 5feb024c2..320dc81dc 100644
--- a/packages/core/tests/figma-api/variants/set-properties.test.ts
+++ b/packages/core/tests/figma-api/variants/set-properties.test.ts
@@ -1,8 +1,12 @@
-import { expect, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
// Recorded with the same script in Figma desktop 126.
function setup() {
diff --git a/packages/core/tests/helpers/figma-api.ts b/packages/core/tests/helpers/figma-api.ts
index 93c55e3b1..66cb7d275 100644
--- a/packages/core/tests/helpers/figma-api.ts
+++ b/packages/core/tests/helpers/figma-api.ts
@@ -1,4 +1,5 @@
import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
+import { fontManager } from '@open-pencil/core/text'
import { SceneGraph, type Fill } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
@@ -6,6 +7,18 @@ export function createAPI(): FigmaAPI {
return new FigmaAPI(new SceneGraph())
}
+/**
+ * Registers the app's bundled variable Inter as `family`, upright and italic, as a host's own
+ * fonts are, so `loadFontAsync` loads any weight of it. Plugin text edits refuse fonts that are
+ * not loaded, as in Figma, so tests that edit text load their fonts first, as scripts do.
+ */
+export async function registerTestFont(family = 'Inter'): Promise<void> {
+ const data = await fontManager.fetchBundledFont('/InterVariable.ttf')
+ if (!data) throw new Error('The bundled Inter font is missing')
+ await fontManager.markLoaded(family, 'Regular', data)
+ await fontManager.markLoaded(family, 'Regular Italic', data)
+}
+
/** Reads a proxy through Figma's `TextNode` surface, which `wrapNode()` cannot name. */
export function asTextNode(node: FigmaNodeProxy): FigmaNodeProxy & TextNode {
return node as FigmaNodeProxy & TextNode
diff --git a/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts b/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts
index e17720835..1a3bf3f4b 100644
--- a/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts
+++ b/packages/core/tests/io/formats/fig/export/nested-override-address.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
@@ -10,6 +10,10 @@ import { initCodec, type NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
/** The Kiwi codec types only `symbolID`; the rest of the symbol payload is read through here. */
const symbolDataOf = (record: NodeChange): SymbolData | undefined =>
record.symbolData as SymbolData | undefined
diff --git a/packages/core/tests/io/formats/fig/instance/component-sync.test.ts b/packages/core/tests/io/formats/fig/instance/component-sync.test.ts
index a053c9b3b..49798f2ac 100644
--- a/packages/core/tests/io/formats/fig/instance/component-sync.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/component-sync.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
import { guid } from '#core-tests/helpers/fig/guid'
@@ -8,6 +8,10 @@ import { interpretInstance, materializeInstance } from '@open-pencil/fig/instanc
import { initCodec, type NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
test('nested instances retain their outer source-child correspondence during sync', () => {
const source: NodeChange[] = [
{ guid: guid(1), type: 'SYMBOL' },
diff --git a/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts b/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts
index 26e115b26..d1cde90e4 100644
--- a/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/derived-geometry.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
import { guid } from '#core-tests/helpers/fig/guid'
@@ -7,6 +7,10 @@ import { interpretInstance, materializeInstance } from '@open-pencil/fig/instanc
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
test('text overrides discard inherited glyph data but accept occurrence-derived replacement data', () => {
const changes = [
{ guid: guid(1), type: 'SYMBOL' },
diff --git a/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts b/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts
index 0c0784d0b..06f11a5b5 100644
--- a/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/gold/preview.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'
@@ -16,6 +16,13 @@ import {
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(async () => {
+ await registerTestFont()
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Inter', style: 'Medium' })
+})
+
function named(node: InstanceOccurrence, name: string): InstanceOccurrence {
const child = node.children.find((candidate) => candidate.properties.name === name)
if (!child) throw new Error(`Missing ${name} under ${node.properties.name}`)
diff --git a/packages/core/tests/io/formats/fig/instance/override-reopen-sync.test.ts b/packages/core/tests/io/formats/fig/instance/override-reopen-sync.test.ts
index de0af5e0c..c346ecdff 100644
--- a/packages/core/tests/io/formats/fig/instance/override-reopen-sync.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/override-reopen-sync.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
import { FigmaAPI } from '@open-pencil/core/figma-api'
@@ -14,6 +14,10 @@ import {
} from '#core/kiwi/fig/population/delta'
import { populateFigPage } from '#core/kiwi/fig/session/document-state'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
function instanceNamed(graph: SceneGraph, name: string): SceneNode {
const instance = [...graph.getAllNodes()].find(
(node) => node.type === 'INSTANCE' && node.name === name
diff --git a/packages/core/tests/io/formats/fig/instance/source-children.test.ts b/packages/core/tests/io/formats/fig/instance/source-children.test.ts
index cb3880271..4f6a80877 100644
--- a/packages/core/tests/io/formats/fig/instance/source-children.test.ts
+++ b/packages/core/tests/io/formats/fig/instance/source-children.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
import { guid } from '#core-tests/helpers/fig/guid'
@@ -14,6 +14,10 @@ import {
import { initCodec, type NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
test('derives repeated nested child correspondence from materialized component occurrences', async () => {
const changes: NodeChange[] = [
{ guid: guid(1), type: 'SYMBOL' },
diff --git a/packages/core/tests/tools/analyze/diff/tools.test.ts b/packages/core/tests/tools/analyze/diff/tools.test.ts
index 5f9e27231..ea3cf8b89 100644
--- a/packages/core/tests/tools/analyze/diff/tools.test.ts
+++ b/packages/core/tests/tools/analyze/diff/tools.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
@@ -7,6 +7,10 @@ import { ALL_TOOLS, diffDocuments } from '@open-pencil/core/tools'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
type DiffResult = { diff?: string | null; message?: string; error?: string }
type ApplyResult = {
error?: string
diff --git a/packages/core/tests/tools/create/connector.test.ts b/packages/core/tests/tools/create/connector.test.ts
index 5b3db72f1..8b0f359d2 100644
--- a/packages/core/tests/tools/create/connector.test.ts
+++ b/packages/core/tests/tools/create/connector.test.ts
@@ -1,22 +1,28 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { registerTestFont } from '#core-tests/helpers/figma-api'
import { FigmaAPI, type FigmaConnectorNode } from '@open-pencil/core/figma-api'
import { ALL_TOOLS } from '@open-pencil/core/tools'
import { SceneGraph } from '@open-pencil/scene-graph'
-function createConnector(figma: FigmaAPI, args: Record<string, unknown>) {
+beforeAll(() => registerTestFont())
+
+/** Runs the tool as its executors do, loading the label's font first. */
+async function createConnector(figma: FigmaAPI, args: Record<string, unknown>) {
const tool = ALL_TOOLS.find((item) => item.name === 'create_connector')
if (!tool) throw new Error('No create_connector tool')
+ await tool.loadFonts(figma, args)
return tool.execute(figma, args)
}
describe('create_connector', () => {
- test('joins two layers with a labelled elbow that follows them', () => {
+ test('joins two layers with a labelled elbow that follows them', async () => {
const figma = new FigmaAPI(new SceneGraph())
const a = figma.createRectangle()
const b = figma.createRectangle()
b.x = 400
- const summary = createConnector(figma, {
+ const summary = await createConnector(figma, {
start: { id: a.id },
end: { id: b.id, magnet: 'LEFT' },
label: 'Next'
@@ -27,10 +33,10 @@ describe('create_connector', () => {
expect(connector.text.characters).toBe('Next')
})
- test('a straight connector to a point attaches by the layer centre', () => {
+ test('a straight connector to a point attaches by the layer centre', async () => {
const figma = new FigmaAPI(new SceneGraph())
const a = figma.createRectangle()
- const summary = createConnector(figma, {
+ const summary = await createConnector(figma, {
start: { id: a.id },
end: { x: 300, y: 300 },
line_type: 'STRAIGHT',
diff --git a/packages/docs/es/programmable/cli/scripting.md b/packages/docs/es/programmable/cli/scripting.md
index 196a2a8f5..9e9b03fe9 100644
--- a/packages/docs/es/programmable/cli/scripting.md
+++ b/packages/docs/es/programmable/cli/scripting.md
@@ -104,7 +104,7 @@ Las propiedades habituales se leen y modifican mediante el objeto correspondient
- `figma.mixed`
- `figma.createImage(data)`
-- `figma.loadFontAsync(fontName)` — no bloquea la edición de texto;
+- `figma.loadFontAsync(fontName)` — carga la fuente; como en Figma, cambiar el texto, su tamaño o su fuente exige cargar antes las fuentes que usa;
- `figma.listAvailableFontsAsync()` — devuelve las fuentes del sistema;
- `figma.notify(message)` — escribe un aviso cuando no hay interfaz;
- `figma.viewport`.
diff --git a/packages/docs/pl/programmable/cli/scripting.md b/packages/docs/pl/programmable/cli/scripting.md
index 5f61182bf..512bf1a5e 100644
--- a/packages/docs/pl/programmable/cli/scripting.md
+++ b/packages/docs/pl/programmable/cli/scripting.md
@@ -101,7 +101,7 @@ Najczęściej używane właściwości można odczytywać i zapisywać przez poś
- `figma.mixed`
- `figma.createImage(data)`
-- `figma.loadFontAsync(fontName)` niczego nie wykonuje, ponieważ OpenPencil nie blokuje zmiany tekstu do czasu załadowania czcionki przez wtyczkę
+- `figma.loadFontAsync(fontName)` wczytuje czcionkę; jak w Figmie, zmiana tekstu, jego rozmiaru lub czcionki wymaga wcześniejszego wczytania używanych czcionek
- `figma.listAvailableFontsAsync()` zwraca dostępne czcionki systemowe
- `figma.notify(message)` zapisuje ostrzeżenie w trybie bez interfejsu
- `figma.viewport`
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index b425bf311..4aa57ee3b 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -246,7 +246,8 @@ Common node properties are readable/writable through the proxy, including:
- `figma.util.rgb(color)`, `figma.util.rgba(color, alphaOverride?)`, and `figma.util.solidPaint(color, overrides?)` read a hex or CSS color string (`rgb()`, `hsl()`, `lab()`, `oklab()`, `oklch()`, `color(display-p3 …)`, or a name), clipped to sRGB, or an `{ r, g, b, a? }` object with channels from 0 to 1; `solidPaint` takes its color and opacity from `color` and its other properties from `overrides`, such as an existing paint
- `figma.createImage(data)` takes a PNG, JPEG, or GIF up to 4096 pixels a side and gives Figma's `Image`: its `hash`, `getBytesAsync()`, and `getSizeAsync()`; `figma.getImageByHash(hash)` gives a stored image back
- `figma.createImageAsync(url)` loads an `http(s)://` URL or a data URI. The desktop app fetches through its native proxy, as Figma fetches through its servers; in the browser, the image's host must allow cross-origin requests
-- `figma.loadFontAsync(fontName)` loads the font so text measures and draws with it; a family named without a style loads every style it has. OpenPencil does not gate text edits on it
+- `figma.loadFontAsync(fontName)` loads the font so text measures and draws with it; a family named without a style loads every style it has, and a variable family its named styles too. A font that cannot load rejects with Figma's `The font "Family Style" could not be loaded`
+- As in Figma, an edit that lays text out again throws `Cannot write to node with unloaded font` until every font the text uses is loaded: `characters`, `insertCharacters`, `deleteCharacters`, `fontSize`, spacing, case, decoration, alignment, `textAutoResize`, truncation, and the matching `setRange…` methods. A new `fontName` has to be loaded too, but it replaces the text's own, so text in a missing font can take a loaded one. Paints, links, size, and transforms need no font
- `figma.getFontFamilyVariationAxes(family)` lists a variable family's axis tags, or `null` for a static one; unlike Figma, the family has to be loaded first
- A font set with `variationSettings` and no style, through `fontName` or `setRangeFontName`, takes the nearest named style, and an axis the family lacks throws Figma's error
- `figma.listAvailableFontsAsync()` returns host-provided fonts when available
diff --git a/packages/docs/ru/programmable/cli/scripting.md b/packages/docs/ru/programmable/cli/scripting.md
index 1cc85dbbc..2a2869392 100644
--- a/packages/docs/ru/programmable/cli/scripting.md
+++ b/packages/docs/ru/programmable/cli/scripting.md
@@ -140,7 +140,7 @@ API намеренно близок к Figma Plugin API, но работает
- `figma.mixed`
- `figma.createImage(data)`
-- `figma.loadFontAsync(fontName)` ничего не делает, поскольку OpenPencil не блокирует изменение текста до загрузки шрифта плагином
+- `figma.loadFontAsync(fontName)` загружает шрифт; как в Figma, изменить текст, его размер или шрифт можно только после загрузки шрифтов, которые он использует
- `figma.listAvailableFontsAsync()` возвращает доступные системные шрифты
- `figma.notify(message)` записывает предупреждение в режиме без интерфейса
- `figma.viewport`
diff --git a/packages/scene-graph/src/connectors/sublayers.ts b/packages/scene-graph/src/connectors/sublayers.ts
index e1913229e..51f906367 100644
--- a/packages/scene-graph/src/connectors/sublayers.ts
+++ b/packages/scene-graph/src/connectors/sublayers.ts
@@ -14,6 +14,8 @@ export const CONNECTOR_STROKE_WEIGHT = 4
/** FigJam's line menu draws a connector Thin, at its default weight, or Thick, at twice it. */
export const CONNECTOR_THICK_STROKE_WEIGHT = 8
export const CONNECTOR_CORNER_RADIUS = 24
+/** The face a connector's label starts in, as FigJam's: Inter Medium. */
+export const CONNECTOR_LABEL_FONT = { family: 'Inter', weight: 500 } as const
/** The dash FigJam's line menu draws a connector with, longer for a thick line. Measured in FigJam. */
export function connectorDash(weight: number): number[] {
@@ -138,8 +140,8 @@ export function buildConnectorSublayers(
const label = graph.createNode('TEXT', connector.id, {
name: 'Label',
text: '',
- fontFamily: 'Inter',
- fontWeight: 500,
+ fontFamily: CONNECTOR_LABEL_FONT.family,
+ fontWeight: CONNECTOR_LABEL_FONT.weight,
fontSize: 16,
lineHeight: pixelLength(24),
textAlignHorizontal: 'CENTER',
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index 38be20042..2a8063858 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -156,9 +156,11 @@ openpencil eval -c '
buttons.length + " buttons updated"
'
-# Modify and save to the same file
+# Modify and save to the same file; text edits need the text's fonts loaded first, as in Figma
openpencil eval design.fig -w -c '
- const texts = figma.currentPage.findAll(n => n.type === "TEXT");
+ const texts = figma.currentPage.findAll(n => n.type === "TEXT" && n.characters.length > 0);
+ const fonts = texts.flatMap(t => t.getRangeAllFontNames(0, t.characters.length));
+ await Promise.all(fonts.map(font => figma.loadFontAsync(font)));
texts.forEach(t => { t.fontSize = 16 });
'
@@ -171,12 +173,16 @@ echo 'figma.currentPage.children.map(n => n.name)' | openpencil eval design.fig
# Style part of a text, and read how it is styled
openpencil eval design.fig -w -c '
const title = figma.currentPage.findOne(n => n.type === "TEXT" && n.name === "Title");
+ const fonts = [...title.getRangeAllFontNames(0, title.characters.length), { family: "Inter", style: "Bold" }];
+ await Promise.all(fonts.map(font => figma.loadFontAsync(font)));
title.setRangeFontName(0, 5, { family: "Inter", style: "Bold" });
title.setRangeFills(0, 5, [{ type: "SOLID", color: { r: 0.9, g: 0.1, b: 0.1 } }]);
title.getStyledTextSegments(["fontName", "fills"]).map(s => [s.characters, s.fontName.style])
'
```
+Text edits follow Figma's font rule: anything that lays text out again (`characters`, `fontSize`, `fontName`, spacing, case, alignment, auto-resize, and the matching `setRange…` methods) throws `Cannot write to node with unloaded font` until `figma.loadFontAsync` has loaded every font the text uses, and a new font has to be loaded before it is set. A font that is not available rejects `loadFontAsync`; replace it with `fontName = { family, style }` in a loaded font. The built-in text tools load fonts themselves.
+
Text styles follow Figma's per-character model: `getStyledTextSegments(fields)` reads runs, `getRange…`/`setRange…` read and set font, size, fills, letter spacing, line height, decorations, text case, hyperlinks, text and fill style IDs, and bound variables for `[start, end)`, and a text's `fontSize`, `fontName`, `fills`, and similar read `figma.mixed` while characters differ. Check for it before using the value. Paints everywhere take Figma's shape: a solid `color` is `{ r, g, b }` with the alpha in `opacity`, and an image is `{ type: "IMAGE", imageHash, scaleMode: "FILL" | "FIT" | "CROP" | "TILE" }` with optional `rotation` and `scalingFactor`.
Next to `figma`, scripts get `openpencil`: what OpenPencil adds to the Figma API, in its style. A main component can behave as a Reka UI control, by its own property and slot names:
diff --git a/src/app/ai/tools/runner.ts b/src/app/ai/tools/runner.ts
index 4d56d1a9d..1bc9b123f 100644
--- a/src/app/ai/tools/runner.ts
+++ b/src/app/ai/tools/runner.ts
@@ -1,6 +1,11 @@
import { executeAtomicTool, isEmptyDocumentChange, type DocumentChange } from '@open-pencil/core'
import type { FigmaAPI } from '@open-pencil/core/figma-api'
-import { isAtomicTool, toolChangesDocument, type ToolDef } from '@open-pencil/core/tools'
+import {
+ isAtomicTool,
+ toolChangesDocument,
+ toolFailure,
+ type ToolDef
+} from '@open-pencil/core/tools'
import {
AI_UNDO_PREFIX,
@@ -154,6 +159,12 @@ async function editAndRecord(call: EditorToolCall, reply: ReplyCall | null): Pro
export async function runEditorTool(call: EditorToolCall): Promise<unknown> {
const { store, figma, def, args } = call
if (!def.mutates) return def.execute(figma, args)
+ // Fonts load before the edit takes its turn, so an edit never waits on the network.
+ try {
+ await def.loadFonts(figma, args)
+ } catch (error) {
+ return toolFailure(error)
+ }
const reply = call.reply ?? null
const release = await editLock(store)()
// Whatever fails from here, the lock and the reply's count of running tools are released.
diff --git a/src/app/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.ts
index 6581c9a29..8e5cae147 100644
--- a/src/app/automation/bridge/figma-factory.ts
+++ b/src/app/automation/bridge/figma-factory.ts
@@ -3,7 +3,7 @@ import { createCanvasKitRasterCodec } from '@open-pencil/core/io/formats/raster'
import { renderAutomationImage } from '@/app/automation/bridge/export-handlers'
import type { EditorStore } from '@/app/editor/active-store'
-import { listFamilies, listFonts, loadFont } from '@/app/editor/fonts'
+import { listFamilies, listFonts } from '@/app/editor/fonts'
import { createTauriFetch } from '@/app/tauri/http'
import { IS_TAURI } from '@/constants'
@@ -45,9 +45,6 @@ export function makeFigmaFromStore(
opts.pageId ?? pageId
)
if (store.renderer) api.rasterCodec = createCanvasKitRasterCodec(store.renderer.ck)
- api.loadFontAsync = async ({ family, style }) => {
- await loadFont(family, style).catch(() => null)
- }
api.listAvailableFontsAsync = async () => {
const [systemFonts, familyOptions] = await Promise.all([listFonts(), listFamilies()])
const fonts = systemFonts.flatMap(({ family, styles }) =>
diff --git a/tests/engine/io/fig/instance/text-marker-roundtrip.test.ts b/tests/engine/io/fig/instance/text-marker-roundtrip.test.ts
index 7683415be..57a676aa1 100644
--- a/tests/engine/io/fig/instance/text-marker-roundtrip.test.ts
+++ b/tests/engine/io/fig/instance/text-marker-roundtrip.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
@@ -6,6 +6,10 @@ import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
import { getInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'
+import { registerTestFont } from '#tests/helpers/fonts/bundled'
+
+beforeAll(() => registerTestFont())
+
for (const text of ['User edit', '']) {
test(`preserves API instance text edit ${JSON.stringify(text)} across save/reload`, async () => {
await initCodec()
diff --git a/tests/engine/tools/modify.test.ts b/tests/engine/tools/modify.test.ts
index c7c0559c9..4caaef7c0 100644
--- a/tests/engine/tools/modify.test.ts
+++ b/tests/engine/tools/modify.test.ts
@@ -1,11 +1,14 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
-import { computeAllLayouts } from '@open-pencil/core/layout'
+import { computeAllLayouts, estimateTextSize } from '@open-pencil/core/layout'
import { fontManager } from '@open-pencil/core/text'
import { expectDefined, expectFills, getNodeOrThrow } from '#tests/helpers/assert'
+import { registerTestFont } from '#tests/helpers/fonts/bundled'
import { repoPath } from '#tests/helpers/paths'
-import { getTool, setupToolTest, type ToolResult } from '#tests/helpers/tools'
+import { getTool, runTool, setupToolTest, type ToolResult } from '#tests/helpers/tools'
+
+beforeAll(() => registerTestFont())
describe('set_fill', () => {
test('sets solid fill', () => {
@@ -219,7 +222,7 @@ describe('set_constraints', () => {
})
describe('set_font_range', () => {
- test('returns an empty or overlong range as an error and changes nothing', () => {
+ test('returns an empty or overlong range as an error and changes nothing', async () => {
const { figma, graph } = setupToolTest()
const created = getTool('create_shape').execute(figma, {
type: 'TEXT',
@@ -229,36 +232,33 @@ describe('set_font_range', () => {
height: 20
}) as ToolResult
const id = expectDefined(created.id, 'created node id')
- getTool('set_text').execute(figma, { id, text: 'Hello' })
- const setFontRange = getTool('set_font_range')
+ await runTool(figma, 'set_text', { id, text: 'Hello' })
- expect(setFontRange.execute(figma, { id, start: 2, end: 2, size: 18 })).toEqual({
+ expect(await runTool(figma, 'set_font_range', { id, start: 2, end: 2, size: 18 })).toEqual({
error: "in setRangeFontSize: Empty range selected. 'end' must be greater than 'start'"
})
- expect(setFontRange.execute(figma, { id, start: 0, end: 9, size: 18 })).toMatchObject({
+ expect(
+ await runTool(figma, 'set_font_range', { id, start: 0, end: 9, size: 18 })
+ ).toMatchObject({
error: expect.stringContaining('Range outside of available characters')
})
- expect(setFontRange.execute(figma, { id, start: 2, end: 2 })).toEqual({
+ expect(await runTool(figma, 'set_font_range', { id, start: 2, end: 2 })).toEqual({
error: 'set_font_range needs at least one of family, size, style, variations, or color'
})
expect(getNodeOrThrow(graph, id).styleRuns).toEqual([])
})
- test('applies font style to text range and survives serialization', () => {
+ test('applies font style to text range and survives serialization', async () => {
const { figma, graph } = setupToolTest()
- const createText = getTool('create_shape')
- const setText = getTool('set_text')
- const setFontRange = getTool('set_font_range')
-
- const created = createText.execute(figma, {
+ const created = getTool('create_shape').execute(figma, {
type: 'TEXT',
x: 0,
y: 0,
width: 200,
height: 20
}) as ToolResult
- setText.execute(figma, { id: created.id, text: 'Hello World' })
- setFontRange.execute(figma, {
+ await runTool(figma, 'set_text', { id: created.id, text: 'Hello World' })
+ await runTool(figma, 'set_font_range', {
id: created.id,
start: 0,
end: 5,
@@ -280,21 +280,17 @@ describe('set_font_range', () => {
expect(expectDefined(boldRun, 'bold style run').length).toBe(5)
})
- test('applies color to text range', () => {
+ test('applies color to text range', async () => {
const { figma, graph } = setupToolTest()
- const createText = getTool('create_shape')
- const setText = getTool('set_text')
- const setFontRange = getTool('set_font_range')
-
- const created = createText.execute(figma, {
+ const created = getTool('create_shape').execute(figma, {
type: 'TEXT',
x: 0,
y: 0,
width: 200,
height: 20
}) as ToolResult
- setText.execute(figma, { id: created.id, text: 'Red text' })
- setFontRange.execute(figma, { id: created.id, start: 0, end: 3, color: '#ff0000' })
+ await runTool(figma, 'set_text', { id: created.id, text: 'Red text' })
+ await runTool(figma, 'set_font_range', { id: created.id, start: 0, end: 3, color: '#ff0000' })
const node = getNodeOrThrow(graph, expectDefined(created.id, 'created node id'))
const colorRun = node.styleRuns.find((r) => r.style.fills?.length)
@@ -317,19 +313,70 @@ describe('set_font', () => {
const { figma } = setupToolTest()
const text = figma.createText()
text.characters = 'Hello'
- const setFont = getTool('set_font')
-
expect(
- setFont.execute(figma, { id: text.id, family, variations: { wght: 650 } })
+ await runTool(figma, 'set_font', { id: text.id, family, variations: { wght: 650 } })
).toMatchObject({
fontName: { family, style: 'Bold', variationSettings: { wght: 650 } }
})
expect(
- setFont.execute(figma, { id: text.id, style: 'Regular', variations: { wght: 450 } })
+ await runTool(figma, 'set_font', { id: text.id, style: 'Regular', variations: { wght: 450 } })
).toMatchObject({ fontName: { style: 'Regular', variationSettings: { wght: 450 } } })
- expect(setFont.execute(figma, { id: text.id, variations: { slnt: -10 } })).toEqual({
+ expect(await runTool(figma, 'set_font', { id: text.id, variations: { slnt: -10 } })).toEqual({
error:
'in setRangeFontName: "slnt" is not a valid variation setting. Valid settings are ["opsz","wght"].'
})
})
})
+
+describe('text tools load fonts first', () => {
+ test('a new font loads before it is set, so auto-width text takes its width', async () => {
+ const family = 'Tool Load Sans'
+ const data = await Bun.file(
+ repoPath('tests/fixtures/fonts/NotoSansSC-Regular.ttf')
+ ).arrayBuffer()
+ fontManager.setHostFontLoader(async (requested, style) =>
+ requested === family && style === 'Regular' ? data : null
+ )
+ try {
+ const { figma, graph } = setupToolTest()
+ const text = figma.createText()
+ text.characters = 'Wide lettering'
+ const before = text.width
+
+ await runTool(figma, 'set_font', { id: text.id, family, style: 'Regular' })
+ expect(fontManager.isStyleLoaded(family, 'Regular')).toBe(true)
+ // Measured in the font it was given, not estimated while that font loaded.
+ const measured = estimateTextSize(getNodeOrThrow(graph, text.id))
+ expect([text.width, text.height]).toEqual([measured.width, measured.height])
+ expect(text.width).not.toBe(before)
+ } finally {
+ fontManager.setHostFontLoader(null)
+ }
+ })
+
+ test('a font that cannot load is reported and the text is left as it was', async () => {
+ const { figma, graph } = setupToolTest()
+ const text = figma.createText()
+ text.characters = 'Label'
+ const before = structuredClone(getNodeOrThrow(graph, text.id))
+
+ expect(
+ await runTool(figma, 'set_font', { id: text.id, family: 'Nowhere Sans', style: 'Bold' })
+ ).toEqual({ error: 'The font "Nowhere Sans Bold" could not be loaded' })
+ expect(getNodeOrThrow(graph, text.id)).toEqual(before)
+ })
+
+ test('a range colour needs no font, so text in a missing font can be recoloured', async () => {
+ const { figma, graph } = setupToolTest()
+ const text = figma.createText()
+ text.characters = 'Label'
+ graph.updateNode(text.id, { fontFamily: 'Nowhere Sans' })
+
+ expect(
+ await runTool(figma, 'set_font_range', { id: text.id, start: 0, end: 2, color: '#ff0000' })
+ ).toEqual({ id: text.id, range: { start: 0, end: 2 } })
+ expect(
+ await runTool(figma, 'set_font_range', { id: text.id, start: 0, end: 2, size: 20 })
+ ).toEqual({ error: 'The font "Nowhere Sans Regular" could not be loaded' })
+ })
+})
diff --git a/tests/engine/tools/read.test.ts b/tests/engine/tools/read.test.ts
index 4b6c1cd42..dabf81990 100644
--- a/tests/engine/tools/read.test.ts
+++ b/tests/engine/tools/read.test.ts
@@ -1,12 +1,15 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
import { DEFAULT_FONT_FAMILY } from '@open-pencil/core/constants'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { fontManager } from '@open-pencil/core/text'
import { expectDefined } from '#tests/helpers/assert'
+import { registerTestFont } from '#tests/helpers/fonts/bundled'
import { getTool, setupToolTest, type ALL_TOOLS, type ToolResult } from '#tests/helpers/tools'
+beforeAll(() => registerTestFont())
+
/** The `list_pages` tool answers with the document's pages. */
interface ListPagesResult extends ToolResult {
pages: Array<{ id: string; name: string }>
@@ -158,10 +161,11 @@ describe('query_nodes', () => {
describe('get_font_status', () => {
test('returns font fidelity diagnostics for agents', () => {
- const { figma } = setupToolTest()
+ const { figma, graph } = setupToolTest()
const text = figma.createText()
text.name = 'Missing label'
- text.fontName = { family: 'Unavailable Sans', style: 'Regular' }
+ // A document can name a font this machine lacks; a script cannot set one it did not load.
+ graph.updateNode(text.id, { fontFamily: 'Unavailable Sans' })
const tool = getTool('get_font_status')
const result = tool.execute(figma, {}) as {
diff --git a/tests/helpers/fonts/bundled.ts b/tests/helpers/fonts/bundled.ts
new file mode 100644
index 000000000..3ac9b5e80
--- /dev/null
+++ b/tests/helpers/fonts/bundled.ts
@@ -0,0 +1,13 @@
+import { fontManager } from '@open-pencil/core/text'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+/**
+ * Registers the app's bundled variable Inter as `family`, upright and italic, as a host's own
+ * fonts are, so `loadFontAsync` loads any weight of it: text edits refuse unloaded fonts.
+ */
+export async function registerTestFont(family = 'Inter'): Promise<void> {
+ const data = expectDefined(await fontManager.fetchBundledFont('/InterVariable.ttf'), 'Inter')
+ await fontManager.markLoaded(family, 'Regular', data)
+ await fontManager.markLoaded(family, 'Regular Italic', data)
+}
diff --git a/tests/helpers/tools.ts b/tests/helpers/tools.ts
index 8b057e76b..8bd5e7aef 100644
--- a/tests/helpers/tools.ts
+++ b/tests/helpers/tools.ts
@@ -1,5 +1,5 @@
import { FigmaAPI } from '@open-pencil/core/figma-api'
-import { ALL_TOOLS } from '@open-pencil/core/tools'
+import { ALL_TOOLS, toolFailure } from '@open-pencil/core/tools'
import { SceneGraph } from '@open-pencil/scene-graph'
export { ALL_TOOLS }
@@ -28,3 +28,21 @@ export function getTool(name: string): (typeof ALL_TOOLS)[number] {
`tool ${name}`
)
}
+
+/**
+ * Runs a tool as the app's runner does: the fonts its text edits need load first, and one that
+ * cannot load is the call's error.
+ */
+export async function runTool(
+ figma: FigmaAPI,
+ name: string,
+ args: Record<string, unknown>
+): Promise<unknown> {
+ const tool = getTool(name)
+ try {
+ await tool.loadFonts(figma, args)
+ } catch (error) {
+ return toolFailure(error)
+ }
+ return tool.execute(figma, args)
+}