AI-native design editor. Open-source Figma alternative.
feat(app): cache downloaded fonts
Danila Poyarkov25ea361fd714
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 27dd9f36d..9afdcf0ac 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -40,7 +40,7 @@ jobs:- name: Unit testsrun: bun test tests/engine/env:- BUN_HEAVY_TESTS: '1'+ BUN_HEAVY_TESTS: 'false'- name: Copy-paste detectionrun: bun run test:dupesdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex f72fbfd62..3b75b5189 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -37,6 +37,7 @@### Performance+- Cache downloaded remote fonts in app-local storage so reopened documents can reuse them without repeated network fetches.- Cache instance override resolution and lazily populate opened `.fig` pages to reduce load time for large community files.- Reduce zoom and overlay rendering work by separating scene rendering from rulers, selection, labels, and input overlays.diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex afb0e0a6f..41e7aa3dc 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -171,6 +171,7 @@ export {normalizeFontFamily,isVariableFont,styleToVariant,+ type DownloadedFontCache,type FontInfo,type LocalFontAccessState} from './text/fonts'diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.tsindex fbfd8ec0c..b8374222c 100644--- a/packages/core/src/text/fonts.ts+++ b/packages/core/src/text/fonts.ts@@ -20,6 +20,11 @@ export interface FontInfo {export type LocalFontAccessState = 'unsupported' | 'prompt' | 'granted' | 'denied'+export interface DownloadedFontCache {+ read(family: string, style: string): Promise<ArrayBuffer | null>+ write(family: string, style: string, data: ArrayBuffer): Promise<void>+}+type FindLocalFontOptions = { allowVariable?: boolean }const BUNDLED_FONTS: Record<string, string> = {@@ -101,6 +106,7 @@ export class FontManager {private fontProvider: TypefaceFontProvider | null = nullprivate localFonts: FontInfo[] | null = nullprivate localFontAccessState: LocalFontAccessState = IS_BROWSER ? 'prompt' : 'unsupported'+ private downloadedFontCache: DownloadedFontCache | null = nullprivate googleFontsCache = new Map<string, Record<string, string>>()private googleFontsFailed = new Set<string>()private cjkFallbackFamilies: string[] = []@@ -128,6 +134,16 @@ export class FontManager {return this.localFontAccessState}+ setDownloadedFontCache(cache: DownloadedFontCache | null): void {+ this.downloadedFontCache = cache+ }++ async loadCachedFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {+ const cached = await this.readDownloadedFont(family, style)+ if (!cached) return null+ return this.registerAndCache(family, style, cached)+ }+async requestLocalFontAccess(): Promise<FontInfo[]> {if (!IS_BROWSER || !window.queryLocalFonts) {this.localFontAccessState = 'unsupported'@@ -185,13 +201,19 @@ export class FontManager {return cached}+ const downloadedBuffer = await this.loadCachedFont(family, style)+ if (downloadedBuffer) return downloadedBuffer+const localBuffer = await this.findLocalFont(family, style)if (localBuffer) return this.registerAndCache(family, style, localBuffer)if (typeof fetch !== 'undefined') {try {const buffer = await this.fetchGoogleFont(family, style)- if (buffer) return this.registerAndCache(family, style, buffer)+ if (buffer) {+ await this.writeDownloadedFont(family, style, buffer)+ return this.registerAndCache(family, style, buffer)+ }} catch (e) {console.warn(`Google Fonts fetch failed for "${family}" ${style}:`, e)}@@ -331,6 +353,25 @@ export class FontManager {}}+ private async readDownloadedFont(family: string, style: string): Promise<ArrayBuffer | null> {+ if (!this.downloadedFontCache) return null+ try {+ return await this.downloadedFontCache.read(family, style)+ } catch (e) {+ console.warn(`Downloaded font cache read failed for "${family}" ${style}:`, e)+ return null+ }+ }++ private async writeDownloadedFont(family: string, style: string, data: ArrayBuffer): Promise<void> {+ if (!this.downloadedFontCache) return+ try {+ await this.downloadedFontCache.write(family, style, data)+ } catch (e) {+ console.warn(`Downloaded font cache write failed for "${family}" ${style}:`, e)+ }+ }+private async retryWithNormalizedFamily(family: string): Promise<Record<string, string> | null> {const normalized = normalizeFontFamily(family)if (normalized === family) {diff --git a/src/app/editor/font-cache.ts b/src/app/editor/font-cache.tsnew file mode 100644index 000000000..b97e8ffc1--- /dev/null+++ b/src/app/editor/font-cache.ts@@ -0,0 +1,100 @@+import type { DownloadedFontCache } from '@open-pencil/core/text'++type FontCacheEntry = {+ family: string+ style: string+ file: string+ byteLength: number+ sha256: string+ updatedAt: number+}++type FontCacheManifest = {+ version: 1+ entries: Partial<Record<string, FontCacheEntry>>+}++const CACHE_DIR = 'font-cache/v1'+const MANIFEST_PATH = `${CACHE_DIR}/manifest.json`+const EMPTY_MANIFEST: FontCacheManifest = { version: 1, entries: {} }++const textEncoder = new TextEncoder()+const textDecoder = new TextDecoder()++async function cacheKey(family: string, style: string) {+ return hashText(`${family}\0${style}`)+}++async function hashText(value: string) {+ const digest = await crypto.subtle.digest('SHA-256', textEncoder.encode(value))+ return hexDigest(digest)+}++async function hashBytes(data: ArrayBuffer) {+ const digest = await crypto.subtle.digest('SHA-256', data)+ return hexDigest(digest)+}++function hexDigest(data: ArrayBuffer) {+ return [...new Uint8Array(data)].map((byte) => byte.toString(16).padStart(2, '0')).join('')+}++async function readManifest(): Promise<FontCacheManifest> {+ const { BaseDirectory, readFile } = await import('@tauri-apps/plugin-fs')+ try {+ const data = await readFile(MANIFEST_PATH, { baseDir: BaseDirectory.AppLocalData })+ const parsed = JSON.parse(textDecoder.decode(data)) as Partial<FontCacheManifest>+ if (parsed.version !== 1 || !parsed.entries) return EMPTY_MANIFEST+ return { version: 1, entries: parsed.entries }+ } catch {+ return { version: 1, entries: {} }+ }+}++async function writeManifest(manifest: FontCacheManifest) {+ const { BaseDirectory, mkdir, writeFile } = await import('@tauri-apps/plugin-fs')+ await mkdir(CACHE_DIR, { baseDir: BaseDirectory.AppLocalData, recursive: true })+ await writeFile(MANIFEST_PATH, textEncoder.encode(JSON.stringify(manifest)), {+ baseDir: BaseDirectory.AppLocalData+ })+}++export function createTauriDownloadedFontCache(): DownloadedFontCache {+ return {+ async read(family, style) {+ const { BaseDirectory, readFile } = await import('@tauri-apps/plugin-fs')+ const manifest = await readManifest()+ const entry = manifest.entries[await cacheKey(family, style)]+ if (!entry) return null++ const data = await readFile(`${CACHE_DIR}/${entry.file}`, { baseDir: BaseDirectory.AppLocalData })+ const buffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)+ if (buffer.byteLength !== entry.byteLength) return null+ if ((await hashBytes(buffer)) !== entry.sha256) return null+ return buffer+ },++ async write(family, style, data) {+ const { BaseDirectory, mkdir, writeFile } = await import('@tauri-apps/plugin-fs')+ await mkdir(CACHE_DIR, { baseDir: BaseDirectory.AppLocalData, recursive: true })++ const key = await cacheKey(family, style)+ const sha256 = await hashBytes(data)+ const file = `${key}.ttf`+ await writeFile(`${CACHE_DIR}/${file}`, new Uint8Array(data), {+ baseDir: BaseDirectory.AppLocalData+ })++ const manifest = await readManifest()+ manifest.entries[key] = {+ family,+ style,+ file,+ byteLength: data.byteLength,+ sha256,+ updatedAt: Date.now()+ }+ await writeManifest(manifest)+ }+ }+}diff --git a/src/app/editor/fonts.ts b/src/app/editor/fonts.tsindex 309954ca9..263c103a5 100644--- a/src/app/editor/fonts.ts+++ b/src/app/editor/fonts.ts@@ -1,6 +1,12 @@import { IS_TAURI } from '@open-pencil/core/constants'import { fontManager, styleToWeight, type LocalFontAccessState } from '@open-pencil/core/text'+import { createTauriDownloadedFontCache } from '@/app/editor/font-cache'++if (IS_TAURI) {+ fontManager.setDownloadedFontCache(createTauriDownloadedFontCache())+}+interface TauriFontFamily {family: stringstyles: string[]@@ -64,6 +70,9 @@ export async function listFonts(): Promise<TauriFontFamily[]> {export async function loadFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {if (IS_TAURI) {+ const cached = await fontManager.loadCachedFont(family, style)+ if (cached) return cached+try {const { invoke } = await import('@tauri-apps/api/core')const data = await invoke<number[]>('load_system_font', { family, style })diff --git a/tests/engine/fonts.test.ts b/tests/engine/fonts.test.tsindex d9ce8110d..60a4a82cd 100644--- a/tests/engine/fonts.test.ts+++ b/tests/engine/fonts.test.ts@@ -102,6 +102,27 @@ describe('FontManager loaded font cache', () => {manager.detachProvider(second.provider)expect(manager.provider()).toBeNull()})++ test('loads downloaded cache before other sources', async () => {+ const manager = new FontManager()+ const recording = createRecordingProvider()+ const data = new ArrayBuffer(16)+ let writes = 0++ manager.attachProvider({} as CanvasKit, recording.provider)+ manager.setDownloadedFontCache({+ async read(family, style) {+ return family === 'DownloadedCache' && style === 'Regular' ? data : null+ },+ async write() {+ writes+++ }+ })++ await expect(manager.loadFont('DownloadedCache', 'Regular')).resolves.toBe(data)+ expect(recording.registrations).toEqual([{ family: 'DownloadedCache', byteLength: 16 }])+ expect(writes).toBe(0)+ })})describe('collectFontKeys', () => {