(css: string, subsetsToPreload?: string[])
| 4 | * Walk through the CSS from top to bottom, keeping track of the current subset. |
| 5 | */ |
| 6 | export function findFontFilesInCss(css: string, subsetsToPreload?: string[]) { |
| 7 | // Find font files to download |
| 8 | const fontFiles: Array<{ |
| 9 | googleFontFileUrl: string |
| 10 | preloadFontFile: boolean |
| 11 | }> = [] |
| 12 | |
| 13 | // Keep track of the current subset |
| 14 | let currentSubset = '' |
| 15 | for (const line of css.split('\n')) { |
| 16 | const newSubset = /\/\* (.+?) \*\//.exec(line)?.[1] |
| 17 | if (newSubset) { |
| 18 | // Found new subset in a comment above the next @font-face declaration |
| 19 | currentSubset = newSubset |
| 20 | } else { |
| 21 | const googleFontFileUrl = /src: url\((.+?)\)/.exec(line)?.[1] |
| 22 | if ( |
| 23 | googleFontFileUrl && |
| 24 | !fontFiles.some( |
| 25 | (foundFile) => foundFile.googleFontFileUrl === googleFontFileUrl |
| 26 | ) |
| 27 | ) { |
| 28 | // Found the font file in the @font-face declaration. |
| 29 | fontFiles.push({ |
| 30 | googleFontFileUrl, |
| 31 | preloadFontFile: !!subsetsToPreload?.includes(currentSubset), |
| 32 | }) |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | return fontFiles |
| 38 | } |
no test coverage detected