Skip to content

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

feat: set variable font axes in the panel, and embed fallback fonts in PDFs (#1559)

Danila Poyarkovece1045650fb
diff --git a/changes/1528/changed.md b/changes/1528/changed.md
index a0f0c6d01..062a1ce1c 100644
--- a/changes/1528/changed.md
+++ b/changes/1528/changed.md
@@ -1 +1 @@
-- PDF exports from the editor embed the fonts their text uses, and keep each paragraph broken into the lines the canvas draws, instead of drawing text in a standard PDF font. Text in a variable font is embedded as a static instance at the weight, optical size, and other axes it is drawn with.
+- PDF exports from the editor embed the fonts their text uses, and keep each paragraph broken into the lines the canvas draws, instead of drawing text in a standard PDF font. Text in a variable font is embedded as a static instance at the weight, optical size, and other axes it is drawn with. Characters a font lacks, such as Chinese or Arabic in a Latin font, are embedded in the fallback font the canvas draws them in, at the same weight.
diff --git a/changes/1559/added.md b/changes/1559/added.md
new file mode 100644
index 000000000..3646042c6
--- /dev/null
+++ b/changes/1559/added.md
@@ -0,0 +1 @@
+- Set the axes of a variable font, such as its weight, width, or optical size, in the Typography section, or let the optical size follow the font size, as in Figma.
diff --git a/changes/1559/fixed.md b/changes/1559/fixed.md
new file mode 100644
index 000000000..b2593d70d
--- /dev/null
+++ b/changes/1559/fixed.md
@@ -0,0 +1 @@
+- Undoing a dragged font size, line height, or letter spacing back to where a document was saved marks it saved again, instead of keeping it marked as edited.
diff --git a/packages/core/src/canvas/index.ts b/packages/core/src/canvas/index.ts
index a089ed11e..7f6adce49 100644
--- a/packages/core/src/canvas/index.ts
+++ b/packages/core/src/canvas/index.ts
@@ -43,3 +43,4 @@ export type {
export { hitTestStatusLabels, type PlacedStatusLabel } from './labels/status'
export { LabelCache, type CachedComponent, type CachedSection } from './labels/cache'
export { withFigExportRuntime } from './text/shape'
+export { drawnFontAxes, type DrawnFontAxes, type DrawnFontAxis } from './text/font-families'
diff --git a/packages/core/src/canvas/text/font-families.ts b/packages/core/src/canvas/text/font-families.ts
index 43ab16d81..e38f2d893 100644
--- a/packages/core/src/canvas/text/font-families.ts
+++ b/packages/core/src/canvas/text/font-families.ts
@@ -7,6 +7,7 @@ import { ResourceCache } from '#core/cache/resource'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
import type { FamilyFace } from '#core/text/font/faces'
+import type { FontAxis } from '#core/text/font/variation'
import { fontManager, fontWeightMatchOrder } from '#core/text/fonts'
const familiesCache = new ResourceCache<string, string[]>({ maxEntries: 256 })
@@ -40,6 +41,25 @@ export function drawnFontVariations(font: DrawnFontAxes): FontVariation[] {
return [...axes].map(([axis, value]) => ({ axis, value }))
}
+/** An axis of the variable font text is drawn in, with the value it is drawn at. */
+export interface DrawnFontAxis extends FontAxis {
+ value: number
+}
+
+/**
+ * The axes of the variable font text is drawn in, in the font's order, each at the value it is
+ * drawn at, within its range. `null` when the family's loaded faces are static or it has none.
+ */
+export function drawnFontAxes(font: DrawnFontAxes): DrawnFontAxis[] | null {
+ const variation = fontManager.familyVariation(font.family, font.italic)
+ if (!variation) return null
+ const drawn = new Map(drawnFontVariations(font).map(({ axis, value }) => [axis, value]))
+ return variation.axes.map((axis) => ({
+ ...axis,
+ value: Math.min(axis.max, Math.max(axis.min, drawn.get(axis.tag) ?? axis.default))
+ }))
+}
+
/**
* The loaded face of a family that text asking for a style is drawn in: that style, or the
* nearest loaded weight in the same slant, then the other, as font matching picks it; `null`
diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.ts
index 02443b4ae..ab80b8551 100644
--- a/packages/core/src/canvas/text/placed.ts
+++ b/packages/core/src/canvas/text/placed.ts
@@ -14,7 +14,12 @@ import type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'
import { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { ELLIPSIS } from '#core/text/ellipsis'
-import { glyphOutlineSourceSync, type GlyphOutlineSource } from '#core/text/font/glyphs'
+import {
+ glyphOutlineSourceSync,
+ shardCovers,
+ type GlyphOutlineSource
+} from '#core/text/font/glyphs'
+import { fontManager } from '#core/text/fonts'
type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]
@@ -64,32 +69,67 @@ function fontAt(node: SceneNode, index: number) {
return { family, weight, italic, style, variations, drawn }
}
+/**
+ * The style a family of the paragraph is drawn in: the face its own family draws the asked style
+ * in, and Regular for the Arabic and CJK fallbacks, as the paragraph asks CanvasKit for them.
+ */
+function sourceStyle(family: string, font: ReturnType<typeof fontAt>): string | null {
+ const scriptFallback =
+ family !== font.family &&
+ (fontManager.getArabicFallbackFamilies().includes(family) ||
+ fontManager.getCJKFallbackFamilies().includes(family))
+ if (scriptFallback) return fontManager.isStyleLoaded(family, 'Regular') ? 'Regular' : null
+ return loadedStyle(family, font.drawn.weight, font.drawn.italic)
+}
+
/** The outline source of each font the paragraph may have drawn a character in, in its order. */
function* candidateSources(font: ReturnType<typeof fontAt>) {
for (const family of paragraphSourceFamilies(font.family)) {
- const style = loadedStyle(family, font.drawn.weight, font.drawn.italic)
+ const style = sourceStyle(family, font)
const source = style ? glyphOutlineSourceSync(family, style, font.variations) : null
if (source) yield source
}
}
+/** The face and file the paragraph draws a character in. */
+export interface CharacterFace {
+ family: string
+ style: string
+ /** Which of the style's files: 0 for its own, then its shards, as `FontManager.shardData` lists them. */
+ file: number
+ /** Whether it is not the character's own family. */
+ fallback: boolean
+}
+
/**
- * The family the paragraph draws the character at `index` of `text` in, as it falls back: the
- * first of the fonts it lists, the style's own then its fallbacks, that maps the character.
+ * The loaded face the paragraph draws the character at `index` of `text` in, as it falls back:
+ * of the fonts it lists, the style's own then its fallbacks, each file then its shards, the first
+ * that maps the character.
*/
-export function characterFamily(node: SceneNode, text: string, index: number): string | null {
+export function characterFace(node: SceneNode, text: string, index: number): CharacterFace | null {
const codePoint = text.codePointAt(index)
if (codePoint === undefined) return null
const character = String.fromCodePoint(codePoint)
const font = fontAt(node, index)
for (const family of paragraphSourceFamilies(font.family)) {
- const style = loadedStyle(family, font.drawn.weight, font.drawn.italic)
- if (style && glyphOutlineSourceSync(family, style, font.variations)?.covers(character))
- return family
+ const style = sourceStyle(family, font)
+ if (!style) continue
+ const fallback = family !== font.family
+ if (glyphOutlineSourceSync(family, style, font.variations)?.covers(character))
+ return { family, style, file: 0, fallback }
+ const shard = fontManager
+ .shardData(family, style)
+ .findIndex((data) => shardCovers(data, character))
+ if (shard !== -1) return { family, style, file: shard + 1, fallback }
}
return null
}
+/** The family the paragraph draws the character at `index` of `text` in; see {@link characterFace}. */
+export function characterFamily(node: SceneNode, text: string, index: number): string | null {
+ return characterFace(node, text, index)?.family ?? null
+}
+
/** Whether a glyph the shaper chose is the one the font maps its character to. */
function drawsOwnGlyph(
source: GlyphOutlineSource,
diff --git a/packages/core/src/io/formats/pdf/document.ts b/packages/core/src/io/formats/pdf/document.ts
index d514c77f7..6a7e01ed0 100644
--- a/packages/core/src/io/formats/pdf/document.ts
+++ b/packages/core/src/io/formats/pdf/document.ts
@@ -1,5 +1,7 @@
import type { SceneGraph } from '@open-pencil/scene-graph'
+import { fontManager } from '#core/text/fonts'
+
import { renderPagesToPDFDetailed, type PDFExportResult } from './export'
import type { PDFPageSpec } from './plan'
import { pdfFontFaces, preparePagesForPDF, preparePDFFonts, withPDFTextLayout } from './prepare'
@@ -26,6 +28,14 @@ export async function exportPDFDocument(
: await preparePDFFonts(graph, specs)
const fonts = options.embedFonts ? pdfFontFaces(status) : undefined
return withPDFTextLayout((textLayout) =>
- renderPagesToPDFDetailed(graph, specs, { fonts, textLayout, title: options.title })
+ renderPagesToPDFDetailed(graph, specs, {
+ fonts,
+ textLayout,
+ fallbackFile: (family, style, file) =>
+ file === 0
+ ? fontManager.loadedData(family, style)
+ : (fontManager.shardData(family, style)[file - 1] ?? null),
+ title: options.title
+ })
)
}
diff --git a/packages/core/src/io/formats/pdf/export.ts b/packages/core/src/io/formats/pdf/export.ts
index ea5d7aae9..5f42cf178 100644
--- a/packages/core/src/io/formats/pdf/export.ts
+++ b/packages/core/src/io/formats/pdf/export.ts
@@ -9,6 +9,7 @@ import {
embeddedFontAlias,
planFontEmbedding,
registerEmbeddedFonts,
+ type PDFFallbackFontFile,
type PDFFontFace,
type PDFFontReport
} from './fonts'
@@ -20,6 +21,8 @@ export interface PDFExportOptions {
fonts?: readonly PDFFontFace[]
/** Line breaks of text nodes as the editor laid them out, so paragraphs stay wrapped. */
textLayout?: SVGTextLayout
+ /** The files of fallback faces the text layout draws characters in, to embed them too. */
+ fallbackFile?: PDFFallbackFontFile
}
export interface PDFExportResult {
@@ -81,7 +84,7 @@ async function renderPages(
options: PDFExportOptions,
parse: SVGPageParser
): Promise<PDFExportResult | null> {
- const embedding = options.fonts ? planFontEmbedding(options.fonts) : null
+ const embedding = options.fonts ? planFontEmbedding(options.fonts, options.fallbackFile) : null
const svgOptions: PageSVGOptions = {
textLayout: options.textLayout,
fontAlias: embedding ? embeddedFontAlias(embedding) : undefined
diff --git a/packages/core/src/io/formats/pdf/fonts.ts b/packages/core/src/io/formats/pdf/fonts.ts
index d6be4e010..cdfd007aa 100644
--- a/packages/core/src/io/formats/pdf/fonts.ts
+++ b/packages/core/src/io/formats/pdf/fonts.ts
@@ -18,6 +18,8 @@ import { hasTrueTypeOutlines, isVariableFont } from '#core/text/font/variation'
export interface PDFFontFace {
family: string
style: string
+ /** Which of the style's files, 0 for its own then its shards; 0 when left out. */
+ file?: number
data: ArrayBuffer | null
/** Why there is no file, when `data` is null. */
missing?: string
@@ -50,12 +52,26 @@ interface PendingInstance {
label: string
}
+/**
+ * A file the canvas draws characters from for want of glyphs in their text's own: of a fallback
+ * face, or a shard of a split one, `file` 0 for the style's own then its shards.
+ */
+export type PDFFallbackFontFile = (
+ family: string,
+ style: string,
+ file: number
+) => ArrayBuffer | null
+
/**
* The faces to embed, by family and style, and what happened to each face. Instances of variable
- * faces are named as the pages ask for them, and cut by {@link cutFontInstances}.
+ * faces are named as the pages ask for them, and cut by {@link cutFontInstances}; so are fallback
+ * faces, whose files `fallbackFile` gives.
*/
export interface PDFFontEmbedding {
faces: Map<string, EmbeddedFace>
+ /** Every face planned, embedded or not, so each is looked at once. */
+ planned: Set<string>
+ fallbackFile?: PDFFallbackFontFile
variable: Map<string, { data: ArrayBuffer; label: string }>
/** Each instance's alias, or null once it could not be cut. */
instances: Map<string, string | null>
@@ -64,7 +80,14 @@ export interface PDFFontEmbedding {
report: PDFFontReport
}
-const faceKey = (family: string, style: string) => `${family}\0${style}`
+const faceKey = (face: { family: string; style: string; file?: number }) =>
+ `${face.family}\0${face.style}\0${face.file ?? 0}`
+
+/** A face as the report names it; a shard by its place among the style's files. */
+const faceLabel = (face: { family: string; style: string; file?: number }) =>
+ face.file
+ ? `${face.family} ${face.style} (file ${face.file + 1})`
+ : `${face.family} ${face.style}`
/** Why jsPDF cannot embed a font file, or null when it can. */
function unsupportedReason(data: ArrayBuffer): string | null {
@@ -81,37 +104,46 @@ function dropInstance(embedding: PDFFontEmbedding, alias: string): void {
}
}
+/** Plans one face: a static file to embed, a variable file to cut, or a reported fallback. */
+function planFace(embedding: PDFFontEmbedding, face: PDFFontFace): void {
+ const key = faceKey(face)
+ embedding.planned.add(key)
+ const label = faceLabel(face)
+ if (!face.data) {
+ embedding.report.fallback.push({
+ face: label,
+ reason: face.missing ?? 'font file not available'
+ })
+ return
+ }
+ const reason = unsupportedReason(face.data)
+ if (reason) {
+ embedding.report.fallback.push({ face: label, reason })
+ return
+ }
+ if (isVariableFont(face.data)) {
+ embedding.variable.set(key, { data: face.data, label })
+ return
+ }
+ embedding.faces.set(key, { alias: aliasOf(embedding), data: face.data, label })
+}
+
/** Picks the faces jsPDF can embed, each under a family name of its own. */
-export function planFontEmbedding(faces: readonly PDFFontFace[]): PDFFontEmbedding {
+export function planFontEmbedding(
+ faces: readonly PDFFontFace[],
+ fallbackFile?: PDFFallbackFontFile
+): PDFFontEmbedding {
const embedding: PDFFontEmbedding = {
faces: new Map(),
+ planned: new Set(),
+ fallbackFile,
variable: new Map(),
instances: new Map(),
pending: [],
aliases: 0,
report: { embedded: [], fallback: [] }
}
- for (const face of faces) {
- const label = `${face.family} ${face.style}`
- if (!face.data) {
- embedding.report.fallback.push({
- face: label,
- reason: face.missing ?? 'font file not available'
- })
- continue
- }
- const reason = unsupportedReason(face.data)
- if (reason) {
- embedding.report.fallback.push({ face: label, reason })
- continue
- }
- const key = faceKey(face.family, face.style)
- if (isVariableFont(face.data)) {
- embedding.variable.set(key, { data: face.data, label })
- continue
- }
- embedding.faces.set(key, { alias: aliasOf(embedding), data: face.data, label })
- }
+ for (const face of faces) planFace(embedding, face)
return embedding
}
@@ -123,7 +155,7 @@ function instanceAlias(
): string | null {
const variations = fontInstanceVariations(face.data, drawnFontVariations(font))
const axes = variations.map(({ axis, value }) => `${axis} ${value}`).join(', ')
- const key = `${faceKey(font.family, font.style)}\0${axes}`
+ const key = `${faceKey(font)}\0${axes}`
const known = embedding.instances.get(key)
if (known !== undefined) return known
const alias = aliasOf(embedding)
@@ -136,7 +168,13 @@ function instanceAlias(
/** The family the SVG names each embedded face by. */
export function embeddedFontAlias(embedding: PDFFontEmbedding): SVGFontAlias {
return (font) => {
- const key = faceKey(font.family, font.style)
+ const key = faceKey(font)
+ // A fallback face or shard is planned the first time the pages draw characters in it.
+ if (!embedding.planned.has(key) && embedding.fallbackFile) {
+ const file = font.file ?? 0
+ const data = embedding.fallbackFile(font.family, font.style, file)
+ planFace(embedding, { family: font.family, style: font.style, file, data })
+ }
const variable = embedding.variable.get(key)
if (variable) return instanceAlias(embedding, variable, font)
return embedding.faces.get(key)?.alias ?? null
diff --git a/packages/core/src/io/formats/pdf/prepare.ts b/packages/core/src/io/formats/pdf/prepare.ts
index 838b65cbc..79505f38a 100644
--- a/packages/core/src/io/formats/pdf/prepare.ts
+++ b/packages/core/src/io/formats/pdf/prepare.ts
@@ -1,31 +1,55 @@
+import { uniq } from 'es-toolkit'
+
import type { ShapedTextGlyph } from '@open-pencil/fig/node-change'
-import type { SceneGraph } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { characterFace } from '#core/canvas/text/placed'
import { withTextShaper } from '#core/canvas/text/shape'
import { getCanvasKit } from '#core/canvaskit'
import { populateFigPage } from '#core/io/formats/fig'
-import type { SVGCharacterEdges, SVGTextLayout } from '#core/io/formats/svg'
+import type { SVGCharacterEdges, SVGFallbackFace, SVGTextLayout } from '#core/io/formats/svg'
import { computeAllLayouts } from '#core/layout'
import { shownText } from '#core/text/case'
+import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
+import { ARABIC_CHARACTER } from '#core/text/fallbacks'
import type { DocumentFontStatus } from '#core/text/font/status'
import { fontManager } from '#core/text/fonts'
import { prepareGraphFonts } from '#core/text/prepare'
+import { collectGraphFontRequirements } from '#core/text/requirements'
import type { PDFFontFace } from './fonts'
import type { PDFPageSpec } from './plan'
/**
* Loads every font the text of these pages draws with, as the canvas does: the faces, the
- * characters remote fonts must cover, and the script and emoji fallbacks.
+ * characters remote fonts must cover, and the script and emoji fallbacks. Fonts loaded for some
+ * characters only cover the ones jsPDF writes too.
*/
-export function preparePDFFonts(
+export async function preparePDFFonts(
graph: SceneGraph,
specs: readonly PDFPageSpec[]
): Promise<DocumentFontStatus> {
- return prepareGraphFonts(
- graph,
- specs.flatMap((spec) => spec.nodeIds)
- )
+ const nodeIds = specs.flatMap((spec) => spec.nodeIds)
+ return prepareGraphFonts(graph, nodeIds, await pdfWrittenCharacters(graph, nodeIds))
+}
+
+/**
+ * Characters jsPDF writes for the text besides its own: it writes Arabic letters as their
+ * presentation forms, picked by the letters around them, so the embedded fonts must map those.
+ */
+async function pdfWrittenCharacters(
+ graph: SceneGraph,
+ nodeIds: readonly string[]
+): Promise<string> {
+ const texts = collectGraphFontRequirements(graph, nodeIds)
+ .nodes.filter((node) => node.type === 'TEXT')
+ .map(shownText)
+ .filter((text) => ARABIC_CHARACTER.test(text))
+ if (texts.length === 0) return ''
+ const { jsPDF } = await import('jspdf')
+ // jsPDF adds its Arabic parser to each document it makes, as the one it writes the text with.
+ const writer = new jsPDF()
+ return uniq(texts.flatMap((text) => Array.from(writer.processArabic(text)))).join('')
}
/**
@@ -84,18 +108,40 @@ export async function withPDFTextLayout<T>(
const shaped = shape(node)
if (!shaped?.baselines.length) return null
const characters = characterEdges(shaped.glyphs)
+ const fallbacks = fallbackFaces(node, characters)
return shaped.baselines.map((line) => ({
start: line.firstCharacter,
end: line.endCharacter,
x: line.position.x,
y: line.position.y,
width: line.width,
- characters
+ characters,
+ fallbacks
}))
})
)
}
+/**
+ * The face of each drawn character the canvas draws from another file than its text's own: a
+ * fallback font, such as for Chinese in Inter, or a shard of a font split by unicode-range. Emoji
+ * keep their own family: the face the canvas lays them out with has no glyphs to embed.
+ */
+function fallbackFaces(
+ node: SceneNode,
+ characters: ReadonlyMap<number, SVGCharacterEdges>
+): Map<number, SVGFallbackFace> {
+ const text = shownText(node)
+ const fallbacks = new Map<number, SVGFallbackFace>()
+ for (const index of characters.keys()) {
+ const face = characterFace(node, text, index)
+ if (!face || (!face.fallback && face.file === 0) || face.family === EMOJI_METRICS_FAMILY)
+ continue
+ fallbacks.set(index, { family: face.family, style: face.style, file: face.file })
+ }
+ return fallbacks
+}
+
/** The left and right edges of the glyphs each character is drawn with. */
function characterEdges(glyphs: readonly ShapedTextGlyph[]): Map<number, SVGCharacterEdges> {
const edges = new Map<number, SVGCharacterEdges>()
diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.ts
index 3dd372ed8..aa5afa67d 100644
--- a/packages/core/src/io/formats/svg/defs.ts
+++ b/packages/core/src/io/formats/svg/defs.ts
@@ -26,6 +26,8 @@ import type { SVGTextLayout } from './text/lines'
* `opticalSizeFromFontSize` is off, and the axes the text sets.
*/
export interface SVGFontRequest extends FontFaceRef {
+ /** Which of the style's files draws the text, 0 for its own then its shards; 0 when left out. */
+ file?: number
fontSize: number
variations: readonly FontVariation[]
opticalSizeFromFontSize: boolean
diff --git a/packages/core/src/io/formats/svg/index.ts b/packages/core/src/io/formats/svg/index.ts
index c7d274272..dbcf2d41c 100644
--- a/packages/core/src/io/formats/svg/index.ts
+++ b/packages/core/src/io/formats/svg/index.ts
@@ -15,6 +15,6 @@ export {
} from './import'
export { isSVGMarkup } from './metadata'
export type { SVGFontAlias, SVGFontRequest } from './defs'
-export type { SVGCharacterEdges, SVGTextLayout, SVGTextLine } from './text/lines'
+export type { SVGCharacterEdges, SVGFallbackFace, SVGTextLayout, SVGTextLine } from './text/lines'
export { svgImportFonts } from './text/import'
export { renderSVGNode, svg, type SVGNode } from './node'
diff --git a/packages/core/src/io/formats/svg/text/export.ts b/packages/core/src/io/formats/svg/text/export.ts
index 6668bf191..6ef4b1d9f 100644
--- a/packages/core/src/io/formats/svg/text/export.ts
+++ b/packages/core/src/io/formats/svg/text/export.ts
@@ -1,7 +1,9 @@
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
import { textLengthPixels } from '@open-pencil/scene-graph/text'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
+import { drawnFontVariations } from '#core/canvas/text/font-families'
import {
formatColor,
type SVGExportContext,
@@ -14,7 +16,8 @@ import {
explicitNewlineLines,
laidOutTextSpans,
textStyleSpans,
- type SpanAttrs
+ type SpanAttrs,
+ type SVGFallbackFace
} from '#core/io/formats/svg/text/lines'
import { shownText } from '#core/text/case'
import { textFontFace } from '#core/text/requirements'
@@ -79,14 +82,44 @@ function aliasedFontAttrs(
}
}
-/** The face a run of `node` is drawn in, with the size and axes its instance follows. */
-function fontRequest(node: SceneNode, style: CharacterStyleOverride = {}): SVGFontRequest {
- return {
+/**
+ * The font attributes of a span: its face's alias where there is one, otherwise the family of the
+ * fallback face that draws it, if any.
+ */
+function spanFontAttrs(
+ node: SceneNode,
+ style: CharacterStyleOverride,
+ fallback: SVGFallbackFace | undefined,
+ fontAlias: SVGFontAlias | undefined
+): Record<string, string | number> {
+ if (fontAlias) return aliasedFontAttrs(fontRequest(node, style, fallback), fontAlias)
+ return fallback ? { 'font-family': fallback.family } : {}
+}
+
+/**
+ * The face a run of `node` is drawn in, or the fallback face that draws its characters instead,
+ * with the size and axes its instance follows. A fallback is drawn at the axes the run's own font
+ * is drawn at, as the paragraph draws every font it falls back to.
+ */
+function fontRequest(
+ node: SceneNode,
+ style: CharacterStyleOverride = {},
+ fallback?: SVGFallbackFace
+): SVGFontRequest {
+ const own: SVGFontRequest = {
...textFontFace(node, style),
fontSize: style.fontSize ?? node.fontSize,
variations: style.fontVariations ?? node.fontVariations,
opticalSizeFromFontSize: node.opticalSizeFromFontSize
}
+ if (!fallback) return own
+ return {
+ ...own,
+ ...fallback,
+ ...parseFontStyle(fallback.style),
+ variations: drawnFontVariations(own),
+ opticalSizeFromFontSize: false
+ }
}
function isLogicalTextEnd(node: SceneNode, direction: 'LTR' | 'RTL'): boolean {
@@ -171,9 +204,9 @@ export function renderTextNode(
'letter-spacing': letterSpacing ? round(letterSpacing) : undefined,
...(fontAlias ? aliasedFontAttrs(fontRequest(node), fontAlias) : {})
}
- const spanAttrs = (style: CharacterStyleOverride) => ({
+ const spanAttrs = (style: CharacterStyleOverride, fallback?: SVGFallbackFace) => ({
...styleOverrideToTspanAttrs(style, colorSpace, fillOpacity, node),
- ...(fontAlias ? aliasedFontAttrs(fontRequest(node, style), fontAlias) : {})
+ ...spanFontAttrs(node, style, fallback, fontAlias)
})
if (laidOut) {
diff --git a/packages/core/src/io/formats/svg/text/lines.ts b/packages/core/src/io/formats/svg/text/lines.ts
index 32cc8299d..1437214df 100644
--- a/packages/core/src/io/formats/svg/text/lines.ts
+++ b/packages/core/src/io/formats/svg/text/lines.ts
@@ -22,6 +22,21 @@ export interface SVGTextLine {
* after the span before it, which a renderer measures in fonts of its own.
*/
characters?: ReadonlyMap<number, SVGCharacterEdges>
+ /**
+ * The face that draws each character the editor draws from another file than its text's own,
+ * by index in `node.text`: a fallback font, such as for Chinese in a Latin family, or a shard of
+ * a font split by unicode-range. Spans then name that face, for a renderer that draws only the
+ * fonts it is given.
+ */
+ fallbacks?: ReadonlyMap<number, SVGFallbackFace>
+}
+
+/** A face, and which of its style's files, that draws characters their own file has no glyphs for. */
+export interface SVGFallbackFace {
+ family: string
+ style: string
+ /** 0 for the style's own file, then its shards. */
+ file: number
}
export interface SVGCharacterEdges {
@@ -36,7 +51,8 @@ export interface SVGCharacterEdges {
export type SVGTextLayout = (node: SceneNode) => readonly SVGTextLine[] | null
export type SpanAttrs = (
- style: CharacterStyleOverride
+ style: CharacterStyleOverride,
+ fallback?: SVGFallbackFace
) => Record<string, string | number | undefined>
interface TextPiece {
@@ -84,6 +100,32 @@ function spanEdges(line: SVGTextLine, from: number, to: number): SVGCharacterEdg
return left <= right ? { left, right } : null
}
+interface FallbackSegment {
+ from: number
+ to: number
+ fallback?: SVGFallbackFace
+}
+
+const sameFace = (a?: SVGFallbackFace, b?: SVGFallbackFace) =>
+ a?.family === b?.family && a?.style === b?.style && a?.file === b?.file
+
+/** The characters from `from` to `to` cut where the face that draws them changes. */
+function fallbackSegments(line: SVGTextLine, from: number, to: number): FallbackSegment[] {
+ const { fallbacks, characters } = line
+ if (!fallbacks?.size) return [{ from, to }]
+ const segments: FallbackSegment[] = []
+ for (let index = from; index < to; index++) {
+ const last = segments.at(-1)
+ // A character with no glyph of its own, such as the second half of a surrogate pair, goes
+ // with the one before it.
+ const fallback =
+ fallbacks.get(index) ?? (characters && !characters.has(index) ? last?.fallback : undefined)
+ if (last && sameFace(last.fallback, fallback)) last.to = index + 1
+ else segments.push({ from: index, to: index + 1, fallback })
+ }
+ return segments
+}
+
function lineSpans(
node: SceneNode,
pieces: readonly TextPiece[],
@@ -100,16 +142,20 @@ function lineSpans(
const y = round(line.y)
const spans: SVGNode[] = []
for (const piece of pieces) {
- const from = Math.max(piece.from, line.start)
- const to = Math.min(piece.to, end)
- if (to <= from) continue
- const attrs = piece.style ? spanAttrs(piece.style) : {}
- // Every span starts at its left edge, in either direction, since renderers disagree on
- // which side `text-anchor` and `direction` place. Without character edges the first span of
- // a line starts at the line's left edge, and the rest follow on from it.
- const left = spanEdges(line, from, to)?.left ?? (spans.length === 0 ? line.x : null)
- const position = left === null ? {} : { x: round(left), y }
- spans.push(svg('tspan', { ...position, ...attrs }, shownTextSlice(node, from, to)))
+ for (const { from, to, fallback } of fallbackSegments(
+ line,
+ Math.max(piece.from, line.start),
+ Math.min(piece.to, end)
+ )) {
+ if (to <= from) continue
+ const attrs = piece.style || fallback ? spanAttrs(piece.style ?? {}, fallback) : {}
+ // Every span starts at its left edge, in either direction, since renderers disagree on
+ // which side `text-anchor` and `direction` place. Without character edges the first span
+ // of a line starts at the line's left edge, and the rest follow on from it.
+ const left = spanEdges(line, from, to)?.left ?? (spans.length === 0 ? line.x : null)
+ const position = left === null ? {} : { x: round(left), y }
+ spans.push(svg('tspan', { ...position, ...attrs }, shownTextSlice(node, from, to)))
+ }
}
return spans
}
diff --git a/packages/core/src/text/font/glyphs.ts b/packages/core/src/text/font/glyphs.ts
index a5837869b..3055cee39 100644
--- a/packages/core/src/text/font/glyphs.ts
+++ b/packages/core/src/text/font/glyphs.ts
@@ -31,6 +31,20 @@ interface ParsedFontCacheEntry {
const parsedFontCache = new Map<string, ParsedFontCacheEntry>()
+/** Shards of a style, read only to tell which one maps a character. */
+const shardFontCache = new WeakMap<ArrayBuffer, HarfBuzzFont | null>()
+
+/** Whether a shard of a style, one of `FontManager.shardData`'s files, maps `character`. */
+export function shardCovers(data: ArrayBuffer, character: string): boolean {
+ if (!isHarfBuzzLoaded()) return false
+ let parsed = shardFontCache.get(data)
+ if (parsed === undefined) {
+ parsed = harfBuzzFont(data)
+ shardFontCache.set(data, parsed)
+ }
+ return parsed !== null && glyphIndex(parsed, character) !== 0
+}
+
function getParsedFont(family: string, style: string): HarfBuzzFont | null {
if (!isHarfBuzzLoaded()) return null
const key = `${family}|${style}`
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.ts
index 2d7656516..ac8d80707 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/fonts.ts
@@ -699,6 +699,11 @@ export class FontManager {
)
}
+ /** The files of `style` of `family` after its own, such as the shards of a split web font. */
+ shardData(family: string, style: string): readonly ArrayBuffer[] {
+ return this.supplementalFamilyData.get(`${family}|${style}`) ?? []
+ }
+
/** The name one file of `family` is registered under on its own. */
private fileFamily(family: string, data: ArrayBuffer): string {
let name = this.fileFamilies.get(data)
diff --git a/packages/core/src/text/prepare.ts b/packages/core/src/text/prepare.ts
index 31341df32..dc78cdac6 100644
--- a/packages/core/src/text/prepare.ts
+++ b/packages/core/src/text/prepare.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit'
+
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
@@ -41,9 +43,17 @@ function laidOutEmojiCharacters(node: SceneNode): string {
export async function prepareGraphFonts(
graph: SceneGraph,
- nodeIds: readonly string[]
+ nodeIds: readonly string[],
+ /** Characters a writer draws besides the text's own, which the fonts must map too. */
+ extraCharacters = ''
): Promise<DocumentFontStatus> {
- const requirements = collectGraphFontRequirements(graph, nodeIds)
+ const collected = collectGraphFontRequirements(graph, nodeIds)
+ const requirements = extraCharacters
+ ? {
+ ...collected,
+ characters: uniq(Array.from(collected.characters + extraCharacters)).join('')
+ }
+ : collected
const faces = requirements.nodes.flatMap(collectNodeFontFaces)
await Promise.all(
faces.map(({ family, style }) => fontManager.loadFont(family, style, requirements.characters))
diff --git a/packages/core/tests/io/formats/pdf/export.test.ts b/packages/core/tests/io/formats/pdf/export.test.ts
index e95a1f3eb..e336794a2 100644
--- a/packages/core/tests/io/formats/pdf/export.test.ts
+++ b/packages/core/tests/io/formats/pdf/export.test.ts
@@ -1,8 +1,12 @@
import { expect, test } from 'bun:test'
+import { join } from 'node:path'
+
+import { FIXTURES } from '#core-tests/helpers/paths'
import { SceneGraph } from '@open-pencil/scene-graph'
import { exportPDFDocument } from '#core/io/formats/pdf'
+import { fontManager } from '#core/text/fonts'
/** A page with a red square and a gradient, drawn without a browser DOM, as the CLI exports. */
function card() {
@@ -53,3 +57,141 @@ test('exports several PDFs at once', async () => {
expect(results.map((result) => result?.pages.length)).toEqual([1, 1, 1])
expect('document' in globalThis).toBe(false)
})
+
+test('embeds the fallback font that draws characters the text’s own font lacks', async () => {
+ const cjk = await Bun.file(join(FIXTURES, 'fonts', 'NotoSansSC-Regular.ttf')).arrayBuffer()
+ await fontManager.markLoaded('PDF Test CJK', 'Regular', cjk)
+ fontManager.setCJKFallbackFamily('PDF Test CJK')
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const text = graph.createNode('TEXT', pageId, {
+ text: 'Hello 中文',
+ fontFamily: 'Inter',
+ fontSize: 32,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ })
+ // Offline, so the fallback is the one loaded here and not a web font.
+ const providers = fontManager.enabledOnlineFontProviders()
+ fontManager.setOnlineFontProviders({})
+ try {
+ const result = await exportPDFDocument(
+ graph,
+ [{ pageId, nodeIds: [text.id], label: 'Text' }],
+ { embedFonts: true, layOutPages: true }
+ )
+ // Inter has no Chinese, which the canvas draws in a CJK fallback, the one loaded here or one
+ // another test loaded first; the PDF embeds that face too.
+ const embedded = result?.fonts?.embedded ?? []
+ expect(embedded).toHaveLength(2)
+ expect(embedded.filter((face) => !face.startsWith('Inter '))).toHaveLength(1)
+ expect(result?.fonts?.fallback).toEqual([])
+ } finally {
+ fontManager.setOnlineFontProviders(
+ Object.fromEntries(providers.map((provider) => [provider, true]))
+ )
+ }
+})
+
+test('embeds each file of a split web font the text draws from', async () => {
+ const family = 'PDF Test Split'
+ const files = {
+ 'https://fonts.gstatic.com/s/test/pdf-latin.ttf': {
+ range: 'U+0000-00FF',
+ data: await Bun.file(join(FIXTURES, 'fonts', 'InterVariable-Latin.ttf')).arrayBuffer()
+ },
+ 'https://fonts.gstatic.com/s/test/pdf-han.ttf': {
+ range: 'U+4E00-9FFF',
+ data: await Bun.file(join(FIXTURES, 'fonts', 'NotoSansSC-Regular.ttf')).arrayBuffer()
+ }
+ }
+ const providers = fontManager.enabledOnlineFontProviders()
+ fontManager.setOnlineFontProviders({ google: true })
+ fontManager.setWebFontFetch(async (url) => {
+ if (url.startsWith('https://fonts.google.com/metadata/fonts'))
+ return Response.json({ familyMetadataList: [{ family, fonts: { '400': {} }, axes: [] }] })
+ if (url.startsWith('https://fonts.google.com/metadata/icons'))
+ return new Response(`)]}'\n${JSON.stringify({ families: [] })}`)
+ if (url.startsWith('https://fonts.googleapis.com/css2'))
+ return new Response(
+ Object.entries(files)
+ .map(
+ ([src, { range }]) =>
+ `@font-face { font-family: '${family}'; font-weight: 400; src: url(${src}) format('truetype'); unicode-range: ${range}; }`
+ )
+ .join('\n')
+ )
+ const file = Object.entries(files).find(([src]) => src === url)?.[1]
+ return file ? new Response(file.data.slice(0)) : new Response(null, { status: 404 })
+ })
+ try {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const text = graph.createNode('TEXT', pageId, {
+ text: 'Split 中文',
+ fontFamily: family,
+ fontSize: 32,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ })
+ const result = await exportPDFDocument(
+ graph,
+ [{ pageId, nodeIds: [text.id], label: 'Text' }],
+ { embedFonts: true, layOutPages: true }
+ )
+ // The Chinese is in the family's second file, which the canvas draws it from. The first is
+ // variable, so it is embedded as the instance the text draws.
+ expect(result?.fonts?.embedded.toSorted()).toEqual([
+ `${family} Regular (file 2)`,
+ `${family} Regular (opsz 32, wght 400)`
+ ])
+ } finally {
+ fontManager.setWebFontFetch(null)
+ fontManager.setOnlineFontProviders(
+ Object.fromEntries(providers.map((provider) => [provider, true]))
+ )
+ }
+})
+
+test('asks a web font for the forms jsPDF writes Arabic letters in', async () => {
+ const family = 'PDF Test Arabic'
+ const fontURL = 'https://fonts.gstatic.com/s/test/pdf-arabic.ttf'
+ const naskh = await Bun.file(join(FIXTURES, 'fonts', 'NotoNaskhArabic-Regular.ttf')).arrayBuffer()
+ const asked: string[] = []
+ const providers = fontManager.enabledOnlineFontProviders()
+ fontManager.setOnlineFontProviders({ google: true })
+ fontManager.setWebFontFetch(async (url) => {
+ if (url.startsWith('https://fonts.google.com/metadata/fonts'))
+ return Response.json({ familyMetadataList: [{ family, fonts: { '400': {} }, axes: [] }] })
+ if (url.startsWith('https://fonts.google.com/metadata/icons'))
+ return new Response(`)]}'\n${JSON.stringify({ families: [] })}`)
+ if (url.startsWith('https://fonts.googleapis.com/css2')) {
+ asked.push(new URL(url).searchParams.get('text') ?? '')
+ return new Response(
+ `@font-face { font-family: '${family}'; font-weight: 400; src: url(${fontURL}) format('truetype'); }`
+ )
+ }
+ return url === fontURL ? new Response(naskh.slice(0)) : new Response(null, { status: 404 })
+ })
+ try {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const text = graph.createNode('TEXT', pageId, {
+ text: 'مرحبا',
+ fontFamily: family,
+ fontSize: 32,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ })
+ await exportPDFDocument(graph, [{ pageId, nodeIds: [text.id], label: 'Text' }], {
+ embedFonts: true,
+ layOutPages: true
+ })
+ // jsPDF writes مرحبا as ﻣﺮﺣﺒﺎ, so a font subset to the typed letters alone would draw nothing.
+ expect(asked.some((characters) => [...'ﻣﺮﺣﺒﺎ'].every((form) => characters.includes(form)))).toBe(
+ true
+ )
+ } finally {
+ fontManager.setWebFontFetch(null)
+ fontManager.setOnlineFontProviders(
+ Object.fromEntries(providers.map((provider) => [provider, true]))
+ )
+ }
+})
diff --git a/packages/core/tests/io/formats/svg/font-alias.test.ts b/packages/core/tests/io/formats/svg/font-alias.test.ts
index fd8f58ed0..e1a019dae 100644
--- a/packages/core/tests/io/formats/svg/font-alias.test.ts
+++ b/packages/core/tests/io/formats/svg/font-alias.test.ts
@@ -2,7 +2,8 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-import { renderNodesToSVG, type SVGTextLine } from '#core/io/formats/svg'
+import { renderNodesToSVG, type SVGFontRequest, type SVGTextLine } from '#core/io/formats/svg'
+import { fontManager } from '#core/text/fonts'
const ALIASES: Record<string, string> = {
'Inter\0Regular': 'EmbeddedFont0',
@@ -70,4 +71,47 @@ describe('SVG text with font aliases', () => {
expect(textTag(svg)).toContain('font-family="EmbeddedFont0"')
expect(spanTags(svg)[1]).toContain('font-family="Inter"')
})
+
+ test('a fallback span names its face, at the weight the text around it is drawn at', async () => {
+ // Inter is variable, so its Bold is drawn at a weight axis value.
+ await fontManager.loadFont('Inter', 'Bold')
+ const requests: SVGFontRequest[] = []
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const node = graph.createNode('TEXT', pageId, {
+ text: 'Bold 中文',
+ fontFamily: 'Inter',
+ fontWeight: 700,
+ fontSize: 20,
+ width: 200,
+ height: 60
+ })
+ const fallback = { family: 'Noto Sans SC', style: 'Regular', file: 0 }
+ const line: SVGTextLine = {
+ start: 0,
+ end: 7,
+ x: 0,
+ y: 20,
+ width: 100,
+ fallbacks: new Map([
+ [5, fallback],
+ [6, fallback]
+ ])
+ }
+ const svg = renderNodesToSVG(graph, pageId, [node.id], {
+ xmlDeclaration: false,
+ textLayout: () => [line],
+ fontAlias: (font) => {
+ requests.push(font)
+ return `${font.family}/${font.style}`
+ }
+ })
+ expect(spanTags(svg ?? '').map((tag) => tag.match(/font-family="([^"]*)"/)?.[1])).toEqual([
+ undefined,
+ 'Noto Sans SC/Regular'
+ ])
+ // The paragraph draws every font it falls back to at the axes of the text's own.
+ const request = requests.find((font) => font.family === 'Noto Sans SC')
+ expect(request?.variations).toContainEqual({ axis: 'wght', value: 700 })
+ })
})
diff --git a/packages/docs/de/programmable/sdk/api/composables/use-typography.md b/packages/docs/de/programmable/sdk/api/composables/use-typography.md
index ed4664dd6..8b981c2d3 100644
--- a/packages/docs/de/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/de/programmable/sdk/api/composables/use-typography.md
@@ -54,6 +54,15 @@ typography.toggleItalic()
typography.toggleDecoration('UNDERLINE')
```
+### Achsen variabler Schriften setzen
+
+`axes` listet die Achsen der variablen Schrift des ausgewählten Texts mit `tag`, `name`, Bereich und dem `value`, in dem sie gezeichnet wird (`MIXED`, wenn die Ebenen abweichen); bei statischen Schriften oder verschiedenen Familien ist die Liste leer. `previewAxis` zeigt einen Wert beim Ziehen, `setAxis` setzt ihn in einem Undo-Schritt, und `setOpticalSizeAuto` lässt die optische Größe der Schriftgröße folgen oder hält sie fest. Eine neue Stärke, Neigung oder Familie setzt die Achsen auf die des Schnitts zurück.
+
+```ts
+typography.setAxis('wght', 560)
+typography.setOpticalSizeAuto(false)
+```
+
## Siehe auch
- [useTextEdit](./use-text-edit)
diff --git a/packages/docs/de/reference/figma-compatibility.md b/packages/docs/de/reference/figma-compatibility.md
index af6ebb54d..fffa45ed8 100644
--- a/packages/docs/de/reference/figma-compatibility.md
+++ b/packages/docs/de/reference/figma-compatibility.md
@@ -6,7 +6,7 @@ Vergleich der Funktionen von Figma Design mit dem aktuellen Stand von OpenPencil
✅ Unterstützt — funktioniert vollständig · 🟡 Teilweise — Grundfunktion vorhanden, einzelne Teile fehlen · 🔲 Nicht umgesetzt
:::
-**Abdeckung:** 128 von 156 Funktionen berücksichtigt — 111 ✅ vollständig, 17 🟡 teilweise und 28 🔲 nicht umgesetzt. Stand: 2026-10-27.
+**Abdeckung:** 128 von 156 Funktionen berücksichtigt — 112 ✅ vollständig, 16 🟡 teilweise und 28 🔲 nicht umgesetzt. Stand: 2026-10-27.
## Oberfläche und Navigation
@@ -64,7 +64,7 @@ Vektornetze, Zeichenstift, Bleistift, boolesche Operationen (bleiben als boolesc
## Text und Typografie
-Direkte Textbearbeitung, CanvasKit Paragraph, Systemschriften, Schriftwahl, Größe, Zeilenhöhe, horizontale und vertikale Ausrichtung, automatische Textgrößen (Auto width, Auto height, Fixed size), verschachtelte Aufzählungen und nummerierte Listen, Emojis, CJK mit sprachabhängigen Ersatzschriften, RTL mit arabischer Formung und Symbolschriften (Material Symbols, Iconify, SF Symbols ab macOS 14) werden unterstützt. Teilweise umgesetzt sind Text auf Pfaden, Textstile (benannte Stile lassen sich anwenden, aber nicht erstellen oder bearbeiten), Links (bleiben erhalten, lassen sich im Panel aber nicht hinzufügen), OpenType-Funktionen (alle werden dargestellt, das Panel schaltet nur Ligaturen, kontextuelle Alternativen und Unterschneidung) und variable Schriften (Achsen nur über die Plugin API, noch nicht im Panel).
+Direkte Textbearbeitung, CanvasKit Paragraph, Systemschriften, Schriftwahl, Größe, Zeilenhöhe, horizontale und vertikale Ausrichtung, automatische Textgrößen (Auto width, Auto height, Fixed size), verschachtelte Aufzählungen und nummerierte Listen, Emojis, CJK mit sprachabhängigen Ersatzschriften, RTL mit arabischer Formung und Symbolschriften (Material Symbols, Iconify, SF Symbols ab macOS 14) werden unterstützt. Teilweise umgesetzt sind Text auf Pfaden, Textstile (benannte Stile lassen sich anwenden, aber nicht erstellen oder bearbeiten), Links (bleiben erhalten, lassen sich im Panel aber nicht hinzufügen), OpenType-Funktionen (alle werden dargestellt, das Panel schaltet nur Ligaturen, kontextuelle Alternativen und Unterschneidung). Variable Schriften werden unterstützt: Achsen lassen sich im Panel und über die Plugin API setzen.
## Farben, Verläufe und Bilder
diff --git a/packages/docs/de/user-guide/text-editing.md b/packages/docs/de/user-guide/text-editing.md
index 2abc69e4a..136a4f74e 100644
--- a/packages/docs/de/user-guide/text-editing.md
+++ b/packages/docs/de/user-guide/text-editing.md
@@ -38,6 +38,10 @@ Durchgestrichen ist über **S** im Bereich Typografie verfügbar. Die Formatieru
Die Schriftauswahl unterstützt Suche, Vorschau, virtuelles Scrollen und das Anspringen der aktuellen Schrift.
+## Variable Schriften
+
+Ist die Schrift variabel, etwa Inter, zeigt der Bereich Typografie ihre Achsen (Stärke, optische Größe, Breite und weitere) mit dem Wert, in dem sie gezeichnet werden. Ein eingegebener oder gezogener Wert setzt die Achse; eine neue Stärke, Neigung oder Familie setzt die Achsen auf die des Schnitts zurück. Die optische Größe zeigt **Automatisch**, solange sie der Schriftgröße folgt; ein Wert oder **Fest** in ihrem Menü hält sie, **Automatisch** lässt sie wieder folgen.
+
## Schriftquellen
- Inter wird automatisch geladen.
diff --git a/packages/docs/es/programmable/sdk/api/composables/use-typography.md b/packages/docs/es/programmable/sdk/api/composables/use-typography.md
index 863f9db46..0a4c43f11 100644
--- a/packages/docs/es/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/es/programmable/sdk/api/composables/use-typography.md
@@ -16,6 +16,15 @@ description: Leer y modificar fuente, tamaño, espaciado y alineación del texto
Durante la edición de texto, los cambios pueden aplicarse solo al intervalo seleccionado.
+### Ajustar ejes de fuentes variables
+
+`axes` lista los ejes de la fuente variable del texto seleccionado, cada uno con su `tag`, `name`, rango y el `value` con que se dibuja (`MIXED` si las capas difieren); queda vacío con una fuente estática o con capas de familias distintas. `previewAxis` muestra un valor mientras se arrastra, `setAxis` lo fija en un paso de deshacer y `setOpticalSizeAuto` hace que el tamaño óptico siga al tamaño de fuente o lo mantiene. Cambiar grosor, inclinación o familia devuelve los ejes a los del estilo.
+
+```ts
+typography.setAxis('wght', 560)
+typography.setOpticalSizeAuto(false)
+```
+
## Véase también
- [TypographyControlsRoot](../components/typography-controls-root)
diff --git a/packages/docs/es/reference/figma-compatibility.md b/packages/docs/es/reference/figma-compatibility.md
index 138c4b932..aaa19d80c 100644
--- a/packages/docs/es/reference/figma-compatibility.md
+++ b/packages/docs/es/reference/figma-compatibility.md
@@ -6,7 +6,7 @@ Comparación entre las funciones de Figma Design y el estado actual de OpenPenci
✅ Compatible — funciona de principio a fin · 🟡 Parcial — existe el comportamiento principal, pero faltan algunas funciones · 🔲 No implementado
:::
-**Cobertura:** 128 de 156 funciones consideradas — 111 ✅ completas, 17 🟡 parciales y 28 🔲 pendientes. Actualizado: 2026-10-27.
+**Cobertura:** 128 de 156 funciones consideradas — 112 ✅ completas, 16 🟡 parciales y 28 🔲 pendientes. Actualizado: 2026-10-27.
## Interfaz y navegación
@@ -91,7 +91,7 @@ Comparación entre las funciones de Figma Design y el estado actual de OpenPenci
| Enlaces | 🟡 | Los enlaces en intervalos de caracteres se conservan en `.fig`, el portapapeles, HTML y la API de plugins; el panel no permite añadirlos |
| Emoji y símbolos | ✅ | Los emoji en color se dibujan con la fuente de emoji del sistema, se editan como un solo carácter y se conservan en `.fig` y el portapapeles |
| OpenType | 🟡 | Todas las funciones que define un archivo se renderizan y se conservan; el panel solo activa ligaduras, alternativas contextuales y kerning |
-| Fuentes variables | 🟡 | Los estilos con nombre usan sus valores de eje y el tamaño óptico sigue al tamaño de fuente, como en Figma; la API de plugins ajusta cualquier eje, pero el panel aún no tiene controles de ejes |
+| Fuentes variables | ✅ | Los estilos con nombre usan sus valores de eje y el tamaño óptico sigue al tamaño de fuente, como en Figma; la sección Tipografía y la API de plugins ajustan cualquier eje, y el tamaño óptico puede fijarse a mano |
| CJK | ✅ | Fuentes alternativas CJK según el idioma, cargadas antes del primer dibujado, incluido el chino tradicional y las fuentes web divididas |
| RTL | ✅ | Dirección de texto Auto, LTR o RTL con composición del árabe; la disposición automática fluye de derecha a izquierda |
| Fuentes de iconos | ✅ | Material Symbols se dibuja con las fuentes variables de Google con cualquier grosor, relleno y grado; el selector de iconos añade colecciones de Iconify y SF Symbols (macOS 14+) |
diff --git a/packages/docs/es/user-guide/text-editing.md b/packages/docs/es/user-guide/text-editing.md
index 61f9151aa..366510f9e 100644
--- a/packages/docs/es/user-guide/text-editing.md
+++ b/packages/docs/es/user-guide/text-editing.md
@@ -34,3 +34,5 @@ Los estilos parciales se guardan como intervalos y participan en deshacer y reha
## Fuentes
OpenPencil detecta fuentes del sistema cuando el entorno lo permite. Si falta una fuente, muestra su estado y usa una alternativa hasta que esté disponible.
+
+Cuando la fuente es variable, como Inter, la sección Tipografía muestra sus ejes (grosor, tamaño óptico, anchura y otros) con el valor con que se dibuja cada uno; elegir un grosor, una inclinación o una familia los devuelve a los del estilo. El tamaño óptico muestra **Auto** mientras sigue al tamaño de fuente; un valor o **Fijo** en su menú lo fija, y **Auto** hace que vuelva a seguirlo.
diff --git a/packages/docs/fr/programmable/sdk/api/composables/use-typography.md b/packages/docs/fr/programmable/sdk/api/composables/use-typography.md
index 3f290070b..1bd5eda9d 100644
--- a/packages/docs/fr/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/fr/programmable/sdk/api/composables/use-typography.md
@@ -16,6 +16,15 @@ description: Lire et modifier police, taille, espacement et alignement du texte.
Pendant l’édition de texte, les changements peuvent ne s’appliquer qu’à la plage sélectionnée.
+### Régler les axes d’une police variable
+
+`axes` liste les axes de la police variable du texte sélectionné, chacun avec son `tag`, son `name`, sa plage et la `value` à laquelle il est dessiné (`MIXED` si les calques diffèrent) ; la liste est vide pour une police statique ou des calques de familles différentes. `previewAxis` affiche une valeur pendant un glissement, `setAxis` la fixe en une étape d’annulation et `setOpticalSizeAuto` fait suivre la taille optique à la taille de police ou la fige. Changer de graisse, d’inclinaison ou de famille ramène les axes à ceux du style.
+
+```ts
+typography.setAxis('wght', 560)
+typography.setOpticalSizeAuto(false)
+```
+
## Voir aussi
- [TypographyControlsRoot](../components/typography-controls-root)
diff --git a/packages/docs/fr/reference/figma-compatibility.md b/packages/docs/fr/reference/figma-compatibility.md
index f6df7e46d..2a534023e 100644
--- a/packages/docs/fr/reference/figma-compatibility.md
+++ b/packages/docs/fr/reference/figma-compatibility.md
@@ -6,7 +6,7 @@ Comparaison entre les fonctions de Figma Design et l’état actuel d’OpenPenc
✅ Pris en charge — fonctionne de bout en bout · 🟡 Partiel — le comportement principal existe, mais certaines fonctions manquent · 🔲 Non implémenté
:::
-**Couverture :** 128 fonctions sur 156 examinées — 111 ✅ complètes, 17 🟡 partielles et 28 🔲 en attente. Mise à jour : 2026-10-27.
+**Couverture :** 128 fonctions sur 156 examinées — 112 ✅ complètes, 16 🟡 partielles et 28 🔲 en attente. Mise à jour : 2026-10-27.
## Interface et navigation
@@ -40,7 +40,7 @@ Réseaux vectoriels, outils Plume et Crayon, opérations booléennes, aplatissem
## Texte et typographie
-Édition directe, rendu CanvasKit Paragraph, polices système, choix de famille, taille, interligne, alignement horizontal et vertical, modes de redimensionnement, listes, emoji, CJK, RTL et polices d’icônes fonctionnent. Le texte sur un tracé reste partiel, car modifier ses caractères demande les contours de sa police en local. Styles de texte, liens, fonctions OpenType et polices variables le sont aussi : il leur manque surtout des réglages dans le panneau.
+Édition directe, rendu CanvasKit Paragraph, polices système, choix de famille, taille, interligne, alignement horizontal et vertical, modes de redimensionnement, listes, emoji, CJK, RTL et polices d’icônes fonctionnent. Les polices variables fonctionnent aussi, avec leurs axes réglables dans le panneau. Le texte sur un tracé reste partiel, car modifier ses caractères demande les contours de sa police en local. Styles de texte, liens et fonctions OpenType le sont aussi : il leur manque surtout des réglages dans le panneau.
## Couleurs, dégradés et images
diff --git a/packages/docs/fr/user-guide/text-editing.md b/packages/docs/fr/user-guide/text-editing.md
index 3b2323a00..f18d1d3b5 100644
--- a/packages/docs/fr/user-guide/text-editing.md
+++ b/packages/docs/fr/user-guide/text-editing.md
@@ -34,3 +34,5 @@ Les mises en forme partielles sont conservées sous forme de plages et participe
## Polices
OpenPencil détecte les polices du système lorsque l’environnement le permet. Si une police manque, son état est signalé et une police de remplacement est utilisée jusqu’à sa disponibilité.
+
+Quand la police est variable, comme Inter, la section Typographie affiche ses axes (graisse, taille optique, chasse et autres) avec la valeur à laquelle chacun est dessiné ; choisir une graisse, une inclinaison ou une famille les ramène à ceux du style. La taille optique affiche **Auto** tant qu’elle suit la taille de police ; une valeur ou **Fixe** dans son menu la fige, et **Auto** la fait suivre à nouveau.
diff --git a/packages/docs/it/programmable/sdk/api/composables/use-typography.md b/packages/docs/it/programmable/sdk/api/composables/use-typography.md
index 249e803e4..e50298653 100644
--- a/packages/docs/it/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/it/programmable/sdk/api/composables/use-typography.md
@@ -9,6 +9,15 @@ description: Leggere e modificare font, dimensione, spaziatura e allineamento de
Durante la modifica del testo, i cambiamenti possono applicarsi solo all’intervallo selezionato.
+### Impostare gli assi dei font variabili
+
+`axes` elenca gli assi del font variabile del testo selezionato, ciascuno con `tag`, `name`, intervallo e il `value` a cui è disegnato (`MIXED` se i livelli differiscono); è vuoto per un font statico o per livelli di famiglie diverse. `previewAxis` mostra un valore durante il trascinamento, `setAxis` lo imposta in un solo passo di annullamento e `setOpticalSizeAuto` fa seguire alla dimensione ottica la dimensione del font o la blocca. Cambiare peso, inclinazione o famiglia riporta gli assi a quelli dello stile.
+
+```ts
+typography.setAxis('wght', 560)
+typography.setOpticalSizeAuto(false)
+```
+
## Vedi anche
- [TypographyControlsRoot](../components/typography-controls-root)
diff --git a/packages/docs/it/reference/figma-compatibility.md b/packages/docs/it/reference/figma-compatibility.md
index 3a49fa80f..f220352e1 100644
--- a/packages/docs/it/reference/figma-compatibility.md
+++ b/packages/docs/it/reference/figma-compatibility.md
@@ -6,7 +6,7 @@ Confronto tra le funzioni di Figma Design e lo stato attuale di OpenPencil.
✅ Supportato · 🟡 Parziale · 🔲 Non implementato
:::
-**Copertura:** 128 funzioni su 156 considerate — 111 complete, 17 parziali e 28 in attesa. Aggiornato: 2026-10-27.
+**Copertura:** 128 funzioni su 156 considerate — 112 complete, 16 parziali e 28 in attesa. Aggiornato: 2026-10-27.
## Interfaccia e navigazione
@@ -22,7 +22,7 @@ Reti vettoriali, Penna, Matita, operazioni booleane, appiattimento e conversione
## Testo e tipografia
-Modifica diretta, rendering CanvasKit Paragraph, font di sistema, famiglia, dimensione, interlinea, allineamento orizzontale e verticale, modalità di ridimensionamento, elenchi, emoji, CJK, RTL e font di icone funzionano. Il testo su tracciato è parziale, perché per modificarne i caratteri servono i contorni del font in locale. Lo sono anche stili di testo, link, funzioni OpenType e font variabili, a cui mancano soprattutto i controlli nel pannello.
+Modifica diretta, rendering CanvasKit Paragraph, font di sistema, famiglia, dimensione, interlinea, allineamento orizzontale e verticale, modalità di ridimensionamento, elenchi, emoji, CJK, RTL e font di icone funzionano. Funzionano anche i font variabili, con gli assi regolabili nel pannello. Il testo su tracciato è parziale, perché per modificarne i caratteri servono i contorni del font in locale. Lo sono anche stili di testo, link e funzioni OpenType, a cui mancano soprattutto i controlli nel pannello.
## Colori, sfumature e immagini
diff --git a/packages/docs/it/user-guide/text-editing.md b/packages/docs/it/user-guide/text-editing.md
index 259488cfb..5f9cc8639 100644
--- a/packages/docs/it/user-guide/text-editing.md
+++ b/packages/docs/it/user-guide/text-editing.md
@@ -34,3 +34,5 @@ La formattazione parziale viene conservata in intervalli e partecipa ad annulla
## Font
OpenPencil rileva i font di sistema quando l’ambiente lo consente. Se un font manca, ne mostra lo stato e usa un’alternativa finché non è disponibile.
+
+Quando il font è variabile, come Inter, la sezione Tipografia mostra i suoi assi (peso, dimensione ottica, larghezza e altri) con il valore a cui ciascuno è disegnato; scegliere un peso, un’inclinazione o una famiglia li riporta a quelli dello stile. La dimensione ottica mostra **Auto** finché segue la dimensione del font; un valore o **Fisso** nel suo menu la blocca, e **Auto** la fa seguire di nuovo.
diff --git a/packages/docs/pl/programmable/sdk/api/composables/use-typography.md b/packages/docs/pl/programmable/sdk/api/composables/use-typography.md
index 6d881361d..d182a0a72 100644
--- a/packages/docs/pl/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/pl/programmable/sdk/api/composables/use-typography.md
@@ -46,6 +46,15 @@ typography.toggleItalic()
typography.toggleDecoration('UNDERLINE')
```
+### Ustawianie osi czcionek zmiennych
+
+`axes` wymienia osie zmiennej czcionki zaznaczonego tekstu, każdą z `tag`, `name`, zakresem i `value`, w jakiej jest rysowana (`MIXED`, gdy warstwy się różnią); lista jest pusta dla czcionki statycznej lub warstw z różnych rodzin. `previewAxis` pokazuje wartość podczas przeciągania, `setAxis` ustawia ją w jednym kroku cofania, a `setOpticalSizeAuto` każe rozmiarowi optycznemu podążać za rozmiarem czcionki albo go zatrzymuje. Zmiana grubości, pochylenia lub rodziny przywraca osie danej odmiany.
+
+```ts
+typography.setAxis('wght', 560)
+typography.setOpticalSizeAuto(false)
+```
+
## Zobacz też
- [useTextEdit](./use-text-edit)
diff --git a/packages/docs/pl/reference/figma-compatibility.md b/packages/docs/pl/reference/figma-compatibility.md
index 7df9d431b..233eb5c81 100644
--- a/packages/docs/pl/reference/figma-compatibility.md
+++ b/packages/docs/pl/reference/figma-compatibility.md
@@ -6,7 +6,7 @@ Porównanie funkcji Figma Design z obecnymi możliwościami OpenPencil.
✅ Obsługiwane — działa w pełnym zakresie · 🟡 Częściowo — podstawowe działanie istnieje, ale brakuje części funkcji · 🔲 Brak
:::
-**Pokrycie:** uwzględniono 128 ze 156 funkcji Figmy — 111 ✅ obsługiwanych, 17 🟡 częściowych i 28 🔲 niezaimplementowanych. Aktualizacja: 2026-10-27.
+**Pokrycie:** uwzględniono 128 ze 156 funkcji Figmy — 112 ✅ obsługiwanych, 16 🟡 częściowych i 28 🔲 niezaimplementowanych. Aktualizacja: 2026-10-27.
## Interfejs i nawigacja
@@ -91,7 +91,7 @@ Porównanie funkcji Figma Design z obecnymi możliwościami OpenPencil.
| Łącza | 🟡 | Łącza na zakresach znaków zachowują się w `.fig`, schowku, HTML i API wtyczek; panel nie pozwala ich dodawać |
| Emoji i symbole | ✅ | Kolorowe emoji rysowane systemową czcionką emoji, edytowane jako jeden znak i zachowywane w `.fig` i schowku |
| OpenType | 🟡 | Każda funkcja ustawiona w pliku jest renderowana i zachowywana; panel przełącza tylko ligatury, warianty kontekstowe i kerning |
-| Czcionki zmienne | 🟡 | Style nazwane są rysowane w swoich wartościach osi, a rozmiar optyczny podąża za rozmiarem czcionki, jak w Figmie; API wtyczek ustawia dowolną oś, ale panel nie ma jeszcze kontrolek osi |
+| Czcionki zmienne | ✅ | Style nazwane są rysowane w swoich wartościach osi, a rozmiar optyczny podąża za rozmiarem czcionki, jak w Figmie; sekcja Typografia i API wtyczek ustawiają dowolną oś, a rozmiar optyczny można ustawić ręcznie |
| CJK | ✅ | Czcionki zastępcze CJK dobierane według języka i wczytywane przed pierwszym renderowaniem, także dla chińskiego tradycyjnego i dzielonych czcionek webowych |
| RTL | ✅ | Kierunek tekstu Auto, LTR lub RTL z kształtowaniem pisma arabskiego; automatyczny układ biegnie od prawej do lewej |
| Czcionki ikon | ✅ | Material Symbols ze zmiennych czcionek Google w dowolnej grubości, wypełnieniu i gradacji; wybór ikon dodaje zestawy Iconify i SF Symbols (macOS 14+) |
diff --git a/packages/docs/pl/user-guide/text-editing.md b/packages/docs/pl/user-guide/text-editing.md
index 61cb380e2..bfc1533f9 100644
--- a/packages/docs/pl/user-guide/text-editing.md
+++ b/packages/docs/pl/user-guide/text-editing.md
@@ -72,6 +72,10 @@ Otwórz wybór czcionki w sekcji „Typografia”.
Dostępne odmiany zależą od rodziny, na przykład Regular, Medium, Bold i Black.
+## Czcionki zmienne
+
+Gdy czcionka jest zmienna, na przykład Inter, sekcja Typografia pokazuje jej osie (grubość, rozmiar optyczny, szerokość i inne) z wartością, w jakiej są rysowane. Wpisana lub przeciągnięta wartość ustawia oś; wybór grubości, pochylenia lub rodziny przywraca osie tej odmiany. Rozmiar optyczny pokazuje **Auto**, dopóki podąża za rozmiarem czcionki; wpisana wartość lub **Stały** w jego menu go zatrzymuje, a **Auto** przywraca.
+
## Źródła czcionek
- **Domyślnie:** Inter jest ładowany automatycznie.
diff --git a/packages/docs/programmable/sdk/api/composables/use-typography.md b/packages/docs/programmable/sdk/api/composables/use-typography.md
index 491c4f4fb..acd421474 100644
--- a/packages/docs/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/programmable/sdk/api/composables/use-typography.md
@@ -20,6 +20,7 @@ It exposes:
- text case and direction
- ending truncation and maximum lines
- OpenType feature toggles
+- variable font axes (`axes`, `opticalSizeAuto`)
- list style (`listType`, `null` when the paragraphs differ) and hanging lists
- helpers for changing family, weight, alignment, and decorations
- `merged(key)` and `fontFeature(tag)`, which return the shared value or `MIXED`
@@ -88,6 +89,15 @@ typography.setHangingList(true)
typography.setParagraphSpacing('listSpacing', 8)
```
+### Set variable font axes
+
+`axes` lists the axes of the selected text's variable font, each with its `tag`, `name`, range, and the `value` it is drawn at (`MIXED` when the layers differ), and is empty for a static font or layers in different families. `previewAxis` shows a value while a field is dragged, `setAxis` sets it in one undo step, and `setOpticalSizeAuto` lets the optical size follow the font size or holds it. Changing weight, slant, or family puts the axes back at the style's own.
+
+```ts
+typography.setAxis('wght', 560)
+typography.setOpticalSizeAuto(false)
+```
+
## Related APIs
- [useTextEdit](./use-text-edit)
diff --git a/packages/docs/reference/figma-compatibility.md b/packages/docs/reference/figma-compatibility.md
index 89a801de5..b7ef1741c 100644
--- a/packages/docs/reference/figma-compatibility.md
+++ b/packages/docs/reference/figma-compatibility.md
@@ -6,7 +6,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu
✅ Supported — feature works end-to-end · 🟡 Partial — core behavior exists, some sub-features missing · 🔲 Not yet implemented
:::
-**Coverage:** 128 of 156 Figma feature items addressed — 111 ✅ fully supported, 17 🟡 partial, 28 🔲 not yet. Last updated: 2026-10-27.
+**Coverage:** 128 of 156 Figma feature items addressed — 112 ✅ fully supported, 16 🟡 partial, 28 🔲 not yet. Last updated: 2026-10-27.
## Interface & Navigation
@@ -92,7 +92,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu
| Links in text | 🟡 | Links on character ranges round-trip through `.fig`, the clipboard, HTML, and the plugin API; no panel control to add one |
| Emojis & smart symbols | ✅ | Color emoji draw with the system emoji font, edit as one character, and survive `.fig` and the clipboard |
| OpenType features | 🟡 | Every feature a file sets renders and round-trips; the panel toggles only ligatures, contextual alternates, and kerning |
-| Variable fonts | 🟡 | Named styles draw at their axis values and optical size follows the font size, as in Figma; the plugin API sets any axis, but the panel has no axis controls yet |
+| Variable fonts | ✅ | Named styles draw at their axis values and optical size follows the font size, as in Figma; the Typography section and the plugin API set any axis, and optical size can be set by hand |
| CJK text support | ✅ | Language-aware CJK fallback fonts load before first paint, including Traditional Chinese and split web fonts |
| RTL text support | ✅ | Text direction Auto, LTR, or RTL with Arabic shaping; auto layout flows right to left |
| Icon fonts | ✅ | Material Symbols draw from Google's variable fonts at any weight, fill, and grade; the icon picker adds Iconify sets and SF Symbols (macOS 14+) |
diff --git a/packages/docs/ru/programmable/sdk/api/composables/use-typography.md b/packages/docs/ru/programmable/sdk/api/composables/use-typography.md
index 76904c760..b9533d248 100644
--- a/packages/docs/ru/programmable/sdk/api/composables/use-typography.md
+++ b/packages/docs/ru/programmable/sdk/api/composables/use-typography.md
@@ -54,6 +54,15 @@ typography.toggleItalic()
typography.toggleDecoration('UNDERLINE')
```
+### Оси вариативных шрифтов
+
+`axes` перечисляет оси вариативного шрифта выделенного текста, каждую с `tag`, `name`, диапазоном и `value`, в котором она рисуется (`MIXED`, если слои различаются); для статического шрифта или слоёв разных семейств список пуст. `previewAxis` показывает значение во время перетаскивания, `setAxis` задаёт его одним шагом отмены, а `setOpticalSizeAuto` включает следование оптического размера за размером шрифта или фиксирует его. Смена толщины, наклона или семейства возвращает оси начертания.
+
+```ts
+typography.setAxis('wght', 560)
+typography.setOpticalSizeAuto(false)
+```
+
## Связанные API
- [useTextEdit](./use-text-edit)
diff --git a/packages/docs/ru/reference/figma-compatibility.md b/packages/docs/ru/reference/figma-compatibility.md
index 1ae67eecb..28764ae47 100644
--- a/packages/docs/ru/reference/figma-compatibility.md
+++ b/packages/docs/ru/reference/figma-compatibility.md
@@ -6,7 +6,7 @@
✅ Поддерживается полностью · 🟡 Поддерживается частично · 🔲 Пока не реализовано
:::
-**Покрытие:** учтены 128 из 156 возможностей Figma — 111 ✅ полностью, 17 🟡 частично и 28 🔲 пока отсутствуют. Обновлено 27 октября 2026 года.
+**Покрытие:** учтены 128 из 156 возможностей Figma — 112 ✅ полностью, 16 🟡 частично и 28 🔲 пока отсутствуют. Обновлено 27 октября 2026 года.
## Интерфейс и навигация
@@ -91,7 +91,7 @@
| Ссылки | 🟡 | Ссылки на фрагментах текста сохраняются при обмене через `.fig`, буфер обмена, HTML и API плагинов; добавить ссылку на панели нельзя |
| Эмодзи и специальные символы | ✅ | Цветные эмодзи рисуются системным шрифтом, редактируются как один символ и сохраняются в `.fig` и буфере обмена |
| OpenType | 🟡 | Все функции, заданные в файле, отображаются и сохраняются; на панели переключаются только лигатуры, контекстные варианты и кернинг |
-| Вариативные шрифты | 🟡 | Именованные начертания рисуются со своими значениями осей, а оптический размер следует за размером шрифта, как в Figma; API плагинов задаёт любую ось, но в панели пока нет управления осями |
+| Вариативные шрифты | ✅ | Именованные начертания рисуются со своими значениями осей, а оптический размер следует за размером шрифта, как в Figma; раздел «Типографика» и API плагинов задают любую ось, а оптический размер можно задать вручную |
| CJK | ✅ | Резервные шрифты CJK с учётом языка, включая традиционный китайский и разбитые на части веб-шрифты, загружаются до первой отрисовки |
| RTL | ✅ | Направление текста Auto, LTR или RTL с арабским шейпингом; автокомпоновка идёт справа налево |
| Иконочные шрифты | ✅ | Material Symbols рисуются из вариативных шрифтов Google с любой толщиной, заливкой и градацией; в выборе иконок есть наборы Iconify и SF Symbols (macOS 14+) |
diff --git a/packages/docs/ru/user-guide/text-editing.md b/packages/docs/ru/user-guide/text-editing.md
index 684e2cdc7..2df96f740 100644
--- a/packages/docs/ru/user-guide/text-editing.md
+++ b/packages/docs/ru/user-guide/text-editing.md
@@ -74,6 +74,10 @@ OpenPencil позволяет создавать текстовые объект
Доступные начертания зависят от семейства, например Regular, Medium, Bold и Black.
+## Вариативные шрифты
+
+Если шрифт вариативный, как Inter, раздел «Типографика» показывает его оси (толщину, оптический размер, ширину и другие) со значениями, в которых он рисуется. Введённое или перетянутое значение задаёт ось; выбор толщины, наклона или семейства возвращает оси этого начертания. Оптический размер показывает **Авто**, пока следует за размером шрифта; введённое значение или **Фиксированный** в его меню фиксирует его, а **Авто** снова включает следование.
+
## Источники шрифтов
- **По умолчанию:** Inter загружается автоматически.
diff --git a/packages/docs/user-guide/text-editing.md b/packages/docs/user-guide/text-editing.md
index 3114b2883..8e39ad18e 100644
--- a/packages/docs/user-guide/text-editing.md
+++ b/packages/docs/user-guide/text-editing.md
@@ -77,6 +77,10 @@ Imported Figma text-on-path layers retain their curved glyph layout. You can edi
Change the font weight in the Typography section of the properties panel. Available weights depend on the selected font family (e.g., Regular, Medium, Bold, Black).
+## Variable Fonts
+
+When the text's font is variable, such as Inter, the Typography section lists its axes (weight, optical size, width, and any others the font has) with the value each is drawn at. Type or drag a value to set it; choosing a weight, slant, or family puts the axes back at that style's own. Optical size reads **Auto** while it follows the font size; set a value, or choose **Fixed** from its menu, to hold it, and **Auto** to follow the size again.
+
## Font Sources
- **Default font** — Inter is loaded automatically
diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.ts
index 52853ec13..9a3060a01 100644
--- a/packages/vue/src/controls/typography/actions.ts
+++ b/packages/vue/src/controls/typography/actions.ts
@@ -20,8 +20,10 @@ import {
paragraphSpacingOf
} from '#vue/canvas/text-edit/paragraphs'
import { MIXED, type MixedValue } from '#vue/controls/node-props/use'
+import { styleFontVariations } from '#vue/controls/typography/axes'
import { useFamilyFaces } from '#vue/controls/typography/faces'
import type { UseTypographyOptions } from '#vue/controls/typography/use'
+import { useUndoBatch } from '#vue/controls/undo-batch/use'
import { selectedNodesAsShown } from '#vue/editor/selection-state/nodes'
import { useSceneComputed } from '#vue/internal/scene-computed/use'
import { useNodeFontStatus } from '#vue/shared/font-status/use'
@@ -141,6 +143,9 @@ export function createTypographyActions({
options
}: TypographyActionOptions) {
const lists = createTextListActions(editor)
+ // A dragged field's previews belong to the step its commit records, so they are not edits of
+ // their own that keep the document unsaved after that step is undone.
+ const batch = useUndoBatch(editor.undo, () => editor.beginInteractiveEdit())
type Preview = { value: SceneNode[keyof SceneNode]; textStyleId: string | null }
let previewKey: keyof SceneNode | undefined
const beforePreview = new Map<string, Preview>()
@@ -208,7 +213,12 @@ export function createTypographyActions({
const fontWeight = face?.weight ?? target.fontWeight
const italic = face?.italic ?? target.italic
await options.fontLoader?.load(family, weightToStyle(fontWeight, italic))
- return { fontFamily: family, fontWeight, italic }
+ return {
+ fontFamily: family,
+ fontWeight,
+ italic,
+ fontVariations: styleFontVariations(target)
+ }
}
)
}
@@ -220,7 +230,7 @@ export function createTypographyActions({
['fontWeight'],
async (target) => {
await options.fontLoader?.load(target.fontFamily, weightToStyle(weight, target.italic))
- return { fontWeight: weight }
+ return { fontWeight: weight, fontVariations: styleFontVariations(target) }
},
targets
)
@@ -340,7 +350,7 @@ export function createTypographyActions({
['italic'],
async (target) => {
await options.fontLoader?.load(target.fontFamily, weightToStyle(target.fontWeight, italic))
- return { italic }
+ return { italic, fontVariations: styleFontVariations(target) }
},
nodes.value.filter((target) => supports(target, target.fontWeight, italic))
)
@@ -366,6 +376,7 @@ export function createTypographyActions({
}
function updateProp(key: keyof SceneNode, value: PropValue) {
+ batch.ensure(`typography:${String(key)}`, `Change ${String(key)}`)
if (previewKey !== key) {
previewKey = key
beforePreview.clear()
@@ -396,6 +407,7 @@ export function createTypographyActions({
})
previewKey = undefined
beforePreview.clear()
+ batch.flush()
}
return {
diff --git a/packages/vue/src/controls/typography/axes.ts b/packages/vue/src/controls/typography/axes.ts
new file mode 100644
index 000000000..1c499e3d5
--- /dev/null
+++ b/packages/vue/src/controls/typography/axes.ts
@@ -0,0 +1,162 @@
+import { computed, type ComputedRef } from 'vue'
+
+import type { Editor } from '@open-pencil/core'
+import { drawnFontAxes, type DrawnFontAxis } from '@open-pencil/core/canvas'
+import type { FontVariation, SceneNode } from '@open-pencil/scene-graph'
+
+import { MIXED, type MixedValue } from '#vue/controls/node-props/use'
+import { useUndoBatch } from '#vue/controls/undo-batch/use'
+
+/** An axis of the selected text's variable font, with the value every layer draws it at. */
+export interface TypographyAxis extends Omit<DrawnFontAxis, 'value'> {
+ value: MixedValue<number>
+}
+
+const OPTICAL_SIZE = 'opsz'
+
+function drawnAxes(node: SceneNode): DrawnFontAxis[] | null {
+ return drawnFontAxes({
+ family: node.fontFamily,
+ weight: node.fontWeight,
+ italic: node.italic,
+ fontSize: node.fontSize,
+ variations: node.fontVariations,
+ opticalSizeFromFontSize: node.opticalSizeFromFontSize
+ })
+}
+
+/**
+ * The axes a text keeps when it changes style, as a named style draws at its own: none, except an
+ * optical size set by hand, which stays set by hand.
+ */
+export function styleFontVariations(node: SceneNode): FontVariation[] {
+ if (node.opticalSizeFromFontSize) return []
+ return node.fontVariations.filter(({ axis }) => axis === OPTICAL_SIZE)
+}
+
+/** The text's axes with `axis` set to `value`; an optical size set by hand no longer follows the size. */
+function axisChanges(node: SceneNode, axis: string, value: number): Partial<SceneNode> {
+ return {
+ fontVariations: [
+ ...node.fontVariations.filter((variation) => variation.axis !== axis),
+ { axis, value }
+ ],
+ ...(axis === OPTICAL_SIZE ? { opticalSizeFromFontSize: false } : {})
+ }
+}
+
+/**
+ * The variation axes of the selected text layers' font, as Figma's Variable type settings list
+ * them, and actions that set them. Layers in different families or slants have no shared axes.
+ */
+export function createTypographyAxes(editor: Editor, nodes: ComputedRef<SceneNode[]>) {
+ const axes = computed<TypographyAxis[]>(() => {
+ const first = nodes.value.at(0)
+ if (!first) return []
+ const same = nodes.value.every(
+ (node) => node.fontFamily === first.fontFamily && node.italic === first.italic
+ )
+ if (!same) return []
+ const perNode = nodes.value.map(drawnAxes)
+ const axesOfFirst = perNode.at(0)
+ if (!axesOfFirst || perNode.some((drawn) => !drawn)) return []
+ return axesOfFirst.map((axis, index) => {
+ const values = perNode.map((drawn) => drawn?.[index]?.value)
+ return { ...axis, value: values.every((value) => value === axis.value) ? axis.value : MIXED }
+ })
+ })
+
+ /**
+ * Whether the optical size can be set: not while text is edited, since whether it follows the
+ * font size belongs to the layer, which selected characters cannot set for themselves.
+ */
+ const opticalSizeEditable = computed(() =>
+ nodes.value.every((node) => editor.state.editingTextId !== node.id)
+ )
+
+ /** Whether the optical size follows the font size on every layer, MIXED when they differ. */
+ const opticalSizeAuto = computed<MixedValue<boolean>>(() => {
+ const first = nodes.value.at(0)
+ if (!first) return MIXED
+ return nodes.value.every(
+ (node) => node.opticalSizeFromFontSize === first.opticalSizeFromFontSize
+ )
+ ? first.opticalSizeFromFontSize
+ : MIXED
+ })
+
+ // A drag or a typed value is previewed, then committed as one undo step from the values it
+ // started at, as the other typography fields are. While text is edited, the editor applies
+ // both to the selected characters, and records the step with what was typed.
+ type AxisValues = Pick<SceneNode, 'fontVariations' | 'opticalSizeFromFontSize'>
+ const beforePreview = new Map<string, AxisValues>()
+ // The previews belong to the step the commit records, so undoing it leaves nothing unsaved.
+ const batch = useUndoBatch(editor.undo, () => editor.beginInteractiveEdit())
+
+ function previewEach(changes: (node: SceneNode) => Partial<SceneNode>) {
+ batch.ensure('typography:axes', 'Change font axes')
+ for (const target of nodes.value) {
+ if (!beforePreview.has(target.id)) {
+ const { fontVariations, opticalSizeFromFontSize } = target
+ beforePreview.set(target.id, { fontVariations, opticalSizeFromFontSize })
+ }
+ editor.updateNode(target.id, changes(target))
+ }
+ editor.requestRender()
+ }
+
+ function commitPreview(label: string) {
+ editor.undo.runBatch(label, () => {
+ for (const [id, before] of beforePreview) editor.commitNodeUpdate(id, before, label)
+ })
+ beforePreview.clear()
+ batch.flush()
+ }
+
+ /** Draws the text at `value` on `axis` while it is dragged or typed. */
+ function previewAxis(axis: string, value: number) {
+ if (axis === OPTICAL_SIZE && !opticalSizeEditable.value) return
+ previewEach((node) => axisChanges(node, axis, value))
+ }
+
+ /** Puts back the axes a cancelled edit previewed. */
+ function cancelAxis() {
+ for (const [id, before] of beforePreview) editor.updateNode(id, before)
+ beforePreview.clear()
+ batch.flush()
+ editor.requestRender()
+ }
+
+ /** Sets `axis` to `value` on every selected text layer in one undo step. */
+ function setAxis(axis: string, value: number) {
+ if (axis === OPTICAL_SIZE && !opticalSizeEditable.value) return
+ previewAxis(axis, value)
+ commitPreview(`Change ${axis} axis`)
+ }
+
+ /**
+ * Lets the optical size follow the font size, or holds it at the size it is drawn at now, as
+ * Figma's "Set optical size automatically" does.
+ */
+ function setOpticalSizeAuto(auto: boolean) {
+ if (!opticalSizeEditable.value) return
+ previewEach((node) => {
+ const drawn = drawnAxes(node)?.find((axis) => axis.tag === OPTICAL_SIZE)
+ const rest = node.fontVariations.filter(({ axis }) => axis !== OPTICAL_SIZE)
+ const fontVariations =
+ auto || !drawn ? rest : [...rest, { axis: OPTICAL_SIZE, value: drawn.value }]
+ return { opticalSizeFromFontSize: auto, fontVariations }
+ })
+ commitPreview('Change optical size')
+ }
+
+ return {
+ axes,
+ opticalSizeAuto,
+ opticalSizeEditable,
+ previewAxis,
+ cancelAxis,
+ setAxis,
+ setOpticalSizeAuto
+ }
+}
diff --git a/packages/vue/src/controls/typography/index.ts b/packages/vue/src/controls/typography/index.ts
index a76616939..8906759de 100644
--- a/packages/vue/src/controls/typography/index.ts
+++ b/packages/vue/src/controls/typography/index.ts
@@ -1,2 +1,3 @@
export { useTypography } from './use'
export type { UseTypographyOptions } from './use'
+export type { TypographyAxis } from './axes'
diff --git a/packages/vue/src/controls/typography/use.ts b/packages/vue/src/controls/typography/use.ts
index 466ec5122..44cc2f0d6 100644
--- a/packages/vue/src/controls/typography/use.ts
+++ b/packages/vue/src/controls/typography/use.ts
@@ -1,4 +1,5 @@
import { createTypographyActions, createTypographyState } from '#vue/controls/typography/actions'
+import { createTypographyAxes } from '#vue/controls/typography/axes'
import { useEditor } from '#vue/editor/context'
/**
@@ -24,10 +25,12 @@ export function useTypography(options: UseTypographyOptions = {}) {
const editor = useEditor()
const typographyState = createTypographyState(editor)
const actions = createTypographyActions({ editor, ...typographyState, options })
+ const axes = createTypographyAxes(editor, typographyState.nodes)
return {
editor,
...typographyState,
- ...actions
+ ...actions,
+ ...axes
}
}
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 8e03b6d77..08a515587 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -59,6 +59,7 @@
"openTypeFeatures": "Schrifteigenschaften",
"standardLigatures": "Standardligaturen",
"contextualAlternates": "Kontextvarianten",
+ "opticalSizeMode": "Modus der optischen Größe",
"kerning": "Kerning",
"textFormatting": "Textformatierung",
"pageBackground": "Seitenhintergrund",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 7f00137ad..b42df5830 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -71,6 +71,7 @@
"openTypeFeatures": "Funciones de fuente",
"standardLigatures": "Ligaduras estándar",
"contextualAlternates": "Alternativas contextuales",
+ "opticalSizeMode": "Modo del tamaño óptico",
"kerning": "Kerning",
"textFormatting": "Formato de texto",
"pageBackground": "Fondo de página",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 608adbfec..ff57c94f4 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -59,6 +59,7 @@
"openTypeFeatures": "Propriétés de police",
"standardLigatures": "Ligatures standard",
"contextualAlternates": "Variantes contextuelles",
+ "opticalSizeMode": "Mode de taille optique",
"kerning": "Crénage",
"textFormatting": "Mise en forme du texte",
"pageBackground": "Arrière-plan de la page",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 2d52fd638..8c0ac7050 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -59,6 +59,7 @@
"openTypeFeatures": "Funzioni del font",
"standardLigatures": "Legature standard",
"contextualAlternates": "Alternative contestuali",
+ "opticalSizeMode": "Modalità della dimensione ottica",
"kerning": "Crenatura",
"textFormatting": "Formattazione testo",
"pageBackground": "Sfondo pagina",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 06e622239..86b6933cf 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -71,6 +71,7 @@
"openTypeFeatures": "フォント機能",
"standardLigatures": "標準合字",
"contextualAlternates": "文脈依存字形",
+ "opticalSizeMode": "オプティカルサイズのモード",
"kerning": "カーニング",
"textFormatting": "テキストの書式",
"pageBackground": "ページの背景",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 36754b7ed..117db756c 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -59,6 +59,7 @@
"openTypeFeatures": "Funkcje czcionki",
"standardLigatures": "Ligatury standardowe",
"contextualAlternates": "Alternatywy kontekstowe",
+ "opticalSizeMode": "Tryb rozmiaru optycznego",
"kerning": "Kerning",
"textFormatting": "Formatowanie tekstu",
"pageBackground": "Tło strony",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 1492e87df..b602b195a 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -59,6 +59,7 @@
"openTypeFeatures": "Свойства шрифта",
"standardLigatures": "Стандартные лигатуры",
"contextualAlternates": "Контекстные варианты",
+ "opticalSizeMode": "Режим оптического размера",
"kerning": "Кернинг",
"textFormatting": "Форматирование текста",
"pageBackground": "Фон страницы",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 5b4884b84..f4615e2ed 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -59,6 +59,7 @@
"openTypeFeatures": "字体功能",
"standardLigatures": "标准连字",
"contextualAlternates": "上下文替代字形",
+ "opticalSizeMode": "光学尺寸模式",
"kerning": "字距调整",
"textFormatting": "文本格式",
"pageBackground": "页面背景",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 757d4b1d8..6d93a9258 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -213,6 +213,7 @@ export const panelMessageDefaults = {
standardLigatures: 'Standard ligatures',
contextualAlternates: 'Contextual alternates',
kerning: 'Kerning',
+ opticalSizeMode: 'Optical size mode',
textFormatting: 'Text formatting',
pageBackground: 'Page background',
variables: 'Variables',
diff --git a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
index f2812264c..952bb1511 100644
--- a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
+++ b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue
@@ -36,7 +36,11 @@ const actions = {
formatting: onFormattingChange,
toggleBold: ctx.toggleBold,
toggleItalic: ctx.toggleItalic,
- toggleDecoration: ctx.toggleDecoration
+ toggleDecoration: ctx.toggleDecoration,
+ previewAxis: ctx.previewAxis,
+ cancelAxis: ctx.cancelAxis,
+ setAxis: ctx.setAxis,
+ setOpticalSizeAuto: ctx.setOpticalSizeAuto
}
</script>
@@ -52,6 +56,9 @@ const actions = {
:has-missing-fonts="ctx.hasMissingFonts"
:active-formatting="ctx.activeFormatting"
:list-type="ctx.listType"
+ :axes="ctx.axes"
+ :optical-size-auto="ctx.opticalSizeAuto"
+ :optical-size-editable="ctx.opticalSizeEditable"
:actions="actions"
/>
</template>
diff --git a/packages/vue/tests/controls/typography.test.ts b/packages/vue/tests/controls/typography.test.ts
index 4ff91e1df..3e264e92b 100644
--- a/packages/vue/tests/controls/typography.test.ts
+++ b/packages/vue/tests/controls/typography.test.ts
@@ -3,10 +3,13 @@ import { afterAll, beforeAll, expect, test } from 'bun:test'
import { computed, effectScope, nextTick, shallowRef } from 'vue'
import { createEditor } from '@open-pencil/core'
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
import { DEFAULT_WEB_FONT_PROVIDER_SETTINGS, fontManager } from '@open-pencil/core/text'
import type { SceneNode } from '@open-pencil/scene-graph'
import { createTypographyActions } from '#vue/controls/typography/actions'
+import { createTypographyAxes } from '#vue/controls/typography/axes'
import { useFamilyFaces } from '#vue/controls/typography/faces'
// The faces Figma lists for these families (desktop 126), given as installed fonts so no test
@@ -181,3 +184,133 @@ test('the weight list follows a font catalog that arrives after the first lookup
stop()
fontManager.setHostFontCatalog(CATALOG)
})
+
+/** A text layer in the bundled variable Inter, which has weight and optical size axes. */
+async function variableText(fontSize = 24) {
+ await fontManager.loadFont('Inter', 'Regular')
+ const editor = createEditor()
+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {
+ text: 'a',
+ fontFamily: 'Inter',
+ fontSize
+ })
+ const scope = effectScope()
+ const axes = scope.run(() => createTypographyAxes(editor, computed(() => [text])))
+ if (!axes) throw new Error('Expected the axes')
+ return { editor, text, axes, stop: () => scope.stop() }
+}
+
+test('lists the variable font’s axes at the values the text is drawn at', async () => {
+ const { axes, stop } = await variableText()
+ const values = Object.fromEntries(axes.axes.value.map((axis) => [axis.tag, axis.value]))
+ // Regular is weight 400, and the optical size follows the font size.
+ expect(values).toMatchObject({ wght: 400, opsz: 24 })
+ expect(axes.opticalSizeAuto.value).toBe(true)
+ stop()
+})
+
+test('an axis set by hand is one undo step, and an optical size set by hand stops following', async () => {
+ const { editor, text, axes, stop } = await variableText()
+ axes.previewAxis('wght', 520)
+ axes.previewAxis('wght', 560)
+ axes.setAxis('wght', 560)
+ axes.setAxis('opsz', 16)
+ expect(text.fontVariations).toEqual([
+ { axis: 'wght', value: 560 },
+ { axis: 'opsz', value: 16 }
+ ])
+ expect(text.opticalSizeFromFontSize).toBe(false)
+ editor.undo.undo()
+ editor.undo.undo()
+ expect(text.fontVariations).toEqual([])
+ expect(text.opticalSizeFromFontSize).toBe(true)
+ stop()
+})
+
+test('turning automatic optical size off holds the size it is drawn at', async () => {
+ const { text, axes, stop } = await variableText(20)
+ axes.setOpticalSizeAuto(false)
+ expect(text.fontVariations).toEqual([{ axis: 'opsz', value: 20 }])
+ axes.setOpticalSizeAuto(true)
+ expect(text.fontVariations).toEqual([])
+ stop()
+})
+
+test('a named weight draws at its own axes, keeping an optical size set by hand', async () => {
+ const { editor, text, stop } = await variableText()
+ editor.graph.updateNode(text.id, {
+ fontVariations: [
+ { axis: 'wght', value: 560 },
+ { axis: 'opsz', value: 16 }
+ ],
+ opticalSizeFromFontSize: false
+ })
+ const actions = createTypographyActions({
+ editor,
+ nodes: computed(() => [text]),
+ activeFormatting: computed(() => []),
+ supports: () => true,
+ options: {}
+ })
+ await actions.setWeight(700)
+ expect(text.fontWeight).toBe(700)
+ expect(text.fontVariations).toEqual([{ axis: 'opsz', value: 16 }])
+ stop()
+})
+
+test('a cancelled axis edit puts back the axes it previewed', async () => {
+ const { text, axes, stop } = await variableText()
+ axes.previewAxis('opsz', 18)
+ expect(text.opticalSizeFromFontSize).toBe(false)
+ axes.cancelAxis()
+ expect(text.fontVariations).toEqual([])
+ expect(text.opticalSizeFromFontSize).toBe(true)
+ stop()
+})
+
+test('an axis set while text is edited styles the selected characters, and undoes', async () => {
+ await fontManager.loadFont('Inter', 'Regular')
+ const ck = await initCanvasKit()
+ const surface = ck.MakeSurface(200, 200)
+ if (!surface) throw new Error('Expected a surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ const editor = createEditor()
+ editor.setCanvasKit(ck, renderer)
+ await renderer.loadFonts()
+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {
+ text: 'Hello world',
+ fontFamily: 'Inter',
+ width: 200,
+ height: 20
+ })
+ editor.startTextEditing(text.id)
+ const state = editor.textEditor?.state
+ if (!state) throw new Error('Expected a text editor')
+ state.selectionAnchor = 6
+ state.cursor = 11
+ const scope = effectScope()
+ const axes = scope.run(() => createTypographyAxes(editor, computed(() => [text])))
+ if (!axes) throw new Error('Expected the axes')
+ const node = () => editor.graph.getNode(text.id)
+ try {
+ axes.previewAxis('wght', 500)
+ axes.setAxis('wght', 600)
+ expect(node()?.fontVariations).toEqual([])
+ expect(node()?.styleRuns).toEqual([
+ { start: 6, length: 5, style: { fontVariations: [{ axis: 'wght', value: 600 }] } }
+ ])
+ editor.undoAction()
+ expect(node()?.styleRuns).toEqual([])
+ // Whether optical size follows the font size is the layer's, which selected characters
+ // cannot set for themselves.
+ expect(axes.opticalSizeEditable.value).toBe(false)
+ axes.setOpticalSizeAuto(false)
+ axes.setAxis('opsz', 20)
+ expect(node()?.opticalSizeFromFontSize).toBe(true)
+ expect(node()?.styleRuns).toEqual([])
+ } finally {
+ scope.stop()
+ editor.dispose()
+ renderer.destroy()
+ }
+})
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 200690ad4..0c88b84e7 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -11,6 +11,7 @@ import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'
import FontPicker from '@/components/font-picker/FontPicker.vue'
import NumberField from '@/components/inputs/NumberField.vue'
import SharedStyleField from '@/components/properties/shared-style/SharedStyleField.vue'
+import FontAxisField from '@/components/properties/typography/FontAxisField.vue'
import LetterSpacingField from '@/components/properties/typography/LetterSpacingField.vue'
import LineHeightField from '@/components/properties/typography/LineHeightField.vue'
import VariableNumberField from '@/components/properties/VariableNumberField.vue'
@@ -144,6 +145,25 @@ function picked<T>(value: MixedValue<T>): T | '' {
</PanelFieldGroup>
</PanelGrid>
+ <PanelGrid
+ v-if="ctx.axes.value.length > 0"
+ :columns="2"
+ class="mb-3"
+ data-property="variable-axes"
+ >
+ <PanelFieldGroup v-for="axis in ctx.axes.value" :key="axis.tag" :label="axis.name">
+ <FontAxisField
+ :axis="axis"
+ :optical-size-auto="ctx.opticalSizeAuto.value"
+ :optical-size-editable="ctx.opticalSizeEditable.value"
+ @preview="ctx.actions.previewAxis(axis.tag, $event)"
+ @commit="ctx.actions.setAxis(axis.tag, $event)"
+ @cancel="ctx.actions.cancelAxis()"
+ @update:optical-size-auto="ctx.actions.setOpticalSizeAuto($event)"
+ />
+ </PanelFieldGroup>
+ </PanelGrid>
+
<PanelGrid :columns="2" class="mb-3">
<PanelFieldGroup :label="panels.lineHeight">
<LineHeightField
diff --git a/src/components/properties/typography/FontAxisField.vue b/src/components/properties/typography/FontAxisField.vue
new file mode 100644
index 000000000..e3b119e8b
--- /dev/null
+++ b/src/components/properties/typography/FontAxisField.vue
@@ -0,0 +1,84 @@
+<script setup lang="ts">
+import { SelectRoot, SelectTrigger } from 'reka-ui'
+import { computed } from 'vue'
+
+import type { MixedValue } from '@open-pencil/vue/controls/node-props'
+import type { TypographyAxis } from '@open-pencil/vue/controls/typography'
+import { useI18n } from '@open-pencil/vue/i18n'
+import { useRetainedPopup } from '@open-pencil/vue/lifecycle/retention'
+
+import NumberField from '@/components/inputs/NumberField.vue'
+import AppSelectContent from '@/components/ui/select/AppSelectContent.vue'
+import AppSelectItem from '@/components/ui/select/AppSelectItem.vue'
+
+/**
+ * One axis of a variable font. Optical size reads Auto while it follows the font size, as line
+ * height reads Auto, and its menu switches between that and a size set by hand.
+ */
+const { axis, opticalSizeAuto, opticalSizeEditable } = defineProps<{
+ axis: TypographyAxis
+ opticalSizeAuto: MixedValue<boolean>
+ /** False while text is edited: whether optical size follows the font size is the layer's. */
+ opticalSizeEditable: boolean
+}>()
+const emit = defineEmits<{
+ preview: [value: number]
+ commit: [value: number]
+ cancel: []
+ 'update:opticalSizeAuto': [auto: boolean]
+}>()
+const { panels } = useI18n()
+const { open: popupOpen, portalActive } = useRetainedPopup()
+const opticalSize = computed(() => axis.tag === 'opsz')
+const automatic = computed(() => opticalSize.value && opticalSizeAuto === true)
+/** Axes without an icon of their own show their tag, as Position shows X and Y. */
+const tagIcon = computed(() =>
+ ['wght', 'wdth', 'slnt', 'ital', 'opsz'].includes(axis.tag) ? undefined : axis.tag
+)
+</script>
+
+<template>
+ <NumberField
+ :model-value="axis.value"
+ :aria-label="axis.name"
+ :min="axis.min"
+ :max="axis.max"
+ :icon="tagIcon"
+ :disabled="opticalSize && !opticalSizeEditable"
+ :data-property="`font-axis-${axis.tag}`"
+ @update:model-value="emit('preview', $event)"
+ @commit="(value: number) => emit('commit', value)"
+ @cancel="emit('cancel')"
+ >
+ <template v-if="!tagIcon" #icon>
+ <icon-lucide-bold v-if="axis.tag === 'wght'" class="size-3" />
+ <icon-lucide-move-horizontal v-else-if="axis.tag === 'wdth'" class="size-3" />
+ <icon-lucide-italic v-else-if="axis.tag === 'slnt' || axis.tag === 'ital'" class="size-3" />
+ <icon-lucide-type v-else class="size-3" />
+ </template>
+ <template v-if="automatic" #display
+ ><span class="min-w-0 flex-1 truncate text-surface">{{ panels.auto }}</span></template
+ >
+ <template v-if="opticalSize" #suffix>
+ <SelectRoot
+ v-model:open="popupOpen"
+ :model-value="automatic ? 'AUTO' : 'FIXED'"
+ @update:model-value="emit('update:opticalSizeAuto', $event === 'AUTO')"
+ >
+ <SelectTrigger
+ :aria-label="panels.opticalSizeMode"
+ :disabled="!opticalSizeEditable"
+ class="flex shrink-0 items-center self-stretch px-1 text-muted"
+ data-property="optical-size-mode"
+ @pointerdown.stop
+ @keydown.stop
+ ><icon-lucide-chevron-down class="size-3"
+ /></SelectTrigger>
+ <AppSelectContent v-if="portalActive" align="end">
+ <AppSelectItem value="AUTO">{{ panels.auto }}</AppSelectItem>
+ <AppSelectItem value="FIXED">{{ panels.sizingFixed }}</AppSelectItem>
+ </AppSelectContent>
+ </SelectRoot>
+ </template>
+ </NumberField>
+</template>
diff --git a/src/components/properties/typography/LineHeightField.vue b/src/components/properties/typography/LineHeightField.vue
index 270633779..d00a34f2e 100644
--- a/src/components/properties/typography/LineHeightField.vue
+++ b/src/components/properties/typography/LineHeightField.vue
@@ -77,6 +77,7 @@ function setMode(mode: string) {
:aria-label="panels.lineHeightMode"
class="flex shrink-0 items-center self-stretch px-1 text-muted"
@pointerdown.stop
+ @keydown.stop
><icon-lucide-chevron-down class="size-3"
/></SelectTrigger>
<AppSelectContent v-if="portalActive" align="end">
diff --git a/tests/engine/app/document/io/changes.test.ts b/tests/engine/app/document/io/changes.test.ts
index 91a84b932..0a38a3734 100644
--- a/tests/engine/app/document/io/changes.test.ts
+++ b/tests/engine/app/document/io/changes.test.ts
@@ -1,13 +1,19 @@
import { expect, test } from 'bun:test'
+import { computed, effectScope } from 'vue'
+
import { createEditor } from '@open-pencil/core'
import { exportFigFile, parseFigFile, populateFigPage } from '@open-pencil/core/io/formats/fig'
import { computeAllLayouts } from '@open-pencil/core/layout'
+import { fontManager } from '@open-pencil/core/text'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
import { createDocumentChanges } from '@/app/document/io/changes'
+import { createTypographyActions } from '#vue/controls/typography/actions'
+import { createTypographyAxes } from '#vue/controls/typography/axes'
+
test('repainting and selection do not dirty a document; content mutations do', () => {
const editor = createEditor()
const changes = createDocumentChanges(editor)
@@ -215,3 +221,52 @@ test('an edit made after undoing past the save leaves the saved state out of rea
expect(changes.hasUnsavedChanges()).toBe(true)
})
})
+
+test('a dragged typography field undone back leaves the document saved', async () => {
+ await fontManager.loadFont('Inter', 'Regular')
+ const editor = createEditor()
+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {
+ text: 'a',
+ fontFamily: 'Inter'
+ })
+ const changes = createDocumentChanges(editor)
+ const scope = effectScope()
+ const nodes = computed(() => [editor.graph.getNode(text.id) ?? text])
+ const controls = scope.run(() => ({
+ actions: createTypographyActions({
+ editor,
+ nodes,
+ activeFormatting: computed(() => []),
+ supports: () => true,
+ options: {}
+ }),
+ axes: createTypographyAxes(editor, nodes)
+ }))
+ if (!controls) throw new Error('Expected the typography controls')
+ // Each drag step previews in a task of its own, as pointer moves do.
+ const nextTask = () =>
+ new Promise((resolve) => {
+ setTimeout(resolve, 0)
+ })
+ try {
+ changes.markSaved()
+ controls.actions.updateProp('fontSize', 20)
+ await nextTask()
+ controls.actions.updateProp('fontSize', 24)
+ await nextTask()
+ controls.actions.commitProp('fontSize', 24, 14)
+ controls.axes.previewAxis('wght', 500)
+ await nextTask()
+ controls.axes.setAxis('wght', 600)
+ await nextTask()
+ expect(changes.hasUnsavedChanges()).toBe(true)
+ editor.undoAction()
+ editor.undoAction()
+ await nextTask()
+ expect(changes.hasUnsavedChanges()).toBe(false)
+ } finally {
+ scope.stop()
+ changes.dispose()
+ editor.dispose()
+ }
+})