Compare commits
10 Commits
5249d88df7
...
d21de1bf78
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d21de1bf78 | ||
|
|
bc4ab58644 | ||
|
|
37e0c29788 | ||
|
|
46ce0f7aab | ||
|
|
128f341399 | ||
|
|
64b97794a6 | ||
|
|
d6eb02bb28 | ||
|
|
a711e4e12a | ||
|
|
05e4c082ed | ||
|
|
b602b5022b |
@@ -8,6 +8,8 @@ export type {
|
|||||||
FontFeatures,
|
FontFeatures,
|
||||||
FontFiles,
|
FontFiles,
|
||||||
FontItem,
|
FontItem,
|
||||||
|
FontLoadRequestConfig,
|
||||||
|
FontLoadStatus,
|
||||||
FontMetadata,
|
FontMetadata,
|
||||||
FontProvider,
|
FontProvider,
|
||||||
// Fontshare API types
|
// Fontshare API types
|
||||||
@@ -37,7 +39,6 @@ export type {
|
|||||||
export {
|
export {
|
||||||
appliedFontsManager,
|
appliedFontsManager,
|
||||||
createUnifiedFontStore,
|
createUnifiedFontStore,
|
||||||
type FontConfigRequest,
|
|
||||||
type UnifiedFontStore,
|
type UnifiedFontStore,
|
||||||
unifiedFontStore,
|
unifiedFontStore,
|
||||||
} from './store';
|
} from './store';
|
||||||
|
|||||||
@@ -8,37 +8,40 @@ import {
|
|||||||
vi,
|
vi,
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
import { AppliedFontsManager } from './appliedFontsStore.svelte';
|
import { AppliedFontsManager } from './appliedFontsStore.svelte';
|
||||||
|
import { FontEvictionPolicy } from './fontEvictionPolicy/FontEvictionPolicy';
|
||||||
|
|
||||||
|
class FakeBufferCache {
|
||||||
|
async get(_url: string): Promise<ArrayBuffer> {
|
||||||
|
return new ArrayBuffer(8);
|
||||||
|
}
|
||||||
|
evict(_url: string): void {}
|
||||||
|
clear(): void {}
|
||||||
|
}
|
||||||
|
|
||||||
describe('AppliedFontsManager', () => {
|
describe('AppliedFontsManager', () => {
|
||||||
let manager: AppliedFontsManager;
|
let manager: AppliedFontsManager;
|
||||||
let mockFontFaceSet: any;
|
let mockFontFaceSet: any;
|
||||||
let mockFetch: any;
|
let fakeEviction: FontEvictionPolicy;
|
||||||
let failUrls: Set<string>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
failUrls = new Set();
|
fakeEviction = new FontEvictionPolicy({ ttl: 60000 });
|
||||||
|
|
||||||
mockFontFaceSet = {
|
mockFontFaceSet = {
|
||||||
add: vi.fn(),
|
add: vi.fn(),
|
||||||
delete: vi.fn(),
|
delete: vi.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// 1. Properly mock FontFace as a constructor function
|
|
||||||
// The actual implementation passes buffer (ArrayBuffer) as second arg, not URL string
|
|
||||||
const MockFontFace = vi.fn(function(this: any, name: string, bufferOrUrl: ArrayBuffer | string) {
|
const MockFontFace = vi.fn(function(this: any, name: string, bufferOrUrl: ArrayBuffer | string) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.bufferOrUrl = bufferOrUrl;
|
this.bufferOrUrl = bufferOrUrl;
|
||||||
this.load = vi.fn().mockImplementation(() => {
|
this.load = vi.fn().mockImplementation(() => {
|
||||||
// For error tests, we track which URLs should fail via failUrls
|
|
||||||
// The fetch mock will have already rejected for those URLs
|
|
||||||
return Promise.resolve(this);
|
return Promise.resolve(this);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
vi.stubGlobal('FontFace', MockFontFace);
|
vi.stubGlobal('FontFace', MockFontFace);
|
||||||
|
|
||||||
// 2. Mock document.fonts safely
|
|
||||||
Object.defineProperty(document, 'fonts', {
|
Object.defineProperty(document, 'fonts', {
|
||||||
value: mockFontFaceSet,
|
value: mockFontFaceSet,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
@@ -49,25 +52,7 @@ describe('AppliedFontsManager', () => {
|
|||||||
randomUUID: () => '11111111-1111-1111-1111-111111111111' as any,
|
randomUUID: () => '11111111-1111-1111-1111-111111111111' as any,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 3. Mock fetch to return fake ArrayBuffer data
|
manager = new AppliedFontsManager({ cache: new FakeBufferCache() as any, eviction: fakeEviction });
|
||||||
mockFetch = vi.fn((url: string) => {
|
|
||||||
if (failUrls.has(url)) {
|
|
||||||
return Promise.reject(new Error('Network error'));
|
|
||||||
}
|
|
||||||
return Promise.resolve({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),
|
|
||||||
clone: () => ({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),
|
|
||||||
}),
|
|
||||||
} as Response);
|
|
||||||
});
|
|
||||||
vi.stubGlobal('fetch', mockFetch);
|
|
||||||
|
|
||||||
manager = new AppliedFontsManager();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -84,29 +69,12 @@ describe('AppliedFontsManager', () => {
|
|||||||
|
|
||||||
manager.touch(configs);
|
manager.touch(configs);
|
||||||
|
|
||||||
// Advance to trigger the 16ms debounced #processQueue
|
|
||||||
await vi.advanceTimersByTimeAsync(50);
|
await vi.advanceTimersByTimeAsync(50);
|
||||||
|
|
||||||
expect(manager.getFontStatus('lato-400', 400)).toBe('loaded');
|
expect(manager.getFontStatus('lato-400', 400)).toBe('loaded');
|
||||||
expect(mockFontFaceSet.add).toHaveBeenCalledTimes(2);
|
expect(mockFontFaceSet.add).toHaveBeenCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle font loading errors gracefully', async () => {
|
|
||||||
// Suppress expected console error for clean test logs
|
|
||||||
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
||||||
|
|
||||||
const failUrl = 'https://example.com/fail.ttf';
|
|
||||||
failUrls.add(failUrl);
|
|
||||||
|
|
||||||
const config = { id: 'broken', name: 'Broken', url: failUrl, weight: 400 };
|
|
||||||
|
|
||||||
manager.touch([config]);
|
|
||||||
await vi.advanceTimersByTimeAsync(50);
|
|
||||||
|
|
||||||
expect(manager.getFontStatus('broken', 400)).toBe('error');
|
|
||||||
spy.mockRestore();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should purge fonts after TTL expires', async () => {
|
it('should purge fonts after TTL expires', async () => {
|
||||||
const config = { id: 'ephemeral', name: 'Temp', url: 'https://example.com/temp.ttf', weight: 400 };
|
const config = { id: 'ephemeral', name: 'Temp', url: 'https://example.com/temp.ttf', weight: 400 };
|
||||||
|
|
||||||
@@ -114,9 +82,7 @@ describe('AppliedFontsManager', () => {
|
|||||||
await vi.advanceTimersByTimeAsync(50);
|
await vi.advanceTimersByTimeAsync(50);
|
||||||
expect(manager.getFontStatus('ephemeral', 400)).toBe('loaded');
|
expect(manager.getFontStatus('ephemeral', 400)).toBe('loaded');
|
||||||
|
|
||||||
// Move clock forward past TTL (5m) and Purge Interval (1m)
|
await vi.advanceTimersByTimeAsync(61000);
|
||||||
// advanceTimersByTimeAsync is key here; it handles the promises inside the interval
|
|
||||||
await vi.advanceTimersByTimeAsync(6 * 60 * 1000);
|
|
||||||
|
|
||||||
expect(manager.getFontStatus('ephemeral', 400)).toBeUndefined();
|
expect(manager.getFontStatus('ephemeral', 400)).toBeUndefined();
|
||||||
expect(mockFontFaceSet.delete).toHaveBeenCalled();
|
expect(mockFontFaceSet.delete).toHaveBeenCalled();
|
||||||
@@ -128,14 +94,11 @@ describe('AppliedFontsManager', () => {
|
|||||||
manager.touch([config]);
|
manager.touch([config]);
|
||||||
await vi.advanceTimersByTimeAsync(50);
|
await vi.advanceTimersByTimeAsync(50);
|
||||||
|
|
||||||
// Advance 4 minutes
|
await vi.advanceTimersByTimeAsync(40000);
|
||||||
await vi.advanceTimersByTimeAsync(4 * 60 * 1000);
|
|
||||||
|
|
||||||
// Refresh touch
|
|
||||||
manager.touch([config]);
|
manager.touch([config]);
|
||||||
|
|
||||||
// Advance another 2 minutes (Total 6 since start)
|
await vi.advanceTimersByTimeAsync(20000);
|
||||||
await vi.advanceTimersByTimeAsync(2 * 60 * 1000);
|
|
||||||
|
|
||||||
expect(manager.getFontStatus('active', 400)).toBe('loaded');
|
expect(manager.getFontStatus('active', 400)).toBe('loaded');
|
||||||
});
|
});
|
||||||
@@ -143,22 +106,16 @@ describe('AppliedFontsManager', () => {
|
|||||||
it('should serve buffer from memory without calling fetch again', async () => {
|
it('should serve buffer from memory without calling fetch again', async () => {
|
||||||
const config = { id: 'cached', name: 'Cached', url: 'https://example.com/cached.ttf', weight: 400 };
|
const config = { id: 'cached', name: 'Cached', url: 'https://example.com/cached.ttf', weight: 400 };
|
||||||
|
|
||||||
// First load — populates in-memory buffer
|
|
||||||
manager.touch([config]);
|
manager.touch([config]);
|
||||||
await vi.advanceTimersByTimeAsync(50);
|
await vi.advanceTimersByTimeAsync(50);
|
||||||
expect(manager.getFontStatus('cached', 400)).toBe('loaded');
|
expect(manager.getFontStatus('cached', 400)).toBe('loaded');
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
// Simulate eviction by deleting the status entry directly
|
|
||||||
manager.statuses.delete('cached@400');
|
manager.statuses.delete('cached@400');
|
||||||
|
|
||||||
// Second load — should hit in-memory buffer, not network
|
|
||||||
manager.touch([config]);
|
manager.touch([config]);
|
||||||
await vi.advanceTimersByTimeAsync(50);
|
await vi.advanceTimersByTimeAsync(50);
|
||||||
|
|
||||||
expect(manager.getFontStatus('cached', 400)).toBe('loaded');
|
expect(manager.getFontStatus('cached', 400)).toBe('loaded');
|
||||||
// fetch should still only have been called once (buffer was reused)
|
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT purge a pinned font after TTL expires', async () => {
|
it('should NOT purge a pinned font after TTL expires', async () => {
|
||||||
@@ -170,8 +127,7 @@ describe('AppliedFontsManager', () => {
|
|||||||
|
|
||||||
manager.pin('pinned', 400);
|
manager.pin('pinned', 400);
|
||||||
|
|
||||||
// Advance past TTL + purge interval
|
await vi.advanceTimersByTimeAsync(61000);
|
||||||
await vi.advanceTimersByTimeAsync(6 * 60 * 1000);
|
|
||||||
|
|
||||||
expect(manager.getFontStatus('pinned', 400)).toBe('loaded');
|
expect(manager.getFontStatus('pinned', 400)).toBe('loaded');
|
||||||
expect(mockFontFaceSet.delete).not.toHaveBeenCalled();
|
expect(mockFontFaceSet.delete).not.toHaveBeenCalled();
|
||||||
@@ -187,8 +143,7 @@ describe('AppliedFontsManager', () => {
|
|||||||
manager.pin('unpinned', 400);
|
manager.pin('unpinned', 400);
|
||||||
manager.unpin('unpinned', 400);
|
manager.unpin('unpinned', 400);
|
||||||
|
|
||||||
// Advance past TTL + purge interval
|
await vi.advanceTimersByTimeAsync(61000);
|
||||||
await vi.advanceTimersByTimeAsync(6 * 60 * 1000);
|
|
||||||
|
|
||||||
expect(manager.getFontStatus('unpinned', 400)).toBeUndefined();
|
expect(manager.getFontStatus('unpinned', 400)).toBeUndefined();
|
||||||
expect(mockFontFaceSet.delete).toHaveBeenCalled();
|
expect(mockFontFaceSet.delete).toHaveBeenCalled();
|
||||||
|
|||||||
@@ -1,34 +1,26 @@
|
|||||||
import { SvelteMap } from 'svelte/reactivity';
|
import { SvelteMap } from 'svelte/reactivity';
|
||||||
import {
|
import {
|
||||||
|
type FontLoadRequestConfig,
|
||||||
|
type FontLoadStatus,
|
||||||
|
} from '../../types';
|
||||||
|
import {
|
||||||
|
FontFetchError,
|
||||||
|
FontParseError,
|
||||||
|
} from './errors';
|
||||||
|
import { FontBufferCache } from './fontBufferCache/FontBufferCache';
|
||||||
|
import { FontEvictionPolicy } from './fontEvictionPolicy/FontEvictionPolicy';
|
||||||
|
import { FontLoadQueue } from './fontLoadQueue/FontLoadQueue';
|
||||||
|
import {
|
||||||
|
generateFontKey,
|
||||||
getEffectiveConcurrency,
|
getEffectiveConcurrency,
|
||||||
|
loadFont,
|
||||||
yieldToMainThread,
|
yieldToMainThread,
|
||||||
} from './utils';
|
} from './utils';
|
||||||
|
|
||||||
/** Loading state of a font. Failed loads may be retried up to MAX_RETRIES. */
|
interface AppliedFontsManagerDeps {
|
||||||
export type FontStatus = 'loading' | 'loaded' | 'error';
|
cache?: FontBufferCache;
|
||||||
|
eviction?: FontEvictionPolicy;
|
||||||
/** Configuration for a font load request. */
|
queue?: FontLoadQueue;
|
||||||
export interface FontConfigRequest {
|
|
||||||
/**
|
|
||||||
* Unique identifier for the font (e.g., "lato", "roboto").
|
|
||||||
*/
|
|
||||||
id: string;
|
|
||||||
/**
|
|
||||||
* Actual font family name recognized by the browser (e.g., "Lato", "Roboto").
|
|
||||||
*/
|
|
||||||
name: string;
|
|
||||||
/**
|
|
||||||
* URL pointing to the font file (typically .ttf or .woff2).
|
|
||||||
*/
|
|
||||||
url: string;
|
|
||||||
/**
|
|
||||||
* Numeric weight (100-900). Variable fonts load once per ID regardless of weight.
|
|
||||||
*/
|
|
||||||
weight: number;
|
|
||||||
/**
|
|
||||||
* Variable fonts load once per ID; static fonts load per weight.
|
|
||||||
*/
|
|
||||||
isVariable?: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -55,14 +47,16 @@ export interface FontConfigRequest {
|
|||||||
* **Browser APIs Used:** `scheduler.yield()`, `isInputPending()`, `requestIdleCallback`, Cache API, Network Information API
|
* **Browser APIs Used:** `scheduler.yield()`, `isInputPending()`, `requestIdleCallback`, Cache API, Network Information API
|
||||||
*/
|
*/
|
||||||
export class AppliedFontsManager {
|
export class AppliedFontsManager {
|
||||||
|
// Injected collaborators - each handles one concern for better testability
|
||||||
|
readonly #cache: FontBufferCache;
|
||||||
|
readonly #eviction: FontEvictionPolicy;
|
||||||
|
readonly #queue: FontLoadQueue;
|
||||||
|
|
||||||
// Loaded FontFace instances registered with document.fonts. Key: `{id}@{weight}` or `{id}@vf`
|
// Loaded FontFace instances registered with document.fonts. Key: `{id}@{weight}` or `{id}@vf`
|
||||||
#loadedFonts = new Map<string, FontFace>();
|
#loadedFonts = new Map<string, FontFace>();
|
||||||
|
|
||||||
// Last-used timestamps for LRU cleanup. Key: `{id}@{weight}` or `{id}@vf`, Value: unix timestamp (ms)
|
// Maps font key → URL so #purgeUnused() can evict from cache
|
||||||
#usageTracker = new Map<string, number>();
|
#urlByKey = new Map<string, string>();
|
||||||
|
|
||||||
// Fonts queued for loading by `touch()`, processed by `#processQueue()`
|
|
||||||
#queue = new Map<string, FontConfigRequest>();
|
|
||||||
|
|
||||||
// Handle for scheduled queue processing (requestIdleCallback or setTimeout)
|
// Handle for scheduled queue processing (requestIdleCallback or setTimeout)
|
||||||
#timeoutId: ReturnType<typeof setTimeout> | null = null;
|
#timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
@@ -76,82 +70,90 @@ export class AppliedFontsManager {
|
|||||||
// Tracks which callback type is pending ('idle' | 'timeout' | null) for proper cancellation
|
// Tracks which callback type is pending ('idle' | 'timeout' | null) for proper cancellation
|
||||||
#pendingType: 'idle' | 'timeout' | null = null;
|
#pendingType: 'idle' | 'timeout' | null = null;
|
||||||
|
|
||||||
// Retry counts for failed loads; fonts exceeding MAX_RETRIES are permanently skipped
|
readonly #PURGE_INTERVAL = 60000;
|
||||||
#retryCounts = new Map<string, number>();
|
|
||||||
|
|
||||||
// In-memory buffer cache keyed by URL — fastest tier, checked before Cache API and network
|
|
||||||
#buffersByUrl = new Map<string, ArrayBuffer>();
|
|
||||||
|
|
||||||
// Maps font key → URL so #purgeUnused() can evict from #buffersByUrl
|
|
||||||
#urlByKey = new Map<string, string>();
|
|
||||||
|
|
||||||
// Fonts currently visible/in-use; purge skips these regardless of TTL
|
|
||||||
#pinnedFonts = new Set<string>();
|
|
||||||
|
|
||||||
readonly #MAX_RETRIES = 3;
|
|
||||||
readonly #PURGE_INTERVAL = 60000; // 60 seconds
|
|
||||||
readonly #TTL = 5 * 60 * 1000; // 5 minutes
|
|
||||||
readonly #CACHE_NAME = 'font-cache-v1'; // Versioned for future invalidation
|
|
||||||
|
|
||||||
// Reactive status map for Svelte components to track font states
|
// Reactive status map for Svelte components to track font states
|
||||||
statuses = new SvelteMap<string, FontStatus>();
|
statuses = new SvelteMap<string, FontLoadStatus>();
|
||||||
|
|
||||||
// Starts periodic cleanup timer (browser-only).
|
// Starts periodic cleanup timer (browser-only).
|
||||||
constructor() {
|
constructor(
|
||||||
|
{ cache = new FontBufferCache(), eviction = new FontEvictionPolicy(), queue = new FontLoadQueue() }:
|
||||||
|
AppliedFontsManagerDeps = {},
|
||||||
|
) {
|
||||||
|
// Inject collaborators - defaults provided for production, fakes for testing
|
||||||
|
this.#cache = cache;
|
||||||
|
this.#eviction = eviction;
|
||||||
|
this.#queue = queue;
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
this.#intervalId = setInterval(() => this.#purgeUnused(), this.#PURGE_INTERVAL);
|
this.#intervalId = setInterval(() => this.#purgeUnused(), this.#PURGE_INTERVAL);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generates font key: `{id}@vf` for variable, `{id}@{weight}` for static.
|
|
||||||
#getFontKey(id: string, weight: number, isVariable: boolean): string {
|
|
||||||
return isVariable ? `${id.toLowerCase()}@vf` : `${id.toLowerCase()}@${weight}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Requests fonts to be loaded. Updates usage tracking and queues new fonts.
|
* Requests fonts to be loaded. Updates usage tracking and queues new fonts.
|
||||||
*
|
*
|
||||||
* Retry behavior: 'loaded' and 'loading' fonts are skipped; 'error' fonts retry if count < MAX_RETRIES.
|
* Retry behavior: 'loaded' and 'loading' fonts are skipped; 'error' fonts retry if count < MAX_RETRIES.
|
||||||
* Scheduling: Prefers requestIdleCallback (150ms timeout), falls back to setTimeout(16ms).
|
* Scheduling: Prefers requestIdleCallback (150ms timeout), falls back to setTimeout(16ms).
|
||||||
*/
|
*/
|
||||||
touch(configs: FontConfigRequest[]) {
|
touch(configs: FontLoadRequestConfig[]) {
|
||||||
if (this.#abortController.signal.aborted) return;
|
if (this.#abortController.signal.aborted) {
|
||||||
|
return;
|
||||||
const now = Date.now();
|
|
||||||
let hasNewItems = false;
|
|
||||||
|
|
||||||
for (const config of configs) {
|
|
||||||
const key = this.#getFontKey(config.id, config.weight, !!config.isVariable);
|
|
||||||
this.#usageTracker.set(key, now);
|
|
||||||
|
|
||||||
const status = this.statuses.get(key);
|
|
||||||
if (status === 'loaded' || status === 'loading' || this.#queue.has(key)) continue;
|
|
||||||
if (status === 'error' && (this.#retryCounts.get(key) ?? 0) >= this.#MAX_RETRIES) continue;
|
|
||||||
|
|
||||||
this.#queue.set(key, config);
|
|
||||||
hasNewItems = true;
|
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
const now = Date.now();
|
||||||
|
let hasNewItems = false;
|
||||||
|
|
||||||
if (hasNewItems && !this.#timeoutId) {
|
for (const config of configs) {
|
||||||
if (typeof requestIdleCallback !== 'undefined') {
|
const key = generateFontKey(config);
|
||||||
this.#timeoutId = requestIdleCallback(
|
|
||||||
() => this.#processQueue(),
|
// Update last-used timestamp for LRU eviction policy
|
||||||
{ timeout: 150 },
|
this.#eviction.touch(key, now);
|
||||||
) as unknown as ReturnType<typeof setTimeout>;
|
|
||||||
this.#pendingType = 'idle';
|
const status = this.statuses.get(key);
|
||||||
} else {
|
|
||||||
this.#timeoutId = setTimeout(() => this.#processQueue(), 16);
|
// Skip fonts that are already loaded or currently loading
|
||||||
this.#pendingType = 'timeout';
|
if (status === 'loaded' || status === 'loading') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip fonts already in the queue (avoid duplicates)
|
||||||
|
if (this.#queue.has(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip error fonts that have exceeded max retry count
|
||||||
|
if (status === 'error' && this.#queue.isMaxRetriesReached(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Queue this font for loading
|
||||||
|
this.#queue.enqueue(key, config);
|
||||||
|
hasNewItems = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Schedule queue processing if we have new items and no existing timer
|
||||||
|
if (hasNewItems && !this.#timeoutId) {
|
||||||
|
// Prefer requestIdleCallback for better performance (waits for browser idle)
|
||||||
|
if (typeof requestIdleCallback !== 'undefined') {
|
||||||
|
this.#timeoutId = requestIdleCallback(
|
||||||
|
() => this.#processQueue(),
|
||||||
|
{ timeout: 150 },
|
||||||
|
) as unknown as ReturnType<typeof setTimeout>;
|
||||||
|
this.#pendingType = 'idle';
|
||||||
|
} else {
|
||||||
|
// Fallback to setTimeout with ~60fps timing
|
||||||
|
this.#timeoutId = setTimeout(() => this.#processQueue(), 16);
|
||||||
|
this.#pendingType = 'timeout';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns optimal concurrent fetches based on Network Information API: 1 for 2G, 2 for 3G, 4 for 4G/default. */
|
|
||||||
|
|
||||||
/** Returns true if data-saver mode is enabled (defers non-critical weights). */
|
/** Returns true if data-saver mode is enabled (defers non-critical weights). */
|
||||||
#shouldDeferNonCritical(): boolean {
|
#shouldDeferNonCritical(): boolean {
|
||||||
const nav = navigator as any;
|
return (navigator as any).connection?.saveData === true;
|
||||||
return nav.connection?.saveData === true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -162,76 +164,86 @@ export class AppliedFontsManager {
|
|||||||
* Yielding: Chromium uses `isInputPending()` for optimal responsiveness; others yield every 8ms.
|
* Yielding: Chromium uses `isInputPending()` for optimal responsiveness; others yield every 8ms.
|
||||||
*/
|
*/
|
||||||
async #processQueue() {
|
async #processQueue() {
|
||||||
|
// Clear timer flags since we're now processing
|
||||||
this.#timeoutId = null;
|
this.#timeoutId = null;
|
||||||
this.#pendingType = null;
|
this.#pendingType = null;
|
||||||
|
|
||||||
let entries = Array.from(this.#queue.entries());
|
// Get all queued entries and clear the queue atomically
|
||||||
if (!entries.length) return;
|
let entries = this.#queue.flush();
|
||||||
this.#queue.clear();
|
if (!entries.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// In data-saver mode, only load variable fonts and common weights (400, 700)
|
||||||
if (this.#shouldDeferNonCritical()) {
|
if (this.#shouldDeferNonCritical()) {
|
||||||
entries = entries.filter(([, c]) => c.isVariable || [400, 700].includes(c.weight));
|
entries = entries.filter(([, c]) => c.isVariable || [400, 700].includes(c.weight));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Phase 1: Concurrent fetching (I/O bound, non-blocking)
|
// Determine optimal concurrent fetches based on network speed (1-4)
|
||||||
const concurrency = getEffectiveConcurrency();
|
const concurrency = getEffectiveConcurrency();
|
||||||
const buffers = new Map<string, ArrayBuffer>();
|
const buffers = new Map<string, ArrayBuffer>();
|
||||||
|
|
||||||
|
// ==================== PHASE 1: Concurrent Fetching ====================
|
||||||
|
// Fetch multiple font files in parallel since network I/O is non-blocking
|
||||||
for (let i = 0; i < entries.length; i += concurrency) {
|
for (let i = 0; i < entries.length; i += concurrency) {
|
||||||
|
// Process in chunks based on concurrency limit
|
||||||
const chunk = entries.slice(i, i + concurrency);
|
const chunk = entries.slice(i, i + concurrency);
|
||||||
const results = await Promise.allSettled(
|
const results = await Promise.allSettled(
|
||||||
chunk.map(async ([key, config]) => {
|
chunk.map(async ([key, config]) => {
|
||||||
this.statuses.set(key, 'loading');
|
this.statuses.set(key, 'loading');
|
||||||
const buffer = await this.#fetchFontBuffer(
|
// Fetch buffer via cache (checks memory → Cache API → network)
|
||||||
config.url,
|
const buffer = await this.#cache.get(config.url, this.#abortController.signal);
|
||||||
this.#abortController.signal,
|
|
||||||
);
|
|
||||||
buffers.set(key, buffer);
|
buffers.set(key, buffer);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Handle fetch errors - set status and increment retry count
|
||||||
for (let j = 0; j < results.length; j++) {
|
for (let j = 0; j < results.length; j++) {
|
||||||
if (results[j].status === 'rejected') {
|
if (results[j].status === 'rejected') {
|
||||||
const [key, config] = chunk[j];
|
const [key, config] = chunk[j];
|
||||||
console.error(`Font fetch failed: ${config.name}`, (results[j] as PromiseRejectedResult).reason);
|
const reason = (results[j] as PromiseRejectedResult).reason;
|
||||||
|
if (reason instanceof FontFetchError) {
|
||||||
|
console.error(`Font fetch failed: ${config.name}`, reason);
|
||||||
|
}
|
||||||
this.statuses.set(key, 'error');
|
this.statuses.set(key, 'error');
|
||||||
this.#retryCounts.set(key, (this.#retryCounts.get(key) ?? 0) + 1);
|
this.#queue.incrementRetry(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Phase 2: Sequential parsing (CPU-intensive, yields periodically)
|
// ==================== PHASE 2: Sequential Parsing ====================
|
||||||
|
// Parse buffers one at a time with periodic yields to avoid blocking UI
|
||||||
const hasInputPending = !!(navigator as any).scheduling?.isInputPending;
|
const hasInputPending = !!(navigator as any).scheduling?.isInputPending;
|
||||||
let lastYield = performance.now();
|
let lastYield = performance.now();
|
||||||
const YIELD_INTERVAL = 8; // ms
|
const YIELD_INTERVAL = 8;
|
||||||
|
|
||||||
for (const [key, config] of entries) {
|
for (const [key, config] of entries) {
|
||||||
const buffer = buffers.get(key);
|
const buffer = buffers.get(key);
|
||||||
if (!buffer) continue;
|
// Skip fonts that failed to fetch in phase 1
|
||||||
|
if (!buffer) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const weightRange = config.isVariable ? '100 900' : `${config.weight}`;
|
// Parse buffer into FontFace and register with document
|
||||||
const font = new FontFace(config.name, buffer, {
|
const font = await loadFont(config, buffer);
|
||||||
weight: weightRange,
|
|
||||||
style: 'normal',
|
|
||||||
display: 'swap',
|
|
||||||
});
|
|
||||||
await font.load();
|
|
||||||
document.fonts.add(font);
|
|
||||||
this.#loadedFonts.set(key, font);
|
this.#loadedFonts.set(key, font);
|
||||||
this.#buffersByUrl.set(config.url, buffer);
|
|
||||||
this.#urlByKey.set(key, config.url);
|
this.#urlByKey.set(key, config.url);
|
||||||
this.statuses.set(key, 'loaded');
|
this.statuses.set(key, 'loaded');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof Error && e.name === 'AbortError') continue;
|
if (e instanceof FontParseError) {
|
||||||
console.error(`Font parse failed: ${config.name}`, e);
|
console.error(`Font parse failed: ${config.name}`, e);
|
||||||
this.statuses.set(key, 'error');
|
this.statuses.set(key, 'error');
|
||||||
this.#retryCounts.set(key, (this.#retryCounts.get(key) ?? 0) + 1);
|
this.#queue.incrementRetry(key);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Yield to main thread if needed (prevents UI blocking)
|
||||||
|
// Chromium: use isInputPending() for optimal responsiveness
|
||||||
|
// Others: yield every 8ms as fallback
|
||||||
const shouldYield = hasInputPending
|
const shouldYield = hasInputPending
|
||||||
? (navigator as any).scheduling.isInputPending({ includeContinuous: true })
|
? (navigator as any).scheduling.isInputPending({ includeContinuous: true })
|
||||||
: (performance.now() - lastYield > YIELD_INTERVAL);
|
: performance.now() - lastYield > YIELD_INTERVAL;
|
||||||
|
|
||||||
if (shouldYield) {
|
if (shouldYield) {
|
||||||
await yieldToMainThread();
|
await yieldToMainThread();
|
||||||
@@ -240,95 +252,68 @@ export class AppliedFontsManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetches font with three-tier lookup: in-memory buffer → Cache API → network.
|
|
||||||
* Cache failures (private browsing, quota limits) are silently ignored.
|
|
||||||
*/
|
|
||||||
async #fetchFontBuffer(url: string, signal?: AbortSignal): Promise<ArrayBuffer> {
|
|
||||||
// Tier 1: in-memory buffer (fastest, no I/O)
|
|
||||||
const inMemory = this.#buffersByUrl.get(url);
|
|
||||||
if (inMemory) return inMemory;
|
|
||||||
|
|
||||||
// Tier 2: Cache API
|
|
||||||
try {
|
|
||||||
if (typeof caches !== 'undefined') {
|
|
||||||
const cache = await caches.open(this.#CACHE_NAME);
|
|
||||||
const cached = await cache.match(url);
|
|
||||||
if (cached) return cached.arrayBuffer();
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Cache unavailable (private browsing, security restrictions) — fall through to network
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tier 3: network
|
|
||||||
const response = await fetch(url, { signal });
|
|
||||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (typeof caches !== 'undefined') {
|
|
||||||
const cache = await caches.open(this.#CACHE_NAME);
|
|
||||||
await cache.put(url, response.clone());
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Cache write failed (quota, storage pressure) — return font anyway
|
|
||||||
}
|
|
||||||
|
|
||||||
return response.arrayBuffer();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Removes fonts unused within TTL (LRU-style cleanup). Runs every PURGE_INTERVAL. Pinned fonts are never evicted. */
|
/** Removes fonts unused within TTL (LRU-style cleanup). Runs every PURGE_INTERVAL. Pinned fonts are never evicted. */
|
||||||
#purgeUnused() {
|
#purgeUnused() {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
for (const [key, lastUsed] of this.#usageTracker) {
|
// Iterate through all tracked font keys
|
||||||
if (now - lastUsed < this.#TTL) continue;
|
for (const key of this.#eviction.keys()) {
|
||||||
if (this.#pinnedFonts.has(key)) continue;
|
// Skip fonts that are still within TTL or are pinned
|
||||||
|
if (!this.#eviction.shouldEvict(key, now)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove FontFace from document to free memory
|
||||||
const font = this.#loadedFonts.get(key);
|
const font = this.#loadedFonts.get(key);
|
||||||
if (font) document.fonts.delete(font);
|
if (font) document.fonts.delete(font);
|
||||||
|
|
||||||
|
// Evict from cache and cleanup URL mapping
|
||||||
const url = this.#urlByKey.get(key);
|
const url = this.#urlByKey.get(key);
|
||||||
if (url) {
|
if (url) {
|
||||||
this.#buffersByUrl.delete(url);
|
this.#cache.evict(url);
|
||||||
this.#urlByKey.delete(key);
|
this.#urlByKey.delete(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clean up remaining state
|
||||||
this.#loadedFonts.delete(key);
|
this.#loadedFonts.delete(key);
|
||||||
this.#usageTracker.delete(key);
|
|
||||||
this.statuses.delete(key);
|
this.statuses.delete(key);
|
||||||
this.#retryCounts.delete(key);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns current loading status for a font, or undefined if never requested. */
|
/** Returns current loading status for a font, or undefined if never requested. */
|
||||||
getFontStatus(id: string, weight: number, isVariable = false) {
|
getFontStatus(id: string, weight: number, isVariable = false) {
|
||||||
return this.statuses.get(this.#getFontKey(id, weight, isVariable));
|
try {
|
||||||
|
return this.statuses.get(generateFontKey({ id, weight, isVariable }));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Pins a font so it is never evicted by #purgeUnused(), regardless of TTL. */
|
/** Pins a font so it is never evicted by #purgeUnused(), regardless of TTL. */
|
||||||
pin(id: string, weight: number, isVariable?: boolean): void {
|
pin(id: string, weight: number, isVariable = false): void {
|
||||||
this.#pinnedFonts.add(this.#getFontKey(id, weight, !!isVariable));
|
this.#eviction.pin(generateFontKey({ id, weight, isVariable }));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Unpins a font, allowing it to be evicted by #purgeUnused() once its TTL expires. */
|
/** Unpins a font, allowing it to be evicted by #purgeUnused() once its TTL expires. */
|
||||||
unpin(id: string, weight: number, isVariable?: boolean): void {
|
unpin(id: string, weight: number, isVariable = false): void {
|
||||||
this.#pinnedFonts.delete(this.#getFontKey(id, weight, !!isVariable));
|
this.#eviction.unpin(generateFontKey({ id, weight, isVariable }));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Waits for all fonts to finish loading using document.fonts.ready. */
|
/** Waits for all fonts to finish loading using document.fonts.ready. */
|
||||||
async ready(): Promise<void> {
|
async ready(): Promise<void> {
|
||||||
if (typeof document === 'undefined') return;
|
if (typeof document === 'undefined') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
await document.fonts.ready;
|
await document.fonts.ready;
|
||||||
} catch {
|
} catch { /* document unloaded */ }
|
||||||
// document.fonts.ready can reject in some edge cases
|
|
||||||
// (e.g., document unloaded). Silently resolve.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Aborts all operations, removes fonts from document, and clears state. Manager cannot be reused after. */
|
/** Aborts all operations, removes fonts from document, and clears state. Manager cannot be reused after. */
|
||||||
destroy() {
|
destroy() {
|
||||||
|
// Abort all in-flight network requests
|
||||||
this.#abortController.abort();
|
this.#abortController.abort();
|
||||||
|
|
||||||
|
// Cancel pending queue processing (idle callback or timeout)
|
||||||
if (this.#timeoutId !== null) {
|
if (this.#timeoutId !== null) {
|
||||||
if (this.#pendingType === 'idle' && typeof cancelIdleCallback !== 'undefined') {
|
if (this.#pendingType === 'idle' && typeof cancelIdleCallback !== 'undefined') {
|
||||||
cancelIdleCallback(this.#timeoutId as unknown as number);
|
cancelIdleCallback(this.#timeoutId as unknown as number);
|
||||||
@@ -339,25 +324,26 @@ export class AppliedFontsManager {
|
|||||||
this.#pendingType = null;
|
this.#pendingType = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Stop periodic cleanup timer
|
||||||
if (this.#intervalId) {
|
if (this.#intervalId) {
|
||||||
clearInterval(this.#intervalId);
|
clearInterval(this.#intervalId);
|
||||||
this.#intervalId = null;
|
this.#intervalId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remove all loaded fonts from document
|
||||||
if (typeof document !== 'undefined') {
|
if (typeof document !== 'undefined') {
|
||||||
for (const font of this.#loadedFonts.values()) {
|
for (const font of this.#loadedFonts.values()) {
|
||||||
document.fonts.delete(font);
|
document.fonts.delete(font);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clear all state and collaborators
|
||||||
this.#loadedFonts.clear();
|
this.#loadedFonts.clear();
|
||||||
this.#usageTracker.clear();
|
|
||||||
this.#retryCounts.clear();
|
|
||||||
this.#buffersByUrl.clear();
|
|
||||||
this.#urlByKey.clear();
|
this.#urlByKey.clear();
|
||||||
this.#pinnedFonts.clear();
|
this.#cache.clear();
|
||||||
this.statuses.clear();
|
this.#eviction.clear();
|
||||||
this.#queue.clear();
|
this.#queue.clear();
|
||||||
|
this.statuses.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
35
src/entities/Font/model/store/appliedFontsStore/errors.ts
Normal file
35
src/entities/Font/model/store/appliedFontsStore/errors.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
/**
|
||||||
|
* Thrown by {@link FontBufferCache} when a font file cannot be retrieved from the network or cache.
|
||||||
|
*
|
||||||
|
* @property url - The URL that was requested.
|
||||||
|
* @property cause - The underlying error, if any.
|
||||||
|
* @property status - HTTP status code. Present on HTTP errors, absent on network failures.
|
||||||
|
*/
|
||||||
|
export class FontFetchError extends Error {
|
||||||
|
readonly name = 'FontFetchError';
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
public readonly url: string,
|
||||||
|
public readonly cause?: unknown,
|
||||||
|
public readonly status?: number,
|
||||||
|
) {
|
||||||
|
super(status ? `HTTP ${status} fetching font: ${url}` : `Network error fetching font: ${url}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown by {@link loadFont} when a font buffer cannot be parsed into a {@link FontFace}.
|
||||||
|
*
|
||||||
|
* @property fontName - The display name of the font that failed to parse.
|
||||||
|
* @property cause - The underlying error from the FontFace API.
|
||||||
|
*/
|
||||||
|
export class FontParseError extends Error {
|
||||||
|
readonly name = 'FontParseError';
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
public readonly fontName: string,
|
||||||
|
public readonly cause?: unknown,
|
||||||
|
) {
|
||||||
|
super(`Failed to parse font: ${fontName}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
/** @vitest-environment jsdom */
|
||||||
|
import { FontFetchError } from '../errors';
|
||||||
|
import { FontBufferCache } from './FontBufferCache';
|
||||||
|
|
||||||
|
const makeBuffer = () => new ArrayBuffer(8);
|
||||||
|
|
||||||
|
const makeFetcher = (overrides: Partial<Response> = {}) =>
|
||||||
|
vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
arrayBuffer: () => Promise.resolve(makeBuffer()),
|
||||||
|
clone: () => ({ ok: true, status: 200, arrayBuffer: () => Promise.resolve(makeBuffer()) }),
|
||||||
|
...overrides,
|
||||||
|
} as Response);
|
||||||
|
|
||||||
|
describe('FontBufferCache', () => {
|
||||||
|
let cache: FontBufferCache;
|
||||||
|
let fetcher: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fetcher = makeFetcher();
|
||||||
|
cache = new FontBufferCache({ fetcher });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns buffer from memory on second call without fetching', async () => {
|
||||||
|
await cache.get('https://example.com/font.woff2');
|
||||||
|
await cache.get('https://example.com/font.woff2');
|
||||||
|
|
||||||
|
expect(fetcher).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws FontFetchError on HTTP error with correct status', async () => {
|
||||||
|
const errorFetcher = makeFetcher({ ok: false, status: 404 });
|
||||||
|
const errorCache = new FontBufferCache({ fetcher: errorFetcher });
|
||||||
|
|
||||||
|
const err = await errorCache.get('https://example.com/font.woff2').catch(e => e);
|
||||||
|
expect(err).toBeInstanceOf(FontFetchError);
|
||||||
|
expect(err.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws FontFetchError on network failure without status', async () => {
|
||||||
|
const networkFetcher = vi.fn().mockRejectedValue(new Error('network down'));
|
||||||
|
const networkCache = new FontBufferCache({ fetcher: networkFetcher });
|
||||||
|
|
||||||
|
const err = await networkCache.get('https://example.com/font.woff2').catch(e => e);
|
||||||
|
expect(err).toBeInstanceOf(FontFetchError);
|
||||||
|
expect(err.status).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('evict removes url from memory so next call fetches again', async () => {
|
||||||
|
await cache.get('https://example.com/font.woff2');
|
||||||
|
cache.evict('https://example.com/font.woff2');
|
||||||
|
await cache.get('https://example.com/font.woff2');
|
||||||
|
|
||||||
|
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clear wipes all memory cache entries', async () => {
|
||||||
|
await cache.get('https://example.com/a.woff2');
|
||||||
|
await cache.get('https://example.com/b.woff2');
|
||||||
|
cache.clear();
|
||||||
|
await cache.get('https://example.com/a.woff2');
|
||||||
|
|
||||||
|
expect(fetcher).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { FontFetchError } from '../errors';
|
||||||
|
|
||||||
|
type Fetcher = (url: string, init?: RequestInit) => Promise<Response>;
|
||||||
|
|
||||||
|
interface FontBufferCacheOptions {
|
||||||
|
/** Custom fetch implementation. Defaults to `globalThis.fetch`. Inject in tests for isolation. */
|
||||||
|
fetcher?: Fetcher;
|
||||||
|
/** Cache API cache name. Defaults to `'font-cache-v1'`. */
|
||||||
|
cacheName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Three-tier font buffer cache: in-memory → Cache API → network.
|
||||||
|
*
|
||||||
|
* - **Tier 1 (memory):** Fastest — no I/O. Populated after first successful fetch.
|
||||||
|
* - **Tier 2 (Cache API):** Persists across page loads. Silently skipped in private browsing.
|
||||||
|
* - **Tier 3 (network):** Raw fetch. Throws {@link FontFetchError} on failure.
|
||||||
|
*
|
||||||
|
* The `fetcher` option is injectable for testing — pass a `vi.fn()` to avoid real network calls.
|
||||||
|
*/
|
||||||
|
export class FontBufferCache {
|
||||||
|
#buffersByUrl = new Map<string, ArrayBuffer>();
|
||||||
|
|
||||||
|
readonly #fetcher: Fetcher;
|
||||||
|
readonly #cacheName: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
{ fetcher = globalThis.fetch.bind(globalThis), cacheName = 'font-cache-v1' }: FontBufferCacheOptions = {},
|
||||||
|
) {
|
||||||
|
this.#fetcher = fetcher;
|
||||||
|
this.#cacheName = cacheName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves the font buffer for the given URL using the three-tier strategy.
|
||||||
|
* Stores the result in memory on success.
|
||||||
|
*
|
||||||
|
* @throws {@link FontFetchError} if the network request fails or returns a non-OK response.
|
||||||
|
*/
|
||||||
|
async get(url: string, signal?: AbortSignal): Promise<ArrayBuffer> {
|
||||||
|
// Tier 1: in-memory (fastest, no I/O)
|
||||||
|
const inMemory = this.#buffersByUrl.get(url);
|
||||||
|
if (inMemory) return inMemory;
|
||||||
|
|
||||||
|
// Tier 2: Cache API
|
||||||
|
try {
|
||||||
|
if (typeof caches !== 'undefined') {
|
||||||
|
const cache = await caches.open(this.#cacheName);
|
||||||
|
const cached = await cache.match(url);
|
||||||
|
if (cached) {
|
||||||
|
const buffer = await cached.arrayBuffer();
|
||||||
|
this.#buffersByUrl.set(url, buffer);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Cache unavailable (private browsing, security restrictions) — fall through to network
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tier 3: network
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await this.#fetcher(url, { signal });
|
||||||
|
} catch (cause) {
|
||||||
|
throw new FontFetchError(url, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new FontFetchError(url, undefined, response.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (typeof caches !== 'undefined') {
|
||||||
|
const cache = await caches.open(this.#cacheName);
|
||||||
|
await cache.put(url, response.clone());
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Cache write failed (quota, storage pressure) — return font anyway
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = await response.arrayBuffer();
|
||||||
|
this.#buffersByUrl.set(url, buffer);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Removes a URL from the in-memory cache. Next call to `get()` will re-fetch. */
|
||||||
|
evict(url: string): void {
|
||||||
|
this.#buffersByUrl.delete(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clears all in-memory cached buffers. */
|
||||||
|
clear(): void {
|
||||||
|
this.#buffersByUrl.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { FontEvictionPolicy } from './FontEvictionPolicy';
|
||||||
|
|
||||||
|
describe('FontEvictionPolicy', () => {
|
||||||
|
let policy: FontEvictionPolicy;
|
||||||
|
const TTL = 1000;
|
||||||
|
const t0 = 100000;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
policy = new FontEvictionPolicy({ ttl: TTL });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shouldEvict returns false within TTL', () => {
|
||||||
|
policy.touch('a@400', t0);
|
||||||
|
expect(policy.shouldEvict('a@400', t0 + TTL - 1)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shouldEvict returns true at TTL boundary', () => {
|
||||||
|
policy.touch('a@400', t0);
|
||||||
|
expect(policy.shouldEvict('a@400', t0 + TTL)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shouldEvict returns false for pinned key regardless of TTL', () => {
|
||||||
|
policy.touch('a@400', t0);
|
||||||
|
policy.pin('a@400');
|
||||||
|
expect(policy.shouldEvict('a@400', t0 + TTL * 10)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shouldEvict returns true again after unpin past TTL', () => {
|
||||||
|
policy.touch('a@400', t0);
|
||||||
|
policy.pin('a@400');
|
||||||
|
policy.unpin('a@400');
|
||||||
|
expect(policy.shouldEvict('a@400', t0 + TTL)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shouldEvict returns false for untracked key', () => {
|
||||||
|
expect(policy.shouldEvict('never@touched', t0 + TTL * 100)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keys returns all tracked keys', () => {
|
||||||
|
policy.touch('a@400', t0);
|
||||||
|
policy.touch('b@vf', t0);
|
||||||
|
expect(Array.from(policy.keys())).toEqual(expect.arrayContaining(['a@400', 'b@vf']));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clear resets all state', () => {
|
||||||
|
policy.touch('a@400', t0);
|
||||||
|
policy.pin('a@400');
|
||||||
|
policy.clear();
|
||||||
|
expect(Array.from(policy.keys())).toHaveLength(0);
|
||||||
|
expect(policy.shouldEvict('a@400', t0 + TTL * 10)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
interface FontEvictionPolicyOptions {
|
||||||
|
/** TTL in milliseconds. Defaults to 5 minutes. */
|
||||||
|
ttl?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tracks font usage timestamps and pinned keys to determine when a font should be evicted.
|
||||||
|
*
|
||||||
|
* Pure data — no browser APIs. Accepts explicit `now` timestamps so tests
|
||||||
|
* never need fake timers.
|
||||||
|
*/
|
||||||
|
export class FontEvictionPolicy {
|
||||||
|
#usageTracker = new Map<string, number>();
|
||||||
|
#pinnedFonts = new Set<string>();
|
||||||
|
|
||||||
|
readonly #TTL: number;
|
||||||
|
|
||||||
|
constructor({ ttl = 5 * 60 * 1000 }: FontEvictionPolicyOptions = {}) {
|
||||||
|
this.#TTL = ttl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records the last-used time for a font key.
|
||||||
|
* @param key - Font key in `{id}@{weight}` or `{id}@vf` format.
|
||||||
|
* @param now - Current timestamp in ms. Defaults to `Date.now()`.
|
||||||
|
*/
|
||||||
|
touch(key: string, now: number = Date.now()): void {
|
||||||
|
this.#usageTracker.set(key, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pins a font key so it is never evicted regardless of TTL. */
|
||||||
|
pin(key: string): void {
|
||||||
|
this.#pinnedFonts.add(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unpins a font key, allowing it to be evicted once its TTL expires. */
|
||||||
|
unpin(key: string): void {
|
||||||
|
this.#pinnedFonts.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns `true` if the font should be evicted.
|
||||||
|
* A font is evicted when its TTL has elapsed and it is not pinned.
|
||||||
|
* Returns `false` for untracked keys.
|
||||||
|
*
|
||||||
|
* @param key - Font key to check.
|
||||||
|
* @param now - Current timestamp in ms (pass explicitly for deterministic tests).
|
||||||
|
*/
|
||||||
|
shouldEvict(key: string, now: number): boolean {
|
||||||
|
const lastUsed = this.#usageTracker.get(key);
|
||||||
|
if (lastUsed === undefined) return false;
|
||||||
|
if (this.#pinnedFonts.has(key)) return false;
|
||||||
|
return now - lastUsed >= this.#TTL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns an iterator over all tracked font keys. */
|
||||||
|
keys(): IterableIterator<string> {
|
||||||
|
return this.#usageTracker.keys();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clears all usage timestamps and pinned keys. */
|
||||||
|
clear(): void {
|
||||||
|
this.#usageTracker.clear();
|
||||||
|
this.#pinnedFonts.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import type { FontLoadRequestConfig } from '../../../types';
|
||||||
|
import { FontLoadQueue } from './FontLoadQueue';
|
||||||
|
|
||||||
|
const config = (id: string): FontLoadRequestConfig => ({
|
||||||
|
id,
|
||||||
|
name: id,
|
||||||
|
url: `https://example.com/${id}.woff2`,
|
||||||
|
weight: 400,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('FontLoadQueue', () => {
|
||||||
|
let queue: FontLoadQueue;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
queue = new FontLoadQueue();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enqueue returns true for a new key', () => {
|
||||||
|
expect(queue.enqueue('a@400', config('a'))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enqueue returns false for an already-queued key', () => {
|
||||||
|
queue.enqueue('a@400', config('a'));
|
||||||
|
expect(queue.enqueue('a@400', config('a'))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('has returns true after enqueue, false after flush', () => {
|
||||||
|
queue.enqueue('a@400', config('a'));
|
||||||
|
expect(queue.has('a@400')).toBe(true);
|
||||||
|
queue.flush();
|
||||||
|
expect(queue.has('a@400')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('flush returns all entries and atomically clears the queue', () => {
|
||||||
|
queue.enqueue('a@400', config('a'));
|
||||||
|
queue.enqueue('b@700', config('b'));
|
||||||
|
const entries = queue.flush();
|
||||||
|
expect(entries).toHaveLength(2);
|
||||||
|
expect(queue.has('a@400')).toBe(false);
|
||||||
|
expect(queue.has('b@700')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('isMaxRetriesReached returns false below MAX_RETRIES', () => {
|
||||||
|
queue.incrementRetry('a@400');
|
||||||
|
queue.incrementRetry('a@400');
|
||||||
|
expect(queue.isMaxRetriesReached('a@400')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('isMaxRetriesReached returns true at MAX_RETRIES (3)', () => {
|
||||||
|
queue.incrementRetry('a@400');
|
||||||
|
queue.incrementRetry('a@400');
|
||||||
|
queue.incrementRetry('a@400');
|
||||||
|
expect(queue.isMaxRetriesReached('a@400')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clear resets queue and retry counts', () => {
|
||||||
|
queue.enqueue('a@400', config('a'));
|
||||||
|
queue.incrementRetry('a@400');
|
||||||
|
queue.incrementRetry('a@400');
|
||||||
|
queue.incrementRetry('a@400');
|
||||||
|
queue.clear();
|
||||||
|
expect(queue.has('a@400')).toBe(false);
|
||||||
|
expect(queue.isMaxRetriesReached('a@400')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import type { FontLoadRequestConfig } from '../../../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages the font load queue and per-font retry counts.
|
||||||
|
*
|
||||||
|
* Scheduling (when to drain the queue) is handled by the orchestrator —
|
||||||
|
* this class is purely concerned with what is queued and whether retries are exhausted.
|
||||||
|
*/
|
||||||
|
export class FontLoadQueue {
|
||||||
|
#queue = new Map<string, FontLoadRequestConfig>();
|
||||||
|
#retryCounts = new Map<string, number>();
|
||||||
|
|
||||||
|
readonly #MAX_RETRIES = 3;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a font to the queue.
|
||||||
|
* @returns `true` if the key was newly enqueued, `false` if it was already present.
|
||||||
|
*/
|
||||||
|
enqueue(key: string, config: FontLoadRequestConfig): boolean {
|
||||||
|
if (this.#queue.has(key)) return false;
|
||||||
|
this.#queue.set(key, config);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomically snapshots and clears the queue.
|
||||||
|
* @returns All queued entries at the time of the call.
|
||||||
|
*/
|
||||||
|
flush(): Array<[string, FontLoadRequestConfig]> {
|
||||||
|
const entries = Array.from(this.#queue.entries());
|
||||||
|
this.#queue.clear();
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns `true` if the key is currently in the queue. */
|
||||||
|
has(key: string): boolean {
|
||||||
|
return this.#queue.has(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Increments the retry count for a font key. */
|
||||||
|
incrementRetry(key: string): void {
|
||||||
|
this.#retryCounts.set(key, (this.#retryCounts.get(key) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns `true` if the font has reached or exceeded the maximum retry limit. */
|
||||||
|
isMaxRetriesReached(key: string): boolean {
|
||||||
|
return (this.#retryCounts.get(key) ?? 0) >= this.#MAX_RETRIES;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clears all queued fonts and resets all retry counts. */
|
||||||
|
clear(): void {
|
||||||
|
this.#queue.clear();
|
||||||
|
this.#retryCounts.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { generateFontKey } from './generateFontKey';
|
||||||
|
|
||||||
|
describe('generateFontKey', () => {
|
||||||
|
it('should throw an error if font id is not provided', () => {
|
||||||
|
const config = { weight: 400, isVariable: false };
|
||||||
|
// @ts-expect-error
|
||||||
|
expect(() => generateFontKey(config)).toThrow('Font id is required');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should generate a font key for a variable font', () => {
|
||||||
|
const config = { id: 'Roboto', weight: 400, isVariable: true };
|
||||||
|
expect(generateFontKey(config)).toBe('roboto@vf');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw an error if font weight is not provided and is not a variable font', () => {
|
||||||
|
const config = { id: 'Roboto', isVariable: false };
|
||||||
|
// @ts-expect-error
|
||||||
|
expect(() => generateFontKey(config)).toThrow('Font weight is required');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should generate a font key for a non-variable font', () => {
|
||||||
|
const config = { id: 'Roboto', weight: 400, isVariable: false };
|
||||||
|
expect(generateFontKey(config)).toBe('roboto@400');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import type { FontLoadRequestConfig } from '../../../../types';
|
||||||
|
|
||||||
|
export type PartialConfig = Pick<FontLoadRequestConfig, 'id' | 'weight' | 'isVariable'>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a font key for a given font load request configuration.
|
||||||
|
* @param config - The font load request configuration.
|
||||||
|
* @returns The generated font key.
|
||||||
|
*/
|
||||||
|
export function generateFontKey(config: PartialConfig): string {
|
||||||
|
if (!config.id) {
|
||||||
|
throw new Error('Font id is required');
|
||||||
|
}
|
||||||
|
if (config.isVariable) {
|
||||||
|
return `${config.id.toLowerCase()}@vf`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!config.weight) {
|
||||||
|
throw new Error('Font weight is required');
|
||||||
|
}
|
||||||
|
return `${config.id.toLowerCase()}@${config.weight}`;
|
||||||
|
}
|
||||||
@@ -1,2 +1,4 @@
|
|||||||
|
export { generateFontKey } from './generateFontKey/generateFontKey';
|
||||||
export { getEffectiveConcurrency } from './getEffectiveConcurrency/getEffectiveConcurrency';
|
export { getEffectiveConcurrency } from './getEffectiveConcurrency/getEffectiveConcurrency';
|
||||||
|
export { loadFont } from './loadFont/loadFont';
|
||||||
export { yieldToMainThread } from './yieldToMainThread/yieldToMainThread';
|
export { yieldToMainThread } from './yieldToMainThread/yieldToMainThread';
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
/** @vitest-environment jsdom */
|
||||||
|
import { FontParseError } from '../../errors';
|
||||||
|
import { loadFont } from './loadFont';
|
||||||
|
|
||||||
|
describe('loadFont', () => {
|
||||||
|
let mockFontInstance: any;
|
||||||
|
let mockFontFaceSet: { add: ReturnType<typeof vi.fn>; delete: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFontFaceSet = { add: vi.fn(), delete: vi.fn() };
|
||||||
|
Object.defineProperty(document, 'fonts', { value: mockFontFaceSet, configurable: true, writable: true });
|
||||||
|
|
||||||
|
const MockFontFace = vi.fn(
|
||||||
|
function(this: any, name: string, buffer: BufferSource, options: FontFaceDescriptors) {
|
||||||
|
this.name = name;
|
||||||
|
this.buffer = buffer;
|
||||||
|
this.options = options;
|
||||||
|
this.load = vi.fn().mockResolvedValue(this);
|
||||||
|
mockFontInstance = this;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
vi.stubGlobal('FontFace', MockFontFace);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('constructs FontFace with exact weight for static fonts', async () => {
|
||||||
|
const buffer = new ArrayBuffer(8);
|
||||||
|
await loadFont({ name: 'Roboto', weight: 400 }, buffer);
|
||||||
|
|
||||||
|
expect(FontFace).toHaveBeenCalledWith('Roboto', buffer, expect.objectContaining({ weight: '400' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('constructs FontFace with weight range for variable fonts', async () => {
|
||||||
|
const buffer = new ArrayBuffer(8);
|
||||||
|
await loadFont({ name: 'Roboto', weight: 400, isVariable: true }, buffer);
|
||||||
|
|
||||||
|
expect(FontFace).toHaveBeenCalledWith('Roboto', buffer, expect.objectContaining({ weight: '100 900' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets style: normal and display: swap on FontFace options', async () => {
|
||||||
|
await loadFont({ name: 'Lato', weight: 700 }, new ArrayBuffer(8));
|
||||||
|
|
||||||
|
expect(FontFace).toHaveBeenCalledWith(
|
||||||
|
'Lato',
|
||||||
|
expect.anything(),
|
||||||
|
expect.objectContaining({ style: 'normal', display: 'swap' }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes the buffer as the second argument to FontFace', async () => {
|
||||||
|
const buffer = new ArrayBuffer(16);
|
||||||
|
await loadFont({ name: 'Inter', weight: 400 }, buffer);
|
||||||
|
|
||||||
|
expect(FontFace).toHaveBeenCalledWith('Inter', buffer, expect.anything());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls font.load() and adds the font to document.fonts', async () => {
|
||||||
|
const buffer = new ArrayBuffer(8);
|
||||||
|
const result = await loadFont({ name: 'Inter', weight: 400 }, buffer);
|
||||||
|
|
||||||
|
expect(mockFontInstance.load).toHaveBeenCalledOnce();
|
||||||
|
expect(mockFontFaceSet.add).toHaveBeenCalledWith(mockFontInstance);
|
||||||
|
expect(result).toBe(mockFontInstance);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws FontParseError when font.load() rejects', async () => {
|
||||||
|
const loadError = new Error('parse failed');
|
||||||
|
const MockFontFace = vi.fn(
|
||||||
|
function(this: any, name: string, buffer: BufferSource, options: FontFaceDescriptors) {
|
||||||
|
this.load = vi.fn().mockRejectedValue(loadError);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
vi.stubGlobal('FontFace', MockFontFace);
|
||||||
|
|
||||||
|
await expect(loadFont({ name: 'Broken', weight: 400 }, new ArrayBuffer(8))).rejects.toBeInstanceOf(
|
||||||
|
FontParseError,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws FontParseError when document.fonts.add throws', async () => {
|
||||||
|
const addError = new Error('add failed');
|
||||||
|
mockFontFaceSet.add.mockImplementation(() => {
|
||||||
|
throw addError;
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(loadFont({ name: 'Broken', weight: 400 }, new ArrayBuffer(8))).rejects.toBeInstanceOf(
|
||||||
|
FontParseError,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { FontLoadRequestConfig } from '../../../../types';
|
||||||
|
import { FontParseError } from '../../errors';
|
||||||
|
|
||||||
|
export type PartialConfig = Pick<FontLoadRequestConfig, 'weight' | 'name' | 'isVariable'>;
|
||||||
|
/**
|
||||||
|
* Loads a font from a buffer and adds it to the document's font collection.
|
||||||
|
* @param config - The font load request configuration.
|
||||||
|
* @param buffer - The buffer containing the font data.
|
||||||
|
* @returns A promise that resolves to the loaded `FontFace`.
|
||||||
|
* @throws {@link FontParseError} When the font buffer cannot be parsed or added to the document font set.
|
||||||
|
*/
|
||||||
|
export async function loadFont(config: PartialConfig, buffer: BufferSource): Promise<FontFace> {
|
||||||
|
try {
|
||||||
|
const weightRange = config.isVariable ? '100 900' : `${config.weight}`;
|
||||||
|
const font = new FontFace(config.name, buffer, {
|
||||||
|
weight: weightRange,
|
||||||
|
style: 'normal',
|
||||||
|
display: 'swap',
|
||||||
|
});
|
||||||
|
await font.load();
|
||||||
|
document.fonts.add(font);
|
||||||
|
|
||||||
|
return font;
|
||||||
|
} catch (error) {
|
||||||
|
throw new FontParseError(config.name, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,4 @@ export {
|
|||||||
} from './unifiedFontStore.svelte';
|
} from './unifiedFontStore.svelte';
|
||||||
|
|
||||||
// Applied fonts manager (CSS loading - unchanged)
|
// Applied fonts manager (CSS loading - unchanged)
|
||||||
export {
|
export { appliedFontsManager } from './appliedFontsStore/appliedFontsStore.svelte';
|
||||||
appliedFontsManager,
|
|
||||||
type FontConfigRequest,
|
|
||||||
} from './appliedFontsStore/appliedFontsStore.svelte';
|
|
||||||
|
|||||||
@@ -56,3 +56,5 @@ export type {
|
|||||||
FontCollectionSort,
|
FontCollectionSort,
|
||||||
FontCollectionState,
|
FontCollectionState,
|
||||||
} from './store';
|
} from './store';
|
||||||
|
|
||||||
|
export * from './store/appliedFonts';
|
||||||
|
|||||||
30
src/entities/Font/model/types/store/appliedFonts.ts
Normal file
30
src/entities/Font/model/types/store/appliedFonts.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
/**
|
||||||
|
* Configuration for a font load request.
|
||||||
|
*/
|
||||||
|
export interface FontLoadRequestConfig {
|
||||||
|
/**
|
||||||
|
* Unique identifier for the font (e.g., "lato", "roboto").
|
||||||
|
*/
|
||||||
|
id: string;
|
||||||
|
/**
|
||||||
|
* Actual font family name recognized by the browser (e.g., "Lato", "Roboto").
|
||||||
|
*/
|
||||||
|
name: string;
|
||||||
|
/**
|
||||||
|
* URL pointing to the font file (typically .ttf or .woff2).
|
||||||
|
*/
|
||||||
|
url: string;
|
||||||
|
/**
|
||||||
|
* Numeric weight (100-900). Variable fonts load once per ID regardless of weight.
|
||||||
|
*/
|
||||||
|
weight: number;
|
||||||
|
/**
|
||||||
|
* Variable fonts load once per ID; static fonts load per weight.
|
||||||
|
*/
|
||||||
|
isVariable?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loading state of a font.
|
||||||
|
*/
|
||||||
|
export type FontLoadStatus = 'loading' | 'loaded' | 'error';
|
||||||
@@ -15,7 +15,7 @@ import type {
|
|||||||
import { fade } from 'svelte/transition';
|
import { fade } from 'svelte/transition';
|
||||||
import { getFontUrl } from '../../lib';
|
import { getFontUrl } from '../../lib';
|
||||||
import {
|
import {
|
||||||
type FontConfigRequest,
|
type FontLoadRequestConfig,
|
||||||
type UnifiedFont,
|
type UnifiedFont,
|
||||||
appliedFontsManager,
|
appliedFontsManager,
|
||||||
unifiedFontStore,
|
unifiedFontStore,
|
||||||
@@ -54,7 +54,7 @@ const isLoading = $derived(
|
|||||||
);
|
);
|
||||||
|
|
||||||
function handleInternalVisibleChange(visibleItems: UnifiedFont[]) {
|
function handleInternalVisibleChange(visibleItems: UnifiedFont[]) {
|
||||||
const configs: FontConfigRequest[] = [];
|
const configs: FontLoadRequestConfig[] = [];
|
||||||
|
|
||||||
visibleItems.forEach(item => {
|
visibleItems.forEach(item => {
|
||||||
const url = getFontUrl(item, weight);
|
const url = getFontUrl(item, weight);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
* @example
|
* @example
|
||||||
* ```ts
|
* ```ts
|
||||||
* buildQueryString({ category: 'serif', subsets: ['latin', 'latin-ext'] })
|
* buildQueryString({ category: 'serif', subsets: ['latin', 'latin-ext'] })
|
||||||
* // Returns: "?category=serif&subsets=latin%2Clatin-ext"
|
* // Returns: "?category=serif&subsets=latin&subsets=latin-ext"
|
||||||
*
|
*
|
||||||
* buildQueryString({ limit: 50, page: 1 })
|
* buildQueryString({ limit: 50, page: 1 })
|
||||||
* // Returns: "?limit=50&page=1"
|
* // Returns: "?limit=50&page=1"
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
* // Returns: ""
|
* // Returns: ""
|
||||||
*
|
*
|
||||||
* buildQueryString({ search: 'hello world', active: true })
|
* buildQueryString({ search: 'hello world', active: true })
|
||||||
* // Returns: "?search=hello%20world&active=true"
|
* // Returns: "?search=hello+world&active=true"
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ export type QueryParams = Record<string, QueryParamValue | undefined | null>;
|
|||||||
*
|
*
|
||||||
* Handles:
|
* Handles:
|
||||||
* - Primitive values (string, number, boolean) - converted to strings
|
* - Primitive values (string, number, boolean) - converted to strings
|
||||||
* - Arrays - comma-separated values
|
* - Arrays - multiple parameters with same key (e.g., ?key=1&key=2&key=3)
|
||||||
* - null/undefined - omitted from output
|
* - null/undefined - omitted from output
|
||||||
* - Special characters - URL encoded
|
* - Special characters - URL encoded
|
||||||
*
|
*
|
||||||
@@ -51,14 +51,12 @@ export function buildQueryString(params: QueryParams): string {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle arrays (comma-separated values)
|
// Handle arrays - append each item as separate parameter with same key
|
||||||
if (Array.isArray(value)) {
|
if (Array.isArray(value)) {
|
||||||
const joined = value
|
for (const item of value) {
|
||||||
.filter(item => item !== undefined && item !== null)
|
if (item !== undefined && item !== null) {
|
||||||
.map(String)
|
searchParams.append(key, String(item));
|
||||||
.join(',');
|
}
|
||||||
if (joined) {
|
|
||||||
searchParams.append(key, joined);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Handle primitives
|
// Handle primitives
|
||||||
|
|||||||
Reference in New Issue
Block a user