import type { PluginCreator, Root } from "postcss"; import type { Theme } from "../theme"; interface PluginOptions { theme: Theme; /** Google Fonts display parameter (default: 'swap') */ display?: "auto" | "block" | "swap" | "fallback" | "optional"; } const plugin: PluginCreator = (options) => { if (!options?.theme) { throw new Error("postcss-google-fonts: `theme` option is required"); } const { theme, display = "swap" } = options; return { postcssPlugin: "postcss-google-fonts", Once(root: Root, { AtRule }) { const { typography } = theme; if (!typography) return; // Check if a Google Fonts import already exists in this root const hasGoogleFontsImport = root.some( (node) => node.type === "atrule" && node.name === "import" && node.params.includes("fonts.googleapis.com"), ); if (hasGoogleFontsImport) { return; // Skip if import already exists } // Collect all Google fonts const googleFonts: Array<{ family: string; variable?: boolean; weights?: number[] }> = []; const seen = new Set(); const addFont = (font?: { type: string; family: string; variable?: boolean; weights?: number[] }) => { if (font?.type === "google" && !seen.has(font.family)) { seen.add(font.family); googleFonts.push(font); } }; addFont(typography.sans); addFont(typography.serif); if (typography.others) { Object.values(typography.others).forEach(addFont); } if (googleFonts.length === 0) return; // Build the URL const families = googleFonts.map((font) => { const name = font.family.replace(/ /g, "+"); if (font.variable) { return `family=${name}:wght@100..900`; } const weights = (font.weights ?? [400, 500, 600, 700]).sort((a, b) => a - b); return `family=${name}:wght@${weights.join(";")}`; }); const url = `https://fonts.googleapis.com/css2?${families.join("&")}&display=${display}`; console.log("postcss-google-fonts: Importing fonts from", url); const importRule = new AtRule({ name: "import", params: `url("${url}")`, }); // Ensure proper formatting with newline after importRule.raws.afterName = " "; importRule.raws.after = "\n"; root.prepend(importRule); }, }; }; plugin.postcss = true; export default plugin;