(
{ family, weight = 'normal', style = 'normal' }: FontFace,
text = 'BESbswy', // Default text to test font loading.
timeout = 15_000,
)
| 19 | const isClient = typeof window !== 'undefined'; |
| 20 | |
| 21 | const loadFont = async ( |
| 22 | { family, weight = 'normal', style = 'normal' }: FontFace, |
| 23 | text = 'BESbswy', // Default text to test font loading. |
| 24 | timeout = 15_000, |
| 25 | ) => { |
| 26 | // e.g., "italic 700 100px 'Roboto'" |
| 27 | const fontShorthand = `${style} ${weight} 100px "${family}"`; |
| 28 | |
| 29 | // We check for `document.fonts` to prevent errors in non-browser environments (like SSR). |
| 30 | if (!isClient || !document?.fonts) { |
| 31 | // Resolve immediately on the server or in unsupported environments. |
| 32 | console.warn('Font Loading API not supported. Skipping font load.'); |
| 33 | return Promise.resolve(); |
| 34 | } |
| 35 | |
| 36 | let timeoutId: number | undefined; |
| 37 | |
| 38 | const loaderPromise = document.fonts |
| 39 | .load(fontShorthand, text) |
| 40 | .then((fonts) => { |
| 41 | if (fonts.length === 0) { |
| 42 | throw new Error(`Font '${family}' failed to load or was not found.`); |
| 43 | } |
| 44 | }); |
| 45 | |
| 46 | const timeoutPromise = new Promise((_, reject) => { |
| 47 | if (isClient) { |
| 48 | timeoutId = window.setTimeout(() => { |
| 49 | reject(new Error(`Font '${family}' timed out after ${timeout}ms.`)); |
| 50 | }, timeout); |
| 51 | } else { |
| 52 | // On server, immediately reject to avoid hanging promises. |
| 53 | reject(); |
| 54 | } |
| 55 | }); |
| 56 | |
| 57 | try { |
| 58 | return await Promise.race([loaderPromise, timeoutPromise]); |
| 59 | } finally { |
| 60 | // Cleanup to prevent memory leaks. |
| 61 | if (timeoutId && isClient) { |
| 62 | window.clearTimeout(timeoutId); |
| 63 | } |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | const notify = (cacheKey: string) => { |
| 68 | for (const callback of subscribers.get(cacheKey) ?? []) { |
no test coverage detected