Skip to content

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

feat(text): surface missing font substitutions

Danila Poyarkov1eb1f38c780f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98b3223a0..22c0f26bc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@
- Add local crash recovery for unsaved and pathless documents, including MCP-created documents. (#487)
- Allow supported AI model profiles to set a provider-specific reasoning effort. (#454)
+- Show unavailable or substituted document fonts with affected-layer selection and retry actions, and expose font fidelity through the Figma API and MCP tooling. (#503)
### Fixed
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 7def31343..97a3a67ea 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -11,6 +11,7 @@ import { IS_BROWSER } from '#core/constants'
import { setTextMeasurer } from '#core/layout'
import { TextEditor } from '#core/text/editor'
import { fontManager } from '#core/text/fonts'
+import { fontResolver } from '#core/text/resolver'
import { createAlignmentActions } from './alignment'
import { createClipboardBridge } from './bridges/clipboard'
@@ -61,6 +62,9 @@ export function createEditor(options?: EditorOptions) {
const _renderers = new Set<SkiaRenderer>()
let _textEditor: TextEditor | null = null
const events: Emitter<EditorEvents> = createNanoEvents()
+ const stopFontResolutionEvents = fontResolver.subscribe((event, snapshot) => {
+ events.emit('font:resolution-changed', event, snapshot)
+ })
void prefetchFigmaSchema()
@@ -234,6 +238,7 @@ export function createEditor(options?: EditorOptions) {
removeCanvasRenderer,
replaceGraph,
subscribeToGraph,
+ dispose: stopFontResolutionEvents,
// Selection
...selection,
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 0abf0cf86..3d39b9cf5 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -14,6 +14,7 @@ import type { UndoManager } from '@open-pencil/scene-graph/undo'
import type { RulerTheme, SkiaRenderer } from '#core/canvas/renderer'
import type { RenderOverlays } from '#core/canvas/renderer/types'
import type { TextEditor } from '#core/text/editor'
+import type { FontResolutionEvent, FontResolutionSnapshot } from '#core/text/resolver'
export type Tool =
| 'SELECT'
@@ -106,6 +107,7 @@ export interface EditorEvents extends SceneGraphEvents {
'tool:changed': (tool: Tool, previousTool: Tool) => void
'page:changed': (pageId: string, previousPageId: string) => void
'clipboard:images-missing': (resolution: ClipboardImageResolution) => void
+ 'font:resolution-changed': (event: FontResolutionEvent, snapshot: FontResolutionSnapshot) => void
'viewport:changed': (
viewport: { panX: number; panY: number; zoom: number },
previous: { panX: number; panY: number; zoom: number }
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index b170982ec..ef1ef4dab 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -18,6 +18,7 @@ import { canMakeBooleanSourceNode } from '#core/canvas/boolean'
import { flattenNodesToVectorProps } from '#core/canvas/flatten'
import { IS_BROWSER } from '#core/constants'
import type { RasterExportFormat } from '#core/io/formats/raster'
+import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'
import type {
FigmaBooleanOperationNode,
@@ -511,6 +512,10 @@ export class FigmaAPI implements NodeProxyHost {
return []
}
+ getFontStatus(): DocumentFontStatus {
+ return documentFontStatus(this.graph, this.currentPageId)
+ }
+
base64Encode(data: Uint8Array): string {
return encodeBase64(data)
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5dee09252..1d877f463 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -170,8 +170,15 @@ export {
styleToVariant,
type DownloadedFontCache,
type FontInfo,
+ type FontLoadedSource,
type LocalFontAccessState
} from './text/fonts'
+export {
+ documentFontStatus,
+ type DocumentFontFaceStatus,
+ type DocumentFontStatus,
+ type FontFaceStatus
+} from './text/font/status'
export {
fontFaceFromFigmaFontName,
fontFaceRenderFamily,
diff --git a/packages/core/src/text/coverage.ts b/packages/core/src/text/coverage.ts
index 7fc760995..ab4ffbe79 100644
--- a/packages/core/src/text/coverage.ts
+++ b/packages/core/src/text/coverage.ts
@@ -2,7 +2,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { cjkFallbackScriptForLanguage, type FontFallbackScript } from '#core/text/fallbacks'
-import { weightToStyle } from '#core/text/font-style'
+import { weightToStyle } from '#core/text/font/style'
import { fontGlyphCoverageSync } from '#core/text/opentype'
const CJK_IDEOGRAPH_CHAR_RE = /\p{Script=Han}/u
diff --git a/packages/core/src/text/font-sources.ts b/packages/core/src/text/font/sources.ts
similarity index 90%
rename from packages/core/src/text/font-sources.ts
rename to packages/core/src/text/font/sources.ts
index 9c5ae1e5f..f3bd53bca 100644
--- a/packages/core/src/text/font-sources.ts
+++ b/packages/core/src/text/font/sources.ts
@@ -9,6 +9,7 @@ export interface FontInfo {
export type LocalFontAccessState = 'unsupported' | 'prompt' | 'granted' | 'denied'
export type FontFamilySource = 'local' | 'bundled' | 'fallback' | WebFontProviderId
+export type FontLoadedSource = FontFamilySource | 'cache' | 'registered'
export interface FontFamilyOption {
family: string
diff --git a/packages/core/src/text/font/status.ts b/packages/core/src/text/font/status.ts
new file mode 100644
index 000000000..60fae7a4e
--- /dev/null
+++ b/packages/core/src/text/font/status.ts
@@ -0,0 +1,108 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { DEFAULT_FONT_FAMILY } from '#core/constants'
+import type { FontLoadedSource } 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
+ style: string
+ status: FontFaceStatus
+ source: FontLoadedSource | null
+ substituteFamily: string | null
+ nodeIds: string[]
+ nodeNames: string[]
+}
+
+export interface DocumentFontStatus {
+ faithful: boolean
+ faces: DocumentFontFaceStatus[]
+ issues: DocumentFontFaceStatus[]
+}
+
+interface MutableFontFaceUse {
+ family: string
+ style: string
+ nodeIds: Set<string>
+ nodeNames: Set<string>
+}
+
+function faceKey(family: string, style: string): string {
+ return `${family}\0${style}`
+}
+
+function pageTextNodes(graph: SceneGraph, pageId: string): SceneNode[] {
+ return graph.flattenTree(pageId).flatMap(({ node }) => (node.type === 'TEXT' ? [node] : []))
+}
+
+function collectFaceUses(graph: SceneGraph, pageId: string): MutableFontFaceUse[] {
+ const uses = new Map<string, MutableFontFaceUse>()
+ for (const node of pageTextNodes(graph, pageId)) {
+ for (const { family, style } of collectNodeFontFaces(node)) {
+ const key = faceKey(family, style)
+ const use = uses.get(key) ?? {
+ family,
+ style,
+ nodeIds: new Set<string>(),
+ nodeNames: new Set<string>()
+ }
+ use.nodeIds.add(node.id)
+ use.nodeNames.add(node.name)
+ uses.set(key, use)
+ }
+ }
+ return [...uses.values()]
+}
+
+function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFontFaceStatus {
+ const exactSource = manager.loadedFontSource(use.family, use.style)
+ if (exactSource) {
+ return {
+ family: use.family,
+ style: use.style,
+ status: 'available',
+ source: exactSource,
+ substituteFamily: null,
+ nodeIds: [...use.nodeIds],
+ nodeNames: [...use.nodeNames]
+ }
+ }
+
+ if (manager.isLoaded(use.family)) {
+ return {
+ family: use.family,
+ style: use.style,
+ status: 'substituted',
+ source: null,
+ substituteFamily: use.family,
+ nodeIds: [...use.nodeIds],
+ nodeNames: [...use.nodeNames]
+ }
+ }
+
+ const defaultSource = manager.loadedFontSource(DEFAULT_FONT_FAMILY, 'Regular')
+ return {
+ family: use.family,
+ style: use.style,
+ status: defaultSource ? 'substituted' : 'unresolved',
+ source: null,
+ substituteFamily: defaultSource ? DEFAULT_FONT_FAMILY : null,
+ nodeIds: [...use.nodeIds],
+ nodeNames: [...use.nodeNames]
+ }
+}
+
+export function documentFontStatus(
+ graph: SceneGraph,
+ pageId: string,
+ manager: FontManager = fontManager
+): DocumentFontStatus {
+ const faces = collectFaceUses(graph, pageId)
+ .map((use) => faceStatus(use, manager))
+ .sort((a, b) => a.family.localeCompare(b.family) || a.style.localeCompare(b.style))
+ const issues = faces.filter((face) => face.status !== 'available')
+ return { faithful: issues.length === 0, faces, issues }
+}
diff --git a/packages/core/src/text/font-style.ts b/packages/core/src/text/font/style.ts
similarity index 100%
rename from packages/core/src/text/font-style.ts
rename to packages/core/src/text/font/style.ts
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.ts
index cec888807..d3c551d5a 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/fonts.ts
@@ -9,19 +9,20 @@ import {
normalizeFontFamily,
styleToWeight,
weightToStyle
-} from '#core/text/font-style'
+} from '#core/text/font/style'
-export * from '#core/text/font-sources'
-export * from '#core/text/font-style'
+export * from '#core/text/font/sources'
+export * from '#core/text/font/style'
import { fontFallbackEntry } from '#core/text/fallbacks'
import type { FontFallbackScript } from '#core/text/fallbacks'
import type {
DownloadedFontCache,
FontFamilyOption,
FontInfo,
+ FontLoadedSource,
HostFontLoader,
LocalFontAccessState
-} from '#core/text/font-sources'
+} 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'
@@ -39,6 +40,7 @@ const BUNDLED_FONTS: Record<string, string> = {
export class FontManager {
private loadedFamilies = new Map<string, ArrayBuffer>()
+ private loadedFamilySources = new Map<string, FontLoadedSource>()
private supplementalFamilyData = new Map<string, ArrayBuffer[]>()
private remoteCoverage = new Map<string, Set<string>>()
private blockedNodeIds = new Set<string>()
@@ -122,11 +124,6 @@ export class FontManager {
this.hostFontLoader = loader
}
- /** @deprecated Use setHostFontLoader. Scheduled for removal in v0.15. */
- setHostFallbackFontLoader(loader: HostFontLoader | null): void {
- this.setHostFontLoader(loader)
- }
-
setOnlineFontProviders(settings: Partial<Record<WebFontProviderId, boolean>>): void {
this.webFonts.setEnabled(settings)
}
@@ -146,7 +143,7 @@ export class FontManager {
): Promise<ArrayBuffer | null> {
const cached = await this.readDownloadedFont(family, style, characters)
if (!cached) return null
- return this.registerAndCache(family, style, cached)
+ return this.registerAndCache(family, style, cached, 'cache')
}
async requestLocalFontAccess(): Promise<FontInfo[]> {
@@ -208,11 +205,6 @@ export class FontManager {
this.webFonts.preloadFamilies()
}
- preloadGoogleFamilies(): void {
- if (!this.webFonts.enabledProviders().includes('google')) return
- void this.webFonts.listFamilies('google')
- }
-
async fetchBundledFont(url: string): Promise<ArrayBuffer | null> {
if (IS_BROWSER) {
const response = await fetch(url)
@@ -236,15 +228,18 @@ export class FontManager {
return loaded
}
- const localBuffer =
- (await this.loadHostFont(family, style)) ?? (await this.findLocalFont(family, style))
- if (localBuffer) return this.registerAndCache(family, style, localBuffer)
+ const hostBuffer = await this.loadHostFont(family, style)
+ if (hostBuffer) return this.registerAndCache(family, style, hostBuffer, 'local')
+ const localBuffer = await this.findLocalFont(family, style)
+ if (localBuffer) return this.registerAndCache(family, style, localBuffer, 'local')
const bundledURL = BUNDLED_FONTS[cacheKey]
if (!bundledURL) return null
try {
const buffer = await this.fetchBundledFont(bundledURL)
- return buffer && !isVariableFont(buffer) ? this.registerAndCache(family, style, buffer) : null
+ return buffer && !isVariableFont(buffer)
+ ? this.registerAndCache(family, style, buffer, 'bundled')
+ : null
} catch (e) {
console.warn(`Bundled font load failed for "${family}" ${style}:`, e)
return null
@@ -271,15 +266,15 @@ export class FontManager {
)
const normalized = normalizeFontFamily(family)
const families = normalized === family ? [family] : [family, normalized]
- const buffers = await this.webFonts.fetchFont(families, style, requestedCharacters)
- if (buffers.length === 0) return null
- const primary = buffers[0]
+ const resolved = await this.webFonts.fetchFont(families, style, requestedCharacters)
+ if (!resolved || resolved.buffers.length === 0) return null
+ const primary = resolved.buffers[0]
await this.writeDownloadedFont(family, style, primary, requestedCharacters)
- const registered = this.registerAndCache(family, style, primary)
+ const registered = this.registerAndCache(family, style, primary, resolved.provider)
const loadedCoverage = this.remoteCoverage.get(`${family}|${style}`) ?? new Set<string>()
for (const character of requestedCharacters) loadedCoverage.add(character)
this.remoteCoverage.set(`${family}|${style}`, loadedCoverage)
- for (const supplemental of buffers.slice(1)) {
+ for (const supplemental of resolved.buffers.slice(1)) {
this.registerSupplemental(family, style, supplemental)
}
return registered
@@ -315,8 +310,17 @@ export class FontManager {
await this.loadFont(family, weightToStyle(weight))
}
- markLoaded(family: string, style: string, data: ArrayBuffer): void {
- this.registerAndCache(family, style, data)
+ markLoaded(
+ family: string,
+ style: string,
+ data: ArrayBuffer,
+ source: FontLoadedSource = 'registered'
+ ): void {
+ this.registerAndCache(family, style, data, source)
+ }
+
+ loadedFontSource(family: string, style: string): FontLoadedSource | null {
+ return this.loadedFamilySources.get(`${family}|${style}`) ?? null
}
isLoaded(family: string): boolean {
@@ -420,7 +424,7 @@ export class FontManager {
}))
if (
buffer &&
- this.registerAndCache(family, 'Regular', buffer) &&
+ this.registerAndCache(family, 'Regular', buffer, 'fallback') &&
!targetFamilies.includes(family)
) {
targetFamilies.push(family)
@@ -517,15 +521,22 @@ export class FontManager {
this.registerFontInBrowser(family, style, buffer)
}
- private registerAndCache(family: string, style: string, buffer: ArrayBuffer): ArrayBuffer | null {
+ private registerAndCache(
+ family: string,
+ style: string,
+ buffer: ArrayBuffer,
+ source?: FontLoadedSource
+ ): ArrayBuffer | null {
const key = `${family}|${style}`
const existing = this.loadedFamilies.get(key)
if (existing === buffer) {
+ if (source) this.loadedFamilySources.set(key, source)
this.registerFontInCanvasKit(family, buffer)
return buffer
}
if (existing) this.registerSupplemental(family, style, existing)
this.loadedFamilies.set(key, buffer)
+ if (source) this.loadedFamilySources.set(key, source)
this.registerFontInCanvasKit(family, buffer)
this.registerFontInBrowser(family, style, buffer)
return buffer
diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.ts
index d5ca04713..a7ec848c5 100644
--- a/packages/core/src/text/index.ts
+++ b/packages/core/src/text/index.ts
@@ -4,6 +4,7 @@ export * from './direction'
export * from './case'
export * from './coverage'
export * from './fonts'
+export * from './font/status'
export * from './fallbacks'
export * from './resolver'
export * from './requirements'
diff --git a/packages/core/src/text/requirements.ts b/packages/core/src/text/requirements.ts
index e756a4f01..8665e69ca 100644
--- a/packages/core/src/text/requirements.ts
+++ b/packages/core/src/text/requirements.ts
@@ -3,7 +3,24 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { transformTextCase } from '#core/text/case'
import { cjkFallbackScriptForLanguage, type FontFallbackScript } from '#core/text/fallbacks'
-import { weightToStyle } from '#core/text/font-style'
+import { weightToStyle } from '#core/text/font/style'
+
+export function collectNodeFontFaces(node: SceneNode): Array<{ family: string; style: string }> {
+ if (node.type !== 'TEXT') return []
+ const family = node.fontFamily || DEFAULT_FONT_FAMILY
+ const faces = new Map<string, { family: string; style: string }>()
+ const add = (faceFamily: string, style: string) => {
+ faces.set(`${faceFamily}\0${style}`, { family: faceFamily, style })
+ }
+ add(family, weightToStyle(node.fontWeight || 400, node.italic))
+ for (const run of node.styleRuns) {
+ const runFamily = run.style.fontFamily ?? family
+ const weight = run.style.fontWeight ?? node.fontWeight
+ const italic = run.style.italic ?? node.italic
+ add(runFamily, weightToStyle(weight, italic))
+ }
+ return [...faces.values()]
+}
export function collectGraphFontKeys(
graph: SceneGraph,
@@ -14,13 +31,8 @@ export function collectGraphFontKeys(
const node = graph.getNode(nodeId)
if (!node) return
if (node.type === 'TEXT') {
- const family = node.fontFamily || DEFAULT_FONT_FAMILY
- fontKeys.add(`${family}\0${weightToStyle(node.fontWeight || 400, node.italic)}`)
- for (const run of node.styleRuns) {
- const runFamily = run.style.fontFamily ?? family
- const weight = run.style.fontWeight ?? node.fontWeight
- const italic = run.style.italic ?? node.italic
- fontKeys.add(`${runFamily}\0${weightToStyle(weight, italic)}`)
+ for (const { family, style } of collectNodeFontFaces(node)) {
+ fontKeys.add(`${family}\0${style}`)
}
}
for (const childId of node.childIds) collect(childId)
diff --git a/packages/core/src/text/resolver/resolver.ts b/packages/core/src/text/resolver/resolver.ts
index f74fd2ccf..9ea174ca8 100644
--- a/packages/core/src/text/resolver/resolver.ts
+++ b/packages/core/src/text/resolver/resolver.ts
@@ -1,5 +1,6 @@
import type {
FontResolutionDemand,
+ FontResolutionListener,
FontResolutionLoader,
FontResolutionSettled,
FontResolutionSnapshot
@@ -19,9 +20,15 @@ function idleSnapshot(key: string): FontResolutionSnapshot {
export class FontResolver {
private readonly entries = new Map<string, FontResolutionEntry>()
+ private readonly listeners = new Set<FontResolutionListener>()
constructor(private readonly load: FontResolutionLoader) {}
+ subscribe(listener: FontResolutionListener): () => void {
+ this.listeners.add(listener)
+ return () => this.listeners.delete(listener)
+ }
+
state(demand: FontResolutionDemand | string): FontResolutionSnapshot {
const key = typeof demand === 'string' ? demand : demand.key
return this.entries.get(key)?.snapshot ?? idleSnapshot(key)
@@ -82,9 +89,12 @@ export class FontResolver {
reset(demand?: FontResolutionDemand | string): void {
if (demand === undefined) {
this.entries.clear()
+ this.notify('reset', idleSnapshot('*'))
return
}
- this.entries.delete(typeof demand === 'string' ? demand : demand.key)
+ const key = typeof demand === 'string' ? demand : demand.key
+ this.entries.delete(key)
+ this.notify('reset', idleSnapshot(key))
}
private request(
@@ -108,6 +118,7 @@ export class FontResolver {
}
this.addConsumer(entry, onSettled, nodeId)
this.entries.set(demand.key, entry)
+ this.notify('started', snapshot)
entry.promise = this.resolve(entry)
return entry.promise
}
@@ -157,6 +168,7 @@ export class FontResolver {
): FontResolutionSnapshot {
if (this.entries.get(entry.demand.key) !== entry) return idleSnapshot(entry.demand.key)
entry.snapshot = snapshot
+ this.notify('settled', snapshot)
for (const [callback, nodeIds] of entry.callbacks) {
try {
callback(snapshot, [...nodeIds])
@@ -168,4 +180,8 @@ export class FontResolver {
entry.nodeIds.clear()
return snapshot
}
+
+ private notify(event: Parameters<FontResolutionListener>[0], snapshot: FontResolutionSnapshot) {
+ for (const listener of this.listeners) listener(event, snapshot)
+ }
}
diff --git a/packages/core/src/text/resolver/types.ts b/packages/core/src/text/resolver/types.ts
index 7db854b03..07acf0948 100644
--- a/packages/core/src/text/resolver/types.ts
+++ b/packages/core/src/text/resolver/types.ts
@@ -1,5 +1,12 @@
export type FontResolutionState = 'idle' | 'loading' | 'loaded' | 'failed' | 'exhausted'
+export type FontResolutionEvent = 'started' | 'settled' | 'reset'
+
+export type FontResolutionListener = (
+ event: FontResolutionEvent,
+ snapshot: FontResolutionSnapshot
+) => void
+
export type FontCandidateSource = 'registered' | 'local' | 'cache' | 'remote' | 'fallback'
export interface FontResolutionCandidate {
diff --git a/packages/core/src/text/web-fonts.ts b/packages/core/src/text/web-fonts.ts
index 4e67d6eb9..1f243a284 100644
--- a/packages/core/src/text/web-fonts.ts
+++ b/packages/core/src/text/web-fonts.ts
@@ -89,6 +89,11 @@ function isArrayBuffer(value: ArrayBuffer | null): value is ArrayBuffer {
return value !== null
}
+export interface ResolvedWebFont {
+ buffers: ArrayBuffer[]
+ provider: WebFontProviderId
+}
+
export class WebFontResolver {
private enabled = new Set<WebFontProviderId>(
WEB_FONT_PROVIDER_IDS.filter((provider) => DEFAULT_WEB_FONT_PROVIDER_SETTINGS[provider])
@@ -135,18 +140,22 @@ export class WebFontResolver {
return promise
}
- async fetchFont(families: string[], style: string, characters = ''): Promise<ArrayBuffer[]> {
+ async fetchFont(
+ families: string[],
+ style: string,
+ characters = ''
+ ): Promise<ResolvedWebFont | null> {
const providers = this.enabledProviders()
- if (providers.length === 0 || (IS_BROWSER && !this.remoteFetch)) return []
+ if (providers.length === 0 || (IS_BROWSER && !this.remoteFetch)) return null
for (const family of families) {
for (const provider of providers) {
const buffers = await this.fetchFromProvider(family, style, provider, characters)
- if (buffers.length > 0) return buffers
+ if (buffers.length > 0) return { buffers, provider }
}
}
- return []
+ return null
}
private async withFetchProxy<T>(operation: () => Promise<T>): Promise<T> {
diff --git a/packages/core/src/tools/read.ts b/packages/core/src/tools/read.ts
index fbae3370a..e26465362 100644
--- a/packages/core/src/tools/read.ts
+++ b/packages/core/src/tools/read.ts
@@ -1,5 +1,5 @@
export { getComponents } from './read/components'
-export { listAvailableFonts, listFonts } from './read/fonts'
+export { getFontStatus, listAvailableFonts, listFonts } from './read/fonts'
export { diffJSX, getJSX } from './read/jsx'
export { findNodes, getNode, getPageTree } from './read/nodes'
export { getCurrentPage, listPages, pageBounds, switchPage } from './read/pages'
diff --git a/packages/core/src/tools/read/fonts.ts b/packages/core/src/tools/read/fonts.ts
index 4a9446c34..5b466b21e 100644
--- a/packages/core/src/tools/read/fonts.ts
+++ b/packages/core/src/tools/read/fonts.ts
@@ -2,6 +2,15 @@ import { uniq } from 'es-toolkit/array'
import { defineTool } from '#core/tools/schema'
+export const getFontStatus = defineTool({
+ name: 'get_font_status',
+ description:
+ 'Report whether fonts used on the current page are faithfully available. Returns requested ' +
+ 'faces, their loaded source, active substitutions, and affected nodes.',
+ params: {},
+ execute: (figma) => figma.getFontStatus()
+})
+
export const listFonts = defineTool({
name: 'list_fonts',
description: 'List fonts used in the current page.',
diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.ts
index 8e0ffab12..7fdd062e9 100644
--- a/packages/core/src/tools/registry-extended.ts
+++ b/packages/core/src/tools/registry-extended.ts
@@ -39,6 +39,7 @@ import {
diffJSX,
getComponents,
getCurrentPage,
+ getFontStatus,
getPageTree,
listAvailableFonts,
listFonts,
@@ -110,6 +111,7 @@ export const EXTENDED_TOOLS: ToolDef[] = [
getComponents,
switchPage,
pageBounds,
+ getFontStatus,
listFonts,
listAvailableFonts,
diffJSX,
diff --git a/packages/vue/src/i18n/locales/de/dialogs.json b/packages/vue/src/i18n/locales/de/dialogs.json
index 58107c21d..be621a723 100644
--- a/packages/vue/src/i18n/locales/de/dialogs.json
+++ b/packages/vue/src/i18n/locales/de/dialogs.json
@@ -180,6 +180,16 @@
"closeTab": "{name} schließen",
"showUI": "UI anzeigen ({shortcut})",
"fontSettings": "Schrifteinstellungen",
+ "fontIssueFound": "Ein Schriftschnitt ist nicht verfügbar oder wurde ersetzt",
+ "fontIssuesFound": "{count} Schriftschnitte sind nicht verfügbar oder wurden ersetzt",
+ "selectAffectedLayers": "Ebenen auswählen",
+ "retryFonts": "Schriften erneut laden",
+ "retryingFonts": "Wird erneut versucht…",
+ "expandFontIssues": "Schriftprobleme anzeigen",
+ "collapseFontIssues": "Schriftprobleme ausblenden",
+ "noFontSubstitute": "kein Ersatz verfügbar",
+ "affectedLayer": "1 betroffene Ebene",
+ "affectedLayerCount": "{count} betroffene Ebenen",
"fontSettingsDesktopDescription": "Auf Systemschriften, Online-Anbieter, Fallback-Pakete und zwischengespeicherte Downloads zugreifen.",
"fontSettingsBrowserDescription": "Browserzugriff auf lokale Schriften erlauben und Online-Schriftanbieter verwalten.",
"localFonts": "Lokale Schriften",
diff --git a/packages/vue/src/i18n/locales/es/dialogs.json b/packages/vue/src/i18n/locales/es/dialogs.json
index 13fb159df..f7cba0923 100644
--- a/packages/vue/src/i18n/locales/es/dialogs.json
+++ b/packages/vue/src/i18n/locales/es/dialogs.json
@@ -180,6 +180,16 @@
"closeTab": "Cerrar {name}",
"showUI": "Mostrar interfaz ({shortcut})",
"fontSettings": "Ajustes de fuentes",
+ "fontIssueFound": "Un estilo de fuente no está disponible o se ha sustituido",
+ "fontIssuesFound": "{count} estilos de fuente no están disponibles o se han sustituido",
+ "selectAffectedLayers": "Seleccionar capas",
+ "retryFonts": "Reintentar fuentes",
+ "retryingFonts": "Reintentando…",
+ "expandFontIssues": "Mostrar problemas de fuentes",
+ "collapseFontIssues": "Ocultar problemas de fuentes",
+ "noFontSubstitute": "sin sustituto disponible",
+ "affectedLayer": "1 capa afectada",
+ "affectedLayerCount": "{count} capas afectadas",
"fontSettingsDesktopDescription": "Accede a fuentes del sistema, proveedores en línea, paquetes de respaldo y descargas en caché.",
"fontSettingsBrowserDescription": "Permite al navegador acceder a fuentes locales y gestiona proveedores de fuentes en línea.",
"localFonts": "Fuentes locales",
diff --git a/packages/vue/src/i18n/locales/fr/dialogs.json b/packages/vue/src/i18n/locales/fr/dialogs.json
index 345f8e5ff..13c0c7010 100644
--- a/packages/vue/src/i18n/locales/fr/dialogs.json
+++ b/packages/vue/src/i18n/locales/fr/dialogs.json
@@ -180,6 +180,16 @@
"closeTab": "Fermer {name}",
"showUI": "Afficher l’interface ({shortcut})",
"fontSettings": "Réglages des polices",
+ "fontIssueFound": "Un style de police est indisponible ou remplacé",
+ "fontIssuesFound": "{count} styles de police sont indisponibles ou remplacés",
+ "selectAffectedLayers": "Sélectionner les calques",
+ "retryFonts": "Réessayer les polices",
+ "retryingFonts": "Nouvelle tentative…",
+ "expandFontIssues": "Afficher les problèmes de police",
+ "collapseFontIssues": "Masquer les problèmes de police",
+ "noFontSubstitute": "aucun remplacement disponible",
+ "affectedLayer": "1 calque concerné",
+ "affectedLayerCount": "{count} calques concernés",
"fontSettingsDesktopDescription": "Accédez aux polices système, aux fournisseurs en ligne, aux packs de secours et aux téléchargements en cache.",
"fontSettingsBrowserDescription": "Autorisez l’accès du navigateur aux polices locales et gérez les fournisseurs de polices en ligne.",
"localFonts": "Polices locales",
diff --git a/packages/vue/src/i18n/locales/it/dialogs.json b/packages/vue/src/i18n/locales/it/dialogs.json
index 0cc253c0c..40d806bda 100644
--- a/packages/vue/src/i18n/locales/it/dialogs.json
+++ b/packages/vue/src/i18n/locales/it/dialogs.json
@@ -180,6 +180,16 @@
"closeTab": "Chiudi {name}",
"showUI": "Mostra interfaccia ({shortcut})",
"fontSettings": "Impostazioni font",
+ "fontIssueFound": "Uno stile di font non è disponibile o è stato sostituito",
+ "fontIssuesFound": "{count} stili di font non sono disponibili o sono stati sostituiti",
+ "selectAffectedLayers": "Seleziona livelli",
+ "retryFonts": "Riprova i font",
+ "retryingFonts": "Nuovo tentativo…",
+ "expandFontIssues": "Mostra problemi dei font",
+ "collapseFontIssues": "Nascondi problemi dei font",
+ "noFontSubstitute": "nessun sostituto disponibile",
+ "affectedLayer": "1 livello interessato",
+ "affectedLayerCount": "{count} livelli interessati",
"fontSettingsDesktopDescription": "Accedi ai font di sistema, ai provider online, ai pacchetti di fallback e ai download nella cache.",
"fontSettingsBrowserDescription": "Consenti al browser di accedere ai font locali e gestisci i provider di font online.",
"localFonts": "Font locali",
diff --git a/packages/vue/src/i18n/locales/ja/dialogs.json b/packages/vue/src/i18n/locales/ja/dialogs.json
index 9af537aed..e39e94748 100644
--- a/packages/vue/src/i18n/locales/ja/dialogs.json
+++ b/packages/vue/src/i18n/locales/ja/dialogs.json
@@ -180,6 +180,16 @@
"closeTab": "{name} を閉じる",
"showUI": "UIを表示 ({shortcut})",
"fontSettings": "フォント設定",
+ "fontIssueFound": "1 個のフォントスタイルが利用できないか置き換えられています",
+ "fontIssuesFound": "{count} 個のフォントスタイルが利用できないか置き換えられています",
+ "selectAffectedLayers": "該当レイヤーを選択",
+ "retryFonts": "フォントを再試行",
+ "retryingFonts": "再試行中…",
+ "expandFontIssues": "フォントの問題を表示",
+ "collapseFontIssues": "フォントの問題を隠す",
+ "noFontSubstitute": "代替フォントなし",
+ "affectedLayer": "1 個の該当レイヤー",
+ "affectedLayerCount": "{count} 個の該当レイヤー",
"fontSettingsDesktopDescription": "システムフォント、オンラインプロバイダー、フォールバックパック、キャッシュ済みダウンロードにアクセスします。",
"fontSettingsBrowserDescription": "ローカルフォントへのブラウザーアクセスを許可し、オンラインフォントプロバイダーを管理します。",
"localFonts": "ローカルフォント",
diff --git a/packages/vue/src/i18n/locales/pl/dialogs.json b/packages/vue/src/i18n/locales/pl/dialogs.json
index 6ba633410..a0a2fe94a 100644
--- a/packages/vue/src/i18n/locales/pl/dialogs.json
+++ b/packages/vue/src/i18n/locales/pl/dialogs.json
@@ -180,6 +180,16 @@
"closeTab": "Zamknij {name}",
"showUI": "Pokaż interfejs ({shortcut})",
"fontSettings": "Ustawienia czcionek",
+ "fontIssueFound": "Jeden krój czcionki jest niedostępny lub zastąpiony",
+ "fontIssuesFound": "{count} krojów czcionek jest niedostępnych lub zastąpionych",
+ "selectAffectedLayers": "Wybierz warstwy",
+ "retryFonts": "Ponów ładowanie czcionek",
+ "retryingFonts": "Ponawianie…",
+ "expandFontIssues": "Pokaż problemy z czcionkami",
+ "collapseFontIssues": "Ukryj problemy z czcionkami",
+ "noFontSubstitute": "brak dostępnego zamiennika",
+ "affectedLayer": "1 warstwa z problemem",
+ "affectedLayerCount": "{count} warstw z problemem",
"fontSettingsDesktopDescription": "Uzyskaj dostęp do czcionek systemowych, dostawców online, pakietów zapasowych i pobranych plików w pamięci podręcznej.",
"fontSettingsBrowserDescription": "Zezwól przeglądarce na dostęp do lokalnych czcionek i zarządzaj dostawcami czcionek online.",
"localFonts": "Czcionki lokalne",
diff --git a/packages/vue/src/i18n/locales/ru/dialogs.json b/packages/vue/src/i18n/locales/ru/dialogs.json
index 838345e48..f57398487 100644
--- a/packages/vue/src/i18n/locales/ru/dialogs.json
+++ b/packages/vue/src/i18n/locales/ru/dialogs.json
@@ -180,6 +180,16 @@
"closeTab": "Закрыть {name}",
"showUI": "Показать интерфейс ({shortcut})",
"fontSettings": "Настройки шрифтов",
+ "fontIssueFound": "Одно начертание недоступно или заменено",
+ "fontIssuesFound": "{count} начертаний недоступны или заменены",
+ "selectAffectedLayers": "Выбрать слои",
+ "retryFonts": "Повторить загрузку шрифтов",
+ "retryingFonts": "Повторная попытка…",
+ "expandFontIssues": "Показать проблемы со шрифтами",
+ "collapseFontIssues": "Скрыть проблемы со шрифтами",
+ "noFontSubstitute": "замена недоступна",
+ "affectedLayer": "1 затронутый слой",
+ "affectedLayerCount": "{count} затронутых слоёв",
"fontSettingsDesktopDescription": "Доступ к системным шрифтам, онлайн-провайдерам, резервным наборам и кэшу загрузок.",
"fontSettingsBrowserDescription": "Разрешите браузеру доступ к локальным шрифтам и управляйте онлайн-провайдерами шрифтов.",
"localFonts": "Локальные шрифты",
diff --git a/packages/vue/src/i18n/locales/zh-cn/dialogs.json b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
index ec39ad3d1..8d1349188 100644
--- a/packages/vue/src/i18n/locales/zh-cn/dialogs.json
+++ b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
@@ -180,6 +180,16 @@
"closeTab": "关闭 {name}",
"showUI": "显示界面({shortcut})",
"fontSettings": "字体设置",
+ "fontIssueFound": "1 个字体样式不可用或已被替换",
+ "fontIssuesFound": "{count} 个字体样式不可用或已被替换",
+ "selectAffectedLayers": "选择受影响图层",
+ "retryFonts": "重试字体",
+ "retryingFonts": "正在重试…",
+ "expandFontIssues": "显示字体问题",
+ "collapseFontIssues": "隐藏字体问题",
+ "noFontSubstitute": "没有可用的替代字体",
+ "affectedLayer": "1 个受影响图层",
+ "affectedLayerCount": "{count} 个受影响图层",
"fontSettingsDesktopDescription": "访问系统字体、在线提供商、后备字体包和缓存下载。",
"fontSettingsBrowserDescription": "允许浏览器访问本地字体,并管理在线字体提供商。",
"localFonts": "本地字体",
diff --git a/packages/vue/src/i18n/messages/dialogs.ts b/packages/vue/src/i18n/messages/dialogs.ts
index 8e51f8a74..25827256f 100644
--- a/packages/vue/src/i18n/messages/dialogs.ts
+++ b/packages/vue/src/i18n/messages/dialogs.ts
@@ -52,6 +52,16 @@ export const dialogMessageDefaults = {
recoveryFailed: 'Could not restore this document.',
showUI: params('Show UI ({shortcut})'),
fontSettings: 'Font settings',
+ fontIssueFound: '1 font face is unavailable or substituted',
+ fontIssuesFound: params('{count} font faces are unavailable or substituted'),
+ selectAffectedLayers: 'Select layers',
+ retryFonts: 'Retry fonts',
+ retryingFonts: 'Retrying…',
+ expandFontIssues: 'Show font issues',
+ collapseFontIssues: 'Hide font issues',
+ noFontSubstitute: 'no substitute available',
+ affectedLayer: '1 affected layer',
+ affectedLayerCount: params('{count} affected layers'),
fontSettingsDesktopDescription:
'Access system fonts, online providers, fallback packs, and cached downloads.',
fontSettingsBrowserDescription:
diff --git a/src/app/editor/fonts/status.ts b/src/app/editor/fonts/status.ts
new file mode 100644
index 000000000..a4ca3345c
--- /dev/null
+++ b/src/app/editor/fonts/status.ts
@@ -0,0 +1,57 @@
+import { computed, ref } from 'vue'
+
+import { documentFontStatus, fontManager, fontResolver } from '@open-pencil/core/text'
+import { useEditor, useEditorEvent } from '@open-pencil/vue'
+
+import { loadFont, requestLocalFontAccess } from '@/app/editor/fonts'
+
+export function useDocumentFontStatus() {
+ const editor = useEditor()
+ const revision = ref(0)
+ const retrying = ref(false)
+
+ const refresh = () => {
+ revision.value++
+ }
+
+ useEditorEvent('font:resolution-changed', refresh)
+ useEditorEvent('graph:replaced', refresh)
+ useEditorEvent('page:changed', refresh)
+ useEditorEvent('node:created', refresh)
+ useEditorEvent('node:updated', refresh)
+ useEditorEvent('node:deleted', refresh)
+
+ const status = computed(() => {
+ void revision.value
+ return documentFontStatus(editor.graph, editor.state.currentPageId)
+ })
+
+ async function retry() {
+ if (retrying.value) return
+ retrying.value = true
+ try {
+ if (fontManager.localAccessState() === 'prompt') {
+ await requestLocalFontAccess().catch(() => [])
+ }
+ const issues = status.value.issues
+ await Promise.all(
+ issues.map(async ({ family, style }) => {
+ fontResolver.reset(
+ `face:${family.trim().toLocaleLowerCase()}:${style.toLocaleLowerCase()}`
+ )
+ await loadFont(family, style)
+ })
+ )
+ editor.requestRender()
+ refresh()
+ } finally {
+ retrying.value = false
+ }
+ }
+
+ function selectAffectedNodes() {
+ editor.select(status.value.issues.flatMap((issue) => issue.nodeIds))
+ }
+
+ return { status, retrying, retry, selectAffectedNodes }
+}
diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.ts
index 04c237998..897ae4a0e 100644
--- a/src/app/editor/session/modules.ts
+++ b/src/app/editor/session/modules.ts
@@ -85,6 +85,7 @@ export function createEditorStoreModules(
setPlannedFilePath: documentIO.setPlannedFilePath,
startWatchingCurrentFile: documentIO.startWatchingCurrentFile,
dispose: () => {
+ editor.dispose()
editor.clearPageViewports()
documentIO.disposeDocumentIO()
},
diff --git a/src/components/font-status/FontStatusBanner.vue b/src/components/font-status/FontStatusBanner.vue
new file mode 100644
index 000000000..326609acb
--- /dev/null
+++ b/src/components/font-status/FontStatusBanner.vue
@@ -0,0 +1,84 @@
+<script setup lang="ts">
+import { computed, ref } from 'vue'
+
+import { useI18n } from '@open-pencil/vue'
+
+import { useDocumentFontStatus } from '@/app/editor/fonts/status'
+
+const { dialogs } = useI18n()
+const expanded = ref(false)
+const { status, retrying, retry, selectAffectedNodes } = useDocumentFontStatus()
+const issues = computed(() => status.value.issues)
+</script>
+
+<template>
+ <div
+ v-if="issues.length > 0"
+ data-test-id="font-status-banner"
+ class="border-b border-[var(--color-warning-border)] bg-[var(--color-warning-bg)] text-xs text-[var(--color-warning-text)]"
+ >
+ <div class="flex items-center gap-2 px-3 py-1.5">
+ <icon-lucide-triangle-alert class="size-3.5 shrink-0" />
+ <button
+ type="button"
+ data-test-id="font-status-toggle"
+ class="min-w-0 flex-1 text-left font-medium"
+ @click="expanded = !expanded"
+ >
+ {{
+ issues.length === 1
+ ? dialogs.fontIssueFound
+ : dialogs.fontIssuesFound({ count: issues.length })
+ }}
+ </button>
+ <button
+ type="button"
+ data-test-id="font-status-select"
+ class="shrink-0 rounded px-1.5 py-0.5 font-medium text-[var(--color-warning-action)] transition-colors hover:bg-amber-500/20"
+ @click="selectAffectedNodes"
+ >
+ {{ dialogs.selectAffectedLayers }}
+ </button>
+ <button
+ type="button"
+ data-test-id="font-status-retry"
+ class="shrink-0 rounded px-1.5 py-0.5 font-medium text-[var(--color-warning-action)] transition-colors hover:bg-amber-500/20 disabled:opacity-50"
+ :disabled="retrying"
+ @click="retry"
+ >
+ {{ retrying ? dialogs.retryingFonts : dialogs.retryFonts }}
+ </button>
+ <button
+ type="button"
+ :aria-label="expanded ? dialogs.collapseFontIssues : dialogs.expandFontIssues"
+ class="flex size-5 shrink-0 items-center justify-center rounded hover:bg-amber-500/20"
+ @click="expanded = !expanded"
+ >
+ <icon-lucide-chevron-up v-if="expanded" class="size-3.5" />
+ <icon-lucide-chevron-down v-else class="size-3.5" />
+ </button>
+ </div>
+
+ <div v-if="expanded" class="grid gap-1 border-t border-[var(--color-warning-border)] px-3 py-2">
+ <div
+ v-for="issue in issues"
+ :key="`${issue.family}:${issue.style}`"
+ 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>
+ <template v-if="issue.substituteFamily"> → {{ issue.substituteFamily }} </template>
+ <template v-else>— {{ dialogs.noFontSubstitute }}</template>
+ </span>
+ <span class="shrink-0 text-[10px] opacity-75">
+ {{
+ issue.nodeIds.length === 1
+ ? dialogs.affectedLayer
+ : dialogs.affectedLayerCount({ count: issue.nodeIds.length })
+ }}
+ </span>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/src/views/EditorView.vue b/src/views/EditorView.vue
index b51e17517..028432c43 100644
--- a/src/views/EditorView.vue
+++ b/src/views/EditorView.vue
@@ -20,6 +20,7 @@ import { createTab, activeTab, getActiveStore, tabCount } from '@/app/tabs'
import CollabPanel from '@/components/CollabPanel/CollabPanel.vue'
import EditorCanvas from '@/components/EditorCanvas.vue'
+import FontStatusBanner from '@/components/font-status/FontStatusBanner.vue'
import LayersPanel from '@/components/LayersPanel.vue'
import MobileDrawer from '@/components/MobileDrawer.vue'
import MobileHud from '@/components/MobileHud/MobileHud.vue'
@@ -111,6 +112,7 @@ onUnmounted(() => {
<template>
<div data-test-id="editor-root" class="flex h-screen w-screen flex-col">
<SafariBanner />
+ <FontStatusBanner />
<RenameSelectionDialog />
<TabBar />
diff --git a/tests/e2e/fonts/settings.spec.ts b/tests/e2e/fonts/settings.spec.ts
index afb3e8281..e88a0b5d3 100644
--- a/tests/e2e/fonts/settings.spec.ts
+++ b/tests/e2e/fonts/settings.spec.ts
@@ -25,6 +25,19 @@ test('font settings popover exposes web font access without desktop-only cache a
await expect(
typography.getByRole('img', { name: /Missing font: Missing Test Sans/ })
).toBeVisible()
+ const fontBanner = page.getByTestId('font-status-banner')
+ await expect(fontBanner).toContainText('1 font face is unavailable or substituted')
+ await page.getByTestId('font-status-toggle').click()
+ await expect(page.getByTestId('font-status-issue')).toContainText(
+ 'Missing Test Sans Regular → Inter'
+ )
+ await page.getByTestId('font-status-select').click()
+ await expect(page.getByTestId('font-status-banner')).toBeVisible()
+ const selected = await page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ return store ? [...store.state.selectedIds] : []
+ })
+ expect(selected).toHaveLength(1)
const fontSettings = page.getByRole('button', { name: 'Font settings' })
await expect(fontSettings).toHaveAttribute('data-test-id', 'font-settings-trigger')
await fontSettings.hover()
diff --git a/tests/engine/text/fonts/status.test.ts b/tests/engine/text/fonts/status.test.ts
new file mode 100644
index 000000000..f020c39ca
--- /dev/null
+++ b/tests/engine/text/fonts/status.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FontManager, SceneGraph, documentFontStatus } from '@open-pencil/core'
+
+function pageId(graph: SceneGraph): string {
+ return graph.getPages()[0].id
+}
+
+describe('documentFontStatus', () => {
+ test('reports loaded faces and their source without false warnings', () => {
+ const graph = new SceneGraph()
+ const manager = new FontManager()
+ manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')
+ graph.createNode('TEXT', pageId(graph), {
+ name: 'Title',
+ text: 'Hello',
+ fontFamily: 'Inter',
+ fontWeight: 400
+ })
+
+ expect(documentFontStatus(graph, pageId(graph), manager)).toEqual({
+ faithful: true,
+ faces: [
+ {
+ family: 'Inter',
+ style: 'Regular',
+ status: 'available',
+ source: 'bundled',
+ substituteFamily: null,
+ nodeIds: [expect.any(String)],
+ nodeNames: ['Title']
+ }
+ ],
+ issues: []
+ })
+ })
+
+ test('reports the active default-family substitution for missing faces', () => {
+ const graph = new SceneGraph()
+ const manager = new FontManager()
+ manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')
+ const node = graph.createNode('TEXT', pageId(graph), {
+ name: 'Unavailable label',
+ text: 'Hello',
+ fontFamily: 'Missing Sans',
+ fontWeight: 400
+ })
+
+ const status = documentFontStatus(graph, pageId(graph), manager)
+
+ expect(status.faithful).toBe(false)
+ expect(status.issues).toEqual([
+ {
+ family: 'Missing Sans',
+ style: 'Regular',
+ status: 'substituted',
+ source: null,
+ substituteFamily: 'Inter',
+ nodeIds: [node.id],
+ nodeNames: ['Unavailable label']
+ }
+ ])
+ })
+
+ test('reports synthesized styles and style-run faces separately', () => {
+ const graph = new SceneGraph()
+ const manager = new FontManager()
+ manager.markLoaded('Example Sans', 'Regular', new ArrayBuffer(8), 'local')
+ const node = graph.createNode('TEXT', pageId(graph), {
+ name: 'Mixed text',
+ text: 'Bold and serif',
+ fontFamily: 'Example Sans',
+ fontWeight: 700,
+ styleRuns: [
+ {
+ start: 9,
+ length: 5,
+ style: { fontFamily: 'Missing Serif', fontWeight: 400 }
+ }
+ ]
+ })
+
+ const status = documentFontStatus(graph, pageId(graph), manager)
+
+ expect(status.issues).toEqual([
+ {
+ family: 'Example Sans',
+ style: 'Bold',
+ status: 'substituted',
+ source: null,
+ substituteFamily: 'Example Sans',
+ nodeIds: [node.id],
+ nodeNames: ['Mixed text']
+ },
+ {
+ family: 'Missing Serif',
+ style: 'Regular',
+ status: 'unresolved',
+ source: null,
+ substituteFamily: null,
+ nodeIds: [node.id],
+ nodeNames: ['Mixed text']
+ }
+ ])
+ })
+})
diff --git a/tests/engine/text/resolver.test.ts b/tests/engine/text/resolver.test.ts
index ecd73c3ac..e6c92b625 100644
--- a/tests/engine/text/resolver.test.ts
+++ b/tests/engine/text/resolver.test.ts
@@ -98,6 +98,22 @@ describe('FontResolver', () => {
expect(resolver.pendingNodeIds(demand)).toEqual([])
})
+ test('notifies subscribers when resolution starts, settles, and resets', async () => {
+ const resolver = new FontResolver(async () => true)
+ const demand = { key: 'observed', candidates: [candidate('local')] }
+ const events: string[] = []
+ const unsubscribe = resolver.subscribe((event, snapshot) => {
+ events.push(`${event}:${snapshot.state}`)
+ })
+
+ await resolver.demand(demand)
+ resolver.reset(demand)
+ unsubscribe()
+ await resolver.demand({ key: 'ignored', candidates: [candidate('local')] })
+
+ expect(events).toEqual(['started:loading', 'settled:loaded', 'reset:idle'])
+ })
+
test('exhausts after every candidate is unavailable', async () => {
const resolver = new FontResolver(async () => false)
const demand = faceDemand()
diff --git a/tests/engine/tools/read.test.ts b/tests/engine/tools/read.test.ts
index 111d6adeb..5b54824ed 100644
--- a/tests/engine/tools/read.test.ts
+++ b/tests/engine/tools/read.test.ts
@@ -112,6 +112,36 @@ describe('query_nodes', () => {
})
})
+describe('get_font_status', () => {
+ test('returns font fidelity diagnostics for agents', () => {
+ const { figma } = setupToolTest()
+ const text = figma.createText()
+ text.name = 'Missing label'
+ text.fontName = { family: 'Unavailable Sans', style: 'Regular' }
+
+ const tool = getTool('get_font_status')
+ const result = tool.execute(figma, {}) as {
+ faithful: boolean
+ issues: Array<{
+ family: string
+ style: string
+ status: string
+ nodeIds: string[]
+ }>
+ }
+
+ expect(result.faithful).toBe(false)
+ expect(result.issues).toEqual([
+ expect.objectContaining({
+ family: 'Unavailable Sans',
+ style: 'Regular',
+ status: 'unresolved',
+ nodeIds: [text.id]
+ })
+ ])
+ })
+})
+
describe('get_node', () => {
test('returns node details', () => {
const { figma } = setupToolTest()