Skip to content

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

fix!: name font faces as their fonts do, so files open in Figma without missing fonts (#1588)

Danila Poyarkov51daf1b9f6c8
diff --git a/changes/1588/breaking.md b/changes/1588/breaking.md
new file mode 100644
index 000000000..9d9750638
--- /dev/null
+++ b/changes/1588/breaking.md
@@ -0,0 +1 @@
+- Text nodes and style runs have a `fontStyle` face name, family faces carry a `style`, and `FONT_WEIGHT_NAMES` uses Google Fonts' names ("SemiBold"). `weightToStyleName`, `weightToFigmaStyle`, `styleToVariant`, and `normalizeFontStyleName` are removed, and `weightToStyle` is renamed `faceLoadKey`.
diff --git a/changes/1588/fixed.md b/changes/1588/fixed.md
new file mode 100644
index 000000000..ddbdc6495
--- /dev/null
+++ b/changes/1588/fixed.md
@@ -0,0 +1 @@
+- Text keeps each font face's own style name ("Semi Bold", "Book", "Italic"), so text saved to `.fig` files or copied to Figma no longer opens there as a missing font in a plain italic or in a family whose names differ from Inter's. The plugin API's `fontName`, the style picker, and the missing fonts banner show the same names, and the banner lists faces of one weight (Avenir Book and Roman) separately.
diff --git a/packages/cli/src/commands/export/font-policy.ts b/packages/cli/src/commands/export/font-policy.ts
index 6e7b46a3d..4771c0db4 100644
--- a/packages/cli/src/commands/export/font-policy.ts
+++ b/packages/cli/src/commands/export/font-policy.ts
@@ -11,7 +11,7 @@ export const FONT_POLICIES = new Set(['allow', 'strict', 'warn'])
*/
export function reportFontStatus(status: DocumentFontStatus, policy: string): void {
if (policy === 'allow' || status.faithful) return
- const names = status.issues.map((face) => `${face.family} ${face.style}`).join(', ')
+ const names = status.issues.map((face) => `${face.family} ${face.name}`).join(', ')
const message = `Font substitution: ${names}`
if (policy === 'strict') {
printError(message)
diff --git a/packages/core/src/canvas/labels/paragraph-cache.ts b/packages/core/src/canvas/labels/paragraph-cache.ts
index 7702cccec..d8021d170 100644
--- a/packages/core/src/canvas/labels/paragraph-cache.ts
+++ b/packages/core/src/canvas/labels/paragraph-cache.ts
@@ -1,6 +1,6 @@
import type { Canvas, CanvasKit, Font, Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import type { Size } from '@open-pencil/scene-graph/primitives'
import { detectTextDirection } from '@open-pencil/scene-graph/text/direction'
@@ -26,7 +26,7 @@ export interface LabelFontOptions {
/** Semibold labels are section titles, drawn in their own face; the rest in Inter. */
function labelFontFamilies(weight: number): string[] {
- const families = resolveParagraphFontFamilies(DEFAULT_FONT_FAMILY, weightToStyle(weight))
+ const families = resolveParagraphFontFamilies(DEFAULT_FONT_FAMILY, faceLoadKey(weight))
return weight >= 600 ? [SECTION_TITLE_FONT_FAMILY, ...families] : families
}
diff --git a/packages/core/src/canvas/renderer/fonts.ts b/packages/core/src/canvas/renderer/fonts.ts
index 3764865e1..c8cc577f4 100644
--- a/packages/core/src/canvas/renderer/fonts.ts
+++ b/packages/core/src/canvas/renderer/fonts.ts
@@ -14,7 +14,7 @@ import {
} from '#core/constants'
import { withTextMeasurer } from '#core/layout/text-measurement'
import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { prepareGraphFonts } from '#core/text/prepare'
import {
fontCoverageDemand,
diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.ts
index 542c1ece5..77ec48c50 100644
--- a/packages/core/src/canvas/renderer/lifecycle.ts
+++ b/packages/core/src/canvas/renderer/lifecycle.ts
@@ -1,6 +1,6 @@
import type { SkiaRenderer } from '#core/canvas/renderer'
import { clearSubtreePictureCache } from '#core/canvas/renderer/state'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
function clearRetainedSceneState(r: SkiaRenderer): void {
r.scenePicture?.delete()
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index f60d08408..83de14a4a 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -15,7 +15,7 @@ import { textLinesOverflow } from '@open-pencil/scene-graph/text'
import { createSceneGeometry, nodeOrientationMatrix, projectedNode } from '#core/geometry'
import { shownText } from '#core/text/case'
import { mayHoldEmoji } from '#core/text/emoji'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import {
addStrokeRunToPath,
strokeRuns,
diff --git a/packages/core/src/canvas/text/decorations.ts b/packages/core/src/canvas/text/decorations.ts
index 99f1b583a..37fc25e64 100644
--- a/packages/core/src/canvas/text/decorations.ts
+++ b/packages/core/src/canvas/text/decorations.ts
@@ -8,7 +8,7 @@ import type {
TextDecorationStyle
} from '@open-pencil/scene-graph'
import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { outlineInk, savedGlyphInk, type InkSpan } from '#core/canvas/text/ink'
import { COMBINING_KEYCAP, drawKeycapFrame } from '#core/canvas/text/keycap'
@@ -166,7 +166,7 @@ function decorationRects(
lines: LineSpan[]
): TextDecorationRect[] {
const metrics =
- fontDecorationMetricsSync(style.fontFamily, weightToStyle(style.fontWeight, style.italic)) ??
+ fontDecorationMetricsSync(style.fontFamily, faceLoadKey(style.fontWeight, style.italic)) ??
UNLOADED_FONT_METRICS
const size = style.fontSize
const underline = style.textDecoration === 'UNDERLINE'
diff --git a/packages/core/src/canvas/text/font-families.ts b/packages/core/src/canvas/text/font-families.ts
index e38f2d893..989141f9a 100644
--- a/packages/core/src/canvas/text/font-families.ts
+++ b/packages/core/src/canvas/text/font-families.ts
@@ -1,14 +1,15 @@
import { uniq } from 'es-toolkit/array'
import type { FontVariation } from '@open-pencil/scene-graph'
-import { parseFontStyle, weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { parseFontStyle, faceLoadKey } from '@open-pencil/scene-graph/font-style'
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 { FaceWeight } from '#core/text/font/faces'
+import { fontManager } from '#core/text/font/manager'
+import { fontWeightMatchOrder } from '#core/text/font/style'
import type { FontAxis } from '#core/text/font/variation'
-import { fontManager, fontWeightMatchOrder } from '#core/text/fonts'
const familiesCache = new ResourceCache<string, string[]>({ maxEntries: 256 })
@@ -30,7 +31,7 @@ export interface DrawnFontAxes {
*/
export function drawnFontVariations(font: DrawnFontAxes): FontVariation[] {
const named =
- fontManager.namedInstanceVariations(font.family, weightToStyle(font.weight, font.italic)) ?? []
+ fontManager.namedInstanceVariations(font.family, faceLoadKey(font.weight, font.italic)) ?? []
const set = font.opticalSizeFromFontSize
? [
...font.variations.filter((variation) => variation.axis !== 'opsz'),
@@ -65,10 +66,10 @@ export function drawnFontAxes(font: DrawnFontAxes): DrawnFontAxis[] | null {
* nearest loaded weight in the same slant, then the other, as font matching picks it; `null`
* when the family has none loaded.
*/
-export function loadedFace(family: string, weight: number, italic: boolean): FamilyFace | null {
+export function loadedFace(family: string, weight: number, italic: boolean): FaceWeight | null {
for (const slant of [italic, !italic]) {
for (const candidate of fontWeightMatchOrder(weight)) {
- if (fontManager.isStyleLoaded(family, weightToStyle(candidate, slant)))
+ if (fontManager.isStyleLoaded(family, faceLoadKey(candidate, slant)))
return { weight: candidate, italic: slant }
}
}
@@ -118,7 +119,7 @@ export function resolveParagraphFontFamilies(
const drawn = loadedFace(primary, asked.weight, asked.italic)
const renderPrimary = renderFamilies(
primary,
- drawn ? weightToStyle(drawn.weight, drawn.italic) : style
+ drawn ? faceLoadKey(drawn.weight, drawn.italic) : style
)
const renderArabicFallbacks = arabicFallbacks.flatMap((family) =>
renderFamilies(family, 'Regular')
diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.ts
index db62066cb..0979c3085 100644
--- a/packages/core/src/canvas/text/index.ts
+++ b/packages/core/src/canvas/text/index.ts
@@ -1,9 +1,9 @@
import type { SceneNode } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { shownCharacters, shownText } from '#core/text/case'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import {
fontCoverageDemand,
fontFaceDemand,
@@ -42,12 +42,12 @@ function requiredNodeFaces(node: SceneNode): Array<{ family: string; style: stri
const baseFamily = node.fontFamily || DEFAULT_FONT_FAMILY
const faces = new Map<string, { family: string; style: string }>()
const add = (family: string, style: string) => faces.set(`${family}\0${style}`, { family, style })
- add(baseFamily, weightToStyle(node.fontWeight, node.italic))
+ add(baseFamily, faceLoadKey(node.fontWeight, node.italic))
for (const run of node.styleRuns) {
const family = run.style.fontFamily ?? baseFamily
const weight = run.style.fontWeight ?? node.fontWeight
const italic = run.style.italic ?? node.italic
- add(family, weightToStyle(weight, italic))
+ add(family, faceLoadKey(weight, italic))
}
return Array.from(faces.values())
}
diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.ts
index 4a1949bfe..09fa2bab8 100644
--- a/packages/core/src/canvas/text/layout/build.ts
+++ b/packages/core/src/canvas/text/layout/build.ts
@@ -1,7 +1,7 @@
import type { Paragraph } from 'canvaskit-wasm'
import type { CharacterStyleOverride, StyleRun } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import {
hasParagraphSpacing,
hasTextList,
@@ -162,7 +162,7 @@ function listStyle(node: ParagraphNode, firstCharacter: number): ListStyle {
return {
em: override?.fontSize ?? (node.fontSize || DEFAULT_FONT_SIZE),
family: override?.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY),
- style: weightToStyle(override?.fontWeight ?? node.fontWeight, override?.italic ?? node.italic),
+ style: faceLoadKey(override?.fontWeight ?? node.fontWeight, override?.italic ?? node.italic),
override
}
}
diff --git a/packages/core/src/canvas/text/paragraph/index.ts b/packages/core/src/canvas/text/paragraph/index.ts
index 43403530f..dc0471584 100644
--- a/packages/core/src/canvas/text/paragraph/index.ts
+++ b/packages/core/src/canvas/text/paragraph/index.ts
@@ -11,7 +11,7 @@ import type {
import type { SceneNode } from '@open-pencil/scene-graph'
import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
@@ -30,7 +30,7 @@ import type { TextRenderer } from '#core/canvas/text/renderer'
import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'
import { shownTextSlice } from '#core/text/case'
import { ELLIPSIS } from '#core/text/ellipsis'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import type { ParagraphNode } from './inputs'
@@ -280,7 +280,7 @@ export function buildSkParagraph(
const fontFamilies = (primary: string, weight: number, italic = false) =>
resolveParagraphFontFamilies(
primary,
- weightToStyle(weight, italic),
+ faceLoadKey(weight, italic),
arabicFallbacks,
cjkFallbacks
)
diff --git a/packages/core/src/canvas/text/placed.ts b/packages/core/src/canvas/text/placed.ts
index 05b3f285b..73959f561 100644
--- a/packages/core/src/canvas/text/placed.ts
+++ b/packages/core/src/canvas/text/placed.ts
@@ -2,7 +2,7 @@ import type { Paragraph } from 'canvaskit-wasm'
import { uniq } from 'es-toolkit/array'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import {
drawnFontVariations,
@@ -19,7 +19,7 @@ import {
shardCovers,
type GlyphOutlineSource
} from '#core/text/font/glyphs'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
type GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]
@@ -43,7 +43,7 @@ export interface LaidOutGlyph {
/** The loaded face of a family the paragraph draws a style in, as its style name. */
function loadedStyle(family: string, weight: number, italic: boolean): string | null {
const face = loadedFace(family, weight, italic)
- return face ? weightToStyle(face.weight, face.italic) : null
+ return face ? faceLoadKey(face.weight, face.italic) : null
}
/**
@@ -56,7 +56,7 @@ function fontAt(node: SceneNode, index: number) {
const family = run?.style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)
const weight = run?.style.fontWeight ?? node.fontWeight
const italic = run?.style.italic ?? node.italic
- const style = weightToStyle(weight, italic)
+ const style = faceLoadKey(weight, italic)
const variations = drawnFontVariations({
family,
weight,
diff --git a/packages/core/src/canvas/text/preparation/index.ts b/packages/core/src/canvas/text/preparation/index.ts
index 614ea9a83..2d3440f95 100644
--- a/packages/core/src/canvas/text/preparation/index.ts
+++ b/packages/core/src/canvas/text/preparation/index.ts
@@ -4,7 +4,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'
import type { TextLayout } from '#core/canvas/text/layout'
import type { ParagraphBuildOptions } from '#core/canvas/text/paint'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import type { PreparedText, TextPreparationCache } from './cache'
diff --git a/packages/core/src/canvas/text/shape.ts b/packages/core/src/canvas/text/shape.ts
index a7f2a9635..bd590712b 100644
--- a/packages/core/src/canvas/text/shape.ts
+++ b/packages/core/src/canvas/text/shape.ts
@@ -19,7 +19,8 @@ import { getCanvasKit } from '#core/canvaskit'
import { shownText } from '#core/text/case'
import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
import type { OutlineCommand } from '#core/text/font/glyphs'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
+import { faceStyleName } from '#core/text/font/names'
import { nextGraphemeBoundary } from '#core/text/graphemes'
/**
@@ -229,8 +230,7 @@ export async function withFigExportRuntime<T>(
ck: CanvasKit | undefined,
write: (runtime: FigNodeChangeExportRuntime) => Promise<T>
): Promise<T> {
- if (!needsShaping(graph)) return write({ ...EMPTY_EXPORT_RUNTIME, textDecorations })
- return withTextShaper(ck ?? (await getCanvasKit()), (shapeText) =>
- write({ shapeText, textDecorations })
- )
+ const named = { textDecorations, fontStyleName: faceStyleName }
+ if (!needsShaping(graph)) return write({ ...EMPTY_EXPORT_RUNTIME, ...named })
+ return withTextShaper(ck ?? (await getCanvasKit()), (shapeText) => write({ shapeText, ...named }))
}
diff --git a/packages/core/src/editor/clipboard/fonts.ts b/packages/core/src/editor/clipboard/fonts.ts
index 865bff451..15b48a654 100644
--- a/packages/core/src/editor/clipboard/fonts.ts
+++ b/packages/core/src/editor/clipboard/fonts.ts
@@ -1,8 +1,8 @@
import type { EditorContext } from '#core/editor/types'
import { computeAllLayouts } from '#core/layout'
-import { fontManager } from '#core/text/fonts'
-import { collectGraphFontRequirements } from '#core/text/requirements'
-import { missingGraphFontScripts } from '#core/text/resolved-requirements'
+import { fontManager } from '#core/text/font/manager'
+import { collectGraphFontRequirements } from '#core/text/requirements/collect'
+import { missingGraphFontScripts } from '#core/text/requirements/resolved'
export function createClipboardFontActions(ctx: EditorContext) {
async function loadFontsForNodes(nodeIds: string[]) {
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 2c202db11..aa338a742 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -20,7 +20,7 @@ import { installTextMeasurer } from '#core/layout'
import { createLayoutRunner } from '#core/layout/mutations'
import { emitNavigationTrace } from '#core/profiler'
import { TextEditor } from '#core/text/editor'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { fontResolver } from '#core/text/resolver'
import { createAlignmentActions } from './alignment'
diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.ts
index a38875b2c..5bcbc8ba2 100644
--- a/packages/core/src/editor/pages.ts
+++ b/packages/core/src/editor/pages.ts
@@ -15,9 +15,9 @@ import {
} from '#core/kiwi/fig/population/client'
import { isReaderPagePending, recoverReaderPage } from '#core/kiwi/fig/session/document-state'
import { computeAllLayouts } from '#core/layout'
-import { fontManager } from '#core/text/fonts'
-import { collectGraphFontRequirements } from '#core/text/requirements'
-import { missingGraphFontScripts } from '#core/text/resolved-requirements'
+import { fontManager } from '#core/text/font/manager'
+import { collectGraphFontRequirements } from '#core/text/requirements/collect'
+import { missingGraphFontScripts } from '#core/text/requirements/resolved'
import { createPageViewportStore } from './page-viewports'
import { createPageLayouts } from './pages/layouts'
diff --git a/packages/core/src/editor/pages/layouts.ts b/packages/core/src/editor/pages/layouts.ts
index 90bb538f4..0b5d2b6ac 100644
--- a/packages/core/src/editor/pages/layouts.ts
+++ b/packages/core/src/editor/pages/layouts.ts
@@ -1,6 +1,6 @@
import type { EditorContext } from '#core/editor/types'
import { getTextMeasurer, type TextMeasurer } from '#core/layout/text-measurement'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
/** What sized a page's text when it was laid out. */
interface TextBasis {
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index 803593bad..ee6020f76 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -1,6 +1,6 @@
import type { SceneNode } from '@open-pencil/scene-graph'
import { copyDerivedGlyphs, copyGeometryPaths } from '@open-pencil/scene-graph/copy'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import {
cloneInstanceOverrideState,
setInstanceOverride,
@@ -36,7 +36,7 @@ import { createVariableBindingActions } from './variable-bindings'
*/
function isPathTextEditable(node: SceneNode): boolean {
if (!node.textPathData) return true
- return hasGlyphOutlines(node.fontFamily, weightToStyle(node.fontWeight, node.italic))
+ return hasGlyphOutlines(node.fontFamily, faceLoadKey(node.fontWeight, node.italic))
}
type PathTextEditSnapshot = Pick<
diff --git a/packages/core/src/editor/text/path-edit.ts b/packages/core/src/editor/text/path-edit.ts
index 9a4b3b66a..4a583595b 100644
--- a/packages/core/src/editor/text/path-edit.ts
+++ b/packages/core/src/editor/text/path-edit.ts
@@ -2,7 +2,7 @@ import { mean } from 'es-toolkit'
import { encodePathCommandsBlob } from '@open-pencil/fig/node-change'
import type { DerivedTextGlyph, SceneNode, TextPathData } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import { textLengthPixels } from '@open-pencil/scene-graph/text'
@@ -44,7 +44,7 @@ function layOutPathText(
const letterSpacing = textLengthPixels(type.letterSpacing, fontSize)
const metrics = getGlyphOutlineMetricsSync(
type.fontFamily,
- weightToStyle(type.fontWeight, type.italic),
+ faceLoadKey(type.fontWeight, type.italic),
type.text,
fontSize
)
@@ -231,7 +231,7 @@ function alignedRun(
if (align !== 'CENTER' && align !== 'RIGHT') return all
const old = getGlyphOutlineMetricsSync(
node.fontFamily,
- weightToStyle(node.fontWeight, node.italic),
+ faceLoadKey(node.fontWeight, node.italic),
node.text,
node.fontSize
)
diff --git a/packages/core/src/editor/text/typeface.ts b/packages/core/src/editor/text/typeface.ts
index deabe67fd..32d521692 100644
--- a/packages/core/src/editor/text/typeface.ts
+++ b/packages/core/src/editor/text/typeface.ts
@@ -3,7 +3,7 @@ import {
figJamTypefaceFields,
type FigJamTypeface
} from '@open-pencil/scene-graph/figjam'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { generatedFrameText } from '@open-pencil/scene-graph/generated'
import { recordSubtreeEdit } from '#core/editor/components/slots/history'
@@ -17,7 +17,7 @@ export function createGeneratedTextActions(ctx: EditorContext) {
*/
async function setGeneratedTextTypeface(ids: Iterable<string>, typeface: FigJamTypeface) {
const { fontFamily, fontWeight } = FIGJAM_TYPEFACES[typeface]
- await ctx.loadFont(fontFamily, weightToStyle(fontWeight, false))
+ await ctx.loadFont(fontFamily, faceLoadKey(fontWeight, false))
const frames = [...ids].flatMap((id) => {
const node = ctx.graph.getNode(id)
return node && generatedFrameText(ctx.graph, node) ? [node] : []
diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.ts
index 0e6fc0e6e..a65837cde 100644
--- a/packages/core/src/figma-api/accessors/text/index.ts
+++ b/packages/core/src/figma-api/accessors/text/index.ts
@@ -12,7 +12,8 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import type { FigmaFontNameInput } from '#core/figma-api/fonts'
+import { assertFontLoaded, assertTextFontsLoaded } from '#core/figma-api/fonts/loaded'
+import type { FigmaFontNameInput } from '#core/figma-api/fonts/names'
import {
getParagraphSpacing,
letterSpacingValue,
@@ -23,10 +24,8 @@ import {
type FigmaLetterSpacing,
type FigmaLineHeight
} from '#core/figma-api/text'
-import { assertFontLoaded, assertTextFontsLoaded } from '#core/figma-api/text/loaded-fonts'
import { getTextStyle, type TextSegmentField } from '#core/figma-api/text/style'
import { styleRunsWithPatch, textStyleChanges } from '#core/text/character-style'
-import { textFontFace } from '#core/text/requirements'
import { hyperlinkTarget } from './hyperlink'
import { fontNameStyle } from './ranges'
@@ -120,7 +119,7 @@ export function installTextNodeProxyAccessors(
mixed,
(node, value) => {
const style = fontNameStyle('set_fontName', node, 0, value)
- assertFontLoaded('set_fontName', textFontFace(node, style))
+ assertFontLoaded('set_fontName', node, style)
return style
},
false
@@ -137,8 +136,9 @@ export function installTextNodeProxyAccessors(
),
// A weight is a face of its own, which has to be loaded as a new font does.
fontWeight: characterStyle<number>(internals, 'fontWeight', mixed, (node, fontWeight) => {
- assertFontLoaded('set_fontWeight', textFontFace(node, { fontWeight }))
- return { fontWeight }
+ const style = { fontWeight, fontStyle: null }
+ assertFontLoaded('set_fontWeight', node, style)
+ return style
}),
textAlignHorizontal: field(internals, 'textAlignHorizontal'),
textAlignVertical: field(internals, 'textAlignVertical'),
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index 78b31a370..8d188d3ae 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -22,15 +22,17 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
+import { assertFontLoaded, assertTextFontsLoaded } from '#core/figma-api/fonts/loaded'
import {
fontNameInputStyle,
- readVariationSettings,
- weightToStyleName,
type CurrentFont,
type FigmaFontName,
- type FigmaFontNameInput,
+ type FigmaFontNameInput
+} from '#core/figma-api/fonts/names'
+import {
+ readVariationSettings,
type FigmaVariationSettings
-} from '#core/figma-api/fonts'
+} from '#core/figma-api/fonts/variations'
import { parseFigmaPaints, type FigmaPaint } from '#core/figma-api/paints'
import {
getRangeIndentation,
@@ -41,7 +43,6 @@ import {
setRangeParagraphSpacing,
type FigmaLetterSpacing
} from '#core/figma-api/text'
-import { assertFontLoaded, assertTextFontsLoaded } from '#core/figma-api/text/loaded-fonts'
import {
assertTextRange,
getRangeTextStyle,
@@ -59,7 +60,7 @@ import {
styleRunsWithPatch,
type TextStylePatch
} from '#core/text/character-style'
-import { textFontFace } from '#core/text/requirements'
+import { textStyleName } from '#core/text/font/names'
import { hyperlinkTarget } from './hyperlink'
import { invalid, received } from './messages'
@@ -154,7 +155,7 @@ function stringProblem(value: unknown, at: string): string | null {
function currentFont(node: SceneNode, index: number): CurrentFont {
const at = Math.min(index, node.text.length - 1)
const [style] = at < 0 ? [nodeStyle(node)] : characterStyles(node, at, at + 1)
- const name = weightToStyleName(style.fontWeight, style.italic)
+ const name = textStyleName(style)
return {
style: name,
fontVariations: style.fontVariations,
@@ -349,7 +350,7 @@ const RANGE_SETTERS: Record<string, RangeSetter> = {
},
setRangeFontName: (method, node, start, _end, value) => {
const style = fontNameStyle(method, node, start, value)
- assertFontLoaded(method, textFontFace(node, style))
+ assertFontLoaded(method, node, style)
return style
},
setRangeFills: (method, _node, _start, _end, value) => ({
diff --git a/packages/core/src/figma-api/fonts.ts b/packages/core/src/figma-api/fonts.ts
deleted file mode 100644
index 6afc01479..000000000
--- a/packages/core/src/figma-api/fonts.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import { uniq, uniqBy } from 'es-toolkit/array'
-
-import type { FontVariation } from '@open-pencil/scene-graph'
-import type { FontFamilyStyle } from '@open-pencil/scene-graph/font-style'
-import {
- FONT_WEIGHT_NAMES,
- parseFontStyle,
- weightToStyle
-} from '@open-pencil/scene-graph/font-style'
-
-import {
- namedInstanceVariations,
- type FontAxis,
- type NamedInstance
-} from '#core/text/font/variation'
-import { fontManager } from '#core/text/fonts'
-
-/** A font as Figma reads one; a variable font's also lists every axis it is drawn at. */
-export type FigmaFontName = FontFamilyStyle & { variationSettings?: FigmaVariationSettings }
-export type FigmaFont = { fontName: FigmaFontName }
-
-export function weightToStyleName(weight: number, italic: boolean): string {
- const base = FONT_WEIGHT_NAMES[weight] ?? 'Regular'
- return italic ? `${base} Italic` : base
-}
-
-/**
- * The style name text asks the font manager for, whichever way a script spells it ("Italic",
- * "Semi Bold"), so a font a script loaded is the one its text edits find loaded.
- */
-function textFaceStyle(style: string): string {
- const { weight, italic } = parseFontStyle(style)
- return weightToStyle(weight, italic)
-}
-
-/** Figma's rejection for a font it cannot load. */
-function fontLoadError(family: string, style: string): Error {
- return new Error(`The font "${family} ${style}" could not be loaded`)
-}
-
-/**
- * Loads a font as Figma's `loadFontAsync` does, so text measures and draws with it from then on,
- * and rejects when it cannot load. A family named alone loads every style it has: one style of
- * each slant first, so the rest reuse its file where one variable file draws the whole slant, and
- * then the named styles a variable file draws, which text set by its axes alone takes.
- */
-export async function loadFigmaFont({ family, style }: FigmaFontNameInput): Promise<void> {
- if (style !== undefined) {
- const face = textFaceStyle(style)
- await fontManager.loadFont(family, face).catch(() => null)
- if (!fontManager.isStyleLoaded(family, face)) throw fontLoadError(family, style)
- return
- }
- const faces = (await fontManager.familyFaces(family).catch(() => null)) ?? [
- { weight: 400, italic: false }
- ]
- const load = (face: string) => fontManager.loadFont(family, face).catch(() => null)
- const first = uniqBy(faces, (face) => face.italic)
- await Promise.all(first.map((face) => load(weightToStyle(face.weight, face.italic))))
- await Promise.all(
- faces
- .filter((face) => !first.includes(face))
- .map((face) => load(weightToStyle(face.weight, face.italic)))
- )
- if (!fontManager.isLoaded(family)) throw fontLoadError(family, 'Regular')
- const named = [false, true].flatMap((italic) =>
- (fontManager.familyVariation(family, italic)?.instances ?? []).map((instance) =>
- weightToStyle(parseFontStyle(instance.name).weight, italic)
- )
- )
- await Promise.all(uniq(named).map(load))
-}
-
-/** Variable font axis values by axis tag, as `FontName.variationSettings` holds them. */
-export type FigmaVariationSettings = Record<string, number>
-
-/** A font to apply, as Figma takes one: `style` may be left out for the axes to pick it. */
-export interface FigmaFontNameInput {
- family: string
- style?: string
- variationSettings?: FigmaVariationSettings
-}
-
-/** Figma lists axis tags in code unit order, so `GRAD` comes before `opsz`. */
-function byCodeUnit(a: string, b: string): number {
- if (a === b) return 0
- return a < b ? -1 : 1
-}
-
-/** The axis tags a family accepts, as `getFontFamilyVariationAxes` lists them. */
-export function variationAxisTags(axes: readonly FontAxis[]): string[] {
- return axes.map((axis) => axis.tag).sort(byCodeUnit)
-}
-
-/**
- * Figma's `variationSettings` for text in `style` of a variable family: every axis, at the named
- * instance's value unless the text sets it. An optical size that follows the font size reads as
- * the instance's own, as Figma reads it. Nothing for a static family or one not loaded.
- */
-export function readVariationSettings(
- family: string,
- style: string,
- variations: readonly FontVariation[],
- opticalSizeFromFontSize: boolean
-): FigmaVariationSettings | undefined {
- const variation = fontManager.familyVariation(family, parseFontStyle(style).italic)
- if (!variation) return undefined
- const named = namedInstanceVariations(variation.data, style) ?? []
- const set = opticalSizeFromFontSize
- ? variations.filter((entry) => entry.axis !== 'opsz')
- : variations
- const values = new Map(variation.axes.map((axis) => [axis.tag, axis.default]))
- for (const { axis, value } of [...named, ...set]) if (values.has(axis)) values.set(axis, value)
- return Object.fromEntries([...values].sort(([a], [b]) => byCodeUnit(a, b)))
-}
-
-/** Where `value` sits on an axis, from -1 at its minimum through 0 at its default to 1. */
-function normalized(axis: FontAxis, value: number): number {
- if (value < axis.default) return (value - axis.default) / (axis.default - axis.min || 1)
- return (value - axis.default) / (axis.max - axis.default || 1)
-}
-
-/** How much two distances may differ in floating point and still be as near. */
-const DISTANCE_TOLERANCE = 1e-9
-
-/** The named instance nearest `target` on the font's axes; the later one where two are as near. */
-function nearestInstance(
- axes: readonly FontAxis[],
- instances: readonly NamedInstance[],
- target: Partial<FigmaVariationSettings>
-): string | undefined {
- let nearest: { name: string; distance: number } | undefined
- for (const instance of instances) {
- const distance = instance.variations.reduce((sum, { axis, value }) => {
- const found = axes.find((entry) => entry.tag === axis)
- const wanted = target[axis]
- if (!found || wanted === undefined) return sum
- return sum + (normalized(found, wanted) - normalized(found, value)) ** 2
- }, 0)
- if (!nearest || distance <= nearest.distance + DISTANCE_TOLERANCE) {
- nearest = { name: instance.name, distance }
- }
- }
- return nearest?.name
-}
-
-/**
- * What applying `input` sets on the text: its family and style, and the axes it sets over the
- * style's named instance. A style left out is the named instance nearest the axes, the ones the
- * input leaves out read from `current`; with no axes either, the current style stays. Axes the
- * family does not have throw, as Figma rejects them.
- */
-/** The family's axes in the slant asked for, once each of `tags` is checked among them. */
-function checkedVariation(method: string, family: string, slanted: boolean, tags: string[]) {
- const variation = fontManager.familyVariation(family, slanted)
- if (tags.length > 0 && variation === undefined) {
- throw new Error(
- `in ${method}: Font family "${family}" is not loaded, so its variation axes are unknown. Call loadFontAsync first.`
- )
- }
- if (tags.length > 0 && variation === null) {
- throw new Error(
- `in ${method}: "${tags[0]}" is not a valid variation setting. Font "${family}" has no variation axes.`
- )
- }
- if (variation) {
- const valid = variationAxisTags(variation.axes)
- const invalid = tags.find((tag) => !valid.includes(tag))
- if (invalid) {
- throw new Error(
- `in ${method}: "${invalid}" is not a valid variation setting. Valid settings are ${JSON.stringify(valid)}.`
- )
- }
- }
- return variation
-}
-
-/** The font a character has before a new one is set over it. */
-export interface CurrentFont {
- style: string
- /** The axes the text sets itself, over its style's. */
- fontVariations: readonly FontVariation[]
- variationSettings?: FigmaVariationSettings
-}
-
-export function fontNameInputStyle(
- method: string,
- input: FigmaFontNameInput,
- current?: CurrentFont
-): { fontFamily: string; fontWeight: number; italic: boolean; fontVariations: FontVariation[] } {
- const settings = input.variationSettings ?? {}
- const tags = Object.keys(settings)
- const slanted = parseFontStyle(input.style ?? current?.style ?? 'Regular').italic
- const variation = checkedVariation(method, input.family, slanted, tags)
- const style =
- input.style ??
- (tags.length > 0 && variation
- ? nearestInstance(variation.axes, variation.instances, {
- ...current?.variationSettings,
- ...settings
- })
- : undefined) ??
- current?.style ??
- 'Regular'
- const { weight, italic } = parseFontStyle(style)
- return {
- fontFamily: input.family,
- fontWeight: weight,
- // A style picked from the axes keeps the text's slant, whichever file the axes came from.
- italic: input.style ? italic : slanted,
- // A style resets the axes to its own; without one, the axes the text set stay.
- fontVariations: [
- ...(input.style ? [] : (current?.fontVariations ?? [])).filter(
- ({ axis }) => !tags.includes(axis)
- ),
- ...tags.map((axis) => ({ axis, value: settings[axis] ?? 0 }))
- ]
- }
-}
diff --git a/packages/core/src/figma-api/fonts/load.ts b/packages/core/src/figma-api/fonts/load.ts
new file mode 100644
index 000000000..81769db0c
--- /dev/null
+++ b/packages/core/src/figma-api/fonts/load.ts
@@ -0,0 +1,54 @@
+import { uniq, uniqBy } from 'es-toolkit/array'
+
+import { faceLoadKey, parseFontStyle } from '@open-pencil/scene-graph/font-style'
+
+import type { FigmaFontNameInput } from '#core/figma-api/fonts/names'
+import type { FaceWeight } from '#core/text/font/faces'
+import { fontManager } from '#core/text/font/manager'
+
+/**
+ * The style name text asks the font manager for, whichever way a script spells it ("Italic",
+ * "Semi Bold"), so a font a script loaded is the one its text edits find loaded.
+ */
+function textFaceStyle(style: string): string {
+ const { weight, italic } = parseFontStyle(style)
+ return faceLoadKey(weight, italic)
+}
+
+/** Figma's rejection for a font it cannot load. */
+function fontLoadError(family: string, style: string): Error {
+ return new Error(`The font "${family} ${style}" could not be loaded`)
+}
+
+/**
+ * Loads a font as Figma's `loadFontAsync` does, so text measures and draws with it from then on,
+ * and rejects when it cannot load. A family named alone loads every style it has: one style of
+ * each slant first, so the rest reuse its file where one variable file draws the whole slant, and
+ * then the named styles a variable file draws, which text set by its axes alone takes.
+ */
+export async function loadFigmaFont({ family, style }: FigmaFontNameInput): Promise<void> {
+ if (style !== undefined) {
+ const face = textFaceStyle(style)
+ await fontManager.loadFont(family, face).catch(() => null)
+ if (!fontManager.isStyleLoaded(family, face)) throw fontLoadError(family, style)
+ return
+ }
+ const faces: FaceWeight[] = (await fontManager.familyFaces(family).catch(() => null)) ?? [
+ { weight: 400, italic: false }
+ ]
+ const load = (face: string) => fontManager.loadFont(family, face).catch(() => null)
+ const first = uniqBy(faces, (face) => face.italic)
+ await Promise.all(first.map((face) => load(faceLoadKey(face.weight, face.italic))))
+ await Promise.all(
+ faces
+ .filter((face) => !first.includes(face))
+ .map((face) => load(faceLoadKey(face.weight, face.italic)))
+ )
+ if (!fontManager.isLoaded(family)) throw fontLoadError(family, 'Regular')
+ const named = [false, true].flatMap((italic) =>
+ (fontManager.familyVariation(family, italic)?.instances ?? []).map((instance) =>
+ faceLoadKey(parseFontStyle(instance.name).weight, italic)
+ )
+ )
+ await Promise.all(uniq(named).map(load))
+}
diff --git a/packages/core/src/figma-api/fonts/loaded.ts b/packages/core/src/figma-api/fonts/loaded.ts
new file mode 100644
index 000000000..61c2003c6
--- /dev/null
+++ b/packages/core/src/figma-api/fonts/loaded.ts
@@ -0,0 +1,65 @@
+import { uniqBy } from 'es-toolkit/array'
+
+import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+
+import { fontManager } from '#core/text/font/manager'
+import { textFaceName } from '#core/text/font/names'
+import { textFontFace } from '#core/text/requirements/collect'
+
+/** A face text draws in, and its name as Figma names it in its messages. */
+interface DescribedFace {
+ family: string
+ /** The style the font manager loads the face as. */
+ loadStyle: string
+ /** The face's own name, as `fontName` reads it. */
+ style: string
+}
+
+/** The face characters with `style` over the text draw in, named as the text names it. */
+function describedFace(node: SceneNode, style: CharacterStyleOverride = {}): DescribedFace {
+ const face = textFontFace(node, style)
+ return { family: face.family, loadStyle: face.style, style: textFaceName(node, style) }
+}
+
+function loadHint({ family, style }: DescribedFace): string {
+ return `Please call figma.loadFontAsync({ family: "${family}", style: "${style}" }) and await the returned promise first.`
+}
+
+function isLoaded(face: DescribedFace): boolean {
+ return fontManager.isStyleLoaded(face.family, face.loadStyle)
+}
+
+/** Every face the text draws in: its own and each style run's. */
+function textFaces(node: SceneNode): DescribedFace[] {
+ const faces = [
+ describedFace(node),
+ ...node.styleRuns.map((run) => describedFace(node, run.style))
+ ]
+ return uniqBy(faces, (face) => `${face.family}\0${face.loadStyle}`)
+}
+
+/**
+ * Figma refuses an edit that lays text out again until every font the text uses is loaded, so
+ * the text is never measured in a stand-in font. Paints and links need no font. Callers check
+ * the edit's own arguments first, as Figma does.
+ */
+export function assertTextFontsLoaded(method: string, node: SceneNode): void {
+ const font = textFaces(node).find((face) => !isLoaded(face))
+ if (!font) return
+ throw new Error(
+ `in ${method}: Cannot write to node with unloaded font "${font.family} ${font.style}". ${loadHint(font)}`
+ )
+}
+
+/** Figma refuses a font that is not loaded yet, before it checks the text's own. */
+export function assertFontLoaded(
+ method: string,
+ node: SceneNode,
+ style: CharacterStyleOverride
+): void {
+ const font = describedFace(node, style)
+ if (isLoaded(font)) return
+ throw new Error(
+ `in ${method}: Cannot use unloaded font "${font.family} ${font.style}". ${loadHint(font)}`
+ )
+}
diff --git a/packages/core/src/figma-api/fonts/names.ts b/packages/core/src/figma-api/fonts/names.ts
new file mode 100644
index 000000000..bc4764d1e
--- /dev/null
+++ b/packages/core/src/figma-api/fonts/names.ts
@@ -0,0 +1,72 @@
+import type { FontVariation } from '@open-pencil/scene-graph'
+import type { FontFamilyStyle } from '@open-pencil/scene-graph/font-style'
+import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
+
+import {
+ checkedVariation,
+ nearestInstance,
+ type FigmaVariationSettings
+} from '#core/figma-api/fonts/variations'
+import { faceForStyle } from '#core/text/font/names'
+
+/** A font as Figma reads one; a variable font's also lists every axis it is drawn at. */
+export type FigmaFontName = FontFamilyStyle & { variationSettings?: FigmaVariationSettings }
+export type FigmaFont = { fontName: FigmaFontName }
+
+/** A font to apply, as Figma takes one: `style` may be left out for the axes to pick it. */
+export interface FigmaFontNameInput {
+ family: string
+ style?: string
+ variationSettings?: FigmaVariationSettings
+}
+
+/** The font a character has before a new one is set over it. */
+export interface CurrentFont {
+ style: string
+ /** The axes the text sets itself, over its style's. */
+ fontVariations: readonly FontVariation[]
+ variationSettings?: FigmaVariationSettings
+}
+
+/**
+ * What applying `input` sets on the text: its family and style, and the axes it sets over the
+ * style's named instance. A style left out is the named instance nearest the axes, the ones the
+ * input leaves out read from `current`; with no axes either, the current style stays. Axes the
+ * family does not have throw, as Figma rejects them.
+ */
+export function fontNameInputStyle(
+ method: string,
+ input: FigmaFontNameInput,
+ current?: CurrentFont
+) {
+ const settings = input.variationSettings ?? {}
+ const tags = Object.keys(settings)
+ const slanted = parseFontStyle(input.style ?? current?.style ?? 'Regular').italic
+ const variation = checkedVariation(method, input.family, slanted, tags)
+ const style =
+ input.style ??
+ (tags.length > 0 && variation
+ ? nearestInstance(variation.axes, variation.instances, {
+ ...current?.variationSettings,
+ ...settings
+ })
+ : undefined) ??
+ current?.style ??
+ 'Regular'
+ const face = faceForStyle(input.family, style)
+ return {
+ fontFamily: input.family,
+ fontWeight: face.weight,
+ // A style picked from the axes keeps the text's slant, whichever file the axes came from.
+ italic: input.style ? face.italic : slanted,
+ // An instance of the other slant names no face of this one; the family's own name does.
+ fontStyle: input.style !== undefined || face.italic === slanted ? face.style : null,
+ // A style resets the axes to its own; without one, the axes the text set stay.
+ fontVariations: [
+ ...(input.style ? [] : (current?.fontVariations ?? [])).filter(
+ ({ axis }) => !tags.includes(axis)
+ ),
+ ...tags.map((axis) => ({ axis, value: settings[axis] ?? 0 }))
+ ]
+ }
+}
diff --git a/packages/core/src/figma-api/fonts/variations.ts b/packages/core/src/figma-api/fonts/variations.ts
new file mode 100644
index 000000000..a11aa43f5
--- /dev/null
+++ b/packages/core/src/figma-api/fonts/variations.ts
@@ -0,0 +1,100 @@
+import type { FontVariation } from '@open-pencil/scene-graph'
+import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
+
+import { fontManager } from '#core/text/font/manager'
+import {
+ namedInstanceVariations,
+ type FontAxis,
+ type NamedInstance
+} from '#core/text/font/variation'
+
+/** Variable font axis values by axis tag, as `FontName.variationSettings` holds them. */
+export type FigmaVariationSettings = Record<string, number>
+
+/** Figma lists axis tags in code unit order, so `GRAD` comes before `opsz`. */
+function byCodeUnit(a: string, b: string): number {
+ if (a === b) return 0
+ return a < b ? -1 : 1
+}
+
+/** The axis tags a family accepts, as `getFontFamilyVariationAxes` lists them. */
+export function variationAxisTags(axes: readonly FontAxis[]): string[] {
+ return axes.map((axis) => axis.tag).sort(byCodeUnit)
+}
+
+/**
+ * Figma's `variationSettings` for text in `style` of a variable family: every axis, at the named
+ * instance's value unless the text sets it. An optical size that follows the font size reads as
+ * the instance's own, as Figma reads it. Nothing for a static family or one not loaded.
+ */
+export function readVariationSettings(
+ family: string,
+ style: string,
+ variations: readonly FontVariation[],
+ opticalSizeFromFontSize: boolean
+): FigmaVariationSettings | undefined {
+ const variation = fontManager.familyVariation(family, parseFontStyle(style).italic)
+ if (!variation) return undefined
+ const named = namedInstanceVariations(variation.data, style) ?? []
+ const set = opticalSizeFromFontSize
+ ? variations.filter((entry) => entry.axis !== 'opsz')
+ : variations
+ const values = new Map(variation.axes.map((axis) => [axis.tag, axis.default]))
+ for (const { axis, value } of [...named, ...set]) if (values.has(axis)) values.set(axis, value)
+ return Object.fromEntries([...values].sort(([a], [b]) => byCodeUnit(a, b)))
+}
+
+/** Where `value` sits on an axis, from -1 at its minimum through 0 at its default to 1. */
+function normalized(axis: FontAxis, value: number): number {
+ if (value < axis.default) return (value - axis.default) / (axis.default - axis.min || 1)
+ return (value - axis.default) / (axis.max - axis.default || 1)
+}
+
+/** How much two distances may differ in floating point and still be as near. */
+const DISTANCE_TOLERANCE = 1e-9
+
+/** The named instance nearest `target` on the font's axes; the later one where two are as near. */
+export function nearestInstance(
+ axes: readonly FontAxis[],
+ instances: readonly NamedInstance[],
+ target: Partial<FigmaVariationSettings>
+): string | undefined {
+ let nearest: { name: string; distance: number } | undefined
+ for (const instance of instances) {
+ const distance = instance.variations.reduce((sum, { axis, value }) => {
+ const found = axes.find((entry) => entry.tag === axis)
+ const wanted = target[axis]
+ if (!found || wanted === undefined) return sum
+ return sum + (normalized(found, wanted) - normalized(found, value)) ** 2
+ }, 0)
+ if (!nearest || distance <= nearest.distance + DISTANCE_TOLERANCE) {
+ nearest = { name: instance.name, distance }
+ }
+ }
+ return nearest?.name
+}
+
+/** The family's axes in the slant asked for, once each of `tags` is checked among them. */
+export function checkedVariation(method: string, family: string, slanted: boolean, tags: string[]) {
+ const variation = fontManager.familyVariation(family, slanted)
+ if (tags.length > 0 && variation === undefined) {
+ throw new Error(
+ `in ${method}: Font family "${family}" is not loaded, so its variation axes are unknown. Call loadFontAsync first.`
+ )
+ }
+ if (tags.length > 0 && variation === null) {
+ throw new Error(
+ `in ${method}: "${tags[0]}" is not a valid variation setting. Font "${family}" has no variation axes.`
+ )
+ }
+ if (variation) {
+ const valid = variationAxisTags(variation.axes)
+ const invalid = tags.find((tag) => !valid.includes(tag))
+ if (invalid) {
+ throw new Error(
+ `in ${method}: "${invalid}" is not a valid variation setting. Valid settings are ${JSON.stringify(valid)}.`
+ )
+ }
+ }
+ return variation
+}
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index d23a6674d..84c7a7b45 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -18,11 +18,13 @@ import { defaultIcons, type IconProvider } from '#core/icons'
import type { RasterCodec } from '#core/io/formats/raster'
import { createSVGNodes } from '#core/io/formats/svg'
import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { componentFromNode } from './components'
import { flattenSceneNodes } from './flatten'
-import { loadFigmaFont, variationAxisTags, type FigmaFontNameInput } from './fonts'
+import { loadFigmaFont } from './fonts/load'
+import type { FigmaFontNameInput } from './fonts/names'
+import { variationAxisTags } from './fonts/variations'
import * as images from './images'
import type {
FigmaBooleanOperationNode,
@@ -91,7 +93,8 @@ export type {
FigmaVectorNode
} from './node-types'
export type { FigmaFont, FigmaFontName } from './proxy'
-export type { FigmaFontNameInput, FigmaVariationSettings } from './fonts'
+export type { FigmaFontNameInput } from './fonts/names'
+export type { FigmaVariationSettings } from './fonts/variations'
// TODO(figma-api): Implement the full official PluginAPI interface once our compatibility
// layer covers all required node-specific return types and unsupported APIs are modeled explicitly.
diff --git a/packages/core/src/figma-api/overrides.ts b/packages/core/src/figma-api/overrides.ts
index b26dca612..5fa5a2102 100644
--- a/packages/core/src/figma-api/overrides.ts
+++ b/packages/core/src/figma-api/overrides.ts
@@ -40,6 +40,7 @@ const FIGMA_OVERRIDE_FIELDS: Readonly<Partial<Record<string, readonly string[]>>
fontFamily: ['fontName'],
fontWeight: ['fontName'],
italic: ['fontName'],
+ fontStyle: ['fontName'],
letterSpacing: ['letterSpacing'],
lineHeight: ['lineHeight'],
textCase: ['textCase'],
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index dddb32650..df3534e21 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -38,7 +38,7 @@ import {
import { installVisualNodeProxyAccessors } from './accessors/visual'
import { installComponentPropertyAccessors } from './components'
import { installDevStatusAccessors, type FigmaDevStatusValue } from './dev-status'
-import type { FigmaFontName } from './fonts'
+import type { FigmaFontName } from './fonts/names'
import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'
import { installInstanceOverrideAccessors, type FigmaInstanceOverride } from './overrides'
import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
@@ -55,7 +55,7 @@ import type { FigmaTransform } from './types'
const MIXED = Symbol('mixed')
-export { weightToStyleName, type FigmaFont, type FigmaFontName } from './fonts'
+export type { FigmaFont, FigmaFontName } from './fonts/names'
export const INTERNAL_ID = Symbol('id')
export const INTERNAL_GRAPH = Symbol('graph')
diff --git a/packages/core/src/figma-api/text/bindings.ts b/packages/core/src/figma-api/text/bindings.ts
index a96c2b0ca..5f6b6cffd 100644
--- a/packages/core/src/figma-api/text/bindings.ts
+++ b/packages/core/src/figma-api/text/bindings.ts
@@ -10,11 +10,11 @@ import {
type Variable
} from '@open-pencil/scene-graph'
import { copyFills } from '@open-pencil/scene-graph/copy'
-import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
import { getSharedStyles, SHARED_TEXT_STYLE_FIELDS } from '@open-pencil/scene-graph/shared-styles'
import { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'
import { styleRunsWithPatch } from '#core/text/character-style'
+import { faceForStyle } from '#core/text/font/names'
import { getStyledTextSegments } from './style'
@@ -88,8 +88,9 @@ function boundValue(
const value = graph.resolveVariableForNode(node.id, variable.id)
if (typeof value !== 'string') return {}
if (field === 'fontFamily') return { fontFamily: value }
- const { weight, italic } = parseFontStyle(value)
- return { fontWeight: weight, italic }
+ // A style variable names a face of the text's family, as its font names it.
+ const face = faceForStyle(node.fontFamily, value)
+ return { fontWeight: face.weight, italic: face.italic, fontStyle: face.style }
}
const value = graph.resolveNumberVariableForNode(node.id, variable.id)
if (value === undefined || !Number.isFinite(value) || isParagraphField(field)) return {}
diff --git a/packages/core/src/figma-api/text/index.ts b/packages/core/src/figma-api/text/index.ts
index ce8496fe3..4983b9594 100644
--- a/packages/core/src/figma-api/text/index.ts
+++ b/packages/core/src/figma-api/text/index.ts
@@ -26,9 +26,9 @@ import {
} from '@open-pencil/scene-graph/text'
import { invalid, received } from '#core/figma-api/accessors/text/messages'
+import { assertTextFontsLoaded } from '#core/figma-api/fonts/loaded'
import { adjustRunsForDelete, getStyleAt, insertRunsWithStyle } from '#core/text/style-runs'
-import { assertTextFontsLoaded } from './loaded-fonts'
import { assertTextRange } from './style'
/** Figma's plugin API line height: automatic, or a size in pixels or percent of the font size. */
diff --git a/packages/core/src/figma-api/text/loaded-fonts.ts b/packages/core/src/figma-api/text/loaded-fonts.ts
deleted file mode 100644
index 6f12f6eec..000000000
--- a/packages/core/src/figma-api/text/loaded-fonts.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { uniqBy } from 'es-toolkit/array'
-
-import type { SceneNode } from '@open-pencil/scene-graph'
-
-import { weightToStyleName } from '#core/figma-api/fonts'
-import type { FontFaceRef } from '#core/text/face'
-import { fontManager } from '#core/text/fonts'
-import { textFontFace } from '#core/text/requirements'
-
-/**
- * A face as Figma names it in its messages, as `fontName` reads it: "Semi Bold", not "SemiBold",
- * and a weight between named ones by the nearest, as the font manager loads it.
- */
-function described(face: FontFaceRef): { family: string; style: string } {
- const weight = Math.round(face.weight / 100) * 100
- return { family: face.family, style: weightToStyleName(weight, face.italic) }
-}
-
-function loadHint({ family, style }: { family: string; style: string }): string {
- return `Please call figma.loadFontAsync({ family: "${family}", style: "${style}" }) and await the returned promise first.`
-}
-
-function isLoaded(face: FontFaceRef): boolean {
- return fontManager.isStyleLoaded(face.family, face.style)
-}
-
-/** Every face the text draws in: its own and each style run's. */
-function textFaces(node: SceneNode): FontFaceRef[] {
- const faces = [textFontFace(node), ...node.styleRuns.map((run) => textFontFace(node, run.style))]
- return uniqBy(faces, (face) => `${face.family}\0${face.style}`)
-}
-
-/**
- * Figma refuses an edit that lays text out again until every font the text uses is loaded, so
- * the text is never measured in a stand-in font. Paints and links need no font. Callers check
- * the edit's own arguments first, as Figma does.
- */
-export function assertTextFontsLoaded(method: string, node: SceneNode): void {
- const unloaded = textFaces(node).find((face) => !isLoaded(face))
- if (!unloaded) return
- const font = described(unloaded)
- throw new Error(
- `in ${method}: Cannot write to node with unloaded font "${font.family} ${font.style}". ${loadHint(font)}`
- )
-}
-
-/** Figma refuses a font that is not loaded yet, before it checks the text's own. */
-export function assertFontLoaded(method: string, face: FontFaceRef): void {
- if (isLoaded(face)) return
- const font = described(face)
- throw new Error(
- `in ${method}: Cannot use unloaded font "${font.family} ${font.style}". ${loadHint(font)}`
- )
-}
diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.ts
index 616b932fb..cf450f1df 100644
--- a/packages/core/src/figma-api/text/style.ts
+++ b/packages/core/src/figma-api/text/style.ts
@@ -8,10 +8,11 @@ import {
paragraphStyleAt
} from '@open-pencil/scene-graph/text'
-import { readVariationSettings, weightToStyleName } from '#core/figma-api/fonts'
+import { readVariationSettings } from '#core/figma-api/fonts/variations'
import { toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'
import { variableAlias } from '#core/figma-api/variables/values'
import { characterStyles, nodeStyle, type CharacterStyle } from '#core/text/character-style'
+import { textStyleName } from '#core/text/font/names'
/** The fields `getStyledTextSegments` takes, in the order Figma lists them. */
export const TEXT_SEGMENT_FIELDS = [
@@ -100,7 +101,7 @@ function spacing(field: 'paragraphSpacing' | 'listSpacing' | 'paragraphIndent')
const FIELD_READERS: Record<TextSegmentField, (context: FieldContext) => unknown> = {
fontSize: ({ style }) => style.fontSize,
fontName: ({ style }) => {
- const name = weightToStyleName(style.fontWeight, style.italic)
+ const name = textStyleName(style)
const variationSettings = readVariationSettings(
style.fontFamily,
name,
diff --git a/packages/core/src/io/formats/pdf/document.ts b/packages/core/src/io/formats/pdf/document.ts
index 6a7e01ed0..edf5fee44 100644
--- a/packages/core/src/io/formats/pdf/document.ts
+++ b/packages/core/src/io/formats/pdf/document.ts
@@ -1,6 +1,6 @@
import type { SceneGraph } from '@open-pencil/scene-graph'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { renderPagesToPDFDetailed, type PDFExportResult } from './export'
import type { PDFPageSpec } from './plan'
diff --git a/packages/core/src/io/formats/pdf/prepare.ts b/packages/core/src/io/formats/pdf/prepare.ts
index 79505f38a..51410abf2 100644
--- a/packages/core/src/io/formats/pdf/prepare.ts
+++ b/packages/core/src/io/formats/pdf/prepare.ts
@@ -12,10 +12,10 @@ 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 { fontManager } from '#core/text/font/manager'
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 { collectGraphFontRequirements } from '#core/text/requirements/collect'
import type { PDFFontFace } from './fonts'
import type { PDFPageSpec } from './plan'
diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.ts
index aa5afa67d..8f1db25c7 100644
--- a/packages/core/src/io/formats/svg/defs.ts
+++ b/packages/core/src/io/formats/svg/defs.ts
@@ -15,7 +15,7 @@ import {
import { imageMimeType } from '@open-pencil/scene-graph/images'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import type { FontFaceRef } from '#core/text/face'
+import type { FontFaceRef } from '#core/text/font/faces'
import { svg, type SVGNode } from './node'
import { round } from './paths'
diff --git a/packages/core/src/io/formats/svg/text/export.ts b/packages/core/src/io/formats/svg/text/export.ts
index 795f5d934..0be92ed21 100644
--- a/packages/core/src/io/formats/svg/text/export.ts
+++ b/packages/core/src/io/formats/svg/text/export.ts
@@ -20,7 +20,7 @@ import {
type SVGFallbackFace
} from '#core/io/formats/svg/text/lines'
import { shownText } from '#core/text/case'
-import { textFontFace } from '#core/text/requirements'
+import { textFontFace } from '#core/text/requirements/collect'
function styleOverrideToTspanAttrs(
style: CharacterStyleOverride,
diff --git a/packages/core/src/io/formats/svg/text/import.ts b/packages/core/src/io/formats/svg/text/import.ts
index cc6176932..1c79ea6ee 100644
--- a/packages/core/src/io/formats/svg/text/import.ts
+++ b/packages/core/src/io/formats/svg/text/import.ts
@@ -7,7 +7,7 @@ import type {
StyleRun
} from '@open-pencil/scene-graph'
import { localTransformFromWorld } from '@open-pencil/scene-graph/coordinate'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import Matrix from '@open-pencil/scene-graph/matrix'
import { pixelLength } from '@open-pencil/scene-graph/text'
@@ -143,7 +143,7 @@ export function svgImportFonts(data: Pick<SVGVectorizeResult, 'texts'>): Array<{
const fonts = new Map<string, { family: string; style: string; characters: string }>()
for (const run of data.texts.flatMap((text) => text.pieces.flatMap((piece) => piece.runs))) {
const family = run.fontFamily ?? 'Inter'
- const style = weightToStyle(run.fontWeight, run.italic)
+ const style = faceLoadKey(run.fontWeight, run.italic)
const key = `${family}\u0000${style}`
const font = fonts.get(key) ?? { family, style, characters: '' }
fonts.set(key, { ...font, characters: font.characters + run.text })
diff --git a/packages/core/src/kiwi/fig/node-change/font/digests.ts b/packages/core/src/kiwi/fig/node-change/font/digests.ts
index 1b4d942ee..c7da56540 100644
--- a/packages/core/src/kiwi/fig/node-change/font/digests.ts
+++ b/packages/core/src/kiwi/fig/node-change/font/digests.ts
@@ -1,7 +1,7 @@
import type { SceneGraph } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
const fontDigestCache = new Map<string, Uint8Array>()
@@ -29,13 +29,13 @@ function documentFontKeys(graph: SceneGraph): Set<string> {
const fontKeys = new Set<string>()
for (const node of graph.getAllNodes()) {
if (node.type !== 'TEXT') continue
- const baseStyle = weightToStyle(node.fontWeight, node.italic)
+ const baseStyle = faceLoadKey(node.fontWeight, node.italic)
fontKeys.add(`${node.fontFamily}|${baseStyle}`)
for (const run of node.styleRuns) {
const family = run.style.fontFamily ?? node.fontFamily
const weight = run.style.fontWeight ?? node.fontWeight
const italic = run.style.italic ?? node.italic
- fontKeys.add(`${family}|${weightToStyle(weight, italic)}`)
+ fontKeys.add(`${family}|${faceLoadKey(weight, italic)}`)
}
}
return fontKeys
diff --git a/packages/core/src/layout/text-measurement.ts b/packages/core/src/layout/text-measurement.ts
index 88d23a3ef..6d34fcfb5 100644
--- a/packages/core/src/layout/text-measurement.ts
+++ b/packages/core/src/layout/text-measurement.ts
@@ -1,5 +1,5 @@
import type { SceneNode } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { lineHeightPixels } from '@open-pencil/scene-graph/text'
import { measureTextWithFont } from '#core/text/font/glyphs'
@@ -19,7 +19,7 @@ export function estimateTextSize(
): { width: number; height: number } {
const fontSize = node.fontSize || 14
const family = node.fontFamily || 'Inter'
- const style = weightToStyle(node.fontWeight || 400, node.italic)
+ const style = faceLoadKey(node.fontWeight || 400, node.italic)
const text = node.text || ''
const ownLineH = lineHeightPixels(node.lineHeight, fontSize) ?? 0
diff --git a/packages/core/src/library/snapshot.ts b/packages/core/src/library/snapshot.ts
index a3be1ba19..7ac418366 100644
--- a/packages/core/src/library/snapshot.ts
+++ b/packages/core/src/library/snapshot.ts
@@ -1,5 +1,6 @@
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { cloneNodeProps } from '@open-pencil/scene-graph/copy'
+import { standardStyleName } from '@open-pencil/scene-graph/font-style'
import { contentPluginData } from '@open-pencil/scene-graph/plugin-data'
import { existingAssetKey } from './asset-keys'
@@ -114,6 +115,24 @@ export function extractLibrarySnapshot(
}
}
+/** A field as an asset's content compares it. */
+function libraryField(node: SceneNode, key: string, value: unknown): unknown {
+ // Plugin content such as a behaviour is part of the asset; its bookkeeping is not.
+ if (key === 'pluginData') return contentPluginData(node.pluginData)
+ if (key === 'fontStyle') return libraryStyleName(node)
+ return normalizedLibraryField(key, value)
+}
+
+/**
+ * The face a text's name names, compared as a name: a file writes the name the text left to its
+ * weight and slant, and spells some as Figma's fonts do ("Semi Bold" for "SemiBold").
+ */
+function libraryStyleName(node: SceneNode): string {
+ return (node.fontStyle ?? standardStyleName(node.fontWeight, node.italic))
+ .toLowerCase()
+ .replace(/\s+/gu, '')
+}
+
function normalizedLibraryField(key: string, value: unknown): unknown {
if (key === 'lineHeight' && (value === null || value === 17)) return null
if (
@@ -156,13 +175,7 @@ export function canonicalLibraryNode(
key !== 'name' &&
key !== 'symbolDescription'
)
- .map(([key, value]) => [
- key,
- // Plugin content such as a behaviour is part of the asset; its bookkeeping is not.
- key === 'pluginData'
- ? contentPluginData(node.pluginData)
- : normalizedLibraryField(key, value)
- ])
+ .map(([key, value]) => [key, libraryField(node, key, value)])
)
const component = node.componentId ? graph.getNode(node.componentId) : undefined
const dependencyKey =
diff --git a/packages/core/src/text/character-style.ts b/packages/core/src/text/character-style.ts
index 99b1d43a5..777e79a1a 100644
--- a/packages/core/src/text/character-style.ts
+++ b/packages/core/src/text/character-style.ts
@@ -11,6 +11,8 @@ import {
type TextLength
} from '@open-pencil/scene-graph'
import {
+ FACE_KEYS,
+ rangeFontStyle,
SHARED_TEXT_STYLE_FIELDS,
styleDetachmentChanges
} from '@open-pencil/scene-graph/shared-styles'
@@ -35,6 +37,7 @@ export type CharacterStyle = Required<
| 'textCase'
>
> & {
+ fontStyle: string | null
lineHeight: TextLength | null
textDecorationThickness: number | null
textUnderlineOffset: number | null
@@ -50,6 +53,7 @@ export const TEXT_STYLE_KEYS = [
'fontFamily',
'fontWeight',
'italic',
+ 'fontStyle',
'fontSize',
'letterSpacing',
'lineHeight',
@@ -83,6 +87,7 @@ export function nodeStyle(node: SceneNode): CharacterStyle {
fontFamily: node.fontFamily,
fontWeight: node.fontWeight,
italic: node.italic,
+ fontStyle: node.fontStyle,
fontSize: node.fontSize,
letterSpacing: node.letterSpacing,
lineHeight: node.lineHeight,
@@ -112,7 +117,11 @@ export function characterStyles(node: SceneNode, start: number, end: number): Ch
const from = Math.max(start, run.start)
const to = Math.min(end, run.start + run.length)
for (let index = from; index < to; index++) {
- styles[index - start] = { ...styles[index - start], ...definedOverrides(run.style) }
+ styles[index - start] = {
+ ...styles[index - start],
+ ...definedOverrides(run.style),
+ fontStyle: rangeFontStyle(node, run.style)
+ }
}
}
return styles
@@ -168,16 +177,12 @@ function detachedStyles(
style: CharacterStyleOverride | undefined
): CharacterStyleOverride {
if (!style) return {}
- const styled = {
- ...node,
- textStyleId: current.textStyleId !== undefined ? current.textStyleId : node.textStyleId,
- fillStyleId: current.fillStyleId !== undefined ? current.fillStyleId : node.fillStyleId
- }
+ const styled = { ...node, ...current }
const changes = pick(style, [...TEXT_STYLE_KEYS, 'fills', 'textStyleId', 'fillStyleId'])
const detached = styleDetachmentChanges(styled, changes)
return pick(
detached,
- (['textStyleId', 'fillStyleId'] as const).filter(
+ (['textStyleId', 'fillStyleId', 'fontStyle'] as const).filter(
(key) => !Object.hasOwn(changes, key) && Object.hasOwn(detached, key)
)
)
@@ -241,7 +246,11 @@ export function textStyleChanges(
...(changed.some((key) => (SHARED_TEXT_STYLE_FIELDS as readonly string[]).includes(key))
? (['textStyleId'] as const)
: []),
- ...(changed.includes('fills') ? (['fillStyleId'] as const) : [])
+ ...(changed.includes('fills') ? (['fillStyleId'] as const) : []),
+ // A range's face name names none once the text's face changes under it.
+ ...(changed.some((key) => (FACE_KEYS as readonly string[]).includes(key))
+ ? (['fontStyle'] as const)
+ : [])
]
const runs = node.styleRuns.map((run) => ({ ...run, style: omit(run.style, keys) }))
const updated = { ...node, ...changes }
diff --git a/packages/core/src/text/coverage.ts b/packages/core/src/text/coverage.ts
index b5547b57d..33fb5d8cc 100644
--- a/packages/core/src/text/coverage.ts
+++ b/packages/core/src/text/coverage.ts
@@ -1,5 +1,5 @@
import type { SceneNode } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import {
@@ -53,7 +53,7 @@ function styleForCharacter(
if (run.style.textLanguage !== undefined) language = run.style.textLanguage
}
- return { family, style: weightToStyle(weight, italic), language }
+ return { family, style: faceLoadKey(weight, italic), language }
}
/**
diff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.ts
index aa8a439e8..b7bf05d82 100644
--- a/packages/core/src/text/editor.ts
+++ b/packages/core/src/text/editor.ts
@@ -1,7 +1,7 @@
import type { CanvasKit } from 'canvaskit-wasm'
import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
@@ -69,7 +69,7 @@ export class TextEditor {
if (!node?.textPathData || !node.derivedTextGlyphs?.length) return null
const metrics = fontVerticalMetricsSync(
node.fontFamily,
- weightToStyle(node.fontWeight, node.italic)
+ faceLoadKey(node.fontWeight, node.italic)
)
return metrics ? { glyphs: node.derivedTextGlyphs, metrics } : null
}
diff --git a/packages/core/src/text/face.ts b/packages/core/src/text/face.ts
deleted file mode 100644
index 112ae6fd4..000000000
--- a/packages/core/src/text/face.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { parseFontStyle, type ParsedFontStyle } from '@open-pencil/scene-graph/font-style'
-
-export interface FontFaceRef extends ParsedFontStyle {
- family: string
- style: string
- postscriptName?: string
-}
-
-export function fontFaceFromFigmaFontName(fontName: {
- family?: string
- style?: string
- postscript?: string
-}): FontFaceRef {
- const style = fontName.style ?? 'Regular'
- return {
- family: fontName.family ?? 'Inter',
- style,
- postscriptName: fontName.postscript,
- ...parseFontStyle(style)
- }
-}
-
-export function fontFaceRenderFamily(family: string, style: string): string {
- return `__op_font__${family.replace(/[^a-z0-9_-]+/giu, '_')}__${style.replace(/[^a-z0-9_-]+/giu, '_')}`
-}
diff --git a/packages/core/src/text/font/bundled.ts b/packages/core/src/text/font/bundled.ts
new file mode 100644
index 000000000..47d0353de
--- /dev/null
+++ b/packages/core/src/text/font/bundled.ts
@@ -0,0 +1,80 @@
+import { IS_BROWSER } from '#core/constants'
+
+/** Inter's weights, each drawn from Inter's variable files at its named instance. */
+const INTER_WEIGHTS = [
+ 'Thin',
+ 'ExtraLight',
+ 'Light',
+ 'Regular',
+ 'Medium',
+ 'SemiBold',
+ 'Bold',
+ 'ExtraBold',
+ 'Black'
+]
+
+/** The font files bundled in `@open-pencil/core/assets`, by family and style key. */
+const BUNDLED_FONTS: Record<string, string> = {
+ ...Object.fromEntries(INTER_WEIGHTS.map((weight) => [`Inter|${weight}`, '/InterVariable.ttf'])),
+ ...Object.fromEntries(
+ INTER_WEIGHTS.map((weight) => [`Inter|${weight} Italic`, '/InterVariable-Italic.ttf'])
+ ),
+ 'Noto Naskh Arabic|Regular': '/NotoNaskhArabic-Regular.ttf',
+ 'OpenPencil Emoji Metrics|Regular': '/OpenPencilEmojiMetrics-Regular.ttf'
+}
+
+/**
+ * Maps a bundled font's file name (`InterVariable.ttf`) to the URL a browser fetches it from.
+ * Mirrors CanvasKit's `locateFile`; the default expects the host to serve
+ * `@open-pencil/core/assets` at the site root.
+ */
+export type BundledFontLocator = (file: string) => string
+
+const defaultBundledFontLocator: BundledFontLocator = (file) => `/${file}`
+
+/** The bundled fonts: which file draws each face, and reading the files where the host put them. */
+export class BundledFonts {
+ private locate: BundledFontLocator = defaultBundledFontLocator
+ private readonly requests = new Map<string, Promise<ArrayBuffer | null>>()
+
+ /** Lets a host that bundles `@open-pencil/core/assets` itself say where each file ended up. */
+ setLocator(locate: BundledFontLocator | null): void {
+ this.locate = locate ?? defaultBundledFontLocator
+ }
+
+ /** The file that draws a face, or nothing for a face not bundled. */
+ file(family: string, style: string): string | undefined {
+ return BUNDLED_FONTS[`${family}|${style}`]
+ }
+
+ /** The style keys a family's bundled faces are loaded as. */
+ styles(family: string): string[] {
+ return Object.keys(BUNDLED_FONTS)
+ .filter((key) => key.startsWith(`${family}|`))
+ .map((key) => key.slice(family.length + 1))
+ }
+
+ /**
+ * Reads a bundled font. Concurrent loads of one face share a request, so they get the same
+ * buffer; it is forgotten once settled, so a failed request can be retried.
+ */
+ fetch(url: string): Promise<ArrayBuffer | null> {
+ const pending = this.requests.get(url)
+ if (pending) return pending
+ const request = this.read(url).finally(() => this.requests.delete(url))
+ this.requests.set(url, request)
+ return request
+ }
+
+ private async read(url: string): Promise<ArrayBuffer | null> {
+ if (IS_BROWSER) {
+ const response = await fetch(this.locate(url.replace(/^\//, '')))
+ // A missing file answers with an error page, which must not be read as a font.
+ return response.ok ? response.arrayBuffer() : null
+ }
+ const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')
+ const packageJSONURL = import.meta.resolve('@open-pencil/core/package.json')
+ const buf = await readFile(new URL(`assets${url}`, packageJSONURL))
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
+ }
+}
diff --git a/packages/core/src/text/font/catalog.ts b/packages/core/src/text/font/catalog.ts
new file mode 100644
index 000000000..8e759a8df
--- /dev/null
+++ b/packages/core/src/text/font/catalog.ts
@@ -0,0 +1,110 @@
+import {
+ facesFromStyles,
+ hasFamilyFace,
+ standardFaces,
+ type FamilyFace
+} from '#core/text/font/faces'
+import type { FontInfo } from '#core/text/font/sources'
+
+/** Where a family's faces come from besides the host's catalog. */
+export interface FamilyFaceSources {
+ /** The browser's installed fonts, once listed. */
+ localFonts(): FontInfo[] | null
+ /** A web provider's faces for a family; none when no provider has it. */
+ webFaces(family: string): Promise<FamilyFace[]>
+ /** The style keys of a family's bundled faces. */
+ bundledStyles(family: string): string[]
+}
+
+/** The faces each family has, as its installed, web, or bundled fonts list them. */
+export class FamilyFaceCatalog {
+ private hostStyles = new Map<string, readonly string[]>()
+ private lookups = new Map<string, Promise<FamilyFace[] | null>>()
+ private found = new Map<string, FamilyFace[] | null>()
+ private listeners = new Set<() => void>()
+
+ constructor(private readonly sources: FamilyFaceSources) {}
+
+ /** The system fonts a desktop host lists, by family, with the style names of their faces. */
+ setHostCatalog(fonts: readonly { family: string; styles: readonly string[] }[]): void {
+ this.hostStyles = new Map(fonts.map((font) => [font.family, [...font.styles]]))
+ this.forget()
+ }
+
+ /**
+ * The faces a family has: its installed fonts', else a web provider's, else the bundled ones;
+ * `null` when nothing says, so a caller offers every weight.
+ */
+ faces(family: string): Promise<FamilyFace[] | null> {
+ let lookup = this.lookups.get(family)
+ if (!lookup) {
+ const pending = this.lookUp(family).then((faces) => {
+ // Faces forgotten while the lookup ran came from the sources it read before.
+ if (this.lookups.get(family) === pending) this.found.set(family, faces)
+ return faces
+ })
+ lookup = pending
+ this.lookups.set(family, lookup)
+ }
+ return lookup
+ }
+
+ /** The faces `faces` found for a family, once it has; `undefined` before. */
+ foundFaces(family: string): FamilyFace[] | null | undefined {
+ return this.found.get(family)
+ }
+
+ /**
+ * The faces known for a family without asking a provider: those looked up, else its installed
+ * or bundled faces. A web family not looked up has none here, and its faces take Google
+ * Fonts' names, which a provider would give them too.
+ */
+ facesSync(family: string): FamilyFace[] | null {
+ return this.found.get(family) ?? this.installedFaces(family) ?? this.bundledFaces(family)
+ }
+
+ /** Whether a family has this face, or nothing found so far says it has not. */
+ offersFace(family: string, weight: number, italic: boolean): boolean {
+ const faces = this.found.get(family)
+ return !faces || hasFamilyFace(faces, weight, italic)
+ }
+
+ /**
+ * Calls the listener whenever the faces found so far are forgotten, as when the host's font
+ * catalog arrives or online providers change, so a caller asks for its families again.
+ */
+ onReset(listener: () => void): () => void {
+ this.listeners.add(listener)
+ return () => this.listeners.delete(listener)
+ }
+
+ /** Forgets the faces found so far, whose sources changed. */
+ forget(): void {
+ this.lookups.clear()
+ this.found.clear()
+ for (const listener of this.listeners) listener()
+ }
+
+ private async lookUp(family: string): Promise<FamilyFace[] | null> {
+ const installed = this.installedFaces(family)
+ if (installed) return installed
+ const web = await this.sources.webFaces(family)
+ if (web.length > 0) return web
+ return this.bundledFaces(family)
+ }
+
+ /** The faces of an installed family, from the host's catalog or the browser's local fonts. */
+ private installedFaces(family: string): FamilyFace[] | null {
+ // The desktop host lists weights by generated names, so its faces take the standard names.
+ const host = this.hostStyles.get(family)
+ if (host && host.length > 0) return standardFaces(host)
+ const local = this.sources.localFonts()?.filter((font) => font.family === family) ?? []
+ return local.length > 0 ? facesFromStyles(local.map((font) => font.style)) : null
+ }
+
+ /** The bundled fonts name their faces as Google Fonts does; their keys are style keys. */
+ private bundledFaces(family: string): FamilyFace[] | null {
+ const styles = this.sources.bundledStyles(family)
+ return styles.length > 0 ? standardFaces(styles) : null
+ }
+}
diff --git a/packages/core/src/text/font/faces.ts b/packages/core/src/text/font/faces.ts
index bee537188..352fd36f1 100644
--- a/packages/core/src/text/font/faces.ts
+++ b/packages/core/src/text/font/faces.ts
@@ -1,22 +1,44 @@
import { uniqBy } from 'es-toolkit'
-import { parseFontStyle } from '@open-pencil/scene-graph/font-style'
+import {
+ parseFontStyle,
+ standardStyleName,
+ type ParsedFontStyle
+} from '@open-pencil/scene-graph/font-style'
-/** One face a font family has: a weight, upright or italic. */
-export interface FamilyFace {
+/** A weight, upright or italic. */
+export interface FaceWeight {
weight: number
italic: boolean
}
-/** The faces named by a family's style names, such as "Bold Italic" or "SemiBold". */
+/** One face a font family has: a weight, upright or italic, and the name its font gives it. */
+export interface FamilyFace extends FaceWeight {
+ style: string
+}
+
+/**
+ * The faces named by a family's style names, such as "Bold Italic" or "Semi Bold", each keeping
+ * its name. Of two names for one weight and slant, the first listed is the face's.
+ */
export function facesFromStyles(styles: readonly string[]): FamilyFace[] {
return uniqBy(
- styles.map((style) => parseFontStyle(style)),
+ styles.map((style) => ({ ...parseFontStyle(style), style })),
(face) => `${face.weight}${face.italic ? 'i' : ''}`
)
}
-export function hasFamilyFace(faces: readonly FamilyFace[], weight: number, italic: boolean) {
+/** A face named as Google Fonts names it, for a source that gives weights but no names. */
+export function standardFace(weight: number, italic: boolean): FamilyFace {
+ return { weight, italic, style: standardStyleName(weight, italic) }
+}
+
+/** The faces style keys stand for, named as Google Fonts names them. */
+export function standardFaces(styles: readonly string[]): FamilyFace[] {
+ return facesFromStyles(styles).map((face) => standardFace(face.weight, face.italic))
+}
+
+export function hasFamilyFace(faces: readonly FaceWeight[], weight: number, italic: boolean) {
return faces.some((face) => face.weight === weight && face.italic === italic)
}
@@ -41,3 +63,28 @@ export function nearestFamilyFace(
}
return nearest
}
+
+/** A face text asks the font manager for: its family, its style key, and its weight and slant. */
+export interface FontFaceRef extends ParsedFontStyle {
+ family: string
+ style: string
+ postscriptName?: string
+}
+
+export function fontFaceFromFigmaFontName(fontName: {
+ family?: string
+ style?: string
+ postscript?: string
+}): FontFaceRef {
+ const style = fontName.style ?? 'Regular'
+ return {
+ family: fontName.family ?? 'Inter',
+ style,
+ postscriptName: fontName.postscript,
+ ...parseFontStyle(style)
+ }
+}
+
+export function fontFaceRenderFamily(family: string, style: string): string {
+ return `__op_font__${family.replace(/[^a-z0-9_-]+/giu, '_')}__${style.replace(/[^a-z0-9_-]+/giu, '_')}`
+}
diff --git a/packages/core/src/text/font/glyphs.ts b/packages/core/src/text/font/glyphs.ts
index 3055cee39..9e7e8d827 100644
--- a/packages/core/src/text/font/glyphs.ts
+++ b/packages/core/src/text/font/glyphs.ts
@@ -1,6 +1,6 @@
import type { FontVariation } from '@open-pencil/scene-graph'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import {
fontInstance,
diff --git a/packages/core/src/text/font/local.ts b/packages/core/src/text/font/local.ts
new file mode 100644
index 000000000..4723bf3b1
--- /dev/null
+++ b/packages/core/src/text/font/local.ts
@@ -0,0 +1,74 @@
+import { IS_BROWSER } from '#core/constants'
+import { SharedReads } from '#core/text/font/reads'
+import type { FontInfo, LocalFontAccessState } from '#core/text/font/sources'
+import { chooseLocalFontMatch } from '#core/text/font/style'
+
+/** The fonts installed in the browser's system, read through the Local Font Access API. */
+export class LocalFonts {
+ private fonts: FontInfo[] | null = null
+ private state: LocalFontAccessState = IS_BROWSER ? 'prompt' : 'unsupported'
+ private readonly requests = new SharedReads()
+
+ accessState(): LocalFontAccessState {
+ return this.state
+ }
+
+ /** The installed fonts, once access was asked for; `null` before. */
+ list(): FontInfo[] | null {
+ return this.fonts
+ }
+
+ /** Asks for access and lists the installed fonts, one entry per family and style. */
+ async requestAccess(): Promise<FontInfo[]> {
+ if (!IS_BROWSER || !window.queryLocalFonts) {
+ this.state = 'unsupported'
+ this.fonts = []
+ return []
+ }
+ try {
+ const fonts = await window.queryLocalFonts()
+ const seen = new Set<string>()
+ const result: FontInfo[] = []
+ for (const f of fonts) {
+ const key = `${f.family}|${f.style}`
+ if (seen.has(key)) continue
+ seen.add(key)
+ result.push({
+ family: f.family,
+ fullName: f.fullName,
+ style: f.style,
+ postscriptName: f.postscriptName
+ })
+ }
+ this.fonts = result
+ this.state = 'granted'
+ return result
+ } catch {
+ this.fonts = []
+ this.state = 'denied'
+ return []
+ }
+ }
+
+ /** A face's bytes, once access is granted. */
+ read(family: string, style?: string): Promise<ArrayBuffer | null> {
+ if (!IS_BROWSER || !window.queryLocalFonts) return Promise.resolve(null)
+ if (this.state !== 'granted') return Promise.resolve(null)
+ // A query answers with a new blob, and so new bytes, every time; the face decides the match.
+ return this.requests.read(`${family}|${style ?? ''}`, () => this.query(family, style))
+ }
+
+ private async query(family: string, style?: string): Promise<ArrayBuffer | null> {
+ try {
+ const fonts = await window.queryLocalFonts?.()
+ if (!fonts) return null
+ const match = chooseLocalFontMatch(fonts, family, style)
+ if (!match) return null
+ const blob: Blob = await match.blob()
+ return await blob.arrayBuffer()
+ } catch (e) {
+ console.warn(`Local font access failed for "${family}" ${style ?? ''}:`, e)
+ return null
+ }
+ }
+}
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/font/manager.ts
similarity index 76%
rename from packages/core/src/text/fonts.ts
rename to packages/core/src/text/font/manager.ts
index ede0a582e..d5ca84c94 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/font/manager.ts
@@ -3,11 +3,31 @@
import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
import type { FontVariation, SceneGraph } from '@open-pencil/scene-graph'
+import {
+ faceLoadKey,
+ normalizeFontFamily,
+ parseFontStyle,
+ styleToWeight
+} from '@open-pencil/scene-graph/font-style'
import { DEFAULT_FONT_FAMILY, IS_BROWSER } from '#core/constants'
-import { fontFaceRenderFamily } from '#core/text/face'
-import { facesFromStyles, hasFamilyFace, type FamilyFace } from '#core/text/font/faces'
-import { chooseLocalFontMatch } from '#core/text/font/style'
+import { fontFallbackEntry, type FontFallbackScript } from '#core/text/fallbacks'
+import { BundledFonts, type BundledFontLocator } from '#core/text/font/bundled'
+import { FamilyFaceCatalog } from '#core/text/font/catalog'
+import { fontFaceRenderFamily, type FamilyFace } from '#core/text/font/faces'
+import { loadHarfBuzz } from '#core/text/font/harfbuzz'
+import { LocalFonts } from '#core/text/font/local'
+import { sameFontFile, SharedReads, withHarfBuzz } from '#core/text/font/reads'
+import {
+ UnsupportedFontFormatError,
+ type DownloadedFontCache,
+ type FontFamilyOption,
+ type FontInfo,
+ type FontLoadedSource,
+ type FontUnavailableReason,
+ type HostFontLoader,
+ type LocalFontAccessState
+} from '#core/text/font/sources'
import {
fontAxes,
namedInstances,
@@ -15,106 +35,11 @@ import {
type FontAxis,
type NamedInstance
} from '#core/text/font/variation'
+import { collectGraphFontKeys } from '#core/text/requirements/collect'
+import { normalizedCoverageText, WebFontResolver } from '#core/text/web-font/resolver'
+import type { WebFontFetch, WebFontProviderId } from '#core/text/web-font/resolver'
-export * from '#core/text/font/sources'
-export * from '#core/text/font/style'
-export * from '#core/text/font/variation'
-export * from '#core/text/font/woff2'
-import {
- normalizeFontFamily,
- parseFontStyle,
- styleToWeight,
- weightToStyle
-} from '@open-pencil/scene-graph/font-style'
-
-import { fontFallbackEntry } from '#core/text/fallbacks'
-import type { FontFallbackScript } from '#core/text/fallbacks'
-import { loadHarfBuzz } from '#core/text/font/harfbuzz'
-import { UnsupportedFontFormatError } from '#core/text/font/sources'
-import type {
- DownloadedFontCache,
- FontFamilyOption,
- FontInfo,
- FontLoadedSource,
- FontUnavailableReason,
- HostFontLoader,
- LocalFontAccessState
-} from '#core/text/font/sources'
-import { collectGraphFontKeys } from '#core/text/requirements'
-import { normalizedCoverageText, WebFontResolver } from '#core/text/web-fonts'
-import type { WebFontFetch, WebFontProviderId } from '#core/text/web-fonts'
-
-/** Inter's weights, each drawn from Inter's variable files at its named instance. */
-const INTER_WEIGHTS = [
- 'Thin',
- 'ExtraLight',
- 'Light',
- 'Regular',
- 'Medium',
- 'SemiBold',
- 'Bold',
- 'ExtraBold',
- 'Black'
-]
-
-const BUNDLED_FONTS: Record<string, string> = {
- ...Object.fromEntries(INTER_WEIGHTS.map((weight) => [`Inter|${weight}`, '/InterVariable.ttf'])),
- ...Object.fromEntries(
- INTER_WEIGHTS.map((weight) => [`Inter|${weight} Italic`, '/InterVariable-Italic.ttf'])
- ),
- 'Noto Naskh Arabic|Regular': '/NotoNaskhArabic-Regular.ttf',
- 'OpenPencil Emoji Metrics|Regular': '/OpenPencilEmojiMetrics-Regular.ttf'
-}
-
-/**
- * Maps a bundled font's file name (`InterVariable.ttf`) to the URL a browser fetches it from.
- * Mirrors CanvasKit's `locateFile`; the default expects the host to serve
- * `@open-pencil/core/assets` at the site root.
- */
-export type BundledFontLocator = (file: string) => string
-
-const defaultBundledFontLocator: BundledFontLocator = (file) => `/${file}`
-
-/**
- * Shares the in-flight and successful reads of a key, and forgets a null answer so it can be
- * retried. A host or browser read copies the whole face again each time, tens of megabytes for a
- * system CJK face, only for registration to find the same bytes and drop it.
- */
-class SharedReads {
- private readonly reads = new Map<string, Promise<ArrayBuffer | null>>()
-
- read(key: string, load: () => Promise<ArrayBuffer | null>): Promise<ArrayBuffer | null> {
- const existing = this.reads.get(key)
- if (existing) return existing
- const pending = load()
- this.reads.set(key, pending)
- void pending.then((data) => {
- if (!data && this.reads.get(key) === pending) this.reads.delete(key)
- return undefined
- })
- return pending
- }
-
- clear(): void {
- this.reads.clear()
- }
-}
-
-/** Whether two font files hold the same bytes, as one downloaded or read again does. */
-function sameFontFile(a: ArrayBuffer, b: ArrayBuffer): boolean {
- if (a === b) return true
- if (a.byteLength !== b.byteLength) return false
- const left = new Uint8Array(a)
- const right = new Uint8Array(b)
- for (let index = 0; index < left.length; index++) if (left[index] !== right[index]) return false
- return true
-}
-
-/** `load`'s answer once HarfBuzz has loaded too, the two loading side by side. */
-async function withHarfBuzz<T>(load: Promise<T>): Promise<T> {
- const [answer] = await Promise.all([load, loadHarfBuzz()])
- return answer
-}
+export type { BundledFontLocator } from '#core/text/font/bundled'
export class FontManager {
private loadedFamilies = new Map<string, ArrayBuffer>()
@@ -137,24 +62,22 @@ export class FontManager {
>()
private blockedNodeIds = new Set<string>()
private fontProvider: TypefaceFontProvider | null = null
- private bundledFontLocator: BundledFontLocator = defaultBundledFontLocator
- private readonly bundledFontRequests = new Map<string, Promise<ArrayBuffer | null>>()
private fontProviders = new Set<TypefaceFontProvider>()
private providerCanvasKits = new WeakMap<TypefaceFontProvider, CanvasKit>()
private registrationGeneration = 0
private providerRegistrations = new WeakMap<TypefaceFontProvider, Map<string, Set<ArrayBuffer>>>()
- private localFonts: FontInfo[] | null = null
- private readonly localFontRequests = new SharedReads()
- private hostStyles = new Map<string, readonly string[]>()
- private familyFaceLoads = new Map<string, Promise<FamilyFace[] | null>>()
- private knownFamilyFaces = new Map<string, FamilyFace[] | null>()
- private familyFacesListeners = new Set<() => void>()
- private localFontAccessState: LocalFontAccessState = IS_BROWSER ? 'prompt' : 'unsupported'
private downloadedFontCache: DownloadedFontCache | null = null
private fallbackUserAgent: string | undefined
private hostFontLoader: HostFontLoader | null = null
private readonly hostFontRequests = new SharedReads()
private webFonts = new WebFontResolver()
+ private readonly bundled = new BundledFonts()
+ private readonly localFonts = new LocalFonts()
+ private readonly faces = new FamilyFaceCatalog({
+ localFonts: () => this.localFonts.list(),
+ webFaces: (family) => this.webFonts.familyFaces(family),
+ bundledStyles: (family) => this.bundled.styles(family)
+ })
private cjkFallbackFamilies: string[] = []
private cjkFallbackPromise: Promise<string[]> | null = null
private arabicFallbackFamilies: string[] = []
@@ -214,7 +137,7 @@ export class FontManager {
}
localAccessState(): LocalFontAccessState {
- return this.localFontAccessState
+ return this.localFonts.accessState()
}
setDownloadedFontCache(cache: DownloadedFontCache | null): void {
@@ -232,18 +155,17 @@ export class FontManager {
/** Lets a host that bundles `@open-pencil/core/assets` itself say where each file ended up. */
setBundledFontLocator(locate: BundledFontLocator | null): void {
- this.bundledFontLocator = locate ?? defaultBundledFontLocator
+ this.bundled.setLocator(locate)
}
setOnlineFontProviders(settings: Partial<Record<WebFontProviderId, boolean>>): void {
this.webFonts.setEnabled(settings)
- this.forgetFamilyFaces()
+ this.faces.forget()
}
/** The system fonts a desktop host lists, by family, with the style names of their faces. */
setHostFontCatalog(fonts: readonly { family: string; styles: readonly string[] }[]): void {
- this.hostStyles = new Map(fonts.map((font) => [font.family, [...font.styles]]))
- this.forgetFamilyFaces()
+ this.faces.setHostCatalog(fonts)
}
/**
@@ -251,57 +173,27 @@ export class FontManager {
* `null` when nothing says, so a caller offers every weight.
*/
familyFaces(family: string): Promise<FamilyFace[] | null> {
- let load = this.familyFaceLoads.get(family)
- if (!load) {
- const pending = this.loadFamilyFaces(family).then((faces) => {
- // Faces forgotten while the lookup ran came from the sources it read before.
- if (this.familyFaceLoads.get(family) === pending) this.knownFamilyFaces.set(family, faces)
- return faces
- })
- load = pending
- this.familyFaceLoads.set(family, load)
- }
- return load
+ return this.faces.faces(family)
}
/** The faces `familyFaces` found for a family, once it has; `undefined` before. */
loadedFamilyFaces(family: string): FamilyFace[] | null | undefined {
- return this.knownFamilyFaces.get(family)
+ return this.faces.foundFaces(family)
}
/** Whether a family has this face, or nothing found so far says it has not. */
offersFace(family: string, weight: number, italic: boolean): boolean {
- const faces = this.knownFamilyFaces.get(family)
- return !faces || hasFamilyFace(faces, weight, italic)
+ return this.faces.offersFace(family, weight, italic)
}
- /**
- * Calls the listener whenever the faces found so far are forgotten, as when the host's font
- * catalog arrives or online providers change, so a caller asks for its families again.
- */
+ /** Calls the listener whenever the faces found so far are forgotten. */
onFamilyFacesReset(listener: () => void): () => void {
- this.familyFacesListeners.add(listener)
- return () => this.familyFacesListeners.delete(listener)
- }
-
- private async loadFamilyFaces(family: string): Promise<FamilyFace[] | null> {
- const installed =
- this.hostStyles.get(family) ??
- this.localFonts?.filter((font) => font.family === family).map((font) => font.style) ??
- []
- if (installed.length > 0) return facesFromStyles(installed)
- const web = await this.webFonts.familyFaces(family)
- if (web.length > 0) return web
- const bundled = Object.keys(BUNDLED_FONTS)
- .filter((key) => key.startsWith(`${family}|`))
- .map((key) => key.slice(family.length + 1))
- return bundled.length > 0 ? facesFromStyles(bundled) : null
+ return this.faces.onReset(listener)
}
- private forgetFamilyFaces(): void {
- this.familyFaceLoads.clear()
- this.knownFamilyFaces.clear()
- for (const listener of this.familyFacesListeners) listener()
+ /** The faces known for a family without asking a provider; see {@link FamilyFaceCatalog}. */
+ familyFacesSync(family: string): FamilyFace[] | null {
+ return this.faces.facesSync(family)
}
setWebFontFetch(fetcher: WebFontFetch | null): void {
@@ -335,35 +227,9 @@ export class FontManager {
}
async requestLocalFontAccess(): Promise<FontInfo[]> {
- if (!IS_BROWSER || !window.queryLocalFonts) {
- this.localFontAccessState = 'unsupported'
- this.localFonts = []
- return []
- }
- try {
- const fonts = await window.queryLocalFonts()
- const seen = new Set<string>()
- const result: FontInfo[] = []
- for (const f of fonts) {
- const key = `${f.family}|${f.style}`
- if (seen.has(key)) continue
- seen.add(key)
- result.push({
- family: f.family,
- fullName: f.fullName,
- style: f.style,
- postscriptName: f.postscriptName
- })
- }
- this.localFonts = result
- this.localFontAccessState = 'granted'
- this.forgetFamilyFaces()
- return result
- } catch {
- this.localFonts = []
- this.localFontAccessState = 'denied'
- return []
- }
+ const fonts = await this.localFonts.requestAccess()
+ this.faces.forget()
+ return fonts
}
async listFamilies(): Promise<string[]> {
@@ -372,7 +238,7 @@ export class FontManager {
}
async listFamilyOptions(): Promise<FontFamilyOption[]> {
- const fonts = this.localFonts ?? (await this.requestLocalFontAccess())
+ const fonts = this.localFonts.list() ?? (await this.requestLocalFontAccess())
const webFontFamilies = await Promise.all(
this.enabledOnlineFontProviders().map(async (provider) => ({
provider,
@@ -394,28 +260,9 @@ export class FontManager {
this.webFonts.preloadFamilies()
}
- /**
- * Reads a bundled font. Concurrent loads of one face share a request, so they get the same
- * buffer; it is forgotten once settled, so a failed request can be retried.
- */
+ /** Reads a bundled font; concurrent loads of one file share a request. */
fetchBundledFont(url: string): Promise<ArrayBuffer | null> {
- const pending = this.bundledFontRequests.get(url)
- if (pending) return pending
- const request = this.readBundledFont(url).finally(() => this.bundledFontRequests.delete(url))
- this.bundledFontRequests.set(url, request)
- return request
- }
-
- private async readBundledFont(url: string): Promise<ArrayBuffer | null> {
- if (IS_BROWSER) {
- const response = await fetch(this.bundledFontLocator(url.replace(/^\//, '')))
- // A missing file answers with an error page, which must not be read as a font.
- return response.ok ? response.arrayBuffer() : null
- }
- const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')
- const packageJSONURL = import.meta.resolve('@open-pencil/core/package.json')
- const buf = await readFile(new URL(`assets${url}`, packageJSONURL))
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
+ return this.bundled.fetch(url)
}
loadLocalFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {
@@ -440,12 +287,12 @@ export class FontManager {
private async loadInstalledFont(family: string, style: string): Promise<ArrayBuffer | null> {
const hostBuffer = await this.loadHostFont(family, style)
if (hostBuffer) return this.registerAndCache(family, style, hostBuffer, 'local')
- const localBuffer = await this.findLocalFont(family, style)
+ const localBuffer = await this.localFonts.read(family, style)
return localBuffer ? this.registerAndCache(family, style, localBuffer, 'local') : null
}
private async loadBundledFont(family: string, style: string): Promise<ArrayBuffer | null> {
- const bundledURL = BUNDLED_FONTS[`${family}|${style}`]
+ const bundledURL = this.bundled.file(family, style)
if (!bundledURL) return null
try {
const buffer = await this.fetchBundledFont(bundledURL)
@@ -582,7 +429,7 @@ export class FontManager {
}
async ensureNodeFont(family: string, weight: number): Promise<void> {
- await this.loadFont(family, weightToStyle(weight))
+ await this.loadFont(family, faceLoadKey(weight))
}
/** Registers a font the caller already has, resolving once its outlines can be read. */
@@ -802,7 +649,7 @@ export class FontManager {
for (const family of manifest.localFamilies) {
signal?.throwIfAborted()
const buffer =
- (await this.loadHostFont(family, 'Regular')) ?? (await this.findLocalFont(family))
+ (await this.loadHostFont(family, 'Regular')) ?? (await this.localFonts.read(family))
signal?.throwIfAborted()
if (
buffer &&
@@ -896,29 +743,6 @@ export class FontManager {
}
}
- private findLocalFont(family: string, style?: string): Promise<ArrayBuffer | null> {
- if (!IS_BROWSER || !window.queryLocalFonts) return Promise.resolve(null)
- if (this.localFontAccessState !== 'granted') return Promise.resolve(null)
- // A query answers with a new blob, and so new bytes, every time; the face decides the match.
- return this.localFontRequests.read(`${family}|${style ?? ''}`, () =>
- this.readLocalFont(family, style)
- )
- }
-
- private async readLocalFont(family: string, style?: string): Promise<ArrayBuffer | null> {
- try {
- const fonts = await window.queryLocalFonts?.()
- if (!fonts) return null
- const match = chooseLocalFontMatch(fonts, family, style)
- if (!match) return null
- const blob: Blob = await match.blob()
- return await blob.arrayBuffer()
- } catch (e) {
- console.warn(`Local font access failed for "${family}" ${style ?? ''}:`, e)
- return null
- }
- }
-
private registerSupplemental(family: string, style: string, buffer: ArrayBuffer): void {
const key = `${family}|${style}`
const supplemental = this.supplementalFamilyData.get(key) ?? []
diff --git a/packages/core/src/text/font/names.ts b/packages/core/src/text/font/names.ts
new file mode 100644
index 000000000..cf0163fc0
--- /dev/null
+++ b/packages/core/src/text/font/names.ts
@@ -0,0 +1,71 @@
+import { uniqBy } from 'es-toolkit/array'
+
+import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import { parseFontStyle, standardStyleName } from '@open-pencil/scene-graph/font-style'
+import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
+
+import type { FamilyFace } from '#core/text/font/faces'
+import { fontManager } from '#core/text/font/manager'
+import { textFontFace } from '#core/text/requirements/collect'
+
+/** A text's or a character's face: its family, weight, and slant, and the name it was given. */
+export type TextFace = Pick<SceneNode, 'fontFamily' | 'fontWeight' | 'italic' | 'fontStyle'>
+
+/**
+ * The name the family's font gives its face at `weight` and slant, as Figma names a face; the
+ * standard name while the family's faces are unknown or it has no such face.
+ */
+export function faceStyleName(family: string, weight: number, italic: boolean): string {
+ const face = fontManager
+ .familyFacesSync(family)
+ ?.find((candidate) => candidate.weight === weight && candidate.italic === italic)
+ return face?.style ?? standardStyleName(weight, italic)
+}
+
+/** The name of the face a text draws in: the one it was given, else its font's own. */
+export function textStyleName(style: TextFace): string {
+ return style.fontStyle ?? faceStyleName(style.fontFamily, style.fontWeight, style.italic)
+}
+
+/** A name compared without case or spaces, so "Semi Bold" and "SemiBold" name one face. */
+function spellingKey(style: string): string {
+ return style.toLowerCase().replace(/\s+/gu, '')
+}
+
+/**
+ * The face `style` names in the family, by the family's own name for it, where the family names
+ * it alike but for case and spaces, as Inter 3's "Semi Bold" names Inter 4's "SemiBold". A name
+ * the family's faces do not hold, or while they are unknown, stays as asked, with the weight and
+ * slant its words stand for.
+ */
+export function faceForStyle(family: string, style: string): FamilyFace {
+ const faces = fontManager.familyFacesSync(family) ?? []
+ const face =
+ faces.find((candidate) => candidate.style === style) ??
+ faces.find((candidate) => spellingKey(candidate.style) === spellingKey(style))
+ return face ?? { ...parseFontStyle(style), style }
+}
+
+/** The name of the face characters with `style` over the text draw in, as the text names it. */
+export function textFaceName(node: SceneNode, style: CharacterStyleOverride = {}): string {
+ const face = textFontFace(node, style)
+ return textStyleName({
+ fontFamily: face.family,
+ fontWeight: face.weight,
+ italic: face.italic,
+ fontStyle: rangeFontStyle(node, style)
+ })
+}
+
+/** Each face a text draws in, with the style it loads as and its name, once per name. */
+export function collectNamedNodeFontFaces(
+ node: SceneNode
+): Array<{ family: string; style: string; name: string }> {
+ if (node.type !== 'TEXT') return []
+ const styles: CharacterStyleOverride[] = [{}, ...node.styleRuns.map((run) => run.style)]
+ const faces = styles.map((style) => {
+ const { family, style: load } = textFontFace(node, style)
+ return { family, style: load, name: textFaceName(node, style) }
+ })
+ return uniqBy(faces, (face) => `${face.family}\0${face.style}\0${face.name}`)
+}
diff --git a/packages/core/src/text/font/reads.ts b/packages/core/src/text/font/reads.ts
new file mode 100644
index 000000000..ff4bcb17d
--- /dev/null
+++ b/packages/core/src/text/font/reads.ts
@@ -0,0 +1,42 @@
+import { loadHarfBuzz } from '#core/text/font/harfbuzz'
+
+/**
+ * Shares the in-flight and successful reads of a key, and forgets a null answer so it can be
+ * retried. A host or browser read copies the whole face again each time, tens of megabytes for a
+ * system CJK face, only for registration to find the same bytes and drop it.
+ */
+export class SharedReads {
+ private readonly reads = new Map<string, Promise<ArrayBuffer | null>>()
+
+ read(key: string, load: () => Promise<ArrayBuffer | null>): Promise<ArrayBuffer | null> {
+ const existing = this.reads.get(key)
+ if (existing) return existing
+ const pending = load()
+ this.reads.set(key, pending)
+ void pending.then((data) => {
+ if (!data && this.reads.get(key) === pending) this.reads.delete(key)
+ return undefined
+ })
+ return pending
+ }
+
+ clear(): void {
+ this.reads.clear()
+ }
+}
+
+/** Whether two font files hold the same bytes, as one downloaded or read again does. */
+export function sameFontFile(a: ArrayBuffer, b: ArrayBuffer): boolean {
+ if (a === b) return true
+ if (a.byteLength !== b.byteLength) return false
+ const left = new Uint8Array(a)
+ const right = new Uint8Array(b)
+ for (let index = 0; index < left.length; index++) if (left[index] !== right[index]) return false
+ return true
+}
+
+/** `load`'s answer once HarfBuzz has loaded too, the two loading side by side. */
+export async function withHarfBuzz<T>(load: Promise<T>): Promise<T> {
+ const [answer] = await Promise.all([load, loadHarfBuzz()])
+ return answer
+}
diff --git a/packages/core/src/text/font/sources.ts b/packages/core/src/text/font/sources.ts
index d9c1ff62d..e4269e35c 100644
--- a/packages/core/src/text/font/sources.ts
+++ b/packages/core/src/text/font/sources.ts
@@ -1,4 +1,4 @@
-import type { WebFontProviderId } from '#core/text/web-fonts'
+import type { WebFontProviderId } from '#core/text/web-font/resolver'
export interface FontInfo {
family: string
diff --git a/packages/core/src/text/font/status.ts b/packages/core/src/text/font/status.ts
index e4bd842cd..9f7e3e25e 100644
--- a/packages/core/src/text/font/status.ts
+++ b/packages/core/src/text/font/status.ts
@@ -1,15 +1,18 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
+import { fontManager, type FontManager } from '#core/text/font/manager'
+import { collectNamedNodeFontFaces } from '#core/text/font/names'
import type { FontLoadedSource, FontUnavailableReason } from '#core/text/font/sources'
-import { fontManager, type FontManager } from '#core/text/fonts'
-import { collectNodeFontFaces } from '#core/text/requirements'
export type FontFaceStatus = 'available' | 'substituted' | 'unresolved'
export interface DocumentFontFaceStatus {
family: string
+ /** The style the font manager loads the face as. */
style: string
+ /** The face's name, as its text names it ("Book", "Semi Bold"). */
+ name: string
status: FontFaceStatus
source: FontLoadedSource | null
substituteFamily: string | null
@@ -28,12 +31,14 @@ export interface DocumentFontStatus {
interface MutableFontFaceUse {
family: string
style: string
+ name: string
nodeIds: Set<string>
nodeNames: Set<string>
}
-function faceKey(family: string, style: string): string {
- return `${family}\0${style}`
+/** A face by its name and the style it loads as; one name may load as two styles. */
+function faceKey(family: string, style: string, name: string): string {
+ return `${family}\0${style}\0${name}`
}
/** The text nodes under each root, and each root that is itself text. */
@@ -49,11 +54,13 @@ function rootTextNodes(graph: SceneGraph, rootIds: readonly string[]): SceneNode
function collectFaceUses(graph: SceneGraph, rootIds: readonly string[]): MutableFontFaceUse[] {
const uses = new Map<string, MutableFontFaceUse>()
for (const node of rootTextNodes(graph, rootIds)) {
- for (const { family, style } of collectNodeFontFaces(node)) {
- const key = faceKey(family, style)
+ // Faces that load as one style ("Book" and "Roman" at 400) are still faces of their own.
+ for (const { family, style, name } of collectNamedNodeFontFaces(node)) {
+ const key = faceKey(family, style, name)
const use = uses.get(key) ?? {
family,
style,
+ name,
nodeIds: new Set<string>(),
nodeNames: new Set<string>()
}
@@ -71,6 +78,7 @@ function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFont
return {
family: use.family,
style: use.style,
+ name: use.name,
status: 'available',
source: exactSource,
substituteFamily: null,
@@ -84,6 +92,7 @@ function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFont
return {
family: use.family,
style: use.style,
+ name: use.name,
status: 'substituted',
source: null,
substituteFamily: use.family,
@@ -97,6 +106,7 @@ function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFont
return {
family: use.family,
style: use.style,
+ name: use.name,
status: defaultSource ? 'substituted' : 'unresolved',
source: null,
substituteFamily: defaultSource ? DEFAULT_FONT_FAMILY : null,
@@ -114,7 +124,7 @@ export function documentFontStatus(
const roots = typeof rootIds === 'string' ? [rootIds] : rootIds
const faces = collectFaceUses(graph, roots)
.map((use) => faceStatus(use, manager))
- .sort((a, b) => a.family.localeCompare(b.family) || a.style.localeCompare(b.style))
+ .sort((a, b) => a.family.localeCompare(b.family) || a.name.localeCompare(b.name))
const issues = faces.filter((face) => face.status !== 'available')
return { faithful: issues.length === 0, faces, issues }
}
diff --git a/packages/core/src/text/font/variation.ts b/packages/core/src/text/font/variation.ts
index 4576a50e7..53f2d2eb0 100644
--- a/packages/core/src/text/font/variation.ts
+++ b/packages/core/src/text/font/variation.ts
@@ -146,7 +146,7 @@ export function fontAxes(data: ArrayBuffer): FontAxis[] | null {
return variationTable(data)?.axes ?? null
}
-/** A named instance of a variable font, such as Inter's `Semi Bold`, with every axis' value. */
+/** A named instance of a variable font, such as Inter's `SemiBold`, with every axis' value. */
export interface NamedInstance {
name: string
variations: FontVariation[]
diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.ts
index 0386cb2b5..c1884ac06 100644
--- a/packages/core/src/text/index.ts
+++ b/packages/core/src/text/index.ts
@@ -2,18 +2,22 @@ export * from './editor'
export * from './style-runs'
export * from './case'
export * from './coverage'
-export * from './fonts'
+export * from './font/manager'
+export * from './font/sources'
+export * from './font/style'
+export * from './font/variation'
+export * from './font/woff2'
export * from './font/status'
export { setHarfBuzzSubsetLocator, type HarfBuzzSubsetLocator } from './font/harfbuzz'
export * from './fallbacks'
export * from './resolver'
-export * from './requirements'
-export * from './resolved-requirements'
-export * from './web-fonts'
+export * from './requirements/collect'
+export * from './requirements/resolved'
+export * from './web-font/resolver'
export * from './path'
export * from './prepare'
export * from './font/faces'
-export { fontFaceFromFigmaFontName, fontFaceRenderFamily, type FontFaceRef } from './face'
+export * from './font/names'
export {
probeGlyphOutlineCommands,
type GlyphOutlineProbe,
diff --git a/packages/core/src/text/outlines.ts b/packages/core/src/text/outlines.ts
index 422e8c8a8..901b77de1 100644
--- a/packages/core/src/text/outlines.ts
+++ b/packages/core/src/text/outlines.ts
@@ -1,7 +1,7 @@
import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
import {
@@ -9,7 +9,7 @@ import {
getGlyphOutlineMetricsSync,
type OutlineCommand
} from '#core/text/font/glyphs'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
export type TextOutlineUnsupportedReason =
| 'not-text'
@@ -54,7 +54,7 @@ function baseTextStyle(node: SceneNode): TextStyle {
}
function styleName(style: Pick<TextStyle, 'fontWeight' | 'italic'>): string {
- return weightToStyle(style.fontWeight, style.italic)
+ return faceLoadKey(style.fontWeight, style.italic)
}
function styleKey(style: TextStyle): string {
diff --git a/packages/core/src/text/prepare.ts b/packages/core/src/text/prepare.ts
index dc78cdac6..2003d4a59 100644
--- a/packages/core/src/text/prepare.ts
+++ b/packages/core/src/text/prepare.ts
@@ -10,9 +10,9 @@ import {
savedEmojiCharacters
} from '#core/text/emoji'
import { fontGlyphCoverageSync } from '#core/text/font/glyphs'
-import { fontManager } from '#core/text/fonts'
-import { collectGraphFontRequirements, collectNodeFontFaces } from '#core/text/requirements'
-import { missingGraphFontScripts } from '#core/text/resolved-requirements'
+import { fontManager } from '#core/text/font/manager'
+import { collectGraphFontRequirements, collectNodeFontFaces } from '#core/text/requirements/collect'
+import { missingGraphFontScripts } from '#core/text/requirements/resolved'
import { documentFontStatus, type DocumentFontStatus } from './font/status'
diff --git a/packages/core/src/text/requirements.ts b/packages/core/src/text/requirements/collect.ts
similarity index 94%
rename from packages/core/src/text/requirements.ts
rename to packages/core/src/text/requirements/collect.ts
index 122e4357b..b422da9ef 100644
--- a/packages/core/src/text/requirements.ts
+++ b/packages/core/src/text/requirements/collect.ts
@@ -1,12 +1,12 @@
import { uniqBy } from 'es-toolkit/array'
import type { CharacterStyleOverride, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { shownCharacters } from '#core/text/case'
-import type { FontFaceRef } from '#core/text/face'
import { fontFallbackScriptForCharacter, type FontFallbackScript } from '#core/text/fallbacks'
+import type { FontFaceRef } from '#core/text/font/faces'
/** The face a text draws in, or the face a style run over it draws in. */
export function textFontFace(node: SceneNode, style: CharacterStyleOverride = {}): FontFaceRef {
@@ -14,7 +14,7 @@ export function textFontFace(node: SceneNode, style: CharacterStyleOverride = {}
const italic = style.italic ?? node.italic
return {
family: style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY),
- style: weightToStyle(weight, italic),
+ style: faceLoadKey(weight, italic),
weight,
italic
}
diff --git a/packages/core/src/text/resolved-requirements.ts b/packages/core/src/text/requirements/resolved.ts
similarity index 98%
rename from packages/core/src/text/resolved-requirements.ts
rename to packages/core/src/text/requirements/resolved.ts
index f4ba2527d..e12752efe 100644
--- a/packages/core/src/text/resolved-requirements.ts
+++ b/packages/core/src/text/requirements/resolved.ts
@@ -1,6 +1,6 @@
import { textFallbackScriptsWithoutCoverage, textNeededFallbackScripts } from '#core/text/coverage'
import type { FontFallbackScript } from '#core/text/fallbacks'
-import type { GraphFontRequirements } from '#core/text/requirements'
+import type { GraphFontRequirements } from '#core/text/requirements/collect'
export interface MissingGraphFontScriptsOptions {
treatUnknownCoverageAsMissing?: boolean
diff --git a/packages/core/src/text/resolver/index.ts b/packages/core/src/text/resolver/index.ts
index ddd12db91..0cdaf52ee 100644
--- a/packages/core/src/text/resolver/index.ts
+++ b/packages/core/src/text/resolver/index.ts
@@ -1,5 +1,5 @@
import type { FontFallbackScript } from '#core/text/fallbacks'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { FontResolver } from '#core/text/resolver/resolver'
import type {
FontResolutionCandidate,
diff --git a/packages/core/src/text/web-font/assets.ts b/packages/core/src/text/web-font/assets.ts
index 60e94e7fe..7faa085c0 100644
--- a/packages/core/src/text/web-font/assets.ts
+++ b/packages/core/src/text/web-font/assets.ts
@@ -11,7 +11,7 @@ import {
WEB_FONT_PROVIDER_IDS,
type WebFontFetch,
type WebFontProviderId
-} from '#core/text/web-fonts'
+} from '#core/text/web-font/resolver'
export interface ExportWebFontFaceAssetsOptions {
fonts: WebFontFaceRequest[]
diff --git a/packages/core/src/text/web-font/providers.ts b/packages/core/src/text/web-font/providers.ts
index c7fb3088d..46853bfd8 100644
--- a/packages/core/src/text/web-font/providers.ts
+++ b/packages/core/src/text/web-font/providers.ts
@@ -7,7 +7,7 @@ import {
type Unifont
} from 'unifont'
-import type { WebFontProviderId } from '#core/text/web-fonts'
+import type { WebFontProviderId } from '#core/text/web-font/resolver'
export type WebFontProvider =
| ReturnType<typeof providers.google>
diff --git a/packages/core/src/text/web-fonts.ts b/packages/core/src/text/web-font/resolver.ts
similarity index 99%
rename from packages/core/src/text/web-fonts.ts
rename to packages/core/src/text/web-font/resolver.ts
index 83154a63b..cc5db3991 100644
--- a/packages/core/src/text/web-fonts.ts
+++ b/packages/core/src/text/web-font/resolver.ts
@@ -10,7 +10,7 @@ import {
HANGUL_CHARACTER,
KANA_CHARACTER
} from '#core/text/fallbacks'
-import type { FamilyFace } from '#core/text/font/faces'
+import { standardFace, type FamilyFace } from '#core/text/font/faces'
import { sfntFont } from '#core/text/font/woff2'
import {
createProviderUnifont,
@@ -115,7 +115,7 @@ function familyFacesOf(result: ResolveFontResult): FamilyFace[] {
for (const font of result.fonts) {
const italic = font.style === 'italic' || font.style?.startsWith('oblique') === true
for (const weight of faceWeights(font.weight))
- faces.set(`${weight}${italic ? 'i' : ''}`, { weight, italic })
+ faces.set(`${weight}${italic ? 'i' : ''}`, standardFace(weight, italic))
}
return [...faces.values()]
}
diff --git a/packages/core/src/tools/create/connector.ts b/packages/core/src/tools/create/connector.ts
index 1ff3f39a6..59d5397a4 100644
--- a/packages/core/src/tools/create/connector.ts
+++ b/packages/core/src/tools/create/connector.ts
@@ -1,7 +1,7 @@
import * as v from 'valibot'
import { CONNECTOR_LABEL_FONT } from '@open-pencil/scene-graph/connectors'
-import { weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { toolNumber, defineTool, nodeSummary } from '#core/tools/schema'
@@ -55,7 +55,7 @@ export const createConnectorTool = defineTool({
? [
{
family: CONNECTOR_LABEL_FONT.family,
- style: weightToStyle(CONNECTOR_LABEL_FONT.weight)
+ style: faceLoadKey(CONNECTOR_LABEL_FONT.weight)
}
]
: [],
diff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.ts
index b2be027cd..40c06c4af 100644
--- a/packages/core/src/tools/modify/text.ts
+++ b/packages/core/src/tools/modify/text.ts
@@ -3,13 +3,10 @@ import * as v from 'valibot'
import { parseColor } from '@open-pencil/scene-graph/color'
import type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'
-import type {
- FigmaFontName,
- FigmaFontNameInput,
- FigmaVariationSettings
-} from '#core/figma-api/fonts'
+import type { FigmaFontName, FigmaFontNameInput } from '#core/figma-api/fonts/names'
+import type { FigmaVariationSettings } from '#core/figma-api/fonts/variations'
import { OpenPencilAPI } from '#core/openpencil-api'
-import { collectNodeFontFaces } from '#core/text/requirements'
+import { collectNodeFontFaces } from '#core/text/requirements/collect'
import {
toolNumber,
nodeIdInputSchema,
diff --git a/packages/core/src/tools/schema.ts b/packages/core/src/tools/schema.ts
index 445c611e0..cdbcebdae 100644
--- a/packages/core/src/tools/schema.ts
+++ b/packages/core/src/tools/schema.ts
@@ -10,7 +10,7 @@ import * as v from 'valibot'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'
-import type { FigmaFontNameInput } from '#core/figma-api/fonts'
+import type { FigmaFontNameInput } from '#core/figma-api/fonts/names'
export type ToolCapability =
| 'document:read'
diff --git a/packages/core/tests/canvas/renderer/lifecycle.test.ts b/packages/core/tests/canvas/renderer/lifecycle.test.ts
index 46b479eb4..95ff2bf5a 100644
--- a/packages/core/tests/canvas/renderer/lifecycle.test.ts
+++ b/packages/core/tests/canvas/renderer/lifecycle.test.ts
@@ -4,7 +4,7 @@ import { expectDefined } from '#core-tests/helpers/assert'
import { SkiaRenderer } from '#core/canvas'
import { initCanvasKit } from '#core/io/formats/raster/headless'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
const ck = await initCanvasKit()
diff --git a/packages/core/tests/canvas/text/faces.test.ts b/packages/core/tests/canvas/text/faces.test.ts
index 8d813fc19..aa4e752b8 100644
--- a/packages/core/tests/canvas/text/faces.test.ts
+++ b/packages/core/tests/canvas/text/faces.test.ts
@@ -11,8 +11,8 @@ import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import { buildParagraph } from '#core/canvas/text'
import { withFigExportRuntime } from '#core/canvas/text/shape'
import { getCanvasKit } from '#core/canvaskit'
-import { FontManager, fontManager } from '#core/text/fonts'
-import { WEB_FONT_PROVIDER_IDS } from '#core/text/web-fonts'
+import { FontManager, fontManager } from '#core/text/font/manager'
+import { WEB_FONT_PROVIDER_IDS } from '#core/text/web-font/resolver'
import { glyphOutlineSourceSync } from '#core/text/font/glyphs'
/** A family only these tests load, so faces other tests load cannot answer for it. */
diff --git a/packages/core/tests/canvas/text/lines.test.ts b/packages/core/tests/canvas/text/lines.test.ts
index 423bcb87c..01c275501 100644
--- a/packages/core/tests/canvas/text/lines.test.ts
+++ b/packages/core/tests/canvas/text/lines.test.ts
@@ -9,7 +9,7 @@ import { pixelLength } from '@open-pencil/scene-graph/text'
import type { TextLayout } from '#core/canvas/text/layout'
import { buildParagraph } from '#core/canvas/text/layout/build'
import { getCanvasKit } from '#core/canvaskit'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
const run = (start: number, length: number, style: StyleRun['style']): StyleRun => ({
start,
diff --git a/packages/core/tests/canvas/text/lists.test.ts b/packages/core/tests/canvas/text/lists.test.ts
index 850ff805e..b79bf3b76 100644
--- a/packages/core/tests/canvas/text/lists.test.ts
+++ b/packages/core/tests/canvas/text/lists.test.ts
@@ -8,7 +8,7 @@ import { SceneGraph, type SceneNode, type TextParagraphStyle } from '@open-penci
import { buildParagraph } from '#core/canvas/text/layout/build'
import { withFigExportRuntime } from '#core/canvas/text/shape'
import { getCanvasKit } from '#core/canvaskit'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { glyphAdvanceSync } from '#core/text/font/glyphs'
const ul = (indentation = 1): TextParagraphStyle => ({ listType: 'UNORDERED', indentation })
diff --git a/packages/core/tests/canvas/text/readiness.test.ts b/packages/core/tests/canvas/text/readiness.test.ts
index 752157fef..08c3c3d86 100644
--- a/packages/core/tests/canvas/text/readiness.test.ts
+++ b/packages/core/tests/canvas/text/readiness.test.ts
@@ -6,7 +6,7 @@ import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import { nodeFontReadiness } from '#core/canvas/text'
import { getCanvasKit } from '#core/canvaskit'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
/**
* A character no font has, once no fallback is left for it, shows as the font's missing glyph
diff --git a/packages/core/tests/canvas/text/shape.test.ts b/packages/core/tests/canvas/text/shape.test.ts
index 59aa23432..f1744ecf8 100644
--- a/packages/core/tests/canvas/text/shape.test.ts
+++ b/packages/core/tests/canvas/text/shape.test.ts
@@ -13,7 +13,7 @@ import { pixelLength } from '@open-pencil/scene-graph/text'
import { withFigExportRuntime, withTextShaper } from '#core/canvas/text/shape'
import { getCanvasKit } from '#core/canvaskit'
import { EMOJI_METRICS_FAMILY } from '#core/text/emoji'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { getGlyphOutlineMetricsSync } from '#core/text/font/glyphs'
const testFont = (name: string) => join(FIXTURES, 'fonts', name)
diff --git a/packages/core/tests/figma-api/load-font.test.ts b/packages/core/tests/figma-api/fonts/load.test.ts
similarity index 100%
rename from packages/core/tests/figma-api/load-font.test.ts
rename to packages/core/tests/figma-api/fonts/load.test.ts
diff --git a/packages/core/tests/figma-api/text/unloaded-fonts.test.ts b/packages/core/tests/figma-api/fonts/loaded.test.ts
similarity index 95%
rename from packages/core/tests/figma-api/text/unloaded-fonts.test.ts
rename to packages/core/tests/figma-api/fonts/loaded.test.ts
index 85f529f64..e9968cc6b 100644
--- a/packages/core/tests/figma-api/text/unloaded-fonts.test.ts
+++ b/packages/core/tests/figma-api/fonts/loaded.test.ts
@@ -84,9 +84,12 @@ describe('text in a font that is not loaded', () => {
expect(raw()?.textDecoration).toBe('UNDERLINE')
})
- test('names fonts in its messages as Figma does', () => {
+ test('names fonts in its messages by the name the text has for its face', () => {
const { graph, node } = unloadedText()
graph.updateNode(node.id, { fontWeight: 600 })
+ expect(() => (node.fontSize = 20)).toThrow(`unloaded font "${UNLOADED} SemiBold"`)
+ // A file names the face as its font does, which Figma's message repeats.
+ graph.updateNode(node.id, { fontStyle: 'Semi Bold' })
expect(() => (node.fontSize = 20)).toThrow(`unloaded font "${UNLOADED} Semi Bold"`)
})
diff --git a/packages/core/tests/figma-api/fonts/names.test.ts b/packages/core/tests/figma-api/fonts/names.test.ts
new file mode 100644
index 000000000..3ee6b3fa0
--- /dev/null
+++ b/packages/core/tests/figma-api/fonts/names.test.ts
@@ -0,0 +1,51 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { asTextNode, registerTestFont } from '#core-tests/helpers/figma-api'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { fontManager } from '@open-pencil/core/text'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+beforeAll(async () => {
+ await registerTestFont()
+ await fontManager.familyFaces('Inter')
+ const api = new FigmaAPI(new SceneGraph())
+ for (const style of ['SemiBold', 'Bold']) await api.loadFontAsync({ family: 'Inter', style })
+})
+
+function text() {
+ const graph = new SceneGraph()
+ const node = asTextNode(new FigmaAPI(graph).createText())
+ node.characters = 'Hello'
+ return { graph, node, raw: () => graph.getNode(node.id) }
+}
+
+// Measured in Figma desktop (2026-10-28): `fontName.style` is the font's own name for the face.
+describe('font style names', () => {
+ test('reads plain italic as "Italic", as fonts name it', () => {
+ const { node } = text()
+ node.fontName = { family: 'Inter', style: 'Italic' }
+ expect(node.fontName).toMatchObject({ family: 'Inter', style: 'Italic' })
+ })
+
+ test('reads the name a file gives a face', () => {
+ const { graph, node } = text()
+ graph.updateNode(node.id, { fontStyle: 'Semi Bold', fontWeight: 600 })
+ expect(node.fontName).toMatchObject({ style: 'Semi Bold' })
+ expect(node.getRangeFontName(0, 2)).toMatchObject({ style: 'Semi Bold' })
+ })
+
+ test('takes a name spelled another way as the family’s own name for that face', () => {
+ const { node, raw } = text()
+ node.fontName = { family: 'Inter', style: 'Semi Bold' }
+ expect(raw()).toMatchObject({ fontWeight: 600, italic: false, fontStyle: 'SemiBold' })
+ expect(node.fontName).toMatchObject({ style: 'SemiBold' })
+ })
+
+ test('a new weight takes its face’s name', () => {
+ const { graph, node } = text()
+ graph.updateNode(node.id, { fontStyle: 'Semi Bold', fontWeight: 600 })
+ node.fontWeight = 700
+ expect(node.fontName).toMatchObject({ style: 'Bold' })
+ })
+})
diff --git a/packages/core/tests/figma-api/text/variations.test.ts b/packages/core/tests/figma-api/fonts/variations.test.ts
similarity index 98%
rename from packages/core/tests/figma-api/text/variations.test.ts
rename to packages/core/tests/figma-api/fonts/variations.test.ts
index 381402527..f03605a28 100644
--- a/packages/core/tests/figma-api/text/variations.test.ts
+++ b/packages/core/tests/figma-api/fonts/variations.test.ts
@@ -52,10 +52,11 @@ describe('variable fonts in the plugin API', () => {
test('picks the nearest named style for axes without a style, the heavier where two tie', () => {
const { node } = text()
+ // Named as the font names its instances: Inter 4 joins "SemiBold".
for (const [wght, style] of [
[900, 'Black'],
[650, 'Bold'],
- [550, 'Semi Bold'],
+ [550, 'SemiBold'],
[450, 'Medium'],
[1, 'Thin']
] as const) {
diff --git a/packages/core/tests/figma-api/text/autosize.test.ts b/packages/core/tests/figma-api/text/autosize.test.ts
index 893371a1e..cdcc6fd8f 100644
--- a/packages/core/tests/figma-api/text/autosize.test.ts
+++ b/packages/core/tests/figma-api/text/autosize.test.ts
@@ -5,7 +5,7 @@ import { expectDefined } from '#core-tests/helpers/assert'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
// Recorded with the same script in live Figma on 2026-10-07, Inter Regular. Line metrics round
// differently by up to a pixel.
diff --git a/packages/core/tests/io/formats/fig/export/live-document.test.ts b/packages/core/tests/io/formats/fig/export/live-document.test.ts
index b5839d116..535141a78 100644
--- a/packages/core/tests/io/formats/fig/export/live-document.test.ts
+++ b/packages/core/tests/io/formats/fig/export/live-document.test.ts
@@ -9,7 +9,7 @@ import { SceneGraph } from '@open-pencil/scene-graph'
import { emptyBehaviour, readBehaviour } from '@open-pencil/scene-graph/behaviours'
import { settleFontDigestMap } from '#core/kiwi/fig/node-change/font/digests'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
// A save reads the document after its last wait, so the font digests it waits for must cover
// a font an edit brought in while they loaded.
diff --git a/packages/core/tests/io/formats/pdf/export.test.ts b/packages/core/tests/io/formats/pdf/export.test.ts
index e336794a2..3903bcac8 100644
--- a/packages/core/tests/io/formats/pdf/export.test.ts
+++ b/packages/core/tests/io/formats/pdf/export.test.ts
@@ -6,7 +6,7 @@ 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'
+import { fontManager } from '#core/text/font/manager'
/** A page with a red square and a gradient, drawn without a browser DOM, as the CLI exports. */
function card() {
diff --git a/packages/core/tests/io/formats/pdf/fonts.test.ts b/packages/core/tests/io/formats/pdf/fonts.test.ts
index f2581599a..3eba9d475 100644
--- a/packages/core/tests/io/formats/pdf/fonts.test.ts
+++ b/packages/core/tests/io/formats/pdf/fonts.test.ts
@@ -15,7 +15,7 @@ import {
} from '#core/io/formats/pdf/fonts'
import type { SVGFontRequest } from '#core/io/formats/svg'
import { isVariableFont } from '#core/text/font/variation'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
/** Records what jsPDF would be asked to register. */
function pdfDoc() {
diff --git a/packages/core/tests/io/formats/pdf/text-layout.test.ts b/packages/core/tests/io/formats/pdf/text-layout.test.ts
index 7b19982e4..e46a0178d 100644
--- a/packages/core/tests/io/formats/pdf/text-layout.test.ts
+++ b/packages/core/tests/io/formats/pdf/text-layout.test.ts
@@ -7,7 +7,7 @@ import { pixelLength } from '@open-pencil/scene-graph/text'
import { withPDFTextLayout } from '#core/io/formats/pdf/prepare'
import { renderNodesToSVG } from '#core/io/formats/svg'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
const SENTENCE = 'A sentence long enough that it has to wrap onto a second line.'
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 e1a019dae..8d01b468c 100644
--- a/packages/core/tests/io/formats/svg/font-alias.test.ts
+++ b/packages/core/tests/io/formats/svg/font-alias.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { renderNodesToSVG, type SVGFontRequest, type SVGTextLine } from '#core/io/formats/svg'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
const ALIASES: Record<string, string> = {
'Inter\0Regular': 'EmbeddedFont0',
diff --git a/packages/core/tests/io/formats/svg/text/layout.test.ts b/packages/core/tests/io/formats/svg/text/layout.test.ts
index 3243dc000..be642cffc 100644
--- a/packages/core/tests/io/formats/svg/text/layout.test.ts
+++ b/packages/core/tests/io/formats/svg/text/layout.test.ts
@@ -6,7 +6,7 @@ import { SceneGraph } from '@open-pencil/scene-graph'
import { pixelLength } from '@open-pencil/scene-graph/text'
import { BUILTIN_IO_FORMATS, IORegistry } from '#core/io'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
const SENTENCE = 'A sentence long enough that it has to wrap onto a second line.'
diff --git a/packages/core/tests/text/font/faces.test.ts b/packages/core/tests/text/font/faces.test.ts
index c8a3baf67..46f0582a6 100644
--- a/packages/core/tests/text/font/faces.test.ts
+++ b/packages/core/tests/text/font/faces.test.ts
@@ -14,24 +14,24 @@ const lora = facesFromStyles([
'Bold Italic'
])
-test('reads faces from style names, once each', () => {
- expect(facesFromStyles(['Bold', 'Bold', 'Light Italic', 'ExtraLight'])).toEqual([
- { weight: 700, italic: false },
- { weight: 300, italic: true },
- { weight: 200, italic: false }
+test('reads faces from style names, once each, keeping each name', () => {
+ expect(facesFromStyles(['Bold', 'Bold', 'Light Italic', 'Extra Light'])).toEqual([
+ { weight: 700, italic: false, style: 'Bold' },
+ { weight: 300, italic: true, style: 'Light Italic' },
+ { weight: 200, italic: false, style: 'Extra Light' }
])
})
test('the nearest face keeps the slant, as Figma picks one on a family switch', () => {
- expect(nearestFamilyFace(lora, 100, false)).toEqual({ weight: 400, italic: false })
- expect(nearestFamilyFace(lora, 900, false)).toEqual({ weight: 700, italic: false })
- expect(nearestFamilyFace(lora, 500, true)).toEqual({ weight: 500, italic: true })
- expect(nearestFamilyFace(lora, 900, true)).toEqual({ weight: 700, italic: true })
+ expect(nearestFamilyFace(lora, 100, false)).toMatchObject({ weight: 400, italic: false })
+ expect(nearestFamilyFace(lora, 900, false)).toMatchObject({ weight: 700, italic: false })
+ expect(nearestFamilyFace(lora, 500, true)).toMatchObject({ weight: 500, italic: true })
+ expect(nearestFamilyFace(lora, 900, true)).toMatchObject({ style: 'Bold Italic' })
})
test('a family without the slant gives the nearest weight, and a tie takes the lighter', () => {
const upright = facesFromStyles(['Regular', 'SemiBold'])
- expect(nearestFamilyFace(upright, 700, true)).toEqual({ weight: 600, italic: false })
- expect(nearestFamilyFace(upright, 500, false)).toEqual({ weight: 400, italic: false })
+ expect(nearestFamilyFace(upright, 700, true)).toMatchObject({ weight: 600, italic: false })
+ expect(nearestFamilyFace(upright, 500, false)).toMatchObject({ weight: 400, italic: false })
expect(nearestFamilyFace([], 400, false)).toBeNull()
})
diff --git a/packages/core/tests/text/fonts.test.ts b/packages/core/tests/text/font/manager.test.ts
similarity index 91%
rename from packages/core/tests/text/fonts.test.ts
rename to packages/core/tests/text/font/manager.test.ts
index ec0718349..c7d82368e 100644
--- a/packages/core/tests/text/fonts.test.ts
+++ b/packages/core/tests/text/font/manager.test.ts
@@ -32,11 +32,27 @@ test('a face lookup that outlives a new catalog does not overwrite what the cata
expect(await before).toBeNull()
expect(manager.loadedFamilyFaces('Oswald')).toBeUndefined()
expect(await manager.familyFaces('Oswald')).toEqual([
- { weight: 400, italic: false },
- { weight: 700, italic: false }
+ { weight: 400, italic: false, style: 'Regular' },
+ { weight: 700, italic: false, style: 'Bold' }
])
})
+test('names faces as each source can: local fonts by their own names, the rest as Google does', async () => {
+ const manager = offlineManager()
+ // The desktop catalog lists generated names, so its italic takes the standard "Italic".
+ manager.setHostFontCatalog([{ family: 'Host Sans', styles: ['Regular Italic', 'SemiBold'] }])
+ expect(await manager.familyFaces('Host Sans')).toEqual([
+ { weight: 400, italic: true, style: 'Italic' },
+ { weight: 600, italic: false, style: 'SemiBold' }
+ ])
+ // Bundled Inter names its instances as Google Fonts does.
+ expect(await manager.familyFaces('Inter')).toContainEqual({
+ weight: 400,
+ italic: true,
+ style: 'Italic'
+ })
+})
+
test('a new catalog tells listeners to ask for their families again', () => {
const manager = offlineManager()
let resets = 0
diff --git a/packages/core/tests/text/font/names.test.ts b/packages/core/tests/text/font/names.test.ts
new file mode 100644
index 000000000..8a8c0ff2c
--- /dev/null
+++ b/packages/core/tests/text/font/names.test.ts
@@ -0,0 +1,72 @@
+import { beforeAll, expect, test } from 'bun:test'
+
+import { styleRunsWithPatch, textStyleChanges } from '#core/text/character-style'
+
+import { createEditor } from '@open-pencil/core'
+import { fontManager, faceForStyle, textStyleName } from '@open-pencil/core/text'
+
+beforeAll(async () => {
+ await fontManager.familyFaces('Inter')
+})
+
+function textNode(fields: Parameters<ReturnType<typeof createEditor>['graph']['createNode']>[2]) {
+ const editor = createEditor()
+ const node = editor.graph.createNode('TEXT', editor.state.currentPageId, {
+ text: 'Hello world',
+ ...fields
+ })
+ return { editor, node }
+}
+
+test('finds a face by its family’s own name for it, whatever its spelling', () => {
+ // Our Inter 4 joins the names Figma's Inter 3 spaces.
+ expect(faceForStyle('Inter', 'Semi Bold')).toEqual({ weight: 600, italic: false, style: 'SemiBold' })
+ expect(faceForStyle('Inter', 'italic')).toEqual({ weight: 400, italic: true, style: 'Italic' })
+ // A name the family does not hold stays as asked, so a file keeps it.
+ expect(faceForStyle('Nowhere Sans', 'Book')).toEqual({ weight: 400, italic: false, style: 'Book' })
+})
+
+test('names a text by the name it was given, else by its font’s name for its weight', () => {
+ const { editor, node } = textNode({ fontFamily: 'Avenir', fontStyle: 'Book', fontWeight: 400 })
+ try {
+ expect(textStyleName(node)).toBe('Book')
+ editor.graph.updateNode(node.id, { fontStyle: null })
+ expect(textStyleName(node)).toBe('Regular')
+ editor.graph.updateNode(node.id, { fontFamily: 'Inter', italic: true })
+ expect(textStyleName(node)).toBe('Italic')
+ } finally {
+ editor.dispose()
+ }
+})
+
+test('a new weight, slant, or family drops the name, and undo brings it back', () => {
+ const { editor, node } = textNode({ fontFamily: 'Avenir', fontStyle: 'Book' })
+ try {
+ // Setting what the text already has keeps the name the file gave it.
+ editor.updateNodeWithUndo(node.id, { fontFamily: 'Avenir', fontWeight: 400, italic: false })
+ expect(node.fontStyle).toBe('Book')
+ editor.updateNodeWithUndo(node.id, { fontWeight: 700 })
+ expect(node.fontStyle).toBeNull()
+ editor.undoAction()
+ expect([node.fontWeight, node.fontStyle]).toEqual([400, 'Book'])
+ editor.updateNodeWithUndo(node.id, { italic: true })
+ expect(node.fontStyle).toBeNull()
+ editor.updateNodeWithUndo(node.id, { fontFamily: 'Inter', fontStyle: 'Bold', fontWeight: 700 })
+ expect(node.fontStyle).toBe('Bold')
+ } finally {
+ editor.dispose()
+ }
+})
+
+test('a range in a new weight takes no name, and a new weight for all of it clears the ranges’', () => {
+ const { editor, node } = textNode({ fontFamily: 'Avenir', fontStyle: 'Book' })
+ try {
+ const runs = styleRunsWithPatch(node, 6, 11, { fontWeight: 700 })
+ expect(runs).toEqual([{ start: 6, length: 5, style: { fontWeight: 700, fontStyle: null } }])
+ const named = styleRunsWithPatch(node, 6, 11, { fontWeight: 300, fontStyle: 'Light' })
+ editor.graph.updateNode(node.id, { styleRuns: named })
+ expect(textStyleChanges(node, { fontWeight: 900 }).styleRuns).toEqual([])
+ } finally {
+ editor.dispose()
+ }
+})
diff --git a/packages/core/tests/text/font/style.test.ts b/packages/core/tests/text/font/style.test.ts
new file mode 100644
index 000000000..a287f2ed9
--- /dev/null
+++ b/packages/core/tests/text/font/style.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, test } from 'bun:test'
+
+import { chooseLocalFontMatch, fontWeightMatchOrder } from '@open-pencil/core/text'
+
+describe('chooseLocalFontMatch', () => {
+ const fonts = [
+ { family: 'Inter', style: 'Italic' },
+ { family: 'Inter', style: 'Regular' },
+ { family: 'Inter', style: 'Semi Bold' },
+ { family: 'Inter', style: 'Bold Italic' }
+ ]
+
+ test('prefers parsed weight and slant over first family match', () => {
+ expect(chooseLocalFontMatch(fonts, 'Inter', 'SemiBold')?.style).toBe('Semi Bold')
+ expect(chooseLocalFontMatch(fonts, 'Inter', 'Regular')?.style).toBe('Regular')
+ })
+
+ test('does not substitute nearby weights for explicit style requests', () => {
+ expect(chooseLocalFontMatch(fonts, 'Inter', 'Bold')).toBeUndefined()
+ })
+
+ test('without a style, takes the face CSS font matching picks for regular', () => {
+ const faces = [
+ { family: 'Inter', style: 'Black' },
+ { family: 'Inter', style: 'Light Italic' },
+ { family: 'Inter', style: 'Medium' },
+ { family: 'Inter', style: 'Light' }
+ ]
+ // Regular falls to medium before lighter weights, and the upright slant before italic.
+ expect(chooseLocalFontMatch(faces, 'Inter')?.style).toBe('Medium')
+ expect(chooseLocalFontMatch(faces.slice(0, 2), 'Inter')?.style).toBe('Black')
+ })
+})
+
+describe('fontWeightMatchOrder', () => {
+ test('tries weights in CSS font matching order', () => {
+ expect(fontWeightMatchOrder(400)).toEqual([400, 500, 300, 200, 100, 600, 700, 800, 900])
+ expect(fontWeightMatchOrder(700)).toEqual([700, 800, 900, 600, 500, 400, 300, 200, 100])
+ expect(fontWeightMatchOrder(300)).toEqual([300, 200, 100, 400, 500, 600, 700, 800, 900])
+ })
+})
diff --git a/packages/core/tests/text/prepare.test.ts b/packages/core/tests/text/prepare.test.ts
index ee360b345..6dfcea1f0 100644
--- a/packages/core/tests/text/prepare.test.ts
+++ b/packages/core/tests/text/prepare.test.ts
@@ -5,7 +5,7 @@ import { expectDefined } from '#core-tests/helpers/assert'
import { SceneGraph } from '@open-pencil/scene-graph'
import { NOTO_COLOR_EMOJI_FAMILY } from '#core/text/emoji'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { prepareGraphFonts } from '#core/text/prepare'
function graphWithText(text: string) {
diff --git a/packages/core/tests/text/web-fonts.test.ts b/packages/core/tests/text/web-font/resolver.test.ts
similarity index 100%
rename from packages/core/tests/text/web-fonts.test.ts
rename to packages/core/tests/text/web-font/resolver.test.ts
diff --git a/packages/fig/src/instance-overrides/fields.ts b/packages/fig/src/instance-overrides/fields.ts
index 039aca749..f1b9702d1 100644
--- a/packages/fig/src/instance-overrides/fields.ts
+++ b/packages/fig/src/instance-overrides/fields.ts
@@ -105,7 +105,7 @@ export const OVERRIDE_FIELDS = {
stackPrimaryAlignItems: { scene: ['primaryAxisAlign'], kind: 'node' },
stackCounterAlignItems: { scene: ['counterAxisAlign'], kind: 'node' },
stackPositioning: { scene: ['layoutPositioning'], kind: 'node' },
- fontName: { scene: ['fontFamily', 'fontWeight', 'italic'], kind: 'node' },
+ fontName: { scene: ['fontFamily', 'fontWeight', 'italic', 'fontStyle'], kind: 'node' },
fontVariations: { scene: ['fontVariations'], kind: 'node', absent: [] },
detachOpticalSizeFromFontSize: {
scene: ['opticalSizeFromFontSize'],
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 994b6e46f..f32d928a6 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -368,6 +368,7 @@ type TextProps = Pick<
| 'fontFamily'
| 'fontWeight'
| 'italic'
+ | 'fontStyle'
| 'textAlignHorizontal'
| 'textAlignVertical'
| 'textAutoResize'
@@ -459,6 +460,8 @@ function convertTextProps(nc: NodeChange, blobs: Uint8Array[]): TextProps {
fontFamily: nc.fontName?.family ?? DEFAULT_FONT_FAMILY,
fontWeight: styleToWeight(nc.fontName?.style ?? ''),
italic: nc.fontName?.style.toLowerCase().includes('italic') ?? false,
+ // Figma finds the face by this exact name, which the weight and slant cannot always name.
+ fontStyle: nc.fontName?.style || null,
textAlignHorizontal: (nc.textAlignHorizontal ?? 'LEFT') as
| 'LEFT'
| 'CENTER'
diff --git a/packages/fig/src/node-change/derived-text/build.ts b/packages/fig/src/node-change/derived-text/build.ts
index d9433ca07..ed15c4b44 100644
--- a/packages/fig/src/node-change/derived-text/build.ts
+++ b/packages/fig/src/node-change/derived-text/build.ts
@@ -1,8 +1,8 @@
import { groupBy } from 'es-toolkit/array'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
-import { normalizeFontFamily, weightToStyle } from '@open-pencil/scene-graph/font-style'
+import type { CharacterStyleOverride, DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
+import { normalizeFontFamily, faceLoadKey } from '@open-pencil/scene-graph/font-style'
import {
hasTextList,
lineHeightPixels,
@@ -12,7 +12,7 @@ import {
import { bytesToHex } from '../bytes'
import type { PlacedTextGlyph, TextDecorationRecord } from '../export/runtime'
-import { weightToFigmaStyle } from '../font/style'
+import { figmaStyleName, standardStyleNamer, type StyleNamer } from '../font/style'
import { bakeGlyphScale, encodePathCommandsBlob, type OutlineCommand } from '../path/commands'
import { characterStyleIDs } from '../text/data-export'
import { buildDerivedTextData } from './data'
@@ -54,6 +54,8 @@ export interface DerivedTextBuildContext {
glyphBlobMap: Map<string, number>
shapeText(node: SceneNode): ShapedText | null
textDecorations(node: SceneNode, glyphs: readonly PlacedTextGlyph[]): TextDecorationRecord[]
+ /** The name a family's font gives a face; Google Fonts' names when left out. */
+ fontStyleName?: StyleNamer
}
// Figma stores a whitespace glyph as a lone close command.
@@ -70,31 +72,29 @@ function appendGlyphBlob(context: DerivedTextBuildContext, blob: Uint8Array): nu
function fontMetaData(
node: SceneNode,
- digestMap: Map<string, Uint8Array>
+ digestMap: Map<string, Uint8Array>,
+ nameFace: StyleNamer
): DerivedTextData['fontMetaData'] {
const fonts: NonNullable<DerivedTextData['fontMetaData']> = []
const seen = new Set<string>()
- const addFont = (family: string, weight: number, italic: boolean) => {
- const normalized = normalizeFontFamily(family)
- const key = `${normalized}|${weightToStyle(weight, italic)}`
- if (seen.has(key)) return
- seen.add(key)
+ const addFont = (style: CharacterStyleOverride) => {
+ const normalized = normalizeFontFamily(style.fontFamily ?? node.fontFamily)
+ const weight = style.fontWeight ?? node.fontWeight
+ const italic = style.italic ?? node.italic
+ const name = figmaStyleName(node, style, nameFace)
+ // Two faces at one weight and slant ("Roman", "Book") are fonts of their own.
+ if (seen.has(`${normalized}|${name}`)) return
+ seen.add(`${normalized}|${name}`)
fonts.push({
- key: { family: normalized, style: weightToFigmaStyle(weight, italic), postscript: '' },
+ key: { family: normalized, style: name, postscript: '' },
fontLineHeight: 1.2,
- fontDigest: digestMap.get(key),
+ fontDigest: digestMap.get(`${normalized}|${faceLoadKey(weight, italic)}`),
fontStyle: italic ? 'ITALIC' : 'NORMAL',
fontWeight: weight
})
}
- addFont(node.fontFamily, node.fontWeight, node.italic)
- for (const run of node.styleRuns) {
- addFont(
- run.style.fontFamily ?? node.fontFamily,
- run.style.fontWeight ?? node.fontWeight,
- run.style.italic ?? node.italic
- )
- }
+ addFont({})
+ for (const run of node.styleRuns) addFont(run.style)
return fonts
}
@@ -289,7 +289,7 @@ export function buildNodeDerivedTextData(
node: SceneNode,
context: DerivedTextBuildContext
): NodeChange['derivedTextData'] {
- const fonts = fontMetaData(node, context.digestMap)
+ const fonts = fontMetaData(node, context.digestMap, context.fontStyleName ?? standardStyleNamer)
const saved = node.derivedTextGlyphs ?? []
if (saved.length > 0) {
return buildDerivedTextData({
diff --git a/packages/fig/src/node-change/export/runtime.ts b/packages/fig/src/node-change/export/runtime.ts
index 775f8d35f..4c33b5f4d 100644
--- a/packages/fig/src/node-change/export/runtime.ts
+++ b/packages/fig/src/node-change/export/runtime.ts
@@ -1,6 +1,7 @@
import type { DerivedTextGlyph, SceneNode } from '@open-pencil/scene-graph'
import type { ShapedText } from '../derived-text/build'
+import { standardStyleNamer, type StyleNamer } from '../font/style'
import type { OutlineCommand } from '../path/commands'
/**
@@ -27,9 +28,12 @@ export interface FigNodeChangeExportRuntime {
shapeText(node: SceneNode): ShapedText | null
/** The node's underlines and strikethroughs over these glyphs, as Figma saves them. */
textDecorations(node: SceneNode, glyphs: readonly PlacedTextGlyph[]): TextDecorationRecord[]
+ /** The name a family's font gives its face at a weight and slant, which Figma finds it by. */
+ fontStyleName: StyleNamer
}
export const EMPTY_EXPORT_RUNTIME: FigNodeChangeExportRuntime = {
shapeText: () => null,
- textDecorations: () => []
+ textDecorations: () => [],
+ fontStyleName: standardStyleNamer
}
diff --git a/packages/fig/src/node-change/font/style.ts b/packages/fig/src/node-change/font/style.ts
index 88117f732..fe5a34feb 100644
--- a/packages/fig/src/node-change/font/style.ts
+++ b/packages/fig/src/node-change/font/style.ts
@@ -1,7 +1,42 @@
-import { FONT_WEIGHT_NAMES } from '@open-pencil/scene-graph/font-style'
+import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import { normalizeFontFamily, standardStyleName } from '@open-pencil/scene-graph/font-style'
+import { rangeFontStyle } from '@open-pencil/scene-graph/shared-styles'
-export function weightToFigmaStyle(weight: number, italic = false): string {
- const rounded = Math.round(weight / 100) * 100
- const label = FONT_WEIGHT_NAMES[rounded] ?? 'Regular'
- return italic ? `${label} Italic` : label
+/** The name a family's font gives its face at a weight and slant. */
+export type StyleNamer = (family: string, weight: number, italic: boolean) => string
+
+/** Names a face as Google Fonts does, for a writer that cannot read the fonts. */
+export const standardStyleNamer: StyleNamer = (_family, weight, italic) =>
+ standardStyleName(weight, italic)
+
+/**
+ * Figma's names for faces of a font Figma ships in another version than ours, by family and our
+ * name. Figma finds a face by its exact name, and its Inter is Inter 3, which spaces the names
+ * our Inter 4 joins (measured 2026-10-28).
+ */
+const FIGMA_STYLE_NAMES: Readonly<Record<string, Readonly<Record<string, string>>>> = {
+ Inter: {
+ ExtraLight: 'Extra Light',
+ 'ExtraLight Italic': 'Extra Light Italic',
+ SemiBold: 'Semi Bold',
+ 'SemiBold Italic': 'Semi Bold Italic',
+ ExtraBold: 'Extra Bold',
+ 'ExtraBold Italic': 'Extra Bold Italic'
+ }
+}
+
+/**
+ * The face name characters with `style` over the text are saved under, which Figma finds their
+ * font's face by: the name they were given, else the font's own for their weight and slant.
+ */
+export function figmaStyleName(
+ node: SceneNode,
+ style: CharacterStyleOverride,
+ nameFace: StyleNamer
+): string {
+ const family = style.fontFamily ?? node.fontFamily
+ const own = rangeFontStyle(node, style)
+ const name =
+ own ?? nameFace(family, style.fontWeight ?? node.fontWeight, style.italic ?? node.italic)
+ return FIGMA_STYLE_NAMES[normalizeFontFamily(family)]?.[name] ?? name
}
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index 2bd9dcaf5..cd8c65937 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -24,7 +24,7 @@ import {
} from './export/node'
import { EMPTY_EXPORT_RUNTIME, type FigNodeChangeExportRuntime } from './export/runtime'
import { applyFontFeaturesToKiwi } from './font/features'
-import { weightToFigmaStyle } from './font/style'
+import { figmaStyleName } from './font/style'
import { fillToKiwiPaint, safeColor } from './paint'
import { exportTextData, fontVariationToKiwi } from './text/data-export'
import { figmaLetterSpacing, figmaLineHeight } from './text/values'
@@ -94,10 +94,10 @@ function serializeTextProps(
nc.fontSize = node.fontSize
nc.fontName = {
family: normalizeFontFamily(node.fontFamily),
- style: weightToFigmaStyle(node.fontWeight, node.italic),
+ style: figmaStyleName(node, {}, runtime.fontStyleName),
postscript: ''
}
- nc.textData = exportTextData(node, fillToKiwiPaint)
+ nc.textData = exportTextData(node, fillToKiwiPaint, runtime.fontStyleName)
if (node.fontVariations.length > 0) {
nc.fontVariations = node.fontVariations.map(fontVariationToKiwi)
}
@@ -129,7 +129,8 @@ function serializeTextProps(
blobs,
glyphBlobMap: glyphBlobMap ?? new Map(),
shapeText: (textNode) => runtime.shapeText(textNode),
- textDecorations: (textNode, glyphs) => runtime.textDecorations(textNode, glyphs)
+ textDecorations: (textNode, glyphs) => runtime.textDecorations(textNode, glyphs),
+ fontStyleName: runtime.fontStyleName
})
}
if (node.leadingTrim !== 'NONE') nc.leadingTrim = node.leadingTrim
diff --git a/packages/fig/src/node-change/style/runs.ts b/packages/fig/src/node-change/style/runs.ts
index 896e5476f..a129e0bf2 100644
--- a/packages/fig/src/node-change/style/runs.ts
+++ b/packages/fig/src/node-change/style/runs.ts
@@ -77,6 +77,7 @@ function convertStyleOverride(override: NodeChange, text: NodeChange): Character
style.fontFamily = override.fontName.family
style.fontWeight = styleToWeight(override.fontName.style)
style.italic = override.fontName.style.toLowerCase().includes('italic')
+ style.fontStyle = override.fontName.style || null
}
if (override.fontSize !== undefined) style.fontSize = override.fontSize
const fontVariations = convertFontVariations(override)
diff --git a/packages/fig/src/node-change/text/data-export.ts b/packages/fig/src/node-change/text/data-export.ts
index 54b5e5a24..b171aec10 100644
--- a/packages/fig/src/node-change/text/data-export.ts
+++ b/packages/fig/src/node-change/text/data-export.ts
@@ -3,7 +3,7 @@ import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph
import { normalizeFontFamily } from '@open-pencil/scene-graph/font-style'
import { applyFontFeaturesToKiwi } from '../font/features'
-import { weightToFigmaStyle } from '../font/style'
+import { figmaStyleName, standardStyleNamer, type StyleNamer } from '../font/style'
import { stringToFigmaAxisTag } from '../font/variations'
import { exportTextLines } from './lines'
import { figmaLetterSpacing, figmaLineHeight } from './values'
@@ -39,14 +39,13 @@ function textStyleOverrideToKiwi(
id: number,
style: CharacterStyleOverride,
node: SceneNode,
- fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint
+ fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint,
+ nameFace: StyleNamer
): NodeChange {
const override: Record<string, unknown> = { styleID: id }
- const weight = style.fontWeight ?? node.fontWeight
- const italic = style.italic ?? node.italic
override.fontName = {
family: normalizeFontFamily(style.fontFamily ?? node.fontFamily),
- style: weightToFigmaStyle(weight, italic),
+ style: figmaStyleName(node, style, nameFace),
postscript: ''
}
if (style.fontSize !== undefined) override.fontSize = style.fontSize
@@ -107,11 +106,12 @@ export function characterStyleIDs(node: SceneNode): number[] {
export function exportTextData(
node: SceneNode,
- fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint
+ fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint,
+ nameFace: StyleNamer = standardStyleNamer
): NodeChange['textData'] {
const { charIds, styleMap } = collectTextStyleOverrides(node)
const characterOverrides = [...styleMap.values()].map(({ id, style }) =>
- textStyleOverrideToKiwi(id, style, node, fillToKiwiPaint)
+ textStyleOverrideToKiwi(id, style, node, fillToKiwiPaint, nameFace)
)
// Paragraph spacing shares the override table, numbered after the character styles.
const paragraphs = exportTextLines(node, styleMap.size + 1)
diff --git a/packages/fig/src/source-metadata.ts b/packages/fig/src/source-metadata.ts
index 1bef78205..5b11cd6a6 100644
--- a/packages/fig/src/source-metadata.ts
+++ b/packages/fig/src/source-metadata.ts
@@ -61,6 +61,7 @@ const EDITED_RAW_FIELDS: Partial<Record<string, readonly string[]>> = {
fontFamily: ['fontName', 'fontVersion', ...TEXT_DERIVED_RAW_FIELDS],
fontWeight: ['semanticWeight', ...TEXT_DERIVED_RAW_FIELDS],
italic: ['semanticItalic', ...TEXT_DERIVED_RAW_FIELDS],
+ fontStyle: ['fontName', 'fontVersion', ...TEXT_DERIVED_RAW_FIELDS],
textAlignHorizontal: ['textAlignHorizontal', ...TEXT_DERIVED_RAW_FIELDS],
textAlignVertical: ['textAlignVertical', ...TEXT_DERIVED_RAW_FIELDS],
lineHeight: ['lineHeight', ...TEXT_DERIVED_RAW_FIELDS],
diff --git a/packages/fig/tests/node-change/export.test.ts b/packages/fig/tests/node-change/export.test.ts
index 43ef7fbac..a1c92f1ff 100644
--- a/packages/fig/tests/node-change/export.test.ts
+++ b/packages/fig/tests/node-change/export.test.ts
@@ -5,6 +5,7 @@ import { componentPropDefsOf, componentPropRefsOf } from '#fig-tests/helpers/com
import { symbolDataOf } from '#fig/instance-overrides/types'
import {
buildComponentPropIndex,
+ EMPTY_EXPORT_RUNTIME,
mapToFigmaType,
sceneNodeToKiwi,
type FigNodeChangeExportRuntime
@@ -256,7 +257,7 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
})
const blobs: Uint8Array[] = []
const runtime: FigNodeChangeExportRuntime = {
- textDecorations: () => [],
+ ...EMPTY_EXPORT_RUNTIME,
shapeText: () => ({
glyphs: [
{
diff --git a/packages/fig/tests/node-change/font-features.test.ts b/packages/fig/tests/node-change/font/features.test.ts
similarity index 100%
rename from packages/fig/tests/node-change/font-features.test.ts
rename to packages/fig/tests/node-change/font/features.test.ts
diff --git a/packages/fig/tests/node-change/font/style.test.ts b/packages/fig/tests/node-change/font/style.test.ts
new file mode 100644
index 000000000..40bb1f8d4
--- /dev/null
+++ b/packages/fig/tests/node-change/font/style.test.ts
@@ -0,0 +1,93 @@
+import { expect, test } from 'bun:test'
+
+import {
+ EMPTY_EXPORT_RUNTIME,
+ nodeChangeToProps,
+ sceneNodeToKiwi
+} from '@open-pencil/fig/node-change'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+function write(fields: Partial<SceneNode>, runtime = EMPTY_EXPORT_RUNTIME): NodeChange {
+ const graph = new SceneGraph()
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, { text: 'Faces', ...fields })
+ return sceneNodeToKiwi(node, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [], {
+ runtime,
+ fontDigestMap: new Map()
+ })[0]
+}
+
+test('keeps the name a file gives a face, which its weight and slant cannot always name', () => {
+ // Measured in Figma desktop: a face is found by its exact name, as its font gives it.
+ for (const [family, style] of [
+ ['Roboto', 'SemiBold'],
+ ['Avenir', 'Book'],
+ ['Roboto', 'Condensed Bold'],
+ ['SF Pro', 'Regular Italic']
+ ] as const) {
+ const props = nodeChangeToProps(
+ { type: 'TEXT', fontName: { family, style, postscript: '' } } as NodeChange,
+ []
+ )
+ expect(props.fontStyle).toBe(style)
+ expect(write(props).fontName?.style).toBe(style)
+ }
+})
+
+test('keeps the names a file gives its ranges', () => {
+ const props = nodeChangeToProps(
+ {
+ type: 'TEXT',
+ fontName: { family: 'Avenir', style: 'Roman', postscript: '' },
+ textData: {
+ characters: 'Roman Book',
+ characterStyleIDs: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
+ styleOverrideTable: [
+ { styleID: 1, fontName: { family: 'Avenir', style: 'Book', postscript: '' } }
+ ]
+ }
+ } as NodeChange,
+ []
+ )
+ expect(props.styleRuns).toMatchObject([{ start: 6, length: 4, style: { fontStyle: 'Book' } }])
+ const written = write(props)
+ expect(written.fontName?.style).toBe('Roman')
+ expect(written.textData?.styleOverrideTable?.[0]?.fontName?.style).toBe('Book')
+ expect(written.derivedTextData?.fontMetaData?.map((meta) => meta.key?.style)).toEqual([
+ 'Roman',
+ 'Book'
+ ])
+})
+
+test('names a face without a name as the font does, and as Google Fonts does without one', () => {
+ expect(write({ fontFamily: 'Roboto', fontWeight: 600 }).fontName?.style).toBe('SemiBold')
+ expect(write({ fontFamily: 'Roboto', italic: true }).fontName?.style).toBe('Italic')
+ expect(write({ fontFamily: 'Roboto', fontWeight: 700, italic: true }).fontName?.style).toBe(
+ 'Bold Italic'
+ )
+ const avenir = { ...EMPTY_EXPORT_RUNTIME, fontStyleName: () => 'Book' }
+ expect(write({ fontFamily: 'Avenir', fontWeight: 350 }, avenir).fontName?.style).toBe('Book')
+})
+
+test('writes Inter under the names of the Inter Figma ships', () => {
+ // Figma's Inter 3 spaces the names our Inter 4 joins; Figma finds neither spelling by the other.
+ expect(write({ fontFamily: 'Inter', fontWeight: 600 }).fontName?.style).toBe('Semi Bold')
+ expect(write({ fontFamily: 'Inter', fontWeight: 800, italic: true }).fontName?.style).toBe(
+ 'Extra Bold Italic'
+ )
+ expect(write({ fontFamily: 'Inter', fontStyle: 'SemiBold' }).fontName?.style).toBe('Semi Bold')
+ expect(write({ fontFamily: 'Inter', italic: true }).fontName?.style).toBe('Italic')
+ expect(write({ fontFamily: 'Inter', fontWeight: 700 }).fontName?.style).toBe('Bold')
+})
+
+test('names a range that sets another face without a name by that face, not the text’s name', () => {
+ // As HTML or `.pen` import a bold span: a weight and no name.
+ const written = write({
+ fontFamily: 'Avenir',
+ fontStyle: 'Book',
+ text: 'Book Bold',
+ styleRuns: [{ start: 5, length: 4, style: { fontWeight: 700 } }]
+ })
+ expect(written.fontName?.style).toBe('Book')
+ expect(written.textData?.styleOverrideTable?.[0]?.fontName?.style).toBe('Bold')
+})
diff --git a/packages/fig/tests/node-change/font-variations.test.ts b/packages/fig/tests/node-change/font/variations.test.ts
similarity index 100%
rename from packages/fig/tests/node-change/font-variations.test.ts
rename to packages/fig/tests/node-change/font/variations.test.ts
diff --git a/packages/scene-graph/src/font-style.ts b/packages/scene-graph/src/font-style.ts
index ad46ca0ed..87202fa4d 100644
--- a/packages/scene-graph/src/font-style.ts
+++ b/packages/scene-graph/src/font-style.ts
@@ -8,15 +8,19 @@ export interface ParsedFontStyle {
italic: boolean
}
+/**
+ * The standard weights by the names Google Fonts gives them, which most fonts and Figma's font
+ * list use; a font's own names can differ ("Semi Bold", "Book", "Heavy").
+ */
export const FONT_WEIGHT_NAMES: Record<number, string> = {
100: 'Thin',
- 200: 'Extra Light',
+ 200: 'ExtraLight',
300: 'Light',
400: 'Regular',
500: 'Medium',
- 600: 'Semi Bold',
+ 600: 'SemiBold',
700: 'Bold',
- 800: 'Extra Bold',
+ 800: 'ExtraBold',
900: 'Black'
}
@@ -36,7 +40,7 @@ const FONT_WEIGHT_BY_STYLE: ReadonlyMap<string, number> = new Map(
FONT_WEIGHT_ALIASES.flatMap(({ names, weight }) => names.map((name) => [name, weight] as const))
)
-export function normalizeFontStyleName(style: string): string {
+function normalizeFontStyleName(style: string): string {
return style
.toLowerCase()
.replace(/italic|oblique/u, '')
@@ -62,16 +66,18 @@ export function normalizeFontFamily(family: string): string {
return family.replace(/\s+(Variable|\d+(?:pt|px|em))$/i, '')
}
-export function styleToVariant(style: string): string {
- const weight = styleToWeight(style)
- const italic = style.toLowerCase().includes('italic')
- if (weight === 400 && !italic) return 'regular'
- if (weight === 400 && italic) return 'italic'
- return italic ? `${weight}italic` : `${weight}`
-}
-
-export function weightToStyle(weight: number, italic = false): string {
+export function faceLoadKey(weight: number, italic = false): string {
const rounded = Math.round(weight / 100) * 100
- const label = (FONT_WEIGHT_NAMES[rounded] ?? 'Regular').replace(/ /g, '')
+ const label = FONT_WEIGHT_NAMES[rounded] ?? 'Regular'
return italic ? `${label} Italic` : label
}
+
+/**
+ * The name Google Fonts gives the face at `weight` and slant ("SemiBold Italic", and "Italic"
+ * for the regular weight), for a face whose font has not said its own.
+ */
+export function standardStyleName(weight: number, italic = false): string {
+ const label = FONT_WEIGHT_NAMES[Math.round(weight / 100) * 100] ?? 'Regular'
+ if (!italic) return label
+ return label === 'Regular' ? 'Italic' : `${label} Italic`
+}
diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.ts
index 57b4b659d..ce700a65b 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -98,6 +98,7 @@ export function createDefaultNode(
fontFamily: DEFAULT_FONT_FAMILY,
fontWeight: 400,
italic: false,
+ fontStyle: null,
textAlignHorizontal: 'LEFT',
textDirection: 'AUTO',
textLanguage: null,
diff --git a/packages/scene-graph/src/shared-styles.ts b/packages/scene-graph/src/shared-styles.ts
index 7768445fe..b9f4980d7 100644
--- a/packages/scene-graph/src/shared-styles.ts
+++ b/packages/scene-graph/src/shared-styles.ts
@@ -1,5 +1,11 @@
import type { SceneGraph } from './graph'
-import type { SceneNode, SharedStyle, SharedStyleKind, SharedStyleType } from './types'
+import type {
+ CharacterStyleOverride,
+ SceneNode,
+ SharedStyle,
+ SharedStyleKind,
+ SharedStyleType
+} from './types'
const STYLE_REF_KEYS = {
fill: 'fillStyleId',
@@ -25,6 +31,7 @@ export const SHARED_TEXT_STYLE_FIELDS = [
'fontFamily',
'fontWeight',
'italic',
+ 'fontStyle',
'fontSize',
'lineHeight',
'letterSpacing',
@@ -35,6 +42,25 @@ export const SHARED_TEXT_STYLE_FIELDS = [
const TEXT_STYLE_KEYS = new Set<keyof SceneNode>(SHARED_TEXT_STYLE_FIELDS)
+/** The fields that pick a text's face, which its style name names. */
+export const FACE_KEYS = [
+ 'fontFamily',
+ 'fontWeight',
+ 'italic'
+] as const satisfies readonly (keyof SceneNode)[]
+
+/**
+ * The face name of characters with `style` over the text: their own, none where they set another
+ * face without one (as ranges from HTML or `.pen` do), else the text's.
+ */
+export function rangeFontStyle(
+ node: Pick<SceneNode, 'fontStyle'>,
+ style: CharacterStyleOverride
+): string | null {
+ if (style.fontStyle !== undefined) return style.fontStyle
+ return FACE_KEYS.some((key) => style[key] !== undefined) ? null : node.fontStyle
+}
+
export function sharedStyleRefKey(kind: SharedStyleKind): (typeof STYLE_REF_KEYS)[SharedStyleKind] {
return STYLE_REF_KEYS[kind]
}
@@ -70,6 +96,11 @@ export function styleDetachmentChanges(
if ('layoutGrids' in changes && !('gridStyleId' in changes) && node.gridStyleId) {
next.gridStyleId = null
}
+ // A face named for another family, weight, or slant names none; the new one takes its own name.
+ const changesFace = FACE_KEYS.some((key) => key in changes && changes[key] !== node[key])
+ if (changesFace && !('fontStyle' in changes) && node.fontStyle) {
+ next.fontStyle = null
+ }
const changesTextStyle = (Object.keys(changes) as (keyof SceneNode)[]).some((key) =>
TEXT_STYLE_KEYS.has(key)
)
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index a63f73d4c..f278a80c8 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -366,6 +366,8 @@ export interface TextLength {
export interface CharacterStyleOverride {
fontWeight?: number
italic?: boolean
+ /** The characters' face by its font's own name for it; `null` is the face their weight picks. */
+ fontStyle?: string | null
textDecoration?: TextDecoration
textDecorationStyle?: TextDecorationStyle
textDecorationThickness?: number | null
@@ -649,6 +651,11 @@ export interface SceneNode {
fontFamily: string
fontWeight: number
italic: boolean
+ /**
+ * The face by the name its font gives it ("Semi Bold", "Book", "Condensed Bold"), which Figma
+ * finds a font's face by; `null` is the face the weight and slant pick in the family.
+ */
+ fontStyle: string | null
textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'
textDirection: TextDirection
textLanguage: string | null
diff --git a/packages/scene-graph/tests/font-style.test.ts b/packages/scene-graph/tests/font-style.test.ts
new file mode 100644
index 000000000..c619b4049
--- /dev/null
+++ b/packages/scene-graph/tests/font-style.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ faceLoadKey,
+ normalizeFontFamily,
+ standardStyleName,
+ styleToWeight
+} from '@open-pencil/scene-graph/font-style'
+
+describe('styleToWeight', () => {
+ test('maps common style names', () => {
+ expect(styleToWeight('Regular')).toBe(400)
+ expect(styleToWeight('Bold')).toBe(700)
+ expect(styleToWeight('Light')).toBe(300)
+ expect(styleToWeight('Thin')).toBe(100)
+ expect(styleToWeight('Medium')).toBe(500)
+ expect(styleToWeight('SemiBold')).toBe(600)
+ expect(styleToWeight('Semi Bold')).toBe(600)
+ expect(styleToWeight('DemiBold')).toBe(600)
+ expect(styleToWeight('ExtraBold')).toBe(800)
+ expect(styleToWeight('Black')).toBe(900)
+ })
+
+ test('handles italic variants', () => {
+ expect(styleToWeight('Bold Italic')).toBe(700)
+ expect(styleToWeight('Light Italic')).toBe(300)
+ expect(styleToWeight('600 Italic')).toBe(600)
+ })
+
+ test('case insensitive', () => {
+ expect(styleToWeight('bold')).toBe(700)
+ expect(styleToWeight('THIN')).toBe(100)
+ expect(styleToWeight('semibold')).toBe(600)
+ })
+})
+
+describe('faceLoadKey', () => {
+ test('maps weights to style names', () => {
+ expect(faceLoadKey(100)).toBe('Thin')
+ expect(faceLoadKey(200)).toBe('ExtraLight')
+ expect(faceLoadKey(300)).toBe('Light')
+ expect(faceLoadKey(400)).toBe('Regular')
+ expect(faceLoadKey(500)).toBe('Medium')
+ expect(faceLoadKey(600)).toBe('SemiBold')
+ expect(faceLoadKey(700)).toBe('Bold')
+ expect(faceLoadKey(800)).toBe('ExtraBold')
+ expect(faceLoadKey(900)).toBe('Black')
+ })
+
+ test('appends Italic suffix', () => {
+ expect(faceLoadKey(400, true)).toBe('Regular Italic')
+ expect(faceLoadKey(700, true)).toBe('Bold Italic')
+ })
+})
+
+describe('standardStyleName', () => {
+ test('names faces as Google Fonts does, and the regular italic "Italic"', () => {
+ expect(standardStyleName(200)).toBe('ExtraLight')
+ expect(standardStyleName(600)).toBe('SemiBold')
+ expect(standardStyleName(600, true)).toBe('SemiBold Italic')
+ expect(standardStyleName(400, true)).toBe('Italic')
+ expect(standardStyleName(450)).toBe('Medium')
+ })
+})
+
+describe('normalizeFontFamily', () => {
+ test('strips " Variable" suffix', () => {
+ expect(normalizeFontFamily('Inter Variable')).toBe('Inter')
+ expect(normalizeFontFamily('Roboto Flex Variable')).toBe('Roboto Flex')
+ })
+
+ test('case insensitive', () => {
+ expect(normalizeFontFamily('Inter VARIABLE')).toBe('Inter')
+ expect(normalizeFontFamily('Inter variable')).toBe('Inter')
+ })
+
+ test('handles extra whitespace before Variable', () => {
+ expect(normalizeFontFamily('Inter Variable')).toBe('Inter')
+ })
+
+ test('returns unchanged when no Variable suffix', () => {
+ expect(normalizeFontFamily('Inter')).toBe('Inter')
+ expect(normalizeFontFamily('Roboto')).toBe('Roboto')
+ expect(normalizeFontFamily('')).toBe('')
+ })
+
+ test('does not strip Variable in the middle', () => {
+ expect(normalizeFontFamily('Variable Sans')).toBe('Variable Sans')
+ })
+
+ test('strips optical size suffix (pt)', () => {
+ expect(normalizeFontFamily('DM Sans 9pt')).toBe('DM Sans')
+ expect(normalizeFontFamily('DM Sans 14pt')).toBe('DM Sans')
+ })
+
+ test('strips optical size suffix (px)', () => {
+ expect(normalizeFontFamily('Noto Sans 12px')).toBe('Noto Sans')
+ })
+
+ test('strips optical size suffix (em)', () => {
+ expect(normalizeFontFamily('Custom Font 1em')).toBe('Custom Font')
+ })
+
+ test('does not strip size units in the middle', () => {
+ expect(normalizeFontFamily('12pt Serif')).toBe('12pt Serif')
+ })
+})
diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.ts
index 11998494c..ee1f9aad3 100644
--- a/packages/vue/src/controls/typography/actions.ts
+++ b/packages/vue/src/controls/typography/actions.ts
@@ -9,7 +9,7 @@ import type {
TextListType,
TextParagraphSpacingField
} from '@open-pencil/scene-graph'
-import { FONT_WEIGHT_NAMES, weightToStyle } from '@open-pencil/scene-graph/font-style'
+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'
import { shapeWithTextLabel } from '@open-pencil/scene-graph/generated'
import {
@@ -71,11 +71,9 @@ export function createTypographyState(editor: Editor) {
const fontFamily = computed(() => node.value?.fontFamily ?? '')
const fontWeight = computed(() => node.value?.fontWeight ?? 400)
const fontSize = computed(() => node.value?.fontSize ?? 16)
- const currentWeightLabel = computed(
- () => FONT_WEIGHT_NAMES[node.value?.fontWeight ?? 400] ?? 'Regular'
- )
+ const { weights, supports, styleName } = useFamilyFaces(nodes)
+ const currentWeightLabel = computed(() => (node.value ? styleName(node.value) : 'Regular'))
const activeFormatting = computed(() => sharedFormatting(nodes.value))
- const { weights, supports } = useFamilyFaces(nodes)
/**
* The list style every selected text shares, or that of the paragraphs being edited; `null`
* when they differ.
@@ -207,11 +205,13 @@ export function createTypographyActions({
'Change font',
['fontFamily', 'fontWeight', 'italic'],
async (target) => {
- const known = await faces
+ await faces
+ // Asked again, so faces forgotten while loading (a catalog arriving) are read anew.
+ const known = await fontManager.familyFaces(family)
const face = known ? nearestFamilyFace(known, target.fontWeight, target.italic) : null
const fontWeight = face?.weight ?? target.fontWeight
const italic = face?.italic ?? target.italic
- await options.fontLoader?.load(family, weightToStyle(fontWeight, italic))
+ await options.fontLoader?.load(family, faceLoadKey(fontWeight, italic))
return {
fontFamily: family,
fontWeight,
@@ -228,7 +228,7 @@ export function createTypographyActions({
'Change font weight',
['fontWeight'],
async (target) => {
- await options.fontLoader?.load(target.fontFamily, weightToStyle(weight, target.italic))
+ await options.fontLoader?.load(target.fontFamily, faceLoadKey(weight, target.italic))
return { fontWeight: weight, fontVariations: styleFontVariations(target) }
},
targets
@@ -348,7 +348,7 @@ export function createTypographyActions({
'Toggle italic',
['italic'],
async (target) => {
- await options.fontLoader?.load(target.fontFamily, weightToStyle(target.fontWeight, italic))
+ await options.fontLoader?.load(target.fontFamily, faceLoadKey(target.fontWeight, italic))
return { italic, fontVariations: styleFontVariations(target) }
},
nodes.value.filter((target) => supports(target, target.fontWeight, italic))
diff --git a/packages/vue/src/controls/typography/faces.ts b/packages/vue/src/controls/typography/faces.ts
index 6009497ec..8fb8c98ef 100644
--- a/packages/vue/src/controls/typography/faces.ts
+++ b/packages/vue/src/controls/typography/faces.ts
@@ -1,7 +1,7 @@
import { uniq } from 'es-toolkit'
import { computed, onScopeDispose, ref, watch, type ComputedRef } from 'vue'
-import { fontManager } from '@open-pencil/core/text'
+import { faceStyleName, fontManager, textStyleName } from '@open-pencil/core/text'
import type { SceneNode } from '@open-pencil/scene-graph'
import { TYPOGRAPHY_WEIGHTS } from '#vue/controls/typography/weights'
@@ -38,15 +38,33 @@ export function useFamilyFaces(nodes: ComputedRef<SceneNode[]>) {
/**
* The weights every selected layer's family has at that layer's slant, and the weights the
- * layers already use, so the field still names one their family lacks.
+ * layers already use, so the field still names one their family lacks. Each is named as the
+ * first layer's font names that face, as Figma's style menu lists a family's own names.
*/
- const weights = computed(() =>
- TYPOGRAPHY_WEIGHTS.filter(
+ const weights = computed(() => {
+ void arrived.value
+ const first = nodes.value.at(0)
+ return TYPOGRAPHY_WEIGHTS.filter(
({ value }) =>
nodes.value.some((node) => node.fontWeight === value) ||
nodes.value.every((node) => supports(node, value, node.italic))
- )
- )
+ ).map(({ value, label }) => ({
+ value,
+ label: first ? weightName(first, value) : label
+ }))
+ })
+
+ /** A weight's name in a layer's family; its own weight keeps the name the layer has for it. */
+ function weightName(node: SceneNode, weight: number): string {
+ if (weight === node.fontWeight) return textStyleName(node)
+ return faceStyleName(node.fontFamily, weight, node.italic)
+ }
+
+ /** The name of the face a layer is set in, as its font names it once its faces arrive. */
+ function styleName(node: SceneNode): string {
+ void arrived.value
+ return textStyleName(node)
+ }
- return { weights, supports }
+ return { weights, supports, styleName }
}
diff --git a/packages/vue/tests/controls/typography.test.ts b/packages/vue/tests/controls/typography.test.ts
index 08e8c2b97..5d64c11bc 100644
--- a/packages/vue/tests/controls/typography.test.ts
+++ b/packages/vue/tests/controls/typography.test.ts
@@ -117,7 +117,9 @@ test('a family chosen while loading skips layers deleted in the meantime', async
})
/** Text layers in Inter at these styles, with typography actions and face lists over them. */
-function styled(...faces: { fontWeight: number; italic?: boolean; fontFamily?: string }[]) {
+function styled(
+ ...faces: { fontWeight: number; italic?: boolean; fontFamily?: string; fontStyle?: string }[]
+) {
const editor = createEditor()
const page = editor.state.currentPageId
const texts = faces.map((face) =>
@@ -161,6 +163,15 @@ test('the weight list offers only the weights the family has', async () => {
expect(weights.value.map((weight) => weight.value)).toEqual([200, 300, 400, 500, 600, 700])
})
+test('the weight list names faces as the family does, and the text’s own weight as the text does', async () => {
+ const { weights } = styled({ fontWeight: 600, fontStyle: 'Semi Bold' })
+ await fontManager.familyFaces('Inter')
+ await nextTick()
+ const label = (value: number) => weights.value.find((weight) => weight.value === value)?.label
+ // A file from Figma spells Inter 3's name; our Inter 4 names its other faces its own way.
+ expect([label(600), label(800), label(200)]).toEqual(['Semi Bold', 'ExtraBold', 'ExtraLight'])
+})
+
test('italic does nothing on a family without italics, and bold goes to Bold', async () => {
const { texts, actions } = styled({ fontWeight: 400, fontFamily: 'Oswald' })
await fontManager.familyFaces('Oswald')
diff --git a/src/components/font-status/FontStatusBanner.vue b/src/components/font-status/FontStatusBanner.vue
index 0cf52631a..bbe4bf16f 100644
--- a/src/components/font-status/FontStatusBanner.vue
+++ b/src/components/font-status/FontStatusBanner.vue
@@ -59,12 +59,12 @@ const issues = computed(() => status.value.issues)
<div v-if="expanded" class="grid gap-1 border-t border-warning-border px-3 py-2">
<div
v-for="issue in issues"
- :key="`${issue.family}:${issue.style}`"
+ :key="`${issue.family}:${issue.name}`"
data-test-id="font-status-issue"
class="flex min-w-0 items-center gap-2"
>
<span class="min-w-0 flex-1 truncate">
- <strong>{{ issue.family }} {{ issue.style }}</strong>
+ <strong>{{ issue.family }} {{ issue.name }}</strong>
<template v-if="issue.substituteFamily"> → {{ issue.substituteFamily }} </template>
<template v-else>— {{ fonts.noSubstitute }}</template>
<Tip v-if="issue.reason === 'unsupported-format'" :label="fonts.unsupportedFormat">
diff --git a/tests/e2e/fonts/browser-provider.spec.ts b/tests/e2e/fonts/browser-provider.spec.ts
index ff67c42e7..c3b8ed0a6 100644
--- a/tests/e2e/fonts/browser-provider.spec.ts
+++ b/tests/e2e/fonts/browser-provider.spec.ts
@@ -1,4 +1,4 @@
-import type { FontManager } from '#core/text/fonts'
+import type { FontManager } from '#core/text/font/manager'
import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
diff --git a/tests/e2e/fonts/cjk-fallback.spec.ts b/tests/e2e/fonts/cjk-fallback.spec.ts
index 2af1135bf..da39692f9 100644
--- a/tests/e2e/fonts/cjk-fallback.spec.ts
+++ b/tests/e2e/fonts/cjk-fallback.spec.ts
@@ -2,7 +2,7 @@ import { test, expect } from '@playwright/test'
import type * as AppFonts from '@/app/editor/fonts'
-import type { FontManager } from '#core/text/fonts'
+import type { FontManager } from '#core/text/font/manager'
import { CanvasHelper } from '#tests/helpers/canvas'
import { trackFontModuleResources } from '#tests/helpers/fonts/runtime'
@@ -26,7 +26,7 @@ test('tool-created CJK text requests fallback through app font loading', async (
const fontModuleURL = performance
.getEntriesByType('resource')
.map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/fonts.ts'))
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
if (!fontModuleURL) throw new Error('Active font manager module not found')
const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
fontManager: FontManager
@@ -88,7 +88,7 @@ test('CJK text waits for fallback fonts and repaints after they load', async ({
const fontModuleURL = performance
.getEntriesByType('resource')
.map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/fonts.ts'))
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
if (!fontModuleURL) throw new Error('Active font manager module not found')
const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
fontManager: FontManager
diff --git a/tests/e2e/fonts/cjk-rendering-visual.spec.ts b/tests/e2e/fonts/cjk-rendering-visual.spec.ts
index fe3e17210..73f3a23dd 100644
--- a/tests/e2e/fonts/cjk-rendering-visual.spec.ts
+++ b/tests/e2e/fonts/cjk-rendering-visual.spec.ts
@@ -2,7 +2,7 @@ import { Buffer } from 'node:buffer'
import type { Page } from '@playwright/test'
-import type { FontManager } from '#core/text/fonts'
+import type { FontManager } from '#core/text/font/manager'
import { expect, test } from '#tests/e2e/fixtures'
import { CanvasHelper } from '#tests/helpers/canvas'
@@ -59,7 +59,7 @@ test('international text is correct on its first visible paint', async ({ page }
const fontModuleURL = performance
.getEntriesByType('resource')
.map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/fonts.ts'))
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
if (!fontModuleURL) throw new Error('Active font manager module not found')
const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
fontManager: FontManager
@@ -258,7 +258,7 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asy
const fontModuleURL = performance
.getEntriesByType('resource')
.map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/fonts.ts'))
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
if (!fontModuleURL) throw new Error('Active font manager module not found')
const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
fontManager: FontManager
@@ -290,7 +290,7 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asy
const fontModuleURL = performance
.getEntriesByType('resource')
.map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/fonts.ts'))
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
if (!fontModuleURL) throw new Error('Active font manager module not found')
const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
fontManager: FontManager
@@ -306,7 +306,7 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asy
const fontModuleURL = performance
.getEntriesByType('resource')
.map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/fonts.ts'))
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
if (!fontModuleURL) throw new Error('Active font manager module not found')
const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
fontManager: FontManager
@@ -371,7 +371,7 @@ test('substituted fonts still request fallbacks for CJK text', async ({ page })
const fontModuleURL = performance
.getEntriesByType('resource')
.map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/fonts.ts'))
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
if (!fontModuleURL) throw new Error('Active font manager module not found')
const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
fontManager: FontManager
diff --git a/tests/e2e/fonts/variable-weights-visual.spec.ts b/tests/e2e/fonts/variable-weights-visual.spec.ts
index a7f414c11..ce020a879 100644
--- a/tests/e2e/fonts/variable-weights-visual.spec.ts
+++ b/tests/e2e/fonts/variable-weights-visual.spec.ts
@@ -4,7 +4,7 @@ import type { Page } from '@playwright/test'
import type { SceneNode } from '@open-pencil/scene-graph'
-import type { FontManager } from '#core/text/fonts'
+import type { FontManager } from '#core/text/font/manager'
import { expect, test } from '#tests/e2e/fixtures'
import { CanvasHelper } from '#tests/helpers/canvas'
@@ -30,7 +30,7 @@ async function exportLines(page: Page, lines: Array<Partial<SceneNode> & { text:
const fontModuleURL = performance
.getEntriesByType('resource')
.map((entry) => entry.name)
- .find((url) => url.includes('/packages/core/src/text/fonts.ts'))
+ .find((url) => url.includes('/packages/core/src/text/font/manager.ts'))
if (!fontModuleURL) throw new Error('Active font manager module not found')
const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {
fontManager: FontManager
diff --git a/tests/engine/core/editor/text/path-edit.test.ts b/tests/engine/core/editor/text/path-edit.test.ts
index c06fb607e..a095bdc5a 100644
--- a/tests/engine/core/editor/text/path-edit.test.ts
+++ b/tests/engine/core/editor/text/path-edit.test.ts
@@ -5,7 +5,7 @@ import { pixelLength } from '@open-pencil/scene-graph/text'
import { pathTextEditChanges, resizedPathTextGlyphs } from '#core/editor/text/path-edit'
import { getGlyphOutlineMetricsSync } from '#core/text/font/glyphs'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { nearestArcPoint, pointAtArc, sampleTextPath, textPathStartArc } from '#core/text/path'
import { expectDefined } from '#tests/helpers/assert'
diff --git a/tests/engine/core/editor/text/start-editing-gate.test.ts b/tests/engine/core/editor/text/start-editing-gate.test.ts
index 7377c03a4..775f55801 100644
--- a/tests/engine/core/editor/text/start-editing-gate.test.ts
+++ b/tests/engine/core/editor/text/start-editing-gate.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
/**
* Path text can only be edited when the font's glyph OUTLINES are available to
diff --git a/tests/engine/render/canvas/font-readiness.test.ts b/tests/engine/render/canvas/font-readiness.test.ts
index e54f57d24..990854032 100644
--- a/tests/engine/render/canvas/font-readiness.test.ts
+++ b/tests/engine/render/canvas/font-readiness.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import { isNodeFontLoaded } from '#core/canvas/text'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
describe('canvas text font readiness', () => {
test('requires the exact requested font weight before rendering text', async () => {
diff --git a/tests/engine/render/canvas/labels/fonts.test.ts b/tests/engine/render/canvas/labels/fonts.test.ts
index 0978a6412..0a972597c 100644
--- a/tests/engine/render/canvas/labels/fonts.test.ts
+++ b/tests/engine/render/canvas/labels/fonts.test.ts
@@ -5,7 +5,7 @@ import { initCanvasKit } from '#cli/headless'
import { LabelParagraphCache } from '#core/canvas/labels/paragraph-cache'
import { resolveLabelFontCoverage } from '#core/canvas/renderer/fonts'
import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { FontResolver, missingGlyphOccurrences } from '#core/text/resolver'
import { expectDefined } from '#tests/helpers/assert'
diff --git a/tests/engine/render/canvas/painted-text.test.ts b/tests/engine/render/canvas/painted-text.test.ts
index 2342f4ef0..b6e6c427f 100644
--- a/tests/engine/render/canvas/painted-text.test.ts
+++ b/tests/engine/render/canvas/painted-text.test.ts
@@ -6,7 +6,7 @@ import { SceneGraph } from '@open-pencil/scene-graph'
import { initCanvasKit } from '#cli/headless'
import { SkiaRenderer } from '#core/canvas/renderer'
import { withTextParagraph, type TextLayout } from '#core/canvas/text'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { expectDefined } from '#tests/helpers/assert'
import { repoPath } from '#tests/helpers/paths'
diff --git a/tests/engine/render/canvas/text/preparation-cache.test.ts b/tests/engine/render/canvas/text/preparation-cache.test.ts
index bc3828126..d1da6c692 100644
--- a/tests/engine/render/canvas/text/preparation-cache.test.ts
+++ b/tests/engine/render/canvas/text/preparation-cache.test.ts
@@ -10,7 +10,7 @@ import { buildParagraph, nodeFontReadiness } from '#core/canvas/text'
import { TextLayout } from '#core/canvas/text/layout'
import type { ParagraphNode } from '#core/canvas/text/paragraph/inputs'
import { TextPreparationCache } from '#core/canvas/text/preparation/cache'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { expectDefined } from '#tests/helpers/assert'
diff --git a/tests/engine/render/canvas/text/render.test.ts b/tests/engine/render/canvas/text/render.test.ts
index 4351312cc..06813b0d3 100644
--- a/tests/engine/render/canvas/text/render.test.ts
+++ b/tests/engine/render/canvas/text/render.test.ts
@@ -19,7 +19,7 @@ import {
} from '#core/canvas/text'
import { createDerivedGlyphPathCache } from '#core/canvas/text/derived'
import { transformTextCase } from '#core/text/case'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { fontFaceDemand, fontResolver, missingGlyphCharacters } from '#core/text/resolver'
import { expectDefined } from '#tests/helpers/assert'
diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.ts
index a64feb90e..d3915bbeb 100644
--- a/tests/engine/text/edit-undo.test.ts
+++ b/tests/engine/text/edit-undo.test.ts
@@ -9,7 +9,7 @@ import { SceneGraph, type StyleRun, type DerivedTextGlyph } from '@open-pencil/s
import { getInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'
import { UndoManager } from '@open-pencil/scene-graph/undo'
-import { fontManager } from '#core/text/fonts'
+import { fontManager } from '#core/text/font/manager'
import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'
diff --git a/tests/engine/text/fonts/loading.test.ts b/tests/engine/text/fonts/loading.test.ts
index a1a137f56..fe5898f4d 100644
--- a/tests/engine/text/fonts/loading.test.ts
+++ b/tests/engine/text/fonts/loading.test.ts
@@ -4,21 +4,8 @@ import { describe, test, expect } from 'bun:test'
import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
-import {
- chooseLocalFontMatch,
- fontWeightMatchOrder,
- fontManager,
- isVariableFont,
- FontManager
-} from '@open-pencil/core/text'
-import { weightToFigmaStyle } from '@open-pencil/fig/node-change'
+import { fontManager, isVariableFont, FontManager } from '@open-pencil/core/text'
import { SceneGraph } from '@open-pencil/scene-graph'
-import {
- normalizeFontFamily,
- styleToVariant,
- styleToWeight,
- weightToStyle
-} from '@open-pencil/scene-graph/font-style'
import { expectDefined } from '#tests/helpers/assert'
import { fetchStub } from '#tests/helpers/fetch'
@@ -27,64 +14,6 @@ function pageId(graph: SceneGraph) {
return graph.getPages()[0].id
}
-describe('styleToWeight', () => {
- test('maps common style names', () => {
- expect(styleToWeight('Regular')).toBe(400)
- expect(styleToWeight('Bold')).toBe(700)
- expect(styleToWeight('Light')).toBe(300)
- expect(styleToWeight('Thin')).toBe(100)
- expect(styleToWeight('Medium')).toBe(500)
- expect(styleToWeight('SemiBold')).toBe(600)
- expect(styleToWeight('Semi Bold')).toBe(600)
- expect(styleToWeight('DemiBold')).toBe(600)
- expect(styleToWeight('ExtraBold')).toBe(800)
- expect(styleToWeight('Black')).toBe(900)
- })
-
- test('handles italic variants', () => {
- expect(styleToWeight('Bold Italic')).toBe(700)
- expect(styleToWeight('Light Italic')).toBe(300)
- expect(styleToWeight('600 Italic')).toBe(600)
- })
-
- test('case insensitive', () => {
- expect(styleToWeight('bold')).toBe(700)
- expect(styleToWeight('THIN')).toBe(100)
- expect(styleToWeight('semibold')).toBe(600)
- })
-})
-
-describe('weightToStyle', () => {
- test('maps weights to style names', () => {
- expect(weightToStyle(100)).toBe('Thin')
- expect(weightToStyle(200)).toBe('ExtraLight')
- expect(weightToStyle(300)).toBe('Light')
- expect(weightToStyle(400)).toBe('Regular')
- expect(weightToStyle(500)).toBe('Medium')
- expect(weightToStyle(600)).toBe('SemiBold')
- expect(weightToStyle(700)).toBe('Bold')
- expect(weightToStyle(800)).toBe('ExtraBold')
- expect(weightToStyle(900)).toBe('Black')
- })
-
- test('appends Italic suffix', () => {
- expect(weightToStyle(400, true)).toBe('Regular Italic')
- expect(weightToStyle(700, true)).toBe('Bold Italic')
- })
-})
-
-describe('weightToFigmaStyle', () => {
- test('preserves Figma weight name spacing', () => {
- expect(weightToFigmaStyle(200)).toBe('Extra Light')
- expect(weightToFigmaStyle(600)).toBe('Semi Bold')
- expect(weightToFigmaStyle(800)).toBe('Extra Bold')
- })
-
- test('appends Italic suffix', () => {
- expect(weightToFigmaStyle(600, true)).toBe('Semi Bold Italic')
- })
-})
-
function createRecordingProvider() {
const registrations: Array<{ family: string; byteLength: number }> = []
const provider = {
@@ -95,44 +24,6 @@ function createRecordingProvider() {
return { provider, registrations }
}
-describe('chooseLocalFontMatch', () => {
- const fonts = [
- { family: 'Inter', style: 'Italic' },
- { family: 'Inter', style: 'Regular' },
- { family: 'Inter', style: 'Semi Bold' },
- { family: 'Inter', style: 'Bold Italic' }
- ]
-
- test('prefers parsed weight and slant over first family match', () => {
- expect(chooseLocalFontMatch(fonts, 'Inter', 'SemiBold')?.style).toBe('Semi Bold')
- expect(chooseLocalFontMatch(fonts, 'Inter', 'Regular')?.style).toBe('Regular')
- })
-
- test('does not substitute nearby weights for explicit style requests', () => {
- expect(chooseLocalFontMatch(fonts, 'Inter', 'Bold')).toBeUndefined()
- })
-
- test('without a style, takes the face CSS font matching picks for regular', () => {
- const faces = [
- { family: 'Inter', style: 'Black' },
- { family: 'Inter', style: 'Light Italic' },
- { family: 'Inter', style: 'Medium' },
- { family: 'Inter', style: 'Light' }
- ]
- // Regular falls to medium before lighter weights, and the upright slant before italic.
- expect(chooseLocalFontMatch(faces, 'Inter')?.style).toBe('Medium')
- expect(chooseLocalFontMatch(faces.slice(0, 2), 'Inter')?.style).toBe('Black')
- })
-})
-
-describe('fontWeightMatchOrder', () => {
- test('tries weights in CSS font matching order', () => {
- expect(fontWeightMatchOrder(400)).toEqual([400, 500, 300, 200, 100, 600, 700, 800, 900])
- expect(fontWeightMatchOrder(700)).toEqual([700, 800, 900, 600, 500, 400, 300, 200, 100])
- expect(fontWeightMatchOrder(300)).toEqual([300, 200, 100, 400, 500, 600, 700, 800, 900])
- })
-})
-
describe('FontManager loaded font cache', () => {
test('marks and checks font', async () => {
const family = `TestFont_${Date.now()}`
@@ -531,83 +422,6 @@ describe('collectFontKeys', () => {
})
})
-describe('normalizeFontFamily', () => {
- test('strips " Variable" suffix', () => {
- expect(normalizeFontFamily('Inter Variable')).toBe('Inter')
- expect(normalizeFontFamily('Roboto Flex Variable')).toBe('Roboto Flex')
- })
-
- test('case insensitive', () => {
- expect(normalizeFontFamily('Inter VARIABLE')).toBe('Inter')
- expect(normalizeFontFamily('Inter variable')).toBe('Inter')
- })
-
- test('handles extra whitespace before Variable', () => {
- expect(normalizeFontFamily('Inter Variable')).toBe('Inter')
- })
-
- test('returns unchanged when no Variable suffix', () => {
- expect(normalizeFontFamily('Inter')).toBe('Inter')
- expect(normalizeFontFamily('Roboto')).toBe('Roboto')
- expect(normalizeFontFamily('')).toBe('')
- })
-
- test('does not strip Variable in the middle', () => {
- expect(normalizeFontFamily('Variable Sans')).toBe('Variable Sans')
- })
-
- test('strips optical size suffix (pt)', () => {
- expect(normalizeFontFamily('DM Sans 9pt')).toBe('DM Sans')
- expect(normalizeFontFamily('DM Sans 14pt')).toBe('DM Sans')
- })
-
- test('strips optical size suffix (px)', () => {
- expect(normalizeFontFamily('Noto Sans 12px')).toBe('Noto Sans')
- })
-
- test('strips optical size suffix (em)', () => {
- expect(normalizeFontFamily('Custom Font 1em')).toBe('Custom Font')
- })
-
- test('does not strip size units in the middle', () => {
- expect(normalizeFontFamily('12pt Serif')).toBe('12pt Serif')
- })
-})
-
-describe('styleToVariant', () => {
- test('regular → "regular"', () => {
- expect(styleToVariant('Regular')).toBe('regular')
- })
-
- test('italic at 400 → "italic"', () => {
- expect(styleToVariant('Regular Italic')).toBe('italic')
- })
-
- test('bold → "700"', () => {
- expect(styleToVariant('Bold')).toBe('700')
- })
-
- test('bold italic → "700italic"', () => {
- expect(styleToVariant('Bold Italic')).toBe('700italic')
- })
-
- test('light → "300"', () => {
- expect(styleToVariant('Light')).toBe('300')
- })
-
- test('thin italic → "100italic"', () => {
- expect(styleToVariant('Thin Italic')).toBe('100italic')
- })
-
- test('semibold → "600"', () => {
- expect(styleToVariant('SemiBold')).toBe('600')
- })
-
- test('black → "900"', () => {
- expect(styleToVariant('Black')).toBe('900')
- })
-})
-
describe('isVariableFont', () => {
function makeFontBuffer(tables: string[]): ArrayBuffer {
const numTables = tables.length
diff --git a/tests/engine/text/fonts/status.test.ts b/tests/engine/text/fonts/status.test.ts
index 7ed63c046..8f4c3b114 100644
--- a/tests/engine/text/fonts/status.test.ts
+++ b/tests/engine/text/fonts/status.test.ts
@@ -25,6 +25,7 @@ describe('documentFontStatus', () => {
{
family: 'Inter',
style: 'Regular',
+ name: 'Regular',
status: 'available',
source: 'bundled',
substituteFamily: null,
@@ -71,6 +72,7 @@ describe('documentFontStatus', () => {
{
family: 'Missing Sans',
style: 'Regular',
+ name: 'Regular',
status: 'substituted',
source: null,
substituteFamily: 'Inter',
@@ -105,6 +107,7 @@ describe('documentFontStatus', () => {
{
family: 'Example Sans',
style: 'Bold',
+ name: 'Bold',
status: 'substituted',
source: null,
substituteFamily: 'Example Sans',
@@ -115,6 +118,7 @@ describe('documentFontStatus', () => {
{
family: 'Missing Serif',
style: 'Regular',
+ name: 'Regular',
status: 'unresolved',
source: null,
substituteFamily: null,
@@ -146,6 +150,7 @@ describe('documentFontStatus', () => {
{
family: 'PingFang SC',
style: 'Regular',
+ name: 'Regular',
status: 'substituted',
source: null,
substituteFamily: 'Inter',
@@ -163,4 +168,44 @@ describe('documentFontStatus', () => {
expect(await manager.loadLocalFont('PingFang SC', 'Regular')).not.toBeNull()
expect(documentFontStatus(graph, pageId(graph), manager).faithful).toBe(true)
})
+
+ test('names faces as their text does, and keeps two faces of one weight apart', () => {
+ const graph = new SceneGraph()
+ // As pasted from Figma: Avenir's Roman and Book are both weight 400.
+ graph.createNode('TEXT', pageId(graph), {
+ name: 'Mixed',
+ text: 'Roman then Book then Bold',
+ fontFamily: 'Avenir',
+ fontStyle: 'Roman',
+ styleRuns: [
+ { start: 10, length: 4, style: { fontStyle: 'Book' } },
+ // A range from HTML sets a weight and no name, so it takes no name of the text's.
+ { start: 20, length: 5, style: { fontWeight: 700 } }
+ ]
+ })
+
+ const issues = documentFontStatus(graph, pageId(graph), new FontManager()).issues
+ expect(issues.map(({ name, style }) => [name, style])).toEqual([
+ ['Bold', 'Bold'],
+ ['Book', 'Regular'],
+ ['Roman', 'Regular']
+ ])
+ })
+
+ test('a named face is available once the style it loads as is loaded', async () => {
+ const graph = new SceneGraph()
+ graph.createNode('TEXT', pageId(graph), {
+ name: 'Book',
+ text: 'Book',
+ fontFamily: 'Avenir',
+ fontStyle: 'Book'
+ })
+ const manager = new FontManager()
+ await manager.markLoaded('Avenir', 'Regular', new ArrayBuffer(8), 'local')
+
+ expect(documentFontStatus(graph, pageId(graph), manager)).toMatchObject({
+ faithful: true,
+ faces: [{ family: 'Avenir', name: 'Book', style: 'Regular', status: 'available' }]
+ })
+ })
})
diff --git a/tools/checks/architecture/src/steiger-rules/index.ts b/tools/checks/architecture/src/steiger-rules/index.ts
index ee0f0c0be..5d39a3cbe 100644
--- a/tools/checks/architecture/src/steiger-rules/index.ts
+++ b/tools/checks/architecture/src/steiger-rules/index.ts
@@ -146,7 +146,7 @@ const ENGINE_TEST_DOMAIN_REDIRECTS: Array<{
{
from: 'tests/engine/fonts/',
to: 'tests/engine/text/fonts/',
- source: 'packages/core/src/text/fonts.ts'
+ source: 'packages/core/src/text/font/manager.ts'
},
{
from: 'tests/engine/figma-api/',
diff --git a/tools/checks/lint/src/rules/runtime.ts b/tools/checks/lint/src/rules/runtime.ts
index b3b5cb11e..4a6a38c0b 100644
--- a/tools/checks/lint/src/rules/runtime.ts
+++ b/tools/checks/lint/src/rules/runtime.ts
@@ -197,7 +197,8 @@ const noCoreBrowserGlobals = {
'/packages/core/src/constants.ts',
'/packages/core/src/editor/create.ts',
'/packages/core/src/canvas/renderer.ts',
- '/packages/core/src/text/fonts.ts',
+ '/packages/core/src/text/font/manager.ts',
+ '/packages/core/src/text/font/local.ts',
'/packages/core/src/profiler/render-profiler.ts',
'/packages/core/src/figma-api/index.ts',
'/packages/core/src/io/formats/pdf/dom.ts'