import { presetFonts, type Preset } from '@cdx-ui/styles'; import { buildWebFontStylesheetUrl } from './override/webFonts'; const LINK_ID_PREFIX = 'cdx-theme-editor-fonts-'; function buildGoogleFontsUrl(families: readonly string[]): string { return buildWebFontStylesheetUrl( families.map((family) => ({ family, weights: [400, 500, 600, 700], italic: true, })), ); } function injectLink(id: string, href: string): void { const existing = document.getElementById(id); if (existing) { if ((existing as HTMLLinkElement).href === href) return; existing.remove(); } const link = document.createElement('link'); link.id = id; link.rel = 'stylesheet'; link.href = href; document.head.appendChild(link); } function removeLink(id: string): void { document.getElementById(id)?.remove(); } /** * Load the display fonts for a given preset via Google Fonts CDN. * Removes previously loaded preset fonts before injecting. */ export function loadPresetFonts(preset: Preset): void { const presets: Preset[] = ['poise', 'prestige', 'pulse']; for (const p of presets) { if (p !== preset) { removeLink(`${LINK_ID_PREFIX}${p}`); } } const families = presetFonts[preset]; const url = buildGoogleFontsUrl(families); injectLink(`${LINK_ID_PREFIX}${preset}`, url); } /** * Load platform fonts shared across all presets (Inter, IBM Plex Mono). */ export function loadPlatformFonts(): void { const url = buildGoogleFontsUrl(['Inter', 'IBM Plex Mono']); injectLink(`${LINK_ID_PREFIX}platform`, url); } /** * Remove all theme editor font links from the document. */ export function cleanupFontLinks(): void { const presets: Preset[] = ['poise', 'prestige', 'pulse']; for (const p of presets) { removeLink(`${LINK_ID_PREFIX}${p}`); } removeLink(`${LINK_ID_PREFIX}platform`); }