### Install fontless with npm or pnpm Source: https://github.com/unjs/fontaine/blob/main/packages/fontless/docs/content/index.md This snippet shows how to install the fontless package using either npm or pnpm package managers. It's a prerequisite for using fontless in your project. ```bash # npm npm install fontless # pnpm pnpm install fontless ``` -------------------------------- ### Framework Integration Examples with Fontaine Source: https://context7.com/unjs/fontaine/llms.txt Configuration examples for integrating Fontaine's transform plugin into popular JavaScript frameworks like Astro, Gatsby, and Docusaurus. These examples demonstrate how to add Fontaine to the build process for automatic font optimization. ```javascript // Astro - astro.config.mjs import { defineConfig } from 'astro/config' import { FontaineTransform } from 'fontaine' export default defineConfig({ vite: { plugins: [ FontaineTransform.vite({ fallbacks: ['Arial', 'Helvetica Neue'], resolvePath: (id) => new URL(`./public${id}`, import.meta.url) }) ] } }) // Gatsby - gatsby-node.js const { FontaineTransform } = require('fontaine') exports.onCreateWebpackConfig = ({ actions, getConfig }) => { const config = getConfig() config.plugins.push( FontaineTransform.webpack({ fallbacks: { 'Montserrat': ['Arial'], 'Source Code Pro': ['Courier New'] }, resolvePath: (id) => `${__dirname}/static${id}` }) ) actions.replaceWebpackConfig(config) } // Docusaurus - docusaurus.config.js const fontaine = require('fontaine') function fontainePlugin(_context, _options) { return { name: 'fontaine-plugin', configureWebpack(_config, _isServer) { return { plugins: [ fontaine.FontaineTransform.webpack({ fallbacks: ['system-ui', '-apple-system', 'Segoe UI'], resolvePath: (id) => `file://${__dirname}/static${id}` }) ] } } } } module.exports = { plugins: [fontainePlugin] } ``` -------------------------------- ### Install Fontaine with pnpm, npm, or yarn Source: https://github.com/unjs/fontaine/blob/main/README.md Demonstrates how to add Fontaine as a development dependency to your project using different package managers. ```bash pnpm add -D fontaine ``` ```bash npm install -D fontaine ``` ```bash yarn add -D fontaine ``` -------------------------------- ### CSS font-family examples for fontless Source: https://github.com/unjs/fontaine/blob/main/packages/fontless/docs/content/index.md These CSS examples show how to declare font families that `fontless` will automatically optimize. The tool scans these declarations and generates optimized `@font-face` rules. ```css /* Your CSS */ .google-font { font-family: "Poppins", sans-serif; } .bunny-font { font-family: "Aclonica", sans-serif; } ``` -------------------------------- ### JavaScript Configuration Example for Fontaine Fallbacks Source: https://github.com/unjs/fontaine/blob/main/README.md Demonstrates how to configure font fallbacks in Fontaine using JavaScript objects. It shows how to set specific overrides for font families and customize category fallbacks. ```javascript { fallbacks: { // Specific override for Poppins 'Poppins': ['Arial'], // Other sans-serif fonts will use the sans-serif preset // Serif fonts will use the serif preset automatically }, categoryFallbacks: { // Customize the serif preset 'serif': ['Georgia'] } } ``` -------------------------------- ### Configure Fontaine with Docusaurus Plugin Source: https://github.com/unjs/fontaine/blob/main/packages/fontaine/README.md Provides a Docusaurus plugin configuration example to integrate Fontaine, requiring the module and adding the Webpack plugin. ```javascript const fontaine = require('fontaine') function fontainePlugin(_context, _options) { return { name: 'fontaine-plugin', configureWebpack(_config, _isServer) { return { plugins: [ fontaine.FontaineTransform.webpack(options), ], } }, } } ``` -------------------------------- ### Integrate Fontaine with Docusaurus and Gatsby Source: https://github.com/unjs/fontaine/blob/main/README.md Provides code examples for incorporating Fontaine into Docusaurus and Gatsby projects, demonstrating how to leverage their webpack configuration or plugin systems. ```javascript // Docusaurus plugin - to be provided to the plugins option of docusaurus.config.js const fontaine = require('fontaine') function fontainePlugin(_context, _options) { return { name: 'fontaine-plugin', configureWebpack(_config, _isServer) { return { plugins: [ fontaine.FontaineTransform.webpack(options), ], } }, } } // ... in docusaurus.config.js // plugins: [fontainePlugin(options)] ``` ```javascript // Gatsby config - gatsby-node.js const { FontaineTransform } = require('fontaine') exports.onCreateWebpackConfig = ({ stage, actions, getConfig }) => { const config = getConfig() config.plugins.push(FontaineTransform.webpack(options)) actions.replaceWebpackConfig(config) } ``` -------------------------------- ### Fontaine Category-Aware Fallbacks Configuration Source: https://github.com/unjs/fontaine/blob/main/README.md Explains how to configure Fontaine to automatically select appropriate fallback fonts based on font categories (serif, sans-serif, etc.). It shows examples of enabling default category fallbacks or customizing specific categories. ```javascript const options = { fallbacks: {}, } // Or customize specific categories const optionsWithCustomCategories = { categoryFallbacks: { 'serif': ['Georgia', 'Times New Roman'], 'sans-serif': ['Arial', 'Helvetica'], } } ``` -------------------------------- ### CSS Variable Adjustment for Fontaine Source: https://github.com/unjs/fontaine/blob/main/packages/fontaine/README.md Provides an example of modifying CSS variables to work with Fontaine when custom fonts are referenced via variables, ensuring the fallback font is correctly applied. ```css /* ... */ - --ifm-font-family-base: 'Poppins'; + --ifm-font-family-base: 'Poppins', 'Poppins fallback'; ``` -------------------------------- ### CSS Variable Font Family Support Example Source: https://context7.com/unjs/fontaine/llms.txt Demonstrates how to configure CSS variables for font families to work with fontaine, particularly for frameworks like Docusaurus and Tailwind. It requires adding a manual fallback suffix to the variable definitions. The generated `@font-face` rule for the fallback is shown. ```css /* Original CSS variable */ :root { --ifm-font-family-base: 'Poppins'; } /* Updated to work with fontaine - add fallback suffix */ :root { --ifm-font-family-base: 'Poppins', 'Poppins fallback'; } /* Fontaine generates this @font-face automatically */ @font-face { font-family: "Poppins fallback"; src: local("Arial"); size-adjust: 108.2%; ascent-override: 91.8%; descent-override: 24.3%; line-gap-override: 0%; } /* Usage in components */ .content { font-family: var(--ifm-font-family-base); /* Renders with Poppins + optimized fallback */ } ``` -------------------------------- ### Fontless Configuration Options Source: https://github.com/unjs/fontaine/blob/main/packages/fontless/README.md Detailed configuration object for customizing fontless behavior, including providers, priority, defaults, custom families, and assets. ```javascript fontless({ // Configure available providers providers: { google: true, // Google Fonts bunny: true, // Bunny Fonts fontshare: true, // FontShare fontsource: true, // FontSource // Disable a provider adobe: false }, // Provider priority order priority: ['google', 'bunny', 'fontshare'], // Default font settings defaults: { preload: true, weights: [400, 700], styles: ['normal', 'italic'], // Fallbacks use category-aware presets from fontaine // Override specific generic families as needed fallbacks: { 'sans-serif': ['Arial', 'Helvetica Neue'], // serif, monospace, cursive, fantasy, system-ui, etc. use shared defaults } }, // Custom font family configurations families: [ // Configure a specific font { name: 'Poppins', provider: 'google', weights: [300, 400, 600] }, // Manual font configuration { name: 'CustomFont', src: [{ url: '/fonts/custom-font.woff2', format: 'woff2' }], weight: [400] } ], // Asset configuration assets: { prefix: '/assets/_fonts' }, // Experimental features experimental: { disableLocalFallbacks: false } }) ``` -------------------------------- ### Full fontless configuration options Source: https://github.com/unjs/fontaine/blob/main/packages/fontless/docs/content/index.md This JavaScript object illustrates the comprehensive configuration options available for fontless. It covers enabling/disabling providers, setting priority, defining default font settings, custom family configurations, asset paths, and experimental features. ```javascript fontless({ // Configure available providers providers: { google: true, // Google Fonts bunny: true, // Bunny Fonts fontshare: true, // FontShare fontsource: true, // FontSource // Disable a provider adobe: false }, // Provider priority order priority: ['google', 'bunny', 'fontshare'], // Default font settings defaults: { preload: true, weights: [400, 700], styles: ['normal', 'italic'], fallbacks: { 'sans-serif': ['Arial', 'Helvetica Neue'] } }, // Custom font family configurations families: [ // Configure a specific font { name: 'Poppins', provider: 'google', weights: [300, 400, 600] }, // Manual font configuration { name: 'CustomFont', src: [{ url: '/fonts/custom-font.woff2', format: 'woff2' }], weight: [400] } ], // Asset configuration assets: { prefix: '/_fonts' }, // Experimental features experimental: { disableLocalFallbacks: false } }) ``` -------------------------------- ### Configure Fontaine with Astro Source: https://github.com/unjs/fontaine/blob/main/packages/fontaine/README.md Demonstrates integrating Fontaine into an Astro project via its vite configuration, specifying fallbacks and path resolution. ```javascript import { defineConfig } from 'astro/config' export default defineConfig({ integrations: [], vite: { plugins: [ FontaineTransform.vite({ fallbacks: ['Arial'], resolvePath: id => new URL(`./public${id}`, import.meta.url }), ], }, }) ``` -------------------------------- ### Configure Fontaine for Astro with Vite Source: https://github.com/unjs/fontaine/blob/main/README.md Illustrates how to set up Fontaine within an Astro project's Vite configuration, including custom fallback arrays and a dynamic path resolution function. ```javascript import { defineConfig } from 'astro/config' export default defineConfig({ integrations: [], vite: { plugins: [ FontaineTransform.vite({ fallbacks: ['Arial'], resolvePath: id => new URL(`./public${id}`, import.meta.url`), }), ], }, }) ``` -------------------------------- ### Configure Fontaine with Vite Source: https://github.com/unjs/fontaine/blob/main/packages/fontaine/README.md Shows how to integrate Fontaine into a Vite project by using the FontaineTransform.vite plugin in the Vite configuration. ```javascript import { FontaineTransform } from 'fontaine' export default { plugins: [FontaineTransform.vite(options)] } ``` -------------------------------- ### Configure fontless plugin in Vite Source: https://github.com/unjs/fontaine/blob/main/packages/fontless/docs/content/index.md This JavaScript code demonstrates how to integrate the fontless plugin into a Vite build configuration. It involves importing the plugin and adding it to the `plugins` array in `vite.config.js` or `vite.config.ts`. ```javascript // vite.config.js / vite.config.ts import { defineConfig } from 'vite' import { fontless } from 'fontless' export default defineConfig({ plugins: [ // ... other plugins fontless() ], }) ``` -------------------------------- ### Configure Fontaine for Vite and Next.js Source: https://github.com/unjs/fontaine/blob/main/README.md Shows how to integrate Fontaine into Vite and Next.js projects using their respective plugin APIs. It includes options for specifying font fallbacks and resolving font paths. ```javascript import { FontaineTransform } from 'fontaine' const options = { fallbacks: ['BlinkMacSystemFont', 'Segoe UI', 'Helvetica Neue', 'Arial', 'Noto Sans'], resolvePath: id => `file:///path/to/public/dir${id}` } // Vite export default { plugins: [FontaineTransform.vite(options)] } ``` ```javascript import { FontaineTransform } from 'fontaine' const options = { fallbacks: ['BlinkMacSystemFont', 'Segoe UI', 'Helvetica Neue', 'Arial', 'Noto Sans'], resolvePath: id => `file:///path/to/public/dir${id}` } // Next.js export default { webpack(config) { config.plugins = config.plugins || [] config.plugins.push(FontaineTransform.webpack(options)) return config }, } ``` -------------------------------- ### Vite Configuration with Fontless Plugin Source: https://context7.com/unjs/fontaine/llms.txt Configures the Vite build process to use the fontless plugin. It allows customization of font providers, priority, default settings, and per-family configurations. Dependencies include 'vite' and 'fontless'. ```javascript import { defineConfig } from 'vite' import { fontless } from 'fontless' export default defineConfig({ plugins: [ fontless({ // Configure available providers providers: { google: true, bunny: true, fontshare: true, fontsource: true, adobe: false // Disable specific provider }, // Provider priority for resolution priority: ['google', 'bunny', 'fontshare'], // Default settings for all fonts defaults: { preload: true, weights: [400, 700], styles: ['normal', 'italic'], // Category-aware fallbacks (shared with fontaine) fallbacks: { 'sans-serif': ['Arial', 'Helvetica Neue'], // serif, monospace use DEFAULT_CATEGORY_FALLBACKS } }, // Per-family configuration families: [ // Provider-based font { name: 'Poppins', provider: 'google', weights: [300, 400, 600, 700], styles: ['normal', 'italic'], subsets: ['latin', 'latin-ext'], preload: true }, // Manual font with local files { name: 'CustomFont', src: [ { url: '/fonts/custom-regular.woff2', format: 'woff2' }, { url: '/fonts/custom-regular.woff', format: 'woff' } ], weight: [400], fallbacks: ['Arial', 'sans-serif'] }, // Disable provider resolution for specific font { name: 'SystemFont', provider: 'none' } ], // Asset serving configuration assets: { prefix: '/assets/_fonts' }, // Experimental features experimental: { disableLocalFallbacks: false }, // Process CSS variables (for Tailwind, etc.) processCSSVariables: 'font-prefixed-only' }) ] }) // Usage in CSS - fonts are automatically resolved // .heading { font-family: "Poppins", sans-serif; } // .code { font-family: "JetBrains Mono", monospace; } ``` -------------------------------- ### Fontaine Fallback Configuration Options Source: https://github.com/unjs/fontaine/blob/main/packages/fontaine/README.md Illustrates how to configure font fallbacks in Fontaine, either globally or on a per-font-family basis, and how to customize path resolution. ```javascript const options = { fallbacks: ['BlinkMacSystemFont', 'Segoe UI', 'Helvetica Neue', 'Arial', 'Noto Sans'], // fallbacks: { // Poppins: ['Helvetica Neue'], // 'JetBrains Mono': ['Courier New'] // }, resolvePath: id => `file:///path/to/public/dir${id}`, } ``` -------------------------------- ### CSS Font Face Generation with Fontaine Source: https://github.com/unjs/fontaine/blob/main/README.md Illustrates how Fontaine processes @font-face rules to generate fallback font-face declarations. It shows the original @font-face and the generated fallback, including metric overrides. ```css @font-face { font-family: 'Roboto'; font-display: swap; src: url('/fonts/Roboto.woff2') format('woff2'), url('/fonts/Roboto.woff') format('woff'); font-weight: 700; } /* This additional font-face declaration will be added to your CSS. */ @font-face { font-family: 'Roboto fallback'; src: local('BlinkMacSystemFont'), local('Segoe UI'), local('Helvetica Neue'), local('Arial'), local('Noto Sans'); ascent-override: 92.7734375%; descent-override: 24.4140625%; line-gap-override: 0%; } ``` -------------------------------- ### Next.js Integration with FontaineTransform Webpack Plugin Source: https://context7.com/unjs/fontaine/llms.txt Shows how to integrate the FontaineTransform Webpack plugin into a Next.js project. The configuration involves adding the plugin to the existing Webpack configuration, specifying global fallbacks and a resolver for font file paths within the Next.js build environment. ```javascript // Next.js integration export default { webpack(config) { config.plugins = config.plugins || [] config.plugins.push( FontaineTransform.webpack({ fallbacks: ['BlinkMacSystemFont', 'Segoe UI', 'Arial'], resolvePath: (id) => `file://${__dirname}/public${id}` }) ) return config } } ``` -------------------------------- ### Programmatic Metric Calculation with Fontaine Source: https://context7.com/unjs/fontaine/llms.txt Demonstrates how to use Fontaine's `getMetricsForFamily` and `generateFontFace` functions for direct metric manipulation and fallback calculation. This is useful for advanced use cases requiring manual control over font metrics and CSS generation. ```javascript import { getMetricsForFamily, generateFontFace } from 'fontaine' // Get metrics for calculation const preferredMetrics = await getMetricsForFamily('Poppins') const fallbackMetrics = await getMetricsForFamily('Arial') console.log(preferredMetrics) // { // ascent: 1050, // descent: -350, // lineGap: 100, // unitsPerEm: 1000, // xWidthAvg: 491, // category: 'sans-serif' // } // Manual calculation (matches generateFontFace internal logic) const preferredXAvgRatio = preferredMetrics.xWidthAvg / preferredMetrics.unitsPerEm const fallbackXAvgRatio = fallbackMetrics.xWidthAvg / fallbackMetrics.unitsPerEm const sizeAdjust = preferredXAvgRatio / fallbackXAvgRatio const adjustedEmSquare = preferredMetrics.unitsPerEm * sizeAdjust const ascentOverride = (preferredMetrics.ascent / adjustedEmSquare) * 100 const descentOverride = (Math.abs(preferredMetrics.descent) / adjustedEmSquare) * 100 const lineGapOverride = (preferredMetrics.lineGap / adjustedEmSquare) * 100 console.log({ sizeAdjust: `${sizeAdjust.toFixed(4)}%`, ascentOverride: `${ascentOverride.toFixed(4)}%`, descentOverride: `${descentOverride.toFixed(4)}%`, lineGapOverride: `${lineGapOverride.toFixed(4)}%` }) // Generate with additional properties const customFontFace = generateFontFace(preferredMetrics, { name: 'Poppins Optimized', font: 'Arial', metrics: fallbackMetrics, 'font-weight': '300 700', 'font-display': 'swap', 'font-stretch': 'normal' }) ``` -------------------------------- ### Configure Fontaine with Next.js Webpack Source: https://github.com/unjs/fontaine/blob/main/packages/fontaine/README.md Illustrates how to add Fontaine to a Next.js project by pushing FontaineTransform.webpack to the Webpack plugins. ```javascript import { FontaineTransform } from 'fontaine' export default { webpack(config) { config.plugins = config.plugins || [] config.plugins.push(FontaineTransform.webpack(options)) return config }, } ``` -------------------------------- ### Webpack Plugin Configuration for FontaineTransform Source: https://context7.com/unjs/fontaine/llms.txt Demonstrates configuring the FontaineTransform Webpack plugin for font fallback generation. It allows for per-family fallback definitions using an object notation and specifies how to resolve font file paths. This configuration is suitable for Webpack-based build processes. ```javascript // Webpack configuration with per-family overrides export default { plugins: [ FontaineTransform.webpack({ // Object notation for per-family control fallbacks: { 'Poppins': ['Arial', 'Helvetica'], 'JetBrains Mono': ['Courier New', 'Monaco'] }, resolvePath: (id) => `file:///path/to/public${id}` }) ] } ``` -------------------------------- ### readMetrics - Font Metric Extraction Source: https://context7.com/unjs/fontaine/llms.txt Extracts font metrics from local files or remote URLs. Supports woff2, woff, and ttf formats. Implements caching to optimize repeated metric requests. ```APIDOC ## readMetrics - Font Metric Extraction ### Description Extracts font metrics from local files or remote URLs. Supports woff2, woff, and ttf formats. Implements caching to optimize repeated metric requests. ### Method ```javascript import { readMetrics, getMetricsForFamily } from 'fontaine' ``` ### Usage **Read metrics from local file:** ```javascript const localMetrics = await readMetrics('file:///Users/project/public/fonts/custom-font.woff2') console.log(localMetrics) // { // ascent: 1900, // descent: -500, // lineGap: 0, // unitsPerEm: 2048, // xWidthAvg: 1126, // category: 'sans-serif' // } ``` **Read metrics from remote URL:** ```javascript const remoteMetrics = await readMetrics('https://example.com/fonts/font.woff2') ``` **Get metrics from capsizecss font collection:** ```javascript const systemMetrics = await getMetricsForFamily('Arial') const googleFontMetrics = await getMetricsForFamily('Roboto') ``` **Handle missing fonts:** ```javascript const unknownMetrics = await getMetricsForFamily('NonExistentFont') if (!unknownMetrics) { console.log('Font metrics not found') } ``` **Use in path resolution:** ```javascript const resolvePath = (id) => new URL(`./public${id}`, import.meta.url) const resolvedMetrics = await readMetrics(resolvePath('/fonts/custom.woff2')) ``` ``` -------------------------------- ### Complete CSS Transformation with Fallbacks Source: https://context7.com/unjs/fontaine/llms.txt Illustrates the end-to-end CSS transformation performed by fontaine, including automatic fallback injection and font-family augmentation. It shows the input CSS with `@font-face` and `font-family` declarations, and the resulting output CSS with injected fallback `@font-face` rules and updated `font-family` properties. ```css /* Input CSS */ @font-face { font-family: 'Roboto'; font-display: swap; src: url('/fonts/Roboto.woff2') format('woff2'); font-weight: 700; } .heading { font-family: 'Roboto'; font-weight: 700; } .body-text { font-family: "Open Sans", sans-serif; } /* Output CSS after FontaineTransform (with fallbacks: ['Arial']) */ @font-face { font-family: 'Roboto'; font-display: swap; src: url('/fonts/Roboto.woff2') format('woff2'); font-weight: 700; } @font-face { font-family: "Roboto fallback"; src: local("Arial"); size-adjust: 106.5%; ascent-override: 92.7734%; descent-override: 24.4141%; line-gap-override: 0%; font-weight: 700; } .heading { font-family: 'Roboto', "Roboto fallback"; font-weight: 700; } .body-text { font-family: "Open Sans", "Open Sans fallback", sans-serif; } ``` -------------------------------- ### Category-Aware Fallback Resolution with FontaineTransform Source: https://context7.com/unjs/fontaine/llms.txt Illustrates how to configure FontaineTransform to automatically select system fonts based on detected font categories. It shows overriding specific categories, inheriting defaults, and demonstrates programmatic fallback resolution using the `resolveCategoryFallbacks` function. The default category fallbacks are also logged. ```javascript import { FontaineTransform, DEFAULT_CATEGORY_FALLBACKS, resolveCategoryFallbacks } from 'fontaine' // Enable automatic category-based fallbacks const options = { fallbacks: {}, // Empty object enables category detection categoryFallbacks: { // Override specific categories, inherit defaults for others 'serif': ['Georgia', 'Times New Roman'], 'sans-serif': ['Arial', 'Helvetica'], // monospace, display, handwriting use DEFAULT_CATEGORY_FALLBACKS } } // Programmatic fallback resolution const result = resolveCategoryFallbacks({ fontFamily: 'Roboto', fallbacks: {}, metrics: { category: 'sans-serif', ascent: 1900, descent: -500, lineGap: 0, unitsPerEm: 2048, xWidthAvg: 1126 }, categoryFallbacks: { 'sans-serif': ['System Font', 'Arial'] } }) // Returns: ['System Font', 'Arial'] // Priority order demonstration FontaineTransform.vite({ fallbacks: { 'Poppins': ['Arial'], // Highest priority: explicit override // Other fonts use category-based or global defaults }, categoryFallbacks: { 'serif': ['Georgia'] // Used for serif fonts without explicit override } }) // DEFAULT_CATEGORY_FALLBACKS contents: console.log(DEFAULT_CATEGORY_FALLBACKS) // { // 'sans-serif': ['BlinkMacSystemFont', 'Segoe UI', 'Helvetica Neue', 'Arial', 'Noto Sans'], // 'serif': ['Times New Roman', 'Georgia', 'Noto Serif'], // 'monospace': ['Courier New', 'Roboto Mono', 'Noto Sans Mono'], // 'display': ['BlinkMacSystemFont', 'Segoe UI', 'Helvetica Neue', 'Arial', 'Noto Sans'], // 'handwriting': ['BlinkMacSystemFont', 'Segoe UI', 'Helvetica Neue', 'Arial', 'Noto Sans'] // } ``` -------------------------------- ### Configure Fontaine with Gatsby Webpack Source: https://github.com/unjs/fontaine/blob/main/packages/fontaine/README.md Shows how to configure Fontaine within a Gatsby project by modifying the Webpack configuration using `onCreateWebpackConfig`. ```javascript const { FontaineTransform } = require('fontaine') exports.onCreateWebpackConfig = ({ stage, actions, getConfig }) => { const config = getConfig() config.plugins.push(FontaineTransform.webpack(options)) actions.replaceWebpackConfig(config) } ``` -------------------------------- ### parseFontFace - CSS @font-face Parsing Source: https://context7.com/unjs/fontaine/llms.txt Parses CSS to extract @font-face declarations with family names, source URLs, and font properties. Returns structured data for metric calculation and fallback generation. ```APIDOC ## parseFontFace - CSS @font-face Parsing ### Description Parses CSS to extract `@font-face` declarations with family names, source URLs, and font properties. Returns structured data for metric calculation and fallback generation. ### Method ```javascript import { parseFontFace } from 'fontaine' ``` ### Usage **Parse CSS string:** ```javascript const css = ` @font-face { font-family: 'Roboto'; src: url('/fonts/roboto-regular.woff2') format('woff2'), url('/fonts/roboto-regular.woff') format('woff'); font-weight: 400; font-style: normal; } @font-face { font-family: "Open Sans"; src: url('/fonts/opensans-bold.woff2') format('woff2'); font-weight: 700; } ` const fontFaces = parseFontFace(css) console.log(fontFaces) // [ // { // index: 0, // family: 'Roboto', // source: '/fonts/roboto-regular.woff2', // properties: { 'font-weight': '400', 'font-style': 'normal' } // }, // { // index: 0, // family: 'Roboto', // source: '/fonts/roboto-regular.woff', // properties: { 'font-weight': '400', 'font-style': 'normal' } // }, // { // index: 182, // family: 'Open Sans', // source: '/fonts/opensans-bold.woff2', // properties: { 'font-weight': '700' } // } // ] ``` **Use with AST:** ```javascript import { parse } from 'css-tree' const ast = parse(css, { positions: true }) const parsedFromAST = parseFontFace(ast) ``` ``` -------------------------------- ### Extract Font Metrics with Fontaine Source: https://context7.com/unjs/fontaine/llms.txt Extracts font metrics from local files (woff2, woff, ttf) or remote URLs. Supports caching for optimized repeated requests. It takes a file path or URL as input and returns an object containing font metrics such as ascent, descent, and unitsPerEm. Dependencies include the 'fontaine' library. ```javascript import { readMetrics, getMetricsForFamily } from 'fontaine' // Read metrics from local file const localMetrics = await readMetrics('file:///Users/project/public/fonts/custom-font.woff2') console.log(localMetrics) // Read metrics from remote URL const remoteMetrics = await readMetrics('https://example.com/fonts/font.woff2') // Get metrics from capsizecss font collection const systemMetrics = await getMetricsForFamily('Arial') const googleFontMetrics = await getMetricsForFamily('Roboto') // Handle missing fonts const unknownMetrics = await getMetricsForFamily('NonExistentFont') if (!unknownMetrics) { console.log('Font metrics not found') } // Use in path resolution const resolvePath = (id) => new URL(`./public${id}`, import.meta.url) const resolvedMetrics = await readMetrics(resolvePath('/fonts/custom.woff2')) ``` -------------------------------- ### Vite Plugin Configuration for FontaineTransform Source: https://context7.com/unjs/fontaine/llms.txt Configures the FontaineTransform Vite plugin to automatically generate font fallbacks. It accepts an array of fallback font names, a resolver for font file paths, and options for customizing fallback name generation and skipping specific fallbacks. Sourcemaps can also be enabled. ```javascript import { FontaineTransform } from 'fontaine' import { defineConfig } from 'vite' // Vite configuration with array-based fallbacks export default defineConfig({ plugins: [ FontaineTransform.vite({ // Apply same fallbacks to all fonts fallbacks: ['Arial', 'Helvetica Neue', 'Segoe UI'], // Resolve font file paths for metric extraction resolvePath: (id) => new URL(`./public${id}`, import.meta.url), // Optional: customize fallback font name generation fallbackName: (originalName) => `${originalName} Fallback`, // Optional: skip generation for specific fonts skipFontFaceGeneration: (fallbackName) => fallbackName === 'System Font fallback', sourcemap: true }) ] }) ``` -------------------------------- ### Category-Aware Fallbacks in Fontaine Source: https://github.com/unjs/fontaine/blob/main/packages/fontaine/README.md Explains how to configure Fontaine to use automatic category-based fallbacks for different font types (serif, sans-serif, monospace) or customize specific categories. ```javascript const options = { fallbacks: {}, categoryFallbacks: { 'serif': ['Georgia', 'Times New Roman'], 'sans-serif': ['Arial', 'Helvetica'], } } ``` -------------------------------- ### Parse CSS @font-face Declarations with Fontaine Source: https://context7.com/unjs/fontaine/llms.txt Parses CSS strings to extract @font-face declarations, including family names, source URLs, and font properties. It returns structured data suitable for metric calculation and fallback generation. Supports direct CSS string input or an Abstract Syntax Tree (AST) from libraries like 'css-tree'. Dependencies include the 'fontaine' library. ```javascript import { parseFontFace } from 'fontaine' const css = ` @font-face { font-family: 'Roboto'; src: url('/fonts/roboto-regular.woff2') format('woff2'), url('/fonts/roboto-regular.woff') format('woff'); font-weight: 400; font-style: normal; } @font-face { font-family: "Open Sans"; src: url('/fonts/opensans-bold.woff2') format('woff2'); font-weight: 700; } ` const fontFaces = parseFontFace(css) console.log(fontFaces) // Use with AST import { parse } from 'css-tree' const ast = parse(css, { positions: true }) const parsedFromAST = parseFontFace(ast) ``` -------------------------------- ### Generate CSS @font-face Declarations with Fontaine Source: https://context7.com/unjs/fontaine/llms.txt Generates CSS @font-face declarations with calculated metric overrides using preferred font metrics and fallback font details. It takes font family metrics and fallback font configurations as input and outputs a string containing the @font-face CSS rule. Dependencies include the 'fontaine' library. ```javascript import { generateFontFace, getMetricsForFamily } from 'fontaine' // Get metrics for custom and fallback fonts const robotoMetrics = await getMetricsForFamily('Roboto') const arialMetrics = await getMetricsForFamily('Arial') // Generate fallback @font-face rule const fontFaceCSS = generateFontFace(robotoMetrics, { name: 'Roboto fallback', font: 'Arial', metrics: arialMetrics, 'font-weight': '400', 'font-style': 'normal' }) console.log(fontFaceCSS) // Multiple weight support const boldFontFace = generateFontFace(robotoMetrics, { name: 'Roboto fallback', font: 'Arial', metrics: arialMetrics, 'font-weight': '700' }) ``` -------------------------------- ### generateFontFace - CSS @font-face Generation Source: https://context7.com/unjs/fontaine/llms.txt Generates CSS @font-face declarations with calculated metric overrides. This function takes preferred font metrics and fallback font details to create optimized fallback faces. ```APIDOC ## generateFontFace - CSS @font-face Generation ### Description Generates CSS `@font-face` declarations with calculated metric overrides. Takes preferred font metrics and fallback font details to create optimized fallback faces. ### Method ```javascript import { generateFontFace, getMetricsForFamily } from 'fontaine' ``` ### Usage **Get metrics for custom and fallback fonts:** ```javascript const robotoMetrics = await getMetricsForFamily('Roboto') const arialMetrics = await getMetricsForFamily('Arial') ``` **Generate fallback @font-face rule:** ```javascript const fontFaceCSS = generateFontFace(robotoMetrics, { name: 'Roboto fallback', font: 'Arial', metrics: arialMetrics, 'font-weight': '400', 'font-style': 'normal' }) console.log(fontFaceCSS) // Output: // @font-face { // font-family: "Roboto fallback"; // src: local("Arial"); // size-adjust: 106.5%; // ascent-override: 92.7734%; // descent-override: 24.4141%; // line-gap-override: 0%; // font-weight: 400; // font-style: normal; // } ``` **Multiple weight support:** ```javascript const boldFontFace = generateFontFace(robotoMetrics, { name: 'Roboto fallback', font: 'Arial', metrics: arialMetrics, 'font-weight': '700' }) ``` ``` -------------------------------- ### CSS Fallback Adjustment for CSS Variables Source: https://github.com/unjs/fontaine/blob/main/README.md Demonstrates the necessary CSS modification when using custom fonts referenced via CSS variables, such as `--ifm-font-family-base` in Docusaurus. It shows how to append the fallback font name to the variable. ```css /* Before: :root { --ifm-font-family-base: 'Poppins'; } */ /* After: :root { --ifm-font-family-based: 'Poppins', 'Poppins fallback'; } */ ``` -------------------------------- ### CSS Font Family Update with Fontaine Source: https://github.com/unjs/fontaine/blob/main/README.md Shows how Fontaine modifies the font-family property in CSS to include the generated fallback font. This ensures that if the primary font is unavailable, the fallback is used. ```css :root { font-family: 'Roboto'; /* This becomes */ font-family: 'Roboto', 'Roboto fallback'; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.