Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(theme): font declarations with runtime fallback (#788)

Cindy Zhangf87af96a76da
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index 0bee6c91af..2c991ff447 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -697,5 +697,15 @@ Or with a <link> tag:
<App />
</XDSTheme>
`);
+
+ // Print font declaration warnings
+ if (themeDef.fonts && themeDef.fonts.length > 0) {
+ console.log(`\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`);
+ for (const font of themeDef.fonts) {
+ console.log(` ${font.family} — add to your document <head>:`);
+ console.log(` <link rel="stylesheet" href="${font.url}" />`);
+ }
+ console.log('');
+ }
});
}
diff --git a/packages/core/src/theme/XDSTheme.tsx b/packages/core/src/theme/XDSTheme.tsx
index 3c97466afd..d176ef6520 100644
--- a/packages/core/src/theme/XDSTheme.tsx
+++ b/packages/core/src/theme/XDSTheme.tsx
@@ -20,7 +20,7 @@
'use client';
-import React, {useId, useInsertionEffect} from 'react';
+import React, {useId, useInsertionEffect, useLayoutEffect, useRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {ThemeMode} from './types';
import {colorVars, typographyVars} from './tokens.stylex';
@@ -103,6 +103,72 @@ function useThemeStyleInjection(theme: XDSDefinedTheme): void {
}, [theme, id]);
}
+// =============================================================================
+// Font loading for themes that declare fonts
+// =============================================================================
+
+/**
+ * Hook that loads fonts declared in theme.fonts at runtime.
+ *
+ * Uses useLayoutEffect to inject font stylesheets before the browser paints,
+ * minimizing flash of unstyled text (FOUT).
+ *
+ * This is the fallback loading path — the preferred approach is to add
+ * <link rel="stylesheet" href="..."> to your document <head>. For discoverability,
+ * `npx xds theme build` prints font instructions in the build output.
+ *
+ * A console warning is logged for each font loaded at runtime
+ * to encourage moving to the preload path.
+ */
+function useThemeFontLoading(theme: XDSDefinedTheme): void {
+ const injectedLinksRef = useRef<HTMLLinkElement[]>([]);
+
+ useLayoutEffect(() => {
+ if (typeof document === 'undefined') return;
+ if (!theme.fonts || theme.fonts.length === 0) return;
+
+ const newLinks: HTMLLinkElement[] = [];
+
+ for (const font of theme.fonts) {
+ // Check if font is already loaded
+ const isLoaded = document.fonts.check(`16px "${font.family}"`);
+ if (isLoaded) continue;
+
+ // Check if we already injected a link for this URL
+ const existing = document.head.querySelector(
+ `link[rel="stylesheet"][href="${font.url}"]`,
+ );
+ if (existing) continue;
+
+ // Inject the font stylesheet
+ const link = document.createElement('link');
+ link.rel = 'stylesheet';
+ link.href = font.url;
+ document.head.appendChild(link);
+ newLinks.push(link);
+
+ // Dev-mode warning to encourage preloading
+ // Warn to encourage preloading — only visible in devtools
+ console.warn(
+ `[XDS] Theme "${theme.name}" loaded font "${font.family}" at runtime. ` +
+ `For better performance, add to your document <head>:\n` +
+ ` <link rel="stylesheet" href="${font.url}" />`,
+ );
+ }
+
+ injectedLinksRef.current = newLinks;
+
+ return () => {
+ for (const link of injectedLinksRef.current) {
+ if (link.parentNode) {
+ link.parentNode.removeChild(link);
+ }
+ }
+ injectedLinksRef.current = [];
+ };
+ }, [theme.fonts, theme.name]);
+}
+
// =============================================================================
// Component
// =============================================================================
@@ -120,6 +186,7 @@ export function XDSTheme({
children,
}: XDSThemeProps): React.ReactElement {
useThemeStyleInjection(theme);
+ useThemeFontLoading(theme);
// Get color-scheme style
const colorSchemeStyle =
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index 5ee89f4c41..096562d078 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -545,3 +545,53 @@ describe('variants', () => {
);
});
});
+
+describe('defineTheme fonts', () => {
+ it('passes through fonts array from input', () => {
+ const fonts = [
+ {
+ family: 'Figtree',
+ url: 'https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700',
+ },
+ {
+ family: 'JetBrains Mono',
+ url: 'https://fonts.googleapis.com/css2?family=JetBrains+Mono',
+ },
+ ];
+ const theme = defineTheme({name: 'font-test', fonts});
+ expect(theme.fonts).toEqual(fonts);
+ expect(theme.fonts).toHaveLength(2);
+ expect(theme.fonts![0].family).toBe('Figtree');
+ expect(theme.fonts![1].url).toContain('JetBrains');
+ });
+
+ it('returns undefined fonts when not specified', () => {
+ const theme = defineTheme({name: 'no-fonts'});
+ expect(theme.fonts).toBeUndefined();
+ });
+
+ it('handles empty fonts array', () => {
+ const theme = defineTheme({name: 'empty-fonts', fonts: []});
+ expect(theme.fonts).toEqual([]);
+ expect(theme.fonts).toHaveLength(0);
+ });
+
+ it('combines fonts with tokens and other features', () => {
+ const theme = defineTheme({
+ name: 'combo-fonts',
+ tokens: {'--font-heading': '"Figtree", sans-serif'},
+ fonts: [
+ {
+ family: 'Figtree',
+ url: 'https://fonts.googleapis.com/css2?family=Figtree',
+ },
+ ],
+ typeScale: {base: 14, ratio: 1.2},
+ });
+ expect(theme.name).toBe('combo-fonts');
+ expect(theme.fonts).toHaveLength(1);
+ expect(theme.tokens['--font-heading']).toBe('"Figtree", sans-serif');
+ // typeScale tokens should still be present
+ expect(theme.tokens['--heading-4-size']).toBeDefined();
+ });
+});
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index eb3d817ab7..3eee2f3013 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -29,6 +29,7 @@
*/
import type {XDSIconRegistry} from '../Icon/globalIconRegistry';
+import type {ThemeFontSource} from './types';
import {parseStyleKey} from '../utils/parseStyleKey';
import {
colorDefaults,
@@ -253,6 +254,22 @@ export interface XDSDefineThemeInput {
* ```
*/
variants?: Record<string, Record<string, Record<string, string>>>;
+ /**
+ * Font declarations — fonts this theme requires.
+ *
+ * These are not bundled by the build — instead:
+ * - **Best**: Add `<link rel="stylesheet" href="...">` to your document `<head>` for preloading
+ * - **Build**: `npx xds theme build` prints instructions for any declared fonts
+ * - **Runtime**: `XDSTheme` loads missing fonts automatically as a fallback
+ *
+ * @example
+ * ```
+ * fonts: [
+ * { family: 'Figtree', url: 'https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700' },
+ * ]
+ * ```
+ */
+ fonts?: ThemeFontSource[];
}
/** A defined theme — ready to pass to <XDSTheme> */
@@ -269,6 +286,11 @@ export interface XDSDefinedTheme {
variants?: Record<string, string[]>;
/** Whether this theme has been pre-compiled by theme build CLI */
__built?: true;
+ /**
+ * Font declarations — fonts this theme requires.
+ * Passed through from defineTheme input unchanged.
+ */
+ fonts?: ThemeFontSource[];
}
// =============================================================================
@@ -432,6 +454,7 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
components,
icons: input.icons,
variants: variantNames,
+ fonts: input.fonts,
};
}
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index 1445cea128..1817b26f59 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -29,15 +29,9 @@ export type {
XDSStyleOverrides,
} from './defineTheme';
-export type {
- SyntaxTokenName,
- DomainTokenName,
-} from './domainTokens';
+export type {SyntaxTokenName, DomainTokenName} from './domainTokens';
-export {
- syntaxTokenDefaults,
- domainTokenDefaults,
-} from './domainTokens';
+export {syntaxTokenDefaults, domainTokenDefaults} from './domainTokens';
export {expandTypeScale, generateTypeScaleComponents} from './expandTypeScale';
export type {XDSTypeScaleConfig, TypeScaleTokens} from './expandTypeScale';
@@ -108,4 +102,5 @@ export type {
XDSTextSize,
XDSTextWeight,
XDSTextColor,
+ ThemeFontSource,
} from './types';
diff --git a/packages/core/src/theme/types.ts b/packages/core/src/theme/types.ts
index baca767865..120c044519 100644
--- a/packages/core/src/theme/types.ts
+++ b/packages/core/src/theme/types.ts
@@ -4,6 +4,25 @@
* Shared types used across XDS components.
*/
+/**
+ * A font source declaration for a theme.
+ * Used to declare fonts the theme requires so they can be preloaded,
+ * reported at build time, and loaded at runtime as a fallback.
+ *
+ * @example
+ * ```
+ * fonts: [
+ * { family: 'Figtree', url: 'https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700' },
+ * ]
+ * ```
+ */
+export interface ThemeFontSource {
+ /** Font family name, e.g. 'Figtree' */
+ family: string;
+ /** URL to load the font from, e.g. a Google Fonts URL */
+ url: string;
+}
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type StyleXStyles = any;