Skip to content

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

feat(core): read and set variable font axes through the plugin API (#1476)

Danila Poyarkov71436ded8a66
diff --git a/changes/1476/added.md b/changes/1476/added.md
new file mode 100644
index 000000000..2a8f558ba
--- /dev/null
+++ b/changes/1476/added.md
@@ -0,0 +1 @@
+- Plugins and the `set_font` tools read and set variable font axes: `fontName.variationSettings`, a `fontWeight` that follows `wght`, fonts given by axes alone taking the nearest named style, `loadFontAsync` for a whole family, and `getFontFamilyVariationAxes`.
diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.ts
index 6f3f5cd09..d934e80a8 100644
--- a/packages/core/src/figma-api/accessors/text/index.ts
+++ b/packages/core/src/figma-api/accessors/text/index.ts
@@ -13,7 +13,7 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { styleNameToWeight, type FigmaFontName } from '#core/figma-api/fonts'
+import type { FigmaFontNameInput } from '#core/figma-api/fonts'
import {
getParagraphSpacing,
letterSpacingValue,
@@ -28,6 +28,7 @@ import { getTextStyle, type TextSegmentField } from '#core/figma-api/text/style'
import { styleRunsWithPatch, textStyleChanges } from '#core/text/character-style'
import { hyperlinkTarget } from './hyperlink'
+import { fontNameStyle } from './ranges'
/**
* Getter/setter pair for a spacing Figma keeps at zero or more. It reads `mixed` while paragraphs
@@ -105,10 +106,9 @@ export function installTextNodeProxyAccessors(
updateNode(this, internals, { text: value, textParagraphs, styleRuns })
}
},
- fontName: characterStyle<FigmaFontName>(internals, 'fontName', mixed, (_node, value) => {
- const { weight, italic } = styleNameToWeight(value.style)
- return { fontFamily: value.family, fontWeight: weight, italic }
- }),
+ fontName: characterStyle<FigmaFontNameInput>(internals, 'fontName', mixed, (node, value) =>
+ fontNameStyle('set_fontName', node, 0, value)
+ ),
fontSize: characterStyle<number>(internals, 'fontSize', mixed, (_node, fontSize) => ({
fontSize
})),
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index 985ce417c..70fe769c2 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -21,7 +21,15 @@ import {
type ProxyThis
} from '#core/figma-api/accessor-utils'
import { figmaPaintToFill, type FigmaPaint } from '#core/figma-api/accessors/visual'
-import { styleNameToWeight, type FigmaFontName } from '#core/figma-api/fonts'
+import {
+ fontNameInputStyle,
+ readVariationSettings,
+ weightToStyleName,
+ type CurrentFont,
+ type FigmaFontName,
+ type FigmaFontNameInput,
+ type FigmaVariationSettings
+} from '#core/figma-api/fonts'
import {
getRangeIndentation,
getRangeListOptions,
@@ -42,7 +50,12 @@ import {
type TextSegmentField
} from '#core/figma-api/text/style'
import type { FigmaVariableAlias } from '#core/figma-api/variables/values'
-import { styleRunsWithPatch, type TextStylePatch } from '#core/text/character-style'
+import {
+ characterStyles,
+ nodeStyle,
+ styleRunsWithPatch,
+ type TextStylePatch
+} from '#core/text/character-style'
import { hyperlinkTarget } from './hyperlink'
import { invalid, received } from './messages'
@@ -127,17 +140,65 @@ function stringProblem(value: unknown, at: string): string | null {
return typeof value === 'string' ? null : `Expected string, received ${received(value)} at ${at}`
}
-/** A font name Figma takes: a family and style; a style left out reads as regular. */
-function fontNameStyle(method: string, value: unknown): CharacterStyleOverride {
+/** The font Figma reads for the character at `index`, as a font name left out reads from. */
+/** The font of the character at `index`, and the axes it sets itself. */
+function currentFont(node: SceneNode, index: number): CurrentFont {
+ const at = Math.min(index, node.text.length - 1)
+ const [style] = at < 0 ? [nodeStyle(node)] : characterStyles(node, at, at + 1)
+ const name = weightToStyleName(style.fontWeight, style.italic)
+ return {
+ style: name,
+ fontVariations: style.fontVariations,
+ variationSettings: readVariationSettings(
+ style.fontFamily,
+ name,
+ style.fontVariations,
+ node.opticalSizeFromFontSize
+ )
+ }
+}
+
+/**
+ * A font name Figma takes: a family, and a style and variation settings that may be left out, as
+ * in `FontNameInput`. What is left out reads from the font of the character at `start`.
+ */
+export function fontNameStyle(
+ method: string,
+ node: SceneNode,
+ start: number,
+ value: unknown
+): CharacterStyleOverride {
if (!value || typeof value !== 'object') {
throw invalid(method, `Expected object, received ${received(value)}`)
}
const fontName = value as Partial<Record<keyof FigmaFontName, unknown>>
- const style = fontName.style ?? 'Regular'
- const problem = stringProblem(fontName.family, '.family') ?? stringProblem(style, '.style')
+ const problem =
+ stringProblem(fontName.family, '.family') ??
+ (fontName.style === undefined ? null : stringProblem(fontName.style, '.style')) ??
+ variationSettingsProblem(fontName.variationSettings)
if (problem) throw invalid(method, problem)
- const { weight, italic } = styleNameToWeight(style as string)
- return { fontFamily: fontName.family as string, fontWeight: weight, italic }
+ return fontNameInputStyle(
+ method,
+ {
+ family: fontName.family as string,
+ style: fontName.style as string | undefined,
+ variationSettings: fontName.variationSettings as FigmaVariationSettings | undefined
+ },
+ currentFont(node, start)
+ )
+}
+
+/** Variation settings Figma takes: numbers by axis tag. */
+function variationSettingsProblem(value: unknown): string | null {
+ if (value === undefined) return null
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return `Expected object, received ${received(value)} at .variationSettings`
+ }
+ for (const [tag, setting] of Object.entries(value)) {
+ const problem = numberProblem(setting, ` at .variationSettings.${tag}`)
+ if (problem) return problem
+ }
+ return null
}
/** A number from 0 to 1, as Figma takes colour channels and opacity. */
@@ -279,7 +340,7 @@ 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, value),
+ setRangeFontName: (method, node, start, _end, value) => fontNameStyle(method, node, start, value),
setRangeFills: (method, _node, _start, _end, value) => ({
fills: fillsFromPaints(method, value)
}),
@@ -365,7 +426,7 @@ export interface TextRangeMethods {
getRangeFontSize: RangeGetter<number>
setRangeFontSize: RangeSetterMethod<number>
getRangeFontName: RangeGetter<FigmaFontName>
- setRangeFontName: RangeSetterMethod<FigmaFontName>
+ setRangeFontName: RangeSetterMethod<FigmaFontNameInput>
getRangeFontWeight: RangeGetter<number>
getRangeFills: RangeGetter<Fill[]>
setRangeFills: RangeSetterMethod<FigmaPaint[]>
diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.ts
index bc9816f96..ee87ad262 100644
--- a/packages/core/src/figma-api/compatibility.ts
+++ b/packages/core/src/figma-api/compatibility.ts
@@ -26,6 +26,7 @@ export type SupportedPluginAPI = Pick<
| 'base64Decode'
| 'base64Encode'
| 'closePlugin'
+ | 'getFontFamilyVariationAxes'
| 'getImageByHash'
| 'loadAllPagesAsync'
| 'loadFontAsync'
diff --git a/packages/core/src/figma-api/fonts.ts b/packages/core/src/figma-api/fonts.ts
index 2ecfd2e81..797a43467 100644
--- a/packages/core/src/figma-api/fonts.ts
+++ b/packages/core/src/figma-api/fonts.ts
@@ -1,7 +1,16 @@
+import type { FontVariation } from '@open-pencil/scene-graph'
import type { FontFamilyStyle } from '@open-pencil/scene-graph/font-style'
-import { FONT_WEIGHT_NAMES } from '@open-pencil/scene-graph/font-style'
+import { FONT_WEIGHT_NAMES, parseFontStyle } from '@open-pencil/scene-graph/font-style'
-export type FigmaFontName = FontFamilyStyle
+import {
+ namedInstanceVariations,
+ type FontAxis,
+ type NamedInstance
+} from '#core/text/font/variation'
+import { fontManager } from '#core/text/fonts'
+
+/** A font as Figma reads one; a variable font's also lists every axis it is drawn at. */
+export type FigmaFontName = FontFamilyStyle & { variationSettings?: FigmaVariationSettings }
export type FigmaFont = { fontName: FigmaFontName }
export function weightToStyleName(weight: number, italic: boolean): string {
@@ -9,18 +18,149 @@ export function weightToStyleName(weight: number, italic: boolean): string {
return italic ? `${base} Italic` : base
}
-const STYLE_NAME_TO_WEIGHT: Record<string, number> = Object.fromEntries([
- ...Object.entries(FONT_WEIGHT_NAMES).map(([w, name]) => [name.toLowerCase(), Number(w)]),
- ['ultra light', 200],
- ['', 400],
- ['demi bold', 600],
- ['ultra bold', 800],
- ['heavy', 900]
-])
-
-export function styleNameToWeight(style: string): { weight: number; italic: boolean } {
- const lower = style.toLowerCase()
- const italic = lower.includes('italic')
- const clean = lower.replace(/italic/i, '').trim()
- return { weight: STYLE_NAME_TO_WEIGHT[clean] ?? 400, italic }
+/** Variable font axis values by axis tag, as `FontName.variationSettings` holds them. */
+export type FigmaVariationSettings = Record<string, number>
+
+/** A font to apply, as Figma takes one: `style` may be left out for the axes to pick it. */
+export interface FigmaFontNameInput {
+ family: string
+ style?: string
+ variationSettings?: FigmaVariationSettings
+}
+
+/** Figma lists axis tags in code unit order, so `GRAD` comes before `opsz`. */
+function byCodeUnit(a: string, b: string): number {
+ if (a === b) return 0
+ return a < b ? -1 : 1
+}
+
+/** The axis tags a family accepts, as `getFontFamilyVariationAxes` lists them. */
+export function variationAxisTags(axes: readonly FontAxis[]): string[] {
+ return axes.map((axis) => axis.tag).sort(byCodeUnit)
+}
+
+/**
+ * Figma's `variationSettings` for text in `style` of a variable family: every axis, at the named
+ * instance's value unless the text sets it. An optical size that follows the font size reads as
+ * the instance's own, as Figma reads it. Nothing for a static family or one not loaded.
+ */
+export function readVariationSettings(
+ family: string,
+ style: string,
+ variations: readonly FontVariation[],
+ opticalSizeFromFontSize: boolean
+): FigmaVariationSettings | undefined {
+ const variation = fontManager.familyVariation(family, parseFontStyle(style).italic)
+ if (!variation) return undefined
+ const named = namedInstanceVariations(variation.data, style) ?? []
+ const set = opticalSizeFromFontSize
+ ? variations.filter((entry) => entry.axis !== 'opsz')
+ : variations
+ const values = new Map(variation.axes.map((axis) => [axis.tag, axis.default]))
+ for (const { axis, value } of [...named, ...set]) if (values.has(axis)) values.set(axis, value)
+ return Object.fromEntries([...values].sort(([a], [b]) => byCodeUnit(a, b)))
+}
+
+/** Where `value` sits on an axis, from -1 at its minimum through 0 at its default to 1. */
+function normalized(axis: FontAxis, value: number): number {
+ if (value < axis.default) return (value - axis.default) / (axis.default - axis.min || 1)
+ return (value - axis.default) / (axis.max - axis.default || 1)
+}
+
+/** How much two distances may differ in floating point and still be as near. */
+const DISTANCE_TOLERANCE = 1e-9
+
+/** The named instance nearest `target` on the font's axes; the later one where two are as near. */
+function nearestInstance(
+ axes: readonly FontAxis[],
+ instances: readonly NamedInstance[],
+ target: Partial<FigmaVariationSettings>
+): string | undefined {
+ let nearest: { name: string; distance: number } | undefined
+ for (const instance of instances) {
+ const distance = instance.variations.reduce((sum, { axis, value }) => {
+ const found = axes.find((entry) => entry.tag === axis)
+ const wanted = target[axis]
+ if (!found || wanted === undefined) return sum
+ return sum + (normalized(found, wanted) - normalized(found, value)) ** 2
+ }, 0)
+ if (!nearest || distance <= nearest.distance + DISTANCE_TOLERANCE) {
+ nearest = { name: instance.name, distance }
+ }
+ }
+ return nearest?.name
+}
+
+/**
+ * What applying `input` sets on the text: its family and style, and the axes it sets over the
+ * style's named instance. A style left out is the named instance nearest the axes, the ones the
+ * input leaves out read from `current`; with no axes either, the current style stays. Axes the
+ * family does not have throw, as Figma rejects them.
+ */
+/** The family's axes in the slant asked for, once each of `tags` is checked among them. */
+function checkedVariation(method: string, family: string, slanted: boolean, tags: string[]) {
+ const variation = fontManager.familyVariation(family, slanted)
+ if (tags.length > 0 && variation === undefined) {
+ throw new Error(
+ `in ${method}: Font family "${family}" is not loaded, so its variation axes are unknown. Call loadFontAsync first.`
+ )
+ }
+ if (tags.length > 0 && variation === null) {
+ throw new Error(
+ `in ${method}: "${tags[0]}" is not a valid variation setting. Font "${family}" has no variation axes.`
+ )
+ }
+ if (variation) {
+ const valid = variationAxisTags(variation.axes)
+ const invalid = tags.find((tag) => !valid.includes(tag))
+ if (invalid) {
+ throw new Error(
+ `in ${method}: "${invalid}" is not a valid variation setting. Valid settings are ${JSON.stringify(valid)}.`
+ )
+ }
+ }
+ return variation
+}
+
+/** The font a character has before a new one is set over it. */
+export interface CurrentFont {
+ style: string
+ /** The axes the text sets itself, over its style's. */
+ fontVariations: readonly FontVariation[]
+ variationSettings?: FigmaVariationSettings
+}
+
+export function fontNameInputStyle(
+ method: string,
+ input: FigmaFontNameInput,
+ current?: CurrentFont
+): { fontFamily: string; fontWeight: number; italic: boolean; fontVariations: FontVariation[] } {
+ const settings = input.variationSettings ?? {}
+ const tags = Object.keys(settings)
+ const slanted = parseFontStyle(input.style ?? current?.style ?? 'Regular').italic
+ const variation = checkedVariation(method, input.family, slanted, tags)
+ const style =
+ input.style ??
+ (tags.length > 0 && variation
+ ? nearestInstance(variation.axes, variation.instances, {
+ ...current?.variationSettings,
+ ...settings
+ })
+ : undefined) ??
+ current?.style ??
+ 'Regular'
+ const { weight, italic } = parseFontStyle(style)
+ return {
+ fontFamily: input.family,
+ fontWeight: weight,
+ // A style picked from the axes keeps the text's slant, whichever file the axes came from.
+ italic: input.style ? italic : slanted,
+ // A style resets the axes to its own; without one, the axes the text set stay.
+ fontVariations: [
+ ...(input.style ? [] : (current?.fontVariations ?? [])).filter(
+ ({ axis }) => !tags.includes(axis)
+ ),
+ ...tags.map((axis) => ({ axis, value: settings[axis] ?? 0 }))
+ ]
+ }
}
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 68559a781..1b939f3d2 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -1,3 +1,4 @@
+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'
@@ -22,6 +23,7 @@ import { fontManager } from '#core/text/fonts'
import { componentFromNode } from './components'
import { flattenSceneNodes } from './flatten'
+import { variationAxisTags, weightToStyleName, type FigmaFontNameInput } from './fonts'
import * as images from './images'
import type {
FigmaBooleanOperationNode,
@@ -41,14 +43,7 @@ import type {
FigmaVectorNode
} from './node-types'
import { startPendingLayout } from './pending-layout'
-import {
- FigmaNodeProxy,
- INTERNAL_ID,
- MIXED,
- type FigmaFont,
- type FigmaFontName,
- type NodeProxyHost
-} from './proxy'
+import { FigmaNodeProxy, INTERNAL_ID, MIXED, type FigmaFont, type NodeProxyHost } from './proxy'
import { newShapeWithText } from './shape-with-text'
import type { ExportImageOptions } from './types'
import { figmaUtil } from './util'
@@ -97,6 +92,7 @@ export type {
FigmaVectorNode
} from './node-types'
export type { FigmaFont, FigmaFontName } from './proxy'
+export type { FigmaFontNameInput, FigmaVariationSettings } from './fonts'
// TODO(figma-api): Implement the full official PluginAPI interface once our compatibility
// layer covers all required node-specific return types and unsupported APIs are modeled explicitly.
@@ -540,8 +536,36 @@ export class FigmaAPI implements NodeProxyHost {
* 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.
*/
- async loadFontAsync(fontName: FigmaFontName): Promise<void> {
- await fontManager.loadFont(fontName.family, fontName.style).catch(() => null)
+ 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))
+ }
+
+ /**
+ * The axis tags a variable family takes in `variationSettings`, or `null` for a static family.
+ * Figma answers for any family it lists; OpenPencil reads the axes from a file the family has
+ * loaded, so a family has to be loaded first.
+ */
+ getFontFamilyVariationAxes(family: string): string[] | null {
+ const variation = fontManager.familyVariation(family)
+ if (variation === undefined) {
+ throw new Error(
+ `in getFontFamilyVariationAxes: Font family "${family}" is not available. Load it with figma.loadFontAsync({ family: "${family}" }) first.`
+ )
+ }
+ return variation ? variationAxisTags(variation.axes) : null
}
async listAvailableFontsAsync(): Promise<FigmaFont[]> {
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 23e424538..08f7afbe9 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -61,7 +61,7 @@ import type { FigmaTransform } from './types'
const MIXED = Symbol('mixed')
-export { styleNameToWeight, weightToStyleName, type FigmaFont, type FigmaFontName } from './fonts'
+export { weightToStyleName, type FigmaFont, type FigmaFontName } from './fonts'
export const INTERNAL_ID = Symbol('id')
export const INTERNAL_GRAPH = Symbol('graph')
diff --git a/packages/core/src/figma-api/text/bindings.ts b/packages/core/src/figma-api/text/bindings.ts
index 87c4b46de..a96c2b0ca 100644
--- a/packages/core/src/figma-api/text/bindings.ts
+++ b/packages/core/src/figma-api/text/bindings.ts
@@ -10,9 +10,9 @@ import {
type Variable
} from '@open-pencil/scene-graph'
import { copyFills } from '@open-pencil/scene-graph/copy'
+import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
import { getSharedStyles, SHARED_TEXT_STYLE_FIELDS } from '@open-pencil/scene-graph/shared-styles'
-import { styleNameToWeight } from '#core/figma-api/fonts'
import { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'
import { styleRunsWithPatch } from '#core/text/character-style'
@@ -88,7 +88,7 @@ function boundValue(
const value = graph.resolveVariableForNode(node.id, variable.id)
if (typeof value !== 'string') return {}
if (field === 'fontFamily') return { fontFamily: value }
- const { weight, italic } = styleNameToWeight(value)
+ const { weight, italic } = parseFontStyle(value)
return { fontWeight: weight, italic }
}
const value = graph.resolveNumberVariableForNode(node.id, variable.id)
diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.ts
index be9a3c8e8..14a35706d 100644
--- a/packages/core/src/figma-api/text/style.ts
+++ b/packages/core/src/figma-api/text/style.ts
@@ -9,7 +9,7 @@ import {
paragraphStyleAt
} from '@open-pencil/scene-graph/text'
-import { weightToStyleName } from '#core/figma-api/fonts'
+import { readVariationSettings, weightToStyleName } from '#core/figma-api/fonts'
import { toFigmaPaint, type WithFigmaTransforms } from '#core/figma-api/paints'
import { variableAlias } from '#core/figma-api/variables/values'
import { characterStyles, nodeStyle, type CharacterStyle } from '#core/text/character-style'
@@ -84,11 +84,21 @@ function spacing(field: 'paragraphSpacing' | 'listSpacing' | 'paragraphIndent')
*/
const FIELD_READERS: Record<TextSegmentField, (context: FieldContext) => unknown> = {
fontSize: ({ style }) => style.fontSize,
- fontName: ({ style }) => ({
- family: style.fontFamily,
- style: weightToStyleName(style.fontWeight, style.italic)
- }),
- fontWeight: ({ style }) => style.fontWeight,
+ fontName: ({ node, style }) => {
+ const name = weightToStyleName(style.fontWeight, style.italic)
+ const variationSettings = readVariationSettings(
+ style.fontFamily,
+ name,
+ style.fontVariations,
+ node.opticalSizeFromFontSize
+ )
+ return variationSettings
+ ? { family: style.fontFamily, style: name, variationSettings }
+ : { family: style.fontFamily, style: name }
+ },
+ // A weight axis the text sets is its weight, as Figma reads it.
+ fontWeight: ({ style }) =>
+ style.fontVariations.find((variation) => variation.axis === 'wght')?.value ?? style.fontWeight,
fontStyle: ({ style }) => (style.italic ? 'ITALIC' : 'REGULAR'),
textDecoration: ({ style }) => style.textDecoration,
textDecorationStyle: whenUnderlined((style) => style.textDecorationStyle),
diff --git a/packages/core/src/text/character-style.ts b/packages/core/src/text/character-style.ts
index 97973bdb4..c2a341e01 100644
--- a/packages/core/src/text/character-style.ts
+++ b/packages/core/src/text/character-style.ts
@@ -29,6 +29,7 @@ export type CharacterStyle = Required<
| 'textDecorationFills'
| 'textDecorationSkipInk'
| 'fontFeatures'
+ | 'fontVariations'
| 'textCase'
>
> & {
@@ -58,6 +59,7 @@ export const TEXT_STYLE_KEYS = [
'textDecorationSkipInk',
'textUnderlineOffset',
'fontFeatures',
+ 'fontVariations',
'textCase'
] as const satisfies readonly (keyof CharacterStyle)[]
@@ -89,6 +91,7 @@ export function nodeStyle(node: SceneNode): CharacterStyle {
textDecorationSkipInk: node.textDecorationSkipInk,
textUnderlineOffset: node.textUnderlineOffset,
fontFeatures: node.fontFeatures,
+ fontVariations: node.fontVariations,
textCase: node.textCase,
hyperlink: null,
textStyleId: node.textStyleId,
diff --git a/packages/core/src/text/font/variation.ts b/packages/core/src/text/font/variation.ts
index 68dc9b4cc..19187fdd0 100644
--- a/packages/core/src/text/font/variation.ts
+++ b/packages/core/src/text/font/variation.ts
@@ -140,6 +140,28 @@ export function fontAxes(data: ArrayBuffer): FontAxis[] | null {
return variationTable(data)?.axes ?? null
}
+/** A named instance of a variable font, such as Inter's `Semi Bold`, with every axis' value. */
+export interface NamedInstance {
+ name: string
+ variations: FontVariation[]
+}
+
+/** A variable font's named instances, in its order. */
+export function namedInstances(data: ArrayBuffer): NamedInstance[] {
+ const table = variationTable(data)
+ if (!table?.name) return []
+ const { view, axes, instances, name } = table
+ return instances.flatMap((offset) => {
+ const instanceName = fontName(view, name, view.getUint16(offset))
+ if (instanceName === null) return []
+ const variations = axes.map((axis, axisIndex) => ({
+ axis: axis.tag,
+ value: fixed(view, offset + 4 + axisIndex * 4)
+ }))
+ return [{ name: instanceName, variations }]
+ })
+}
+
/**
* Returns the axis coordinates a variable font needs to render `style`, preferring the named
* instance with that name (for example SF Pro `Medium` is `wght` 510) and otherwise clamping the
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.ts
index 7abca1904..921b5138b 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/fonts.ts
@@ -8,7 +8,13 @@ import { DEFAULT_FONT_FAMILY, IS_BROWSER } from '#core/constants'
import { fontFaceRenderFamily } from '#core/text/face'
import { facesFromStyles, hasFamilyFace, type FamilyFace } from '#core/text/font/faces'
import { chooseLocalFontMatch } from '#core/text/font/style'
-import { fontAxes, namedInstanceVariations } from '#core/text/font/variation'
+import {
+ fontAxes,
+ namedInstances,
+ namedInstanceVariations,
+ type FontAxis,
+ type NamedInstance
+} from '#core/text/font/variation'
export * from '#core/text/font/sources'
export * from '#core/text/font/style'
@@ -77,6 +83,10 @@ export class FontManager {
private fileFamilies = new Map<ArrayBuffer, string>()
private remoteCoverage = new Map<string, Set<string>>()
private instanceVariations = new WeakMap<ArrayBuffer, Map<string, FontVariation[] | null>>()
+ private variations = new WeakMap<
+ ArrayBuffer,
+ { axes: FontAxis[]; instances: NamedInstance[] } | null
+ >()
private blockedNodeIds = new Set<string>()
private fontProvider: TypefaceFontProvider | null = null
private bundledFontLocator: BundledFontLocator = defaultBundledFontLocator
@@ -536,6 +546,34 @@ export class FontManager {
return this.loadedFamilies.get(`${family}|${style}`) ?? null
}
+ /**
+ * The variation axes and named instances of a family's variable font, from a face it has loaded,
+ * in the slant asked for where it has one: `null` when the faces it has loaded are static,
+ * `undefined` when it has loaded none.
+ */
+ familyVariation(
+ family: string,
+ italic?: boolean
+ ): { data: ArrayBuffer; axes: FontAxis[]; instances: NamedInstance[] } | null | undefined {
+ let loaded = false
+ let other: { data: ArrayBuffer; axes: FontAxis[]; instances: NamedInstance[] } | null = null
+ for (const [key, data] of this.loadedFamilies) {
+ if (!key.startsWith(`${family}|`)) continue
+ loaded = true
+ let variation = this.variations.get(data)
+ if (variation === undefined) {
+ const axes = fontAxes(data)
+ variation = axes ? { axes, instances: namedInstances(data) } : null
+ this.variations.set(data, variation)
+ }
+ if (!variation) continue
+ const slant = parseFontStyle(key.slice(family.length + 1)).italic
+ if (italic === undefined || slant === italic) return { data, ...variation }
+ other ??= { data, ...variation }
+ }
+ return loaded ? other : undefined
+ }
+
/** Axis coordinates for `style` when the loaded face is a variable font, otherwise `null`. */
namedInstanceVariations(family: string, style: string): FontVariation[] | null {
const data = this.loadedData(family, style)
diff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.ts
index 6fa1c635e..c117ddae1 100644
--- a/packages/core/src/tools/modify/text.ts
+++ b/packages/core/src/tools/modify/text.ts
@@ -2,6 +2,11 @@ import * as v from 'valibot'
import { parseColor } from '@open-pencil/scene-graph/color'
+import type {
+ FigmaFontName,
+ FigmaFontNameInput,
+ FigmaVariationSettings
+} from '#core/figma-api/fonts'
import { OpenPencilAPI } from '#core/openpencil-api'
import {
toolNumber,
@@ -28,6 +33,31 @@ export const setText = defineTool({
}
})
+/** Variable font axes a font tool can set, as Figma's `variationSettings`. */
+const variationsInputSchema = v.optional(
+ v.pipe(
+ v.record(v.pipe(v.string(), v.length(4)), v.number()),
+ v.description(
+ 'Variable font axis values by OpenType tag (e.g. {"wght": 550, "wdth": 75}); axes left out keep the style\'s values. Without a style, the nearest named style is picked.'
+ )
+ )
+)
+
+/**
+ * The font a font tool gives text: what it names, the rest from `current`. Axes without a style
+ * leave the style out, for the nearest named style to be picked.
+ */
+function fontNameInput(
+ args: { family?: string; style?: string; variations?: FigmaVariationSettings },
+ current: FigmaFontName | null
+): FigmaFontNameInput {
+ return {
+ family: args.family ?? current?.family ?? '',
+ style: args.style ?? (args.variations ? undefined : (current?.style ?? 'Regular')),
+ variationSettings: args.variations
+ }
+}
+
export const setFont = defineTool({
name: 'set_font',
@@ -39,13 +69,14 @@ export const setFont = defineTool({
size: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))),
style: v.optional(
v.pipe(v.string(), v.description('Font style (e.g. "Bold", "Regular", "Bold Italic")'))
- )
+ ),
+ variations: variationsInputSchema
}),
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) {
+ 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 =
@@ -53,9 +84,23 @@ export const setFont = defineTool({
? node.getRangeFontName(0, 1)
: node.fontName
const current = typeof fontName === 'symbol' ? null : fontName
- node.fontName = {
- family: args.family ?? current?.family ?? '',
- style: args.style ?? current?.style ?? 'Regular'
+ 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)
}
}
return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }
@@ -74,25 +119,28 @@ export const setFontRange = defineTool({
family: v.optional(v.pipe(v.string(), v.description('Font family name'))),
size: v.optional(toolNumber(v.pipe(v.number(), v.minValue(1), v.description('Font size')))),
style: v.optional(v.pipe(v.string(), v.description('Font style'))),
+ variations: variationsInputSchema,
color: v.optional(v.pipe(v.string(), v.description('Text color (hex)')))
}),
execute: (figma, args) => {
const node = figma.getNodeById(args.id)
if (!node) return nodeNotFound(args.id)
const { start, end } = args
- if (!args.family && !args.size && !args.style && !args.color) {
- return { error: 'set_font_range needs at least one of family, size, style, or color' }
+ if (!args.family && !args.size && !args.style && !args.variations && !args.color) {
+ return {
+ error: 'set_font_range needs at least one of family, size, style, variations, or color'
+ }
}
// The range methods reject an empty range or one past the text, before changing anything.
try {
if (args.size) node.setRangeFontSize(start, end, args.size)
- if (args.family || args.style) {
+ if (args.family || args.style || args.variations) {
const current = node.getRangeFontName(start, start + 1)
- const fontName = typeof current === 'symbol' ? null : current
- node.setRangeFontName(start, end, {
- family: args.family ?? fontName?.family ?? '',
- style: args.style ?? fontName?.style ?? 'Regular'
- })
+ node.setRangeFontName(
+ start,
+ end,
+ fontNameInput(args, typeof current === 'symbol' ? null : current)
+ )
}
if (args.color) {
node.setRangeFills(start, end, [
diff --git a/packages/core/tests/figma-api/text/styles.test.ts b/packages/core/tests/figma-api/text/styles.test.ts
index b743696d0..4b67b3621 100644
--- a/packages/core/tests/figma-api/text/styles.test.ts
+++ b/packages/core/tests/figma-api/text/styles.test.ts
@@ -1,8 +1,9 @@
-import { describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, test } from 'bun:test'
-import { expectFills } from '#core-tests/helpers/assert'
+import { expectDefined, expectFills } from '#core-tests/helpers/assert'
import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { fontManager } from '@open-pencil/core/text'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
@@ -15,16 +16,26 @@ function styledText(characters = 'Hello world\nSecond') {
return { api, text }
}
-const REGULAR = { family: 'Inter', style: 'Regular' }
+// Inter is variable, so its names read every axis it is drawn at.
+const REGULAR = { family: 'Inter', style: 'Regular', variationSettings: { opsz: 14, wght: 400 } }
const BLUE: Color = { r: 0, g: 0, b: 1, a: 1 }
const RGB_BLUE = { r: 0, g: 0, b: 1 }
-const BOLD = { family: 'Inter', style: 'Bold' }
+const BOLD = { family: 'Inter', style: 'Bold', variationSettings: { opsz: 14, wght: 700 } }
+const BOLD_NAME = { family: 'Inter', style: 'Bold' }
+
+beforeAll(async () => {
+ const inter = expectDefined(
+ await fontManager.fetchBundledFont('/InterVariable.ttf'),
+ 'bundled Inter font'
+ )
+ fontManager.markLoaded('Inter', 'Regular', inter)
+})
describe('styled text segments', () => {
test('split only where a requested field changes', () => {
const { text } = styledText()
text.setRangeFontSize(0, 5, 24)
- text.setRangeFontName(6, 11, BOLD)
+ text.setRangeFontName(6, 11, BOLD_NAME)
expect(text.getStyledTextSegments(['fontSize'])).toEqual([
{ characters: 'Hello', start: 0, end: 5, fontSize: 24 },
@@ -126,7 +137,7 @@ describe('character style ranges', () => {
test('read mixed on the node once ranges differ, and setting the node restyles every character', () => {
const { api, text } = styledText()
text.setRangeFontSize(0, 5, 24)
- text.setRangeFontName(6, 11, BOLD)
+ text.setRangeFontName(6, 11, BOLD_NAME)
expect<unknown>(text.fontSize).toBe(api.mixed)
expect<unknown>(text.fontName).toBe(api.mixed)
expect(text.getRangeFontSize(0, 8)).toBe(api.mixed)
diff --git a/packages/core/tests/figma-api/text/variations.test.ts b/packages/core/tests/figma-api/text/variations.test.ts
new file mode 100644
index 000000000..81509a558
--- /dev/null
+++ b/packages/core/tests/figma-api/text/variations.test.ts
@@ -0,0 +1,179 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+import { join } from 'node:path'
+
+import { FIXTURES } from '#core-tests/helpers/paths'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { fontManager } from '@open-pencil/core/text'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Behaviour measured in live Figma (2026-10-25) with its variable Inter and Roboto Flex. These
+// tests draw from our bundled Inter, whose axes are `opsz` and `wght`, with nine named instances
+// from Thin to Black.
+const VARIABLE = 'Variations Test'
+const STATIC = 'Variations Static'
+
+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()
+ fontManager.markLoaded(VARIABLE, 'Regular', variable)
+ fontManager.markLoaded(STATIC, 'Regular', static_)
+})
+
+function text(family = VARIABLE) {
+ const api = new FigmaAPI(new SceneGraph())
+ const node = api.createText()
+ node.fontName = { family, style: 'Regular' }
+ node.characters = 'Hamburg'
+ return { api, node }
+}
+
+describe('variable fonts in the plugin API', () => {
+ test('lists a family’s axis tags in code unit order, null for a static family', () => {
+ const { api } = text()
+ expect(api.getFontFamilyVariationAxes(VARIABLE)).toEqual(['opsz', 'wght'])
+ expect(api.getFontFamilyVariationAxes(STATIC)).toBeNull()
+ expect(() => api.getFontFamilyVariationAxes('Variations Unloaded')).toThrow(
+ 'in getFontFamilyVariationAxes: Font family "Variations Unloaded" is not available.'
+ )
+ })
+
+ test('reads every axis of a variable font, and none of a static one', () => {
+ expect(text().node.fontName).toEqual({
+ family: VARIABLE,
+ style: 'Regular',
+ variationSettings: { opsz: 14, wght: 400 }
+ })
+ expect(text(STATIC).node.fontName).toEqual({ family: STATIC, style: 'Regular' })
+ })
+
+ test('picks the nearest named style for axes without a style, the heavier where two tie', () => {
+ const { node } = text()
+ for (const [wght, style] of [
+ [900, 'Black'],
+ [650, 'Bold'],
+ [550, 'Semi Bold'],
+ [450, 'Medium'],
+ [1, 'Thin']
+ ] as const) {
+ node.setRangeFontName(0, node.characters.length, {
+ family: VARIABLE,
+ variationSettings: { wght }
+ })
+ expect(node.fontName).toMatchObject({ style, variationSettings: { wght } })
+ expect(node.fontWeight).toBe(wght)
+ }
+ })
+
+ test('keeps a named style under the axes set over it, and the current style with no axes', () => {
+ const { node } = text()
+ node.fontName = { family: VARIABLE, style: 'Regular', variationSettings: { wght: 550 } }
+ expect(node.fontName).toEqual({
+ family: VARIABLE,
+ style: 'Regular',
+ variationSettings: { opsz: 14, wght: 550 }
+ })
+ expect(node.fontWeight).toBe(550)
+ node.fontName = { family: VARIABLE, style: 'Bold' }
+ node.setRangeFontName(0, node.characters.length, { family: VARIABLE })
+ expect(node.fontName).toMatchObject({ style: 'Bold', variationSettings: { wght: 700 } })
+ })
+
+ test('keeps the axes and the slant the text set when axes alone change', () => {
+ const { node } = text()
+ node.fontName = { family: VARIABLE, style: 'Italic' }
+ node.setRangeFontName(0, 7, { family: VARIABLE, variationSettings: { wght: 650 } })
+ node.setRangeFontName(0, 7, { family: VARIABLE, variationSettings: { opsz: 20 } })
+ // The optical size still follows the font size, so only the weight shows it was kept.
+ expect(node.fontName).toMatchObject({
+ style: 'Bold Italic',
+ variationSettings: { opsz: 14, wght: 650 }
+ })
+ node.fontName = { family: VARIABLE, style: 'Regular' }
+ expect(node.fontName).toMatchObject({ variationSettings: { opsz: 14, wght: 400 } })
+ })
+
+ test('reads the axes of the face in the text’s slant', async () => {
+ const data = await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()
+ const upright = data.slice(0)
+ const italic = data.slice(0)
+ fontManager.markLoaded('Variations Slant', 'Regular', upright)
+ fontManager.markLoaded('Variations Slant', 'Italic', italic)
+ expect(fontManager.familyVariation('Variations Slant', true)?.data).toBe(italic)
+ expect(fontManager.familyVariation('Variations Slant', false)?.data).toBe(upright)
+ })
+
+ test('rejects axes the family does not have, as Figma does, and axes of a family not loaded', () => {
+ const { node } = text()
+ expect(() => {
+ node.fontName = { family: VARIABLE, style: 'Regular', variationSettings: { slnt: -10 } }
+ }).toThrow(
+ 'in set_fontName: "slnt" is not a valid variation setting. Valid settings are ["opsz","wght"].'
+ )
+ expect(() => {
+ node.fontName = { family: STATIC, style: 'Regular', variationSettings: { wght: 700 } }
+ }).toThrow(
+ `in set_fontName: "wght" is not a valid variation setting. Font "${STATIC}" has no variation axes.`
+ )
+ expect(() => {
+ node.fontName = {
+ family: 'Variations Unloaded',
+ style: 'Regular',
+ variationSettings: { wght: 700 }
+ }
+ }).toThrow('in set_fontName: Font family "Variations Unloaded" is not loaded')
+ })
+
+ test('reads an optical size that follows the font size as the style’s own', () => {
+ const { node } = text()
+ node.fontSize = 48
+ expect(node.fontName).toMatchObject({ variationSettings: { opsz: 14 } })
+ })
+
+ test('sets a range’s font from axes alone', () => {
+ const { node } = text()
+ node.setRangeFontName(0, 3, { family: VARIABLE, variationSettings: { wght: 700 } })
+ expect(node.getRangeFontName(0, 3)).toEqual({
+ family: VARIABLE,
+ style: 'Bold',
+ variationSettings: { opsz: 14, wght: 700 }
+ })
+ expect(node.getRangeFontName(3, 7)).toMatchObject({ style: 'Regular' })
+ })
+
+ test('loads every style of a family named alone, one of each slant before the rest', async () => {
+ const loaded: string[] = []
+ const events: string[] = []
+ // Only the host knows the family, so no web provider is asked for its faces.
+ const providers = fontManager.enabledOnlineFontProviders()
+ fontManager.setOnlineFontProviders({})
+ fontManager.setHostFontCatalog([
+ { family: 'Variations Load', styles: ['Regular', 'Bold', 'Regular Italic', 'Bold Italic'] }
+ ])
+ const data = await Bun.file(join(FIXTURES, 'fonts', 'InterRegular-Faces.ttf')).arrayBuffer()
+ fontManager.setHostFontLoader(async (family, style) => {
+ if (family !== 'Variations Load') return null
+ loaded.push(style)
+ events.push(`start ${style}`)
+ await Promise.resolve()
+ events.push(`end ${style}`)
+ return data.slice(0)
+ })
+ try {
+ await new FigmaAPI(new SceneGraph()).loadFontAsync({ family: 'Variations Load' })
+ } finally {
+ fontManager.setHostFontLoader(null)
+ fontManager.setHostFontCatalog([])
+ fontManager.setOnlineFontProviders(
+ Object.fromEntries(providers.map((provider) => [provider, true]))
+ )
+ }
+ expect(loaded.sort()).toEqual(['Bold', 'Bold Italic', 'Regular', 'Regular Italic'])
+ for (const style of ['Regular', 'Bold', 'Regular Italic', 'Bold Italic'])
+ expect(fontManager.loadedData('Variations Load', style)).not.toBeNull()
+ // A variable file the first style of a slant loads is there for the others to reuse.
+ const firstDone = Math.max(events.indexOf('end Regular'), events.indexOf('end Regular Italic'))
+ const restStart = Math.min(events.indexOf('start Bold'), events.indexOf('start Bold Italic'))
+ expect(firstDone).toBeLessThan(restStart)
+ })
+})
diff --git a/packages/core/tests/tools/create/svg.test.ts b/packages/core/tests/tools/create/svg.test.ts
index 629dc2027..dcd36b5d7 100644
--- a/packages/core/tests/tools/create/svg.test.ts
+++ b/packages/core/tests/tools/create/svg.test.ts
@@ -8,10 +8,10 @@ describe('import_svg', () => {
test('loads the fonts its text uses before creating the text', async () => {
const graph = new SceneGraph()
const figma = new FigmaAPI(graph)
- const loaded: Array<{ family: string; style: string; textsSoFar: number }> = []
+ const loaded: Array<{ family: string; style?: string; textsSoFar: number }> = []
figma.loadFontAsync = async (font) => {
const textsSoFar = [...graph.getAllNodes()].filter((node) => node.type === 'TEXT').length
- loaded.push({ ...font, textsSoFar })
+ loaded.push({ family: font.family, style: font.style, textsSoFar })
}
await importSVG.execute(figma, {
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 3f73de3c0..89879a538 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -233,7 +233,7 @@ Common node properties are readable/writable through the proxy, including:
- Geometry: `x`, `y`, `width`, `height`, `rotation`, `resize(width, height)`
- Appearance: `fills`, `strokes`, `effects`, `opacity`, `visible`, `locked`, `blendMode`, `clipsContent`
- Radius: `cornerRadius`, `topLeftRadius`, `topRightRadius`, `bottomRightRadius`, `bottomLeftRadius`
-- Text: `characters`, `fontSize`, `fontName`, `fontWeight`, `fills`, `letterSpacing`, `lineHeight`, and `textDecoration`, which read `figma.mixed` while characters differ and restyle every character when set, and alignment
+- Text: `characters`, `fontSize`, `fontName` (with `variationSettings`, every axis of a variable font), `fontWeight` (a variable font's `wght`), `fills`, `letterSpacing`, `lineHeight`, and `textDecoration`, which read `figma.mixed` while characters differ and restyle every character when set, and alignment
- Text ranges: `getStyledTextSegments(fields, start?, end?)`, and `getRange…` / `setRange…` for `FontSize`, `FontName`, `Fills`, `LetterSpacing`, `LineHeight`, `TextDecoration` with its `Style`, `Offset`, `Thickness`, `Color`, and `SkipInk`, `TextCase`, `Hyperlink` (a `{ type: 'URL' | 'NODE', value }` link, or `null`), `TextStyleId` and `FillStyleId` (set with `setRangeTextStyleIdAsync` and `setRangeFillStyleIdAsync`, which give the range the style's fields), and `getRangeBoundVariable` / `setRangeBoundVariable` for the text fields Figma binds, plus `getRangeFontWeight`, `getRangeAllFontNames`, and `getRangeOpenTypeFeatures`. Lengths read in pixels; a percent given to a setter is of the font size
- Text lists and paragraphs: `getRangeListOptions` / `setRangeListOptions` for bulleted (`UNORDERED`) and numbered (`ORDERED`) items, `getRangeIndentation` / `setRangeIndentation` for nesting (1–5 for list items), `listSpacing`, `paragraphSpacing`, and `paragraphIndent` for the whole text (`figma.mixed` when paragraphs differ) or per paragraph with `getRangeListSpacing` / `setRangeListSpacing`, `getRangeParagraphSpacing` / `setRangeParagraphSpacing`, and `getRangeParagraphIndent` / `setRangeParagraphIndent`, and `hangingList`
- Auto-layout: `layoutMode`, `primaryAxisAlignItems`, `counterAxisAlignItems`, `itemSpacing`, padding, sizing, and layout positioning fields
@@ -246,7 +246,9 @@ 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)` no-ops because OpenPencil does not gate text edits on plugin font loading
+- `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.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
- `figma.getNodeByIdAsync(id)` and `instance.getMainComponentAsync()` resolve to the same nodes as `figma.getNodeById(id)` and `instance.mainComponent`, for scripts written for Figma's dynamic-page mode
- `figma.setCurrentPageAsync(page)` switches pages as setting `figma.currentPage` does, and `page.loadAsync()` resolves at once because every page is already loaded, for scripts written for Figma's dynamic-page mode
diff --git a/tests/engine/tools/modify.test.ts b/tests/engine/tools/modify.test.ts
index 40d3ddb4f..37cad4ee1 100644
--- a/tests/engine/tools/modify.test.ts
+++ b/tests/engine/tools/modify.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, test } from 'bun:test'
import { computeAllLayouts } from '@open-pencil/core/layout'
+import { fontManager } from '@open-pencil/core/text'
import { expectDefined, expectFills, getNodeOrThrow } from '#tests/helpers/assert'
+import { repoPath } from '#tests/helpers/paths'
import { getTool, setupToolTest, type ToolResult } from '#tests/helpers/tools'
describe('set_fill', () => {
@@ -241,7 +243,7 @@ describe('set_font_range', () => {
error: expect.stringContaining('Range outside of available characters')
})
expect(setFontRange.execute(figma, { id, start: 2, end: 2 })).toEqual({
- error: 'set_font_range needs at least one of family, size, style, or color'
+ error: 'set_font_range needs at least one of family, size, style, variations, or color'
})
expect(getNodeOrThrow(graph, id).styleRuns).toEqual([])
})
@@ -307,3 +309,31 @@ describe('set_font_range', () => {
).toBeCloseTo(1)
})
})
+
+describe('set_font', () => {
+ test('sets variable font axes, picking the nearest named style when none is given', async () => {
+ const family = 'Tool Variations'
+ fontManager.markLoaded(
+ family,
+ 'Regular',
+ await Bun.file(repoPath('tests/fixtures/fonts/InterVariable-Latin.ttf')).arrayBuffer()
+ )
+ 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 } })
+ ).toMatchObject({
+ fontName: { family, style: 'Bold', variationSettings: { wght: 650 } }
+ })
+ expect(
+ setFont.execute(figma, { 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({
+ error:
+ 'in setRangeFontName: "slnt" is not a valid variation setting. Valid settings are ["opsz","wght"].'
+ })
+ })
+})