(
fontFamily: string,
axes: {
wght?: string[]
ital?: string[]
variableAxes?: [string, string][]
},
display: string
)
| 4 | * Generate the Google Fonts URL given the requested weight(s), style(s) and additional variable axes |
| 5 | */ |
| 6 | export function getGoogleFontsUrl( |
| 7 | fontFamily: string, |
| 8 | axes: { |
| 9 | wght?: string[] |
| 10 | ital?: string[] |
| 11 | variableAxes?: [string, string][] |
| 12 | }, |
| 13 | display: string |
| 14 | ) { |
| 15 | // Variants are all combinations of weight and style, each variant will result in a separate font file |
| 16 | const variants: Array<[string, string][]> = [] |
| 17 | if (axes.wght) { |
| 18 | for (const wght of axes.wght) { |
| 19 | if (!axes.ital) { |
| 20 | variants.push([['wght', wght], ...(axes.variableAxes ?? [])]) |
| 21 | } else { |
| 22 | for (const ital of axes.ital) { |
| 23 | variants.push([ |
| 24 | ['ital', ital], |
| 25 | ['wght', wght], |
| 26 | ...(axes.variableAxes ?? []), |
| 27 | ]) |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | } else if (axes.variableAxes) { |
| 32 | // Variable fonts might not have a range of weights, just add optional variable axes in that case |
| 33 | variants.push([...axes.variableAxes]) |
| 34 | } |
| 35 | |
| 36 | // Google api requires the axes to be sorted, starting with lowercase words |
| 37 | if (axes.variableAxes) { |
| 38 | variants.forEach((variant) => { |
| 39 | variant.sort(([a], [b]) => { |
| 40 | const aIsLowercase = a.charCodeAt(0) > 96 |
| 41 | const bIsLowercase = b.charCodeAt(0) > 96 |
| 42 | if (aIsLowercase && !bIsLowercase) return -1 |
| 43 | if (bIsLowercase && !aIsLowercase) return 1 |
| 44 | |
| 45 | return a > b ? 1 : -1 |
| 46 | }) |
| 47 | }) |
| 48 | } |
| 49 | |
| 50 | let url = `https://fonts.googleapis.com/css2?family=${fontFamily.replace( |
| 51 | / /g, |
| 52 | '+' |
| 53 | )}` |
| 54 | |
| 55 | if (variants.length > 0) { |
| 56 | url = `${url}:${variants[0].map(([key]) => key).join(',')}@${variants |
| 57 | .map((variant) => variant.map(([, val]) => val).join(',')) |
| 58 | .sort(sortFontsVariantValues) |
| 59 | .join(';')}` |
| 60 | } |
| 61 | |
| 62 | url = `${url}&display=${display}` |
| 63 |
no test coverage detected