Skip to content

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

refactor(core): centralize font loading

Danila Poyarkov9c11c5b0756f
diff --git a/packages/core/src/canvas/renderer/fonts.ts b/packages/core/src/canvas/renderer/fonts.ts
index 0b598ed9c..b2de4f51f 100644
--- a/packages/core/src/canvas/renderer/fonts.ts
+++ b/packages/core/src/canvas/renderer/fonts.ts
@@ -6,6 +6,7 @@ import {
SECTION_TITLE_FONT_SIZE,
SIZE_FONT_SIZE
} from '#core/constants'
+import { fontManager } from '#core/text/fonts'
import type { SkiaRenderer } from '#core/canvas/renderer'
import type { SceneGraph } from '#core/scene-graph'
@@ -19,12 +20,9 @@ export async function loadFonts(r: SkiaRenderer): Promise<void> {
r.fontProvider?.delete()
r.fontProvider = r.ck.TypefaceFontProvider.Make()
- const { initFontService, loadFont, ensureArabicFallback, ensureCJKFallback } =
- await import('#core/text/fonts')
- if (r.isDestroyed()) return
- initFontService(r.ck, r.fontProvider)
+ fontManager.attachProvider(r.ck, r.fontProvider)
- const fontData = await loadFont(DEFAULT_FONT_FAMILY, 'Regular')
+ const fontData = await fontManager.loadFont(DEFAULT_FONT_FAMILY, 'Regular')
if (r.isDestroyed()) return
if (fontData) {
r.fontProvider.registerFont(fontData, DEFAULT_FONT_FAMILY)
@@ -48,10 +46,10 @@ export async function loadFonts(r: SkiaRenderer): Promise<void> {
r.fontsLoaded = true
r.invalidateAllPictures()
- void ensureCJKFallback().then((families) => {
+ void fontManager.ensureCJKFallback().then((families) => {
if (!r.isDestroyed() && families.length > 0) r.invalidateAllPictures()
})
- void ensureArabicFallback().then((families) => {
+ void fontManager.ensureArabicFallback().then((families) => {
if (!r.isDestroyed() && families.length > 0) r.invalidateAllPictures()
})
}
@@ -62,14 +60,13 @@ export async function prepareForExport(
pageId: string,
nodeIds: string[]
): Promise<() => void> {
- const { collectFontKeys, loadFont } = await import('#core/text/fonts')
const { getTextMeasurer, setTextMeasurer, computeAllLayouts } = await import('#core/layout')
const previousTextMeasurer = getTextMeasurer()
setTextMeasurer((node, maxWidth) => r.measureTextNode(node, maxWidth))
- const fontKeys = collectFontKeys(graph, nodeIds)
- await Promise.all(fontKeys.map(([family, style]) => loadFont(family, style)))
+ const fontKeys = fontManager.collectFontKeys(graph, nodeIds)
+ await Promise.all(fontKeys.map(([family, style]) => fontManager.loadFont(family, style)))
computeAllLayouts(graph, pageId)
diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.ts
index f2b894cbc..d97dadd63 100644
--- a/packages/core/src/canvas/renderer/lifecycle.ts
+++ b/packages/core/src/canvas/renderer/lifecycle.ts
@@ -1,4 +1,4 @@
-import { resetFontService } from '#core/text/fonts'
+import { fontManager } from '#core/text/fonts'
import type { SkiaRenderer } from '#core/canvas/renderer'
@@ -29,7 +29,7 @@ export function destroyRenderer(r: SkiaRenderer): void {
fontProvider?.delete()
r.fontProvider = null
r.fontsLoaded = false
- resetFontService(fontProvider)
+ fontManager.detachProvider(fontProvider)
r.rulerBgPaint.delete()
r.rulerTickPaint.delete()
r.rulerTextPaint.delete()
diff --git a/packages/core/src/canvas/text.ts b/packages/core/src/canvas/text.ts
index 1ce294834..b33f55bac 100644
--- a/packages/core/src/canvas/text.ts
+++ b/packages/core/src/canvas/text.ts
@@ -2,12 +2,7 @@ import { getCanvasKit } from '#core/canvaskit'
import { resolveRGBAForPreview } from '#core/color/management'
import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'
import { resolveNodeTextDirection } from '#core/text/direction'
-import {
- getArabicFallbackFamilies,
- getCJKFallbackFamilies,
- getFontProvider,
- isFontLoaded
-} from '#core/text/fonts'
+import { fontManager } from '#core/text/fonts'
import type { SceneNode } from '#core/scene-graph'
import type { CanvasKit, FontWeight, Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'
@@ -41,7 +36,7 @@ export function isNodeFontLoaded(_r: TextRenderer, node: SceneNode): boolean {
for (const run of node.styleRuns) {
if (run.style.fontFamily) families.add(run.style.fontFamily)
}
- return [...families].every((f) => isFontLoaded(f))
+ return [...families].every((f) => fontManager.isLoaded(f))
}
export function measureTextNode(
@@ -195,8 +190,8 @@ export function buildParagraph(
const ck = r.ck
const baseColor = color ?? ck.BLACK
const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE
- const cjkFallbacks = getCJKFallbackFamilies()
- const arabicFallbacks = getArabicFallbackFamilies()
+ const cjkFallbacks = fontManager.getCJKFallbackFamilies()
+ const arabicFallbacks = fontManager.getArabicFallbackFamilies()
const textDirection = resolveNodeTextDirection(node)
const truncateOpts = buildTruncateOpts(node, baseFontSize)
@@ -250,7 +245,7 @@ export function buildParagraph(
export async function shapeTextForClipboard(node: SceneNode): Promise<ClipboardShapedText | null> {
const ck = await getCanvasKit()
- const fontProvider = getFontProvider()
+ const fontProvider = fontManager.provider()
if (!fontProvider) return null
const paragraph = buildParagraph({ ck, fontProvider, fontsLoaded: true }, node)
diff --git a/packages/core/src/editor/clipboard/fonts.ts b/packages/core/src/editor/clipboard/fonts.ts
index a61fd2e96..dbc41aaaa 100644
--- a/packages/core/src/editor/clipboard/fonts.ts
+++ b/packages/core/src/editor/clipboard/fonts.ts
@@ -1,11 +1,11 @@
import { computeAllLayouts } from '#core/layout'
-import { collectFontKeys } from '#core/text/fonts'
+import { fontManager } from '#core/text/fonts'
import type { EditorContext } from '#core/editor/types'
export function createClipboardFontActions(ctx: EditorContext) {
async function loadFontsForNodes(nodeIds: string[]) {
- const toLoad = collectFontKeys(ctx.graph, nodeIds)
+ const toLoad = fontManager.collectFontKeys(ctx.graph, nodeIds)
if (toLoad.length === 0) return []
const results = await Promise.all(toLoad.map(([family, style]) => ctx.loadFont(family, style)))
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 1db9056e1..37fb0c0cd 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -4,7 +4,7 @@ import { setTextMeasurer } from '#core/layout'
import { SceneGraph } from '#core/scene-graph'
import { UndoManager } from '#core/scene-graph/undo'
import { TextEditor } from '#core/text/editor'
-import { loadFont as defaultLoadFont } from '#core/text/fonts'
+import { fontManager } from '#core/text/fonts'
import { createAlignmentActions } from './alignment'
import { createClipboardBridge } from './bridges/clipboard'
@@ -39,7 +39,7 @@ export function createEditor(options?: EditorOptions) {
let _graph = options?.graph ?? new SceneGraph()
const skipInitialGraphSetup = options?.skipInitialGraphSetup ?? false
const undo = new UndoManager()
- const _loadFont = options?.loadFont ?? defaultLoadFont
+ const _loadFont = options?.loadFont ?? fontManager.loadFont.bind(fontManager)
const _getViewportSize =
options?.getViewportSize ??
(() => {
diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.ts
index cccdf5977..7b4a7100b 100644
--- a/packages/core/src/editor/pages.ts
+++ b/packages/core/src/editor/pages.ts
@@ -1,5 +1,5 @@
import { computeAllLayouts } from '#core/layout'
-import { collectFontKeys } from '#core/text/fonts'
+import { fontManager } from '#core/text/fonts'
import { createPageViewportStore } from './page-viewports'
@@ -21,7 +21,7 @@ export function createPageActions(ctx: EditorContext) {
pageViewportStore.restorePageViewport(pageId)
- const toLoad = collectFontKeys(
+ const toLoad = fontManager.collectFontKeys(
ctx.graph,
ctx.graph.getChildren(pageId).map((n) => n.id)
)
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 4b363f476..afb0e0a6f 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -164,28 +164,15 @@ export {
} from './text/direction'
export {
FONT_WEIGHT_NAMES,
- collectFontKeys,
- loadFont,
- listFamilies,
- initFontService,
- getFontProvider,
- isFontLoaded,
- getLoadedFontData,
- markFontLoaded,
- ensureNodeFont,
- ensureCJKFallback,
- ensureArabicFallback,
- getCJKFallbackFamily,
- getCJKFallbackFamilies,
- getArabicFallbackFamilies,
- setCJKFallbackFamily,
- setArabicFallbackFamily,
+ FontManager,
+ fontManager,
styleToWeight,
weightToStyle,
normalizeFontFamily,
isVariableFont,
styleToVariant,
- fetchBundledFont
+ type FontInfo,
+ type LocalFontAccessState
} from './text/fonts'
export {
parseColor,
diff --git a/packages/core/src/kiwi/node-change/font-digests.ts b/packages/core/src/kiwi/node-change/font-digests.ts
index 05432f28c..bf4cb373d 100644
--- a/packages/core/src/kiwi/node-change/font-digests.ts
+++ b/packages/core/src/kiwi/node-change/font-digests.ts
@@ -1,4 +1,4 @@
-import { getLoadedFontData, weightToStyle } from '#core/text/fonts'
+import { fontManager, weightToStyle } from '#core/text/fonts'
import type { SceneGraph } from '#core/scene-graph'
@@ -16,7 +16,7 @@ async function getFontDigest(family: string, style: string): Promise<Uint8Array
const key = `${family}|${style}`
const cached = fontDigestCache.get(key)
if (cached) return cached
- const data = getLoadedFontData(family, style)
+ const data = fontManager.loadedData(family, style)
if (!data) return null
const digest = await computeFontDigest(data)
fontDigestCache.set(key, digest)
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.ts
index c615b59d1..fbfd8ec0c 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/fonts.ts
@@ -18,52 +18,9 @@ export interface FontInfo {
postscriptName: string
}
-const loadedFamilies = new Map<string, ArrayBuffer>()
-let fontProvider: TypefaceFontProvider | null = null
-
-export function initFontService(_canvasKit: CanvasKit, provider: TypefaceFontProvider) {
- fontProvider = provider
- for (const [cacheKey, data] of loadedFamilies) {
- const family = cacheKey.slice(0, cacheKey.indexOf('|'))
- registerFontInCanvasKit(family, data)
- }
-}
-
-export function getFontProvider(): TypefaceFontProvider | null {
- return fontProvider
-}
+export type LocalFontAccessState = 'unsupported' | 'prompt' | 'granted' | 'denied'
-export function resetFontService(provider?: TypefaceFontProvider | null): void {
- if (!provider || fontProvider === provider) fontProvider = null
-}
-
-async function queryFonts(): Promise<FontInfo[]> {
- if (!IS_BROWSER || !window.queryLocalFonts) 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
- })
- }
- return result
- } catch {
- return []
- }
-}
-
-export async function listFamilies(): Promise<string[]> {
- const fonts = await queryFonts()
- return [...new Set(fonts.map((f) => f.family))].sort()
-}
+type FindLocalFontOptions = { allowVariable?: boolean }
const BUNDLED_FONTS: Record<string, string> = {
'Inter|Regular': '/Inter-Regular.ttf',
@@ -72,49 +29,22 @@ const BUNDLED_FONTS: Record<string, string> = {
'Noto Naskh Arabic|Regular': '/NotoNaskhArabic-Regular.ttf'
}
-const googleFontsCache = new Map<string, Record<string, string>>()
-const googleFontsFailed = new Set<string>()
+export const FONT_WEIGHT_NAMES: Record<number, string> = {
+ 100: 'Thin',
+ 200: 'Extra Light',
+ 300: 'Light',
+ 400: 'Regular',
+ 500: 'Medium',
+ 600: 'Semi Bold',
+ 700: 'Bold',
+ 800: 'Extra Bold',
+ 900: 'Black'
+}
export function normalizeFontFamily(family: string): string {
return family.replace(/\s+(Variable|\d+(?:pt|px|em))$/i, '')
}
-async function retryWithNormalizedFamily(family: string): Promise<Record<string, string> | null> {
- const normalized = normalizeFontFamily(family)
- if (normalized === family) {
- googleFontsFailed.add(family)
- return null
- }
- const result = await fetchGoogleFontFiles(normalized)
- if (result) googleFontsCache.set(family, result)
- else googleFontsFailed.add(family)
- return result
-}
-
-async function fetchGoogleFontFiles(family: string): Promise<Record<string, string> | null> {
- if (googleFontsCache.has(family)) return googleFontsCache.get(family) ?? null
- if (googleFontsFailed.has(family)) return null
-
- const url = `https://www.googleapis.com/webfonts/v1/webfonts?family=${encodeURIComponent(family)}&key=${GOOGLE_FONTS_API_KEY}`
- let response: Response
- try {
- response = await fetch(url)
- } catch {
- googleFontsFailed.add(family)
- return null
- }
- if (!response.ok) return retryWithNormalizedFamily(family)
-
- const data = (await response.json()) as {
- items?: Array<{ files?: Record<string, string> }>
- }
- const files = data.items?.[0]?.files
- if (!files) return retryWithNormalizedFamily(family)
-
- googleFontsCache.set(family, files)
- return files
-}
-
export function styleToVariant(style: string): string {
const weight = styleToWeight(style)
const italic = style.toLowerCase().includes('italic')
@@ -123,108 +53,6 @@ export function styleToVariant(style: string): string {
return italic ? `${weight}italic` : `${weight}`
}
-async function fetchGoogleFont(family: string, style: string): Promise<ArrayBuffer | null> {
- const files = await fetchGoogleFontFiles(family)
- if (!files) return null
-
- const variant = styleToVariant(style)
- const ttfUrl = files[variant] ?? files['regular']
- if (!ttfUrl) return null
-
- const response = await fetch(ttfUrl)
- if (!response.ok) return null
-
- return response.arrayBuffer()
-}
-
-type FindLocalFontOptions = { allowVariable?: boolean }
-
-async function findLocalFont(
- family: string,
- style?: string,
- options: FindLocalFontOptions = {}
-): Promise<ArrayBuffer | null> {
- if (!IS_BROWSER || !window.queryLocalFonts) return null
- try {
- const fonts = await window.queryLocalFonts()
- const families = [family]
- const normalized = normalizeFontFamily(family)
- if (normalized !== family) families.push(normalized)
-
- let match: (typeof fonts)[number] | undefined
- for (const f of families) {
- match = style ? fonts.find((x) => x.family === f && x.style === style) : undefined
- match ??= fonts.find((x) => x.family === f)
- if (match) break
- }
-
- if (!match) return null
- const blob: Blob = await match.blob()
- const buffer = await blob.arrayBuffer()
- // Variable fonts (fvar table) can skew weight for Latin UI fonts. CJK system
- // faces (e.g. Microsoft YaHei) are often variable — still prefer them over
- // missing glyphs (tofu) when explicitly loading CJK fallbacks.
- if (!options.allowVariable && isVariableFont(buffer)) return null
- return buffer
- } catch (e) {
- console.warn(`Local font access failed for "${family}" ${style ?? ''}:`, e)
- return null
- }
-}
-
-export async function fetchBundledFont(url: string): Promise<ArrayBuffer | null> {
- if (IS_BROWSER) {
- const response = await fetch(url)
- return response.arrayBuffer()
- }
- const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')
- const { fileURLToPath } = await import(/* @vite-ignore */ 'node:url')
- const assetPath = fileURLToPath(new URL(`../../assets${url}`, import.meta.url))
- const buf = await readFile(assetPath)
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
-}
-
-function registerAndCache(family: string, style: string, buffer: ArrayBuffer): ArrayBuffer | null {
- if (!registerFontInCanvasKit(family, buffer)) return null
- loadedFamilies.set(`${family}|${style}`, buffer)
- registerFontInBrowser(family, style, buffer)
- return buffer
-}
-
-export async function loadFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {
- const cacheKey = `${family}|${style}`
- if (loadedFamilies.has(cacheKey)) {
- const cached = loadedFamilies.get(cacheKey)
- if (!cached) return null
- registerFontInCanvasKit(family, cached)
- return cached
- }
-
- const localBuffer = await findLocalFont(family, style)
- if (localBuffer) return registerAndCache(family, style, localBuffer)
-
- if (typeof fetch !== 'undefined') {
- try {
- const buffer = await fetchGoogleFont(family, style)
- if (buffer) return registerAndCache(family, style, buffer)
- } catch (e) {
- console.warn(`Google Fonts fetch failed for "${family}" ${style}:`, e)
- }
- }
-
- const bundledUrl = BUNDLED_FONTS[cacheKey]
- if (bundledUrl) {
- try {
- const buffer = await fetchBundledFont(bundledUrl)
- if (buffer && !isVariableFont(buffer)) return registerAndCache(family, style, buffer)
- } catch (e) {
- console.warn(`Bundled font load failed for "${family}" ${style}:`, e)
- }
- }
-
- return null
-}
-
export function isVariableFont(data: ArrayBuffer): boolean {
if (data.byteLength < 12) return false
const view = new DataView(data)
@@ -241,32 +69,6 @@ export function isVariableFont(data: ArrayBuffer): boolean {
return false
}
-function registerFontInCanvasKit(family: string, data: ArrayBuffer): boolean {
- if (!fontProvider || data.byteLength < 4) return false
- try {
- fontProvider.registerFont(data, family)
- return true
- } catch {
- return false
- }
-}
-
-function registerFontInBrowser(family: string, style: string, data: ArrayBuffer) {
- if (!IS_BROWSER) return
- const weight = styleToWeight(style)
- const italic = style.toLowerCase().includes('italic') ? 'italic' : 'normal'
- const face = new FontFace(family, data, {
- weight: String(weight),
- style: italic
- })
- face
- .load()
- .then(() => document.fonts.add(face))
- .catch(() => {
- console.warn(`Failed to load font "${family}" (${style})`)
- })
-}
-
export function styleToWeight(style: string): number {
const s = style.toLowerCase().replace(/[\s-_]/g, '')
if (s.includes('thin') || s.includes('hairline')) return 100
@@ -280,164 +82,371 @@ export function styleToWeight(style: string): number {
return 400
}
-export async function ensureNodeFont(family: string, weight: number): Promise<void> {
- const style = weightToStyle(weight)
- await loadFont(family, style)
+export function weightToStyle(weight: number, italic = false): string {
+ const rounded = Math.round(weight / 100) * 100
+ const label = (FONT_WEIGHT_NAMES[rounded] ?? 'Regular').replace(/ /g, '')
+ return italic ? `${label} Italic` : label
}
-export function markFontLoaded(family: string, style: string, data: ArrayBuffer): void {
- const cacheKey = `${family}|${style}`
- loadedFamilies.set(cacheKey, data)
- registerFontInCanvasKit(family, data)
+function getCJKCandidates(): string[] {
+ if (typeof navigator === 'undefined') return [...CJK_FALLBACK_FAMILIES_LINUX]
+ const ua = navigator.userAgent
+ if (ua.includes('Mac')) return CJK_FALLBACK_FAMILIES_MACOS
+ if (ua.includes('Windows')) return CJK_FALLBACK_FAMILIES_WINDOWS
+ return CJK_FALLBACK_FAMILIES_LINUX
}
-export function isFontLoaded(family: string): boolean {
- return [...loadedFamilies.keys()].some((k) => k.startsWith(`${family}|`))
-}
+export class FontManager {
+ private loadedFamilies = new Map<string, ArrayBuffer>()
+ private fontProvider: TypefaceFontProvider | null = null
+ private localFonts: FontInfo[] | null = null
+ private localFontAccessState: LocalFontAccessState = IS_BROWSER ? 'prompt' : 'unsupported'
+ private googleFontsCache = new Map<string, Record<string, string>>()
+ private googleFontsFailed = new Set<string>()
+ private cjkFallbackFamilies: string[] = []
+ private cjkFallbackPromise: Promise<string[]> | null = null
+ private arabicFallbackFamilies: string[] = []
+ private arabicFallbackPromise: Promise<string[]> | null = null
+
+ attachProvider(_canvasKit: CanvasKit, provider: TypefaceFontProvider): void {
+ this.fontProvider = provider
+ for (const [cacheKey, data] of this.loadedFamilies) {
+ const family = cacheKey.slice(0, cacheKey.indexOf('|'))
+ this.registerFontInCanvasKit(family, data)
+ }
+ }
-export function getLoadedFontData(family: string, style: string): ArrayBuffer | null {
- return loadedFamilies.get(`${family}|${style}`) ?? null
-}
+ detachProvider(provider?: TypefaceFontProvider | null): void {
+ if (!provider || this.fontProvider === provider) this.fontProvider = null
+ }
-export function collectFontKeys(graph: SceneGraph, nodeIds: string[]): Array<[string, string]> {
- const fontKeys = new Set<string>()
- const collect = (id: string) => {
- const node = graph.getNode(id)
- 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 f = run.style.fontFamily ?? family
- const w = run.style.fontWeight ?? node.fontWeight
- const i = run.style.italic ?? node.italic
- fontKeys.add(`${f}\0${weightToStyle(w, i)}`)
+ provider(): TypefaceFontProvider | null {
+ return this.fontProvider
+ }
+
+ localAccessState(): LocalFontAccessState {
+ return this.localFontAccessState
+ }
+
+ 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'
+ return result
+ } catch {
+ this.localFonts = []
+ this.localFontAccessState = 'denied'
+ return []
}
- for (const childId of node.childIds) collect(childId)
}
- for (const id of nodeIds) collect(id)
- return [...fontKeys].map((k) => k.split('\0') as [string, string])
-}
+ async listFamilies(): Promise<string[]> {
+ const fonts = this.localFonts ?? (await this.requestLocalFontAccess())
+ return [...new Set(fonts.map((f) => f.family))].sort()
+ }
-const cjkFallbackFamilies: string[] = []
-let cjkFallbackPromise: Promise<string[]> | null = null
-const arabicFallbackFamilies: string[] = []
-let arabicFallbackPromise: Promise<string[]> | null = null
+ async fetchBundledFont(url: string): Promise<ArrayBuffer | null> {
+ if (IS_BROWSER) {
+ const response = await fetch(url)
+ return response.arrayBuffer()
+ }
+ const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')
+ const { fileURLToPath } = await import(/* @vite-ignore */ 'node:url')
+ const assetPath = fileURLToPath(new URL(`../../assets${url}`, import.meta.url))
+ const buf = await readFile(assetPath)
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
+ }
-function getCJKCandidates(): string[] {
- if (typeof navigator === 'undefined') return [...CJK_FALLBACK_FAMILIES_LINUX]
- const ua = navigator.userAgent
- if (ua.includes('Mac')) return CJK_FALLBACK_FAMILIES_MACOS
- if (ua.includes('Windows')) return CJK_FALLBACK_FAMILIES_WINDOWS
- return CJK_FALLBACK_FAMILIES_LINUX
-}
+ async loadFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {
+ const cacheKey = `${family}|${style}`
+ if (this.loadedFamilies.has(cacheKey)) {
+ const cached = this.loadedFamilies.get(cacheKey)
+ if (!cached) return null
+ this.registerFontInCanvasKit(family, cached)
+ return cached
+ }
-export async function ensureCJKFallback(): Promise<string[]> {
- if (cjkFallbackFamilies.length > 0) return cjkFallbackFamilies
- if (cjkFallbackPromise) return cjkFallbackPromise
+ const localBuffer = await this.findLocalFont(family, style)
+ if (localBuffer) return this.registerAndCache(family, style, localBuffer)
- cjkFallbackPromise = (async () => {
- // Try local system fonts first (allow variable fonts — common for 微软雅黑 / PingFang).
- for (const family of getCJKCandidates()) {
- const buffer = await findLocalFont(family, undefined, {
- allowVariable: true
- })
- if (buffer && registerAndCache(family, 'Regular', buffer)) {
- cjkFallbackFamilies.push(family)
+ if (typeof fetch !== 'undefined') {
+ try {
+ const buffer = await this.fetchGoogleFont(family, style)
+ if (buffer) return this.registerAndCache(family, style, buffer)
+ } catch (e) {
+ console.warn(`Google Fonts fetch failed for "${family}" ${style}:`, e)
}
}
- if (cjkFallbackFamilies.length === 0) {
- const results = await Promise.allSettled(
- CJK_GOOGLE_FONTS.map(async (family) => {
- const data = await loadFont(family, 'Regular')
- return data ? family : null
- })
- )
- for (const result of results) {
- if (result.status === 'fulfilled' && result.value) {
- cjkFallbackFamilies.push(result.value)
+ const bundledUrl = BUNDLED_FONTS[cacheKey]
+ if (bundledUrl) {
+ try {
+ const buffer = await this.fetchBundledFont(bundledUrl)
+ if (buffer && !isVariableFont(buffer)) return this.registerAndCache(family, style, buffer)
+ } catch (e) {
+ console.warn(`Bundled font load failed for "${family}" ${style}:`, e)
+ }
+ }
+
+ return null
+ }
+
+ async ensureNodeFont(family: string, weight: number): Promise<void> {
+ await this.loadFont(family, weightToStyle(weight))
+ }
+
+ markLoaded(family: string, style: string, data: ArrayBuffer): void {
+ this.loadedFamilies.set(`${family}|${style}`, data)
+ this.registerFontInCanvasKit(family, data)
+ }
+
+ isLoaded(family: string): boolean {
+ return [...this.loadedFamilies.keys()].some((k) => k.startsWith(`${family}|`))
+ }
+
+ loadedData(family: string, style: string): ArrayBuffer | null {
+ return this.loadedFamilies.get(`${family}|${style}`) ?? null
+ }
+
+ collectFontKeys(graph: SceneGraph, nodeIds: string[]): Array<[string, string]> {
+ const fontKeys = new Set<string>()
+ const collect = (id: string) => {
+ const node = graph.getNode(id)
+ 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 f = run.style.fontFamily ?? family
+ const w = run.style.fontWeight ?? node.fontWeight
+ const i = run.style.italic ?? node.italic
+ fontKeys.add(`${f}\0${weightToStyle(w, i)}`)
}
}
+ for (const childId of node.childIds) collect(childId)
}
+ for (const id of nodeIds) collect(id)
- return cjkFallbackFamilies
- })()
+ return [...fontKeys].map((k) => k.split('\0') as [string, string])
+ }
- return cjkFallbackPromise
-}
+ async ensureCJKFallback(): Promise<string[]> {
+ if (this.cjkFallbackFamilies.length > 0) return this.cjkFallbackFamilies
+ if (this.cjkFallbackPromise) return this.cjkFallbackPromise
-/** @deprecated Use getCJKFallbackFamilies() instead */
-export function getCJKFallbackFamily(): string | null {
- return cjkFallbackFamilies[0] ?? null
-}
+ this.cjkFallbackPromise = (async () => {
+ for (const family of getCJKCandidates()) {
+ const buffer = await this.findLocalFont(family, undefined, { allowVariable: true })
+ if (buffer && this.registerAndCache(family, 'Regular', buffer)) {
+ this.cjkFallbackFamilies.push(family)
+ }
+ }
-export function getCJKFallbackFamilies(): string[] {
- return cjkFallbackFamilies
-}
+ if (this.cjkFallbackFamilies.length === 0) {
+ const results = await Promise.allSettled(
+ CJK_GOOGLE_FONTS.map(async (family) => {
+ const data = await this.loadFont(family, 'Regular')
+ return data ? family : null
+ })
+ )
+ for (const result of results) {
+ if (result.status === 'fulfilled' && result.value) {
+ this.cjkFallbackFamilies.push(result.value)
+ }
+ }
+ }
+
+ return this.cjkFallbackFamilies
+ })()
-export function setCJKFallbackFamily(family: string): void {
- if (!cjkFallbackFamilies.includes(family)) {
- cjkFallbackFamilies.push(family)
+ return this.cjkFallbackPromise
}
-}
-export async function ensureArabicFallback(): Promise<string[]> {
- if (arabicFallbackFamilies.length > 0) return arabicFallbackFamilies
- if (arabicFallbackPromise) return arabicFallbackPromise
-
- arabicFallbackPromise = (async () => {
- for (const family of [
- 'Noto Naskh Arabic',
- 'Noto Sans Arabic',
- 'Geeza Pro',
- 'Arial',
- 'Tahoma',
- 'Amiri'
- ]) {
- const buffer = await findLocalFont(family)
- if (buffer && registerAndCache(family, 'Regular', buffer)) {
- arabicFallbackFamilies.push(family)
+ getCJKFallbackFamilies(): string[] {
+ return this.cjkFallbackFamilies
+ }
+
+ setCJKFallbackFamily(family: string): void {
+ if (!this.cjkFallbackFamilies.includes(family)) {
+ this.cjkFallbackFamilies.push(family)
+ }
+ }
+
+ async ensureArabicFallback(): Promise<string[]> {
+ if (this.arabicFallbackFamilies.length > 0) return this.arabicFallbackFamilies
+ if (this.arabicFallbackPromise) return this.arabicFallbackPromise
+
+ this.arabicFallbackPromise = (async () => {
+ for (const family of [
+ 'Noto Naskh Arabic',
+ 'Noto Sans Arabic',
+ 'Geeza Pro',
+ 'Arial',
+ 'Tahoma',
+ 'Amiri'
+ ]) {
+ const buffer = await this.findLocalFont(family)
+ if (buffer && this.registerAndCache(family, 'Regular', buffer)) {
+ this.arabicFallbackFamilies.push(family)
+ }
}
+
+ if (this.arabicFallbackFamilies.length === 0) {
+ const data = await this.loadFont('Noto Naskh Arabic', 'Regular')
+ if (data) this.arabicFallbackFamilies.push('Noto Naskh Arabic')
+ }
+
+ return this.arabicFallbackFamilies
+ })()
+
+ return this.arabicFallbackPromise
+ }
+
+ getArabicFallbackFamilies(): string[] {
+ return this.arabicFallbackFamilies
+ }
+
+ setArabicFallbackFamily(family: string): void {
+ if (!this.arabicFallbackFamilies.includes(family)) {
+ this.arabicFallbackFamilies.push(family)
}
+ }
- if (arabicFallbackFamilies.length === 0) {
- const data = await loadFont('Noto Naskh Arabic', 'Regular')
- if (data) arabicFallbackFamilies.push('Noto Naskh Arabic')
+ private async retryWithNormalizedFamily(family: string): Promise<Record<string, string> | null> {
+ const normalized = normalizeFontFamily(family)
+ if (normalized === family) {
+ this.googleFontsFailed.add(family)
+ return null
}
+ const result = await this.fetchGoogleFontFiles(normalized)
+ if (result) this.googleFontsCache.set(family, result)
+ else this.googleFontsFailed.add(family)
+ return result
+ }
- return arabicFallbackFamilies
- })()
+ private async fetchGoogleFontFiles(family: string): Promise<Record<string, string> | null> {
+ if (this.googleFontsCache.has(family)) return this.googleFontsCache.get(family) ?? null
+ if (this.googleFontsFailed.has(family)) return null
- return arabicFallbackPromise
-}
+ const url = `https://www.googleapis.com/webfonts/v1/webfonts?family=${encodeURIComponent(family)}&key=${GOOGLE_FONTS_API_KEY}`
+ let response: Response
+ try {
+ response = await fetch(url)
+ } catch {
+ this.googleFontsFailed.add(family)
+ return null
+ }
+ if (!response.ok) return this.retryWithNormalizedFamily(family)
-export function getArabicFallbackFamilies(): string[] {
- return arabicFallbackFamilies
-}
+ const data = (await response.json()) as {
+ items?: Array<{ files?: Record<string, string> }>
+ }
+ const files = data.items?.[0]?.files
+ if (!files) return this.retryWithNormalizedFamily(family)
-export function setArabicFallbackFamily(family: string): void {
- if (!arabicFallbackFamilies.includes(family)) {
- arabicFallbackFamilies.push(family)
+ this.googleFontsCache.set(family, files)
+ return files
}
-}
-export const FONT_WEIGHT_NAMES: Record<number, string> = {
- 100: 'Thin',
- 200: 'Extra Light',
- 300: 'Light',
- 400: 'Regular',
- 500: 'Medium',
- 600: 'Semi Bold',
- 700: 'Bold',
- 800: 'Extra Bold',
- 900: 'Black'
-}
+ private async fetchGoogleFont(family: string, style: string): Promise<ArrayBuffer | null> {
+ const files = await this.fetchGoogleFontFiles(family)
+ if (!files) return null
-export function weightToStyle(weight: number, italic = false): string {
- const rounded = Math.round(weight / 100) * 100
- const label = (FONT_WEIGHT_NAMES[rounded] ?? 'Regular').replace(/ /g, '')
- return italic ? `${label} Italic` : label
+ const variant = styleToVariant(style)
+ const ttfUrl = files[variant] ?? files['regular']
+ if (!ttfUrl) return null
+
+ const response = await fetch(ttfUrl)
+ if (!response.ok) return null
+
+ return response.arrayBuffer()
+ }
+
+ private async findLocalFont(
+ family: string,
+ style?: string,
+ options: FindLocalFontOptions = {}
+ ): Promise<ArrayBuffer | null> {
+ if (!IS_BROWSER || !window.queryLocalFonts) return null
+ try {
+ const fonts = await window.queryLocalFonts()
+ const families = [family]
+ const normalized = normalizeFontFamily(family)
+ if (normalized !== family) families.push(normalized)
+
+ let match: (typeof fonts)[number] | undefined
+ for (const f of families) {
+ match = style ? fonts.find((x) => x.family === f && x.style === style) : undefined
+ match ??= fonts.find((x) => x.family === f)
+ if (match) break
+ }
+
+ if (!match) return null
+ const blob: Blob = await match.blob()
+ const buffer = await blob.arrayBuffer()
+ if (!options.allowVariable && isVariableFont(buffer)) return null
+ return buffer
+ } catch (e) {
+ console.warn(`Local font access failed for "${family}" ${style ?? ''}:`, e)
+ return null
+ }
+ }
+
+ private registerAndCache(
+ family: string,
+ style: string,
+ buffer: ArrayBuffer
+ ): ArrayBuffer | null {
+ this.loadedFamilies.set(`${family}|${style}`, buffer)
+ this.registerFontInCanvasKit(family, buffer)
+ this.registerFontInBrowser(family, style, buffer)
+ return buffer
+ }
+
+ private registerFontInCanvasKit(family: string, data: ArrayBuffer): boolean {
+ if (!this.fontProvider || data.byteLength < 4) return false
+ try {
+ this.fontProvider.registerFont(data, family)
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ private registerFontInBrowser(family: string, style: string, data: ArrayBuffer) {
+ if (!IS_BROWSER) return
+ const weight = styleToWeight(style)
+ const italic = style.toLowerCase().includes('italic') ? 'italic' : 'normal'
+ const face = new FontFace(family, data, {
+ weight: String(weight),
+ style: italic
+ })
+ face
+ .load()
+ .then(() => document.fonts.add(face))
+ .catch(() => {
+ console.warn(`Failed to load font "${family}" (${style})`)
+ })
+ }
}
+
+export const fontManager = new FontManager()
diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.ts
index 62d232ee9..a3b610002 100644
--- a/packages/core/src/text/opentype.ts
+++ b/packages/core/src/text/opentype.ts
@@ -1,6 +1,6 @@
import * as OpenTypeSync from 'opentype.js'
-import { getLoadedFontData } from './fonts'
+import { fontManager } from './fonts'
interface OutlineCommand {
type: string
@@ -48,7 +48,7 @@ function getParsedFont(family: string, style: string): OutlineFont | null {
const key = `${family}|${style}`
const cached = parsedFontCache.get(key)
if (cached) return cached
- const bytes = getLoadedFontData(family, style)
+ const bytes = fontManager.loadedData(family, style)
if (!bytes) return null
const font = (OpenTypeSync as OpenTypeModule).parse(bytes.slice(0))
parsedFontCache.set(key, font)
@@ -112,7 +112,7 @@ export async function probeGlyphOutlineCommands(
text: string,
fontSize: number
): Promise<GlyphOutlineProbe | null> {
- const bytes = getLoadedFontData(family, style)
+ const bytes = fontManager.loadedData(family, style)
if (!bytes) return null
const font = (OpenTypeSync as OpenTypeModule).parse(bytes.slice(0))
diff --git a/packages/vue/src/primitives/FontPicker/useFontPicker.ts b/packages/vue/src/primitives/FontPicker/useFontPicker.ts
index a9de7ba5b..ea70f4c3b 100644
--- a/packages/vue/src/primitives/FontPicker/useFontPicker.ts
+++ b/packages/vue/src/primitives/FontPicker/useFontPicker.ts
@@ -1,5 +1,5 @@
import { useFilter } from 'reka-ui'
-import { computed, onMounted, ref, watch } from 'vue'
+import { computed, ref, watch } from 'vue'
/**
* Options for {@link useFontPicker}.
@@ -27,12 +27,12 @@ export function useFontPicker(options: UseFontPickerOptions) {
return families.value.filter((family) => contains(family, searchTerm.value))
})
- onMounted(async () => {
- families.value = await options.listFamilies()
- })
-
- watch(open, (isOpen) => {
- if (isOpen) searchTerm.value = ''
+ watch(open, async (isOpen) => {
+ if (!isOpen) return
+ searchTerm.value = ''
+ if (families.value.length === 0) {
+ families.value = await options.listFamilies()
+ }
})
function select(family: string) {
diff --git a/packages/vue/src/shared/font-status/use.ts b/packages/vue/src/shared/font-status/use.ts
index 4ef5f2615..82b2840a1 100644
--- a/packages/vue/src/shared/font-status/use.ts
+++ b/packages/vue/src/shared/font-status/use.ts
@@ -1,7 +1,7 @@
import { computed } from 'vue'
import { DEFAULT_FONT_FAMILY } from '@open-pencil/core/constants'
-import { isFontLoaded } from '@open-pencil/core/text'
+import { fontManager } from '@open-pencil/core/text'
import type { SceneNode } from '@open-pencil/core/scene-graph'
@@ -22,7 +22,7 @@ export function useNodeFontStatus(node: () => SceneNode | null | undefined) {
if (run.style.fontFamily) families.add(run.style.fontFamily)
}
- return [...families].filter((f) => !isFontLoaded(f))
+ return [...families].filter((f) => !fontManager.isLoaded(f))
})
const hasMissingFonts = computed(() => missingFonts.value.length > 0)
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.ts
index 8e9f54358..12bfea7ca 100644
--- a/src/app/ai/tools/index.ts
+++ b/src/app/ai/tools/index.ts
@@ -5,7 +5,7 @@ import * as v from 'valibot'
import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'
import { getActiveEditorStore } from '@/app/editor/active-store'
import { computeAllLayouts } from '@open-pencil/core/layout'
-import { collectFontKeys, isFontLoaded, loadFont } from '@open-pencil/core/text'
+import { fontManager } from '@open-pencil/core/text'
import { CORE_TOOLS, toolsToAI } from '@open-pencil/core/tools'
import type { EditorStore } from '@/app/editor/active-store'
@@ -100,11 +100,11 @@ export function createAITools(store: EditorStore) {
const pageId = store.state.currentPageId
const pageNode = store.graph.getNode(pageId)
if (pageNode) {
- const fontKeys = collectFontKeys(store.graph, pageNode.childIds)
- const missing = fontKeys.filter(([family]) => !isFontLoaded(family))
+ const fontKeys = fontManager.collectFontKeys(store.graph, pageNode.childIds)
+ const missing = fontKeys.filter(([family]) => !fontManager.isLoaded(family))
if (missing.length > 0) {
const results = await Promise.all(
- missing.map(([family, style]) => loadFont(family, style))
+ missing.map(([family, style]) => fontManager.loadFont(family, style))
)
if (results.some((r) => r !== null)) {
for (const [, node] of store.graph.nodes) {
diff --git a/src/app/editor/fonts.ts b/src/app/editor/fonts.ts
index 5a938957e..d3c208a03 100644
--- a/src/app/editor/fonts.ts
+++ b/src/app/editor/fonts.ts
@@ -1,5 +1,5 @@
import { IS_TAURI } from '@open-pencil/core/constants'
-import { loadFont as loadFontCore, markFontLoaded, styleToWeight } from '@open-pencil/core/text'
+import { fontManager, styleToWeight } from '@open-pencil/core/text'
interface TauriFontFamily {
family: string
@@ -7,7 +7,6 @@ interface TauriFontFamily {
}
let tauriFontsCache: TauriFontFamily[] | null = null
-
let tauriFontsPromise: Promise<TauriFontFamily[]> | null = null
async function getTauriFonts(): Promise<TauriFontFamily[]> {
@@ -43,9 +42,7 @@ export async function listFamilies(): Promise<string[]> {
const fonts = await getTauriFonts()
return fonts.map((f) => f.family)
}
-
- const { listFamilies: coreList } = await import('@open-pencil/core/text')
- return coreList()
+ return fontManager.listFamilies()
}
export async function listFonts(): Promise<TauriFontFamily[]> {
@@ -62,7 +59,7 @@ export async function loadFont(family: string, style = 'Regular'): Promise<Array
const data = await invoke<number[]>('load_system_font', { family, style })
const buffer = new Uint8Array(data).buffer
- markFontLoaded(family, style, buffer)
+ fontManager.markLoaded(family, style, buffer)
const weight = styleToWeight(style)
const italic = style.toLowerCase().includes('italic') ? 'italic' : 'normal'
@@ -72,9 +69,9 @@ export async function loadFont(family: string, style = 'Regular'): Promise<Array
return buffer
} catch {
- return loadFontCore(family, style)
+ return fontManager.loadFont(family, style)
}
}
- return loadFontCore(family, style)
+ return fontManager.loadFont(family, style)
}
diff --git a/tests/engine/clipboard-derived-text.test.ts b/tests/engine/clipboard-derived-text.test.ts
index 49c117a03..2c7507e4e 100644
--- a/tests/engine/clipboard-derived-text.test.ts
+++ b/tests/engine/clipboard-derived-text.test.ts
@@ -1,8 +1,7 @@
import { describe, expect, test } from 'bun:test'
import {
- fetchBundledFont,
- markFontLoaded,
+ fontManager,
SceneGraph,
buildFontDigestMap,
buildDerivedTextDataV4,
@@ -13,10 +12,10 @@ describe('clipboard derived text export', () => {
test('builds richer v4 derivedTextData from shaped text + glyph outlines', async () => {
await initCodec()
- const font = await fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
expect(font).toBeTruthy()
if (!font) return
- markFontLoaded('Inter', 'Regular', font)
+ fontManager.markLoaded('Inter', 'Regular', font)
const graph = new SceneGraph()
const page = graph.getPages()[0]
diff --git a/tests/engine/clipboard-text-outlines.test.ts b/tests/engine/clipboard-text-outlines.test.ts
index 7523f518c..25faa457a 100644
--- a/tests/engine/clipboard-text-outlines.test.ts
+++ b/tests/engine/clipboard-text-outlines.test.ts
@@ -1,14 +1,14 @@
import { describe, expect, test } from 'bun:test'
-import { fetchBundledFont, markFontLoaded, probeGlyphOutlineCommands } from '@open-pencil/core'
+import { fontManager, probeGlyphOutlineCommands } from '@open-pencil/core'
describe('clipboard text outline probe', () => {
test('lazy-loads opentype.js and extracts glyph commands from a loaded font', async () => {
- const font = await fetchBundledFont('/Inter-Regular.ttf')
+ const font = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
expect(font).toBeTruthy()
if (!font) return
- markFontLoaded('Inter', 'Regular', font)
+ fontManager.markLoaded('Inter', 'Regular', font)
const probe = await probeGlyphOutlineCommands('Inter', 'Regular', 'Hello', 16)
expect(probe).toBeTruthy()
diff --git a/tests/engine/fonts.test.ts b/tests/engine/fonts.test.ts
index 37bbe0c0c..d9ce8110d 100644
--- a/tests/engine/fonts.test.ts
+++ b/tests/engine/fonts.test.ts
@@ -1,17 +1,16 @@
import { describe, test, expect } from 'bun:test'
import {
- collectFontKeys,
- fetchBundledFont,
- isFontLoaded,
+ fontManager,
isVariableFont,
- markFontLoaded,
normalizeFontFamily,
styleToVariant,
styleToWeight,
weightToStyle,
+ FontManager,
SceneGraph
} from '@open-pencil/core'
+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'
function pageId(graph: SceneGraph) {
return graph.getPages()[0].id
@@ -60,19 +59,48 @@ describe('weightToStyle', () => {
})
})
-describe('markFontLoaded / isFontLoaded', () => {
+function createRecordingProvider() {
+ const registrations: Array<{ family: string; byteLength: number }> = []
+ const provider = {
+ registerFont(data: ArrayBuffer, family: string) {
+ registrations.push({ family, byteLength: data.byteLength })
+ }
+ } as unknown as TypefaceFontProvider
+ return { provider, registrations }
+}
+
+describe('FontManager loaded font cache', () => {
test('marks and checks font', () => {
const family = `TestFont_${Date.now()}`
- expect(isFontLoaded(family)).toBe(false)
- markFontLoaded(family, 'Regular', new ArrayBuffer(8))
- expect(isFontLoaded(family)).toBe(true)
+ expect(fontManager.isLoaded(family)).toBe(false)
+ fontManager.markLoaded(family, 'Regular', new ArrayBuffer(8))
+ expect(fontManager.isLoaded(family)).toBe(true)
})
test('different styles for same family', () => {
const family = `MultiStyle_${Date.now()}`
- expect(isFontLoaded(family)).toBe(false)
- markFontLoaded(family, 'Bold', new ArrayBuffer(8))
- expect(isFontLoaded(family)).toBe(true)
+ expect(fontManager.isLoaded(family)).toBe(false)
+ fontManager.markLoaded(family, 'Bold', new ArrayBuffer(8))
+ expect(fontManager.isLoaded(family)).toBe(true)
+ })
+
+ test('re-registers cached fonts when provider changes', () => {
+ const manager = new FontManager()
+ const canvasKit = {} as CanvasKit
+ const first = createRecordingProvider()
+ const second = createRecordingProvider()
+
+ manager.attachProvider(canvasKit, first.provider)
+ manager.markLoaded('ProviderLifecycle', 'Regular', new ArrayBuffer(12))
+ expect(first.registrations).toEqual([{ family: 'ProviderLifecycle', byteLength: 12 }])
+
+ manager.attachProvider(canvasKit, second.provider)
+ expect(second.registrations).toEqual([{ family: 'ProviderLifecycle', byteLength: 12 }])
+ manager.detachProvider(first.provider)
+ expect(manager.provider()).toBe(second.provider)
+
+ manager.detachProvider(second.provider)
+ expect(manager.provider()).toBeNull()
})
})
@@ -86,7 +114,7 @@ describe('collectFontKeys', () => {
width: 100,
height: 100
}).id
- expect(collectFontKeys(graph, [id])).toEqual([])
+ expect(fontManager.collectFontKeys(graph, [id])).toEqual([])
})
test('includes default font (Inter) in collected keys', () => {
@@ -101,7 +129,7 @@ describe('collectFontKeys', () => {
fontFamily: 'Inter',
fontWeight: 400
}).id
- expect(collectFontKeys(graph, [id])).toEqual([['Inter', 'Regular']])
+ expect(fontManager.collectFontKeys(graph, [id])).toEqual([['Inter', 'Regular']])
})
test('collects non-default font family', () => {
@@ -116,7 +144,7 @@ describe('collectFontKeys', () => {
fontFamily: 'Roboto',
fontWeight: 400
}).id
- const keys = collectFontKeys(graph, [id])
+ const keys = fontManager.collectFontKeys(graph, [id])
expect(keys).toEqual([['Roboto', 'Regular']])
})
@@ -132,7 +160,7 @@ describe('collectFontKeys', () => {
fontFamily: 'Roboto',
fontWeight: 700
}).id
- const keys = collectFontKeys(graph, [id])
+ const keys = fontManager.collectFontKeys(graph, [id])
expect(keys).toEqual([['Roboto', 'Bold']])
})
@@ -149,7 +177,7 @@ describe('collectFontKeys', () => {
fontWeight: 400,
italic: true
}).id
- const keys = collectFontKeys(graph, [id])
+ const keys = fontManager.collectFontKeys(graph, [id])
expect(keys).toEqual([['Roboto', 'Regular Italic']])
})
@@ -177,7 +205,7 @@ describe('collectFontKeys', () => {
fontWeight: 400
})
const ids = graph.getChildren(page).map((n) => n.id)
- const keys = collectFontKeys(graph, ids)
+ const keys = fontManager.collectFontKeys(graph, ids)
expect(keys).toEqual([['Roboto', 'Regular']])
})
@@ -205,7 +233,7 @@ describe('collectFontKeys', () => {
fontWeight: 700
})
const ids = graph.getChildren(page).map((n) => n.id)
- const keys = collectFontKeys(graph, ids)
+ const keys = fontManager.collectFontKeys(graph, ids)
expect(keys).toHaveLength(2)
expect(keys).toContainEqual(['Roboto', 'Regular'])
expect(keys).toContainEqual(['Open Sans', 'Bold'])
@@ -231,7 +259,7 @@ describe('collectFontKeys', () => {
fontFamily: 'Poppins',
fontWeight: 600
})
- const keys = collectFontKeys(graph, [frame])
+ const keys = fontManager.collectFontKeys(graph, [frame])
expect(keys).toEqual([['Poppins', 'SemiBold']])
})
@@ -259,7 +287,7 @@ describe('collectFontKeys', () => {
}
]
}).id
- const keys = collectFontKeys(graph, [id])
+ const keys = fontManager.collectFontKeys(graph, [id])
expect(keys).toHaveLength(2)
expect(keys).toContainEqual(['Roboto', 'Regular'])
expect(keys).toContainEqual(['Montserrat', 'Bold'])
@@ -284,13 +312,13 @@ describe('collectFontKeys', () => {
}
]
}).id
- const keys = collectFontKeys(graph, [id])
+ const keys = fontManager.collectFontKeys(graph, [id])
expect(keys).toEqual([['Lato', 'Light']])
})
test('skips invalid node IDs', () => {
const graph = new SceneGraph()
- expect(collectFontKeys(graph, ['nonexistent'])).toEqual([])
+ expect(fontManager.collectFontKeys(graph, ['nonexistent'])).toEqual([])
})
})
@@ -413,19 +441,19 @@ describe('isVariableFont', () => {
describe('fetchBundledFont', () => {
test('loads Inter-Regular.ttf from assets in headless', async () => {
- const buffer = await fetchBundledFont('/Inter-Regular.ttf')
+ const buffer = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
expect(buffer).toBeInstanceOf(ArrayBuffer)
expect(buffer!.byteLength).toBeGreaterThan(100_000)
})
test('returns valid TTF data', async () => {
- const buffer = await fetchBundledFont('/Inter-Regular.ttf')
+ const buffer = await fontManager.fetchBundledFont('/Inter-Regular.ttf')
const view = new DataView(buffer!)
// TrueType magic: 0x00010000
expect(view.getUint32(0)).toBe(0x00010000)
})
test('throws for nonexistent font', async () => {
- expect(fetchBundledFont('/Nonexistent-Font.ttf')).rejects.toThrow()
+ expect(fontManager.fetchBundledFont('/Nonexistent-Font.ttf')).rejects.toThrow()
})
})
diff --git a/tests/engine/render-text.test.ts b/tests/engine/render-text.test.ts
index 46ef9e46a..51acc0cd8 100644
--- a/tests/engine/render-text.test.ts
+++ b/tests/engine/render-text.test.ts
@@ -2,12 +2,7 @@ import { describe, test, expect, mock } from 'bun:test'
import { initCanvasKit } from '#cli/headless'
import { renderText } from '#core/canvas/scene'
-import {
- initFontService,
- setArabicFallbackFamily,
- setCJKFallbackFamily,
- markFontLoaded
-} from '#core/text/fonts'
+import { fontManager } from '#core/text/fonts'
import { SceneGraph, SkiaRenderer as SkiaRendererClass } from '@open-pencil/core'
import { detectTextDirection, resolveTextDirection } from '@open-pencil/core'
@@ -131,17 +126,17 @@ describe('renderText headless visual', () => {
test('renders CJK text via fallback font through paragraph shaper', async () => {
const ck = await initCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
- initFontService(ck, fontProvider)
+ fontManager.attachProvider(ck, fontProvider)
const interData = await Bun.file('public/Inter-Regular.ttf').arrayBuffer()
fontProvider.registerFont(interData, 'Inter')
- markFontLoaded('Inter', 'Regular', interData)
+ fontManager.markLoaded('Inter', 'Regular', interData)
const notoPath = new URL('../../tests/fixtures/fonts/NotoSansSC-Regular.ttf', import.meta.url)
.pathname
const notoData = await Bun.file(notoPath).arrayBuffer()
fontProvider.registerFont(notoData, 'Noto Sans SC')
- setCJKFallbackFamily('Noto Sans SC')
+ fontManager.setCJKFallbackFamily('Noto Sans SC')
const graph = new SceneGraph()
const page = graph.getPages()[0]
@@ -199,17 +194,17 @@ describe('renderText headless visual', () => {
test('renders Arabic text via fallback font through paragraph shaper', async () => {
const ck = await initCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
- initFontService(ck, fontProvider)
+ fontManager.attachProvider(ck, fontProvider)
const interData = await Bun.file('public/Inter-Regular.ttf').arrayBuffer()
fontProvider.registerFont(interData, 'Inter')
- markFontLoaded('Inter', 'Regular', interData)
+ fontManager.markLoaded('Inter', 'Regular', interData)
const arabicPath = new URL('../fixtures/fonts/NotoNaskhArabic-Regular.ttf', import.meta.url)
.pathname
const arabicData = await Bun.file(arabicPath).arrayBuffer()
fontProvider.registerFont(arabicData, 'Noto Naskh Arabic')
- setArabicFallbackFamily('Noto Naskh Arabic')
+ fontManager.setArabicFallbackFamily('Noto Naskh Arabic')
const graph = new SceneGraph()
const page = graph.getPages()[0]
diff --git a/tests/engine/verify-silhouette-autopsy.test.ts b/tests/engine/verify-silhouette-autopsy.test.ts
index e2b183db3..9537ccbe5 100644
--- a/tests/engine/verify-silhouette-autopsy.test.ts
+++ b/tests/engine/verify-silhouette-autopsy.test.ts
@@ -18,7 +18,7 @@ import { join } from 'node:path'
import { initCanvasKit } from '#cli/headless'
import { SkiaRenderer } from '#core/canvas'
import { SceneGraph } from '#core/scene-graph'
-import { initFontService, markFontLoaded } from '#core/text'
+import { fontManager } from '#core/text'
// === CLAIM EXTRACTION ===
// Each claim is: [doc_section, claim_text, verification_strategy]
@@ -341,13 +341,13 @@ describe('Doc 01/03 — Runtime Behavior Verification', () => {
beforeAll(async () => {
ck = await initCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
- initFontService(ck, fontProvider)
+ fontManager.attachProvider(ck, fontProvider)
// Load Inter font for text tests
const fontPath = join(import.meta.dir, '../../public/Inter-SemiBold.ttf')
try {
const fontData = readFileSync(fontPath)
- markFontLoaded(
+ fontManager.markLoaded(
'Inter',
'SemiBold',
fontData.buffer.slice(fontData.byteOffset, fontData.byteOffset + fontData.byteLength)
diff --git a/tests/engine/visual-inner-shadow-counter.ts b/tests/engine/visual-inner-shadow-counter.ts
index 7704494c5..a93e0f220 100644
--- a/tests/engine/visual-inner-shadow-counter.ts
+++ b/tests/engine/visual-inner-shadow-counter.ts
@@ -4,18 +4,18 @@ import { join } from 'node:path'
import { initCanvasKit } from '#cli/headless'
import { SkiaRenderer } from '#core/canvas'
import { SceneGraph } from '#core/scene-graph'
-import { initFontService, markFontLoaded } from '#core/text'
+import { fontManager } from '#core/text'
async function main() {
const ck = await initCanvasKit()
// Initialize font service
const fontProvider = ck.TypefaceFontProvider.Make()
- initFontService(ck, fontProvider)
+ fontManager.attachProvider(ck, fontProvider)
const fontPath = join(process.cwd(), 'public/Inter-SemiBold.ttf')
const fontData = await readFile(fontPath)
- markFontLoaded(
+ fontManager.markLoaded(
'Inter',
'SemiBold',
fontData.buffer.slice(fontData.byteOffset, fontData.byteOffset + fontData.byteLength)
diff --git a/tests/engine/visual-sdf-test-matrix.ts b/tests/engine/visual-sdf-test-matrix.ts
index a7787c66f..3b2ffc8f1 100644
--- a/tests/engine/visual-sdf-test-matrix.ts
+++ b/tests/engine/visual-sdf-test-matrix.ts
@@ -5,7 +5,7 @@ import { initCanvasKit } from '#cli/headless'
import { SkiaRenderer } from '#core/canvas'
import { renderNodesToImage } from '#core/io/formats/raster'
import { SceneGraph } from '#core/scene-graph'
-import { initFontService, markFontLoaded } from '#core/text'
+import { fontManager } from '#core/text'
interface TestCase {
text: string
@@ -142,11 +142,11 @@ async function main() {
const ck = await initCanvasKit()
const fontProvider = ck.TypefaceFontProvider.Make()
- initFontService(ck, fontProvider)
+ fontManager.attachProvider(ck, fontProvider)
const fontPath = join(process.cwd(), 'public/Inter-SemiBold.ttf')
const fontData = await readFile(fontPath)
- markFontLoaded(
+ fontManager.markLoaded(
'Inter',
'SemiBold',
fontData.buffer.slice(fontData.byteOffset, fontData.byteOffset + fontData.byteLength)
diff --git a/tests/engine/visual-verify-text-inner-shadow.ts b/tests/engine/visual-verify-text-inner-shadow.ts
index 8aaf8bfd6..2254ba9cf 100644
--- a/tests/engine/visual-verify-text-inner-shadow.ts
+++ b/tests/engine/visual-verify-text-inner-shadow.ts
@@ -5,20 +5,20 @@ import { initCanvasKit } from '#cli/headless'
import { SkiaRenderer } from '#core/canvas'
import { renderNodesToImage } from '#core/io/formats/raster'
import { SceneGraph } from '#core/scene-graph'
-import { initFontService, markFontLoaded } from '#core/text'
+import { fontManager } from '#core/text'
async function main() {
const ck = await initCanvasKit()
// Initialize font service
const fontProvider = ck.TypefaceFontProvider.Make()
- initFontService(ck, fontProvider)
+ fontManager.attachProvider(ck, fontProvider)
// Load Inter font from public dir
const fontPath = join(process.cwd(), 'public/Inter-SemiBold.ttf')
console.log('Loading font from:', fontPath)
const fontData = await readFile(fontPath)
- markFontLoaded(
+ fontManager.markLoaded(
'Inter',
'SemiBold',
fontData.buffer.slice(fontData.byteOffset, fontData.byteOffset + fontData.byteLength)