Unverified Commit 4b004957 authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Google fonts multiple weights & styles (#42008)

Enable using multiple weights and styles in the same google font loader
call.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent b9140ed4
This diff is collapsed.
import type { AdjustFontFallback, FontLoader } from 'next/font' import type { AdjustFontFallback, FontLoader } from 'next/font'
// @ts-ignore // @ts-ignore
import { calculateSizeAdjustValues } from 'next/dist/server/font-utils'
// @ts-ignore
import * as Log from 'next/dist/build/output/log' import * as Log from 'next/dist/build/output/log'
// @ts-ignore // @ts-ignore
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
// @ts-ignore // @ts-ignore
// eslint-disable-next-line import/no-extraneous-dependencies
import fontFromBuffer from '@next/font/dist/fontkit'
import { import {
fetchCSSFromGoogleFonts, fetchCSSFromGoogleFonts,
fetchFontFile, fetchFontFile,
...@@ -13,7 +13,6 @@ import { ...@@ -13,7 +13,6 @@ import {
getUrl, getUrl,
validateData, validateData,
} from './utils' } from './utils'
import { calculateFallbackFontValues } from '../utils'
const cssCache = new Map<string, Promise<string>>() const cssCache = new Map<string, Promise<string>>()
const fontCache = new Map<string, any>() const fontCache = new Map<string, any>()
...@@ -29,8 +28,8 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -29,8 +28,8 @@ const downloadGoogleFonts: FontLoader = async ({
const { const {
fontFamily, fontFamily,
weight, weights,
style, styles,
display, display,
preload, preload,
selectedVariableAxes, selectedVariableAxes,
...@@ -50,23 +49,33 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -50,23 +49,33 @@ const downloadGoogleFonts: FontLoader = async ({
) )
} }
const fontAxes = getFontAxes(fontFamily, weight, style, selectedVariableAxes) let fontFaceDeclarations = ''
const url = getUrl(fontFamily, fontAxes, display) for (const weight of weights) {
for (const style of styles) {
const fontAxes = getFontAxes(
fontFamily,
weight,
style,
selectedVariableAxes
)
const url = getUrl(fontFamily, fontAxes, display)
let cachedCssRequest = cssCache.get(url) let cachedCssRequest = cssCache.get(url)
const fontFaceDeclarations = const fontFaceDeclaration =
cachedCssRequest ?? (await fetchCSSFromGoogleFonts(url, fontFamily)) cachedCssRequest ?? (await fetchCSSFromGoogleFonts(url, fontFamily))
if (!cachedCssRequest) { if (!cachedCssRequest) {
cssCache.set(url, fontFaceDeclarations) cssCache.set(url, fontFaceDeclaration)
} else { } else {
cssCache.delete(url) cssCache.delete(url)
}
fontFaceDeclarations += `${fontFaceDeclaration}\n`
}
} }
// Find font files to download // Find font files to download
const fontFiles: Array<{ const fontFiles: Array<{
googleFontFileUrl: string googleFontFileUrl: string
preloadFontFile: boolean preloadFontFile: boolean
isLatin: boolean
}> = [] }> = []
let currentSubset = '' let currentSubset = ''
for (const line of fontFaceDeclarations.split('\n')) { for (const line of fontFaceDeclarations.split('\n')) {
...@@ -81,24 +90,17 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -81,24 +90,17 @@ const downloadGoogleFonts: FontLoader = async ({
googleFontFileUrl, googleFontFileUrl,
preloadFontFile: preloadFontFile:
!!preload && (callSubsets ?? subsets).includes(currentSubset), !!preload && (callSubsets ?? subsets).includes(currentSubset),
isLatin: currentSubset === 'latin',
}) })
} }
} }
} }
// Download font files // Download font files
let latinFont: any
const downloadedFiles = await Promise.all( const downloadedFiles = await Promise.all(
fontFiles.map(async ({ googleFontFileUrl, preloadFontFile, isLatin }) => { fontFiles.map(async ({ googleFontFileUrl, preloadFontFile }) => {
let cachedFontRequest = fontCache.get(googleFontFileUrl) let cachedFontRequest = fontCache.get(googleFontFileUrl)
const fontFileBuffer = const fontFileBuffer =
cachedFontRequest ?? (await fetchFontFile(googleFontFileUrl)) cachedFontRequest ?? (await fetchFontFile(googleFontFileUrl))
if (isLatin) {
try {
latinFont = fontFromBuffer(fontFileBuffer)
} catch {}
}
if (!cachedFontRequest) { if (!cachedFontRequest) {
fontCache.set(googleFontFileUrl, fontFileBuffer) fontCache.set(googleFontFileUrl, fontFileBuffer)
} else { } else {
...@@ -131,13 +133,19 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -131,13 +133,19 @@ const downloadGoogleFonts: FontLoader = async ({
// Add fallback font // Add fallback font
let adjustFontFallbackMetrics: AdjustFontFallback | undefined let adjustFontFallbackMetrics: AdjustFontFallback | undefined
if (adjustFontFallback && latinFont) { if (adjustFontFallback) {
try { try {
adjustFontFallbackMetrics = calculateFallbackFontValues( const { ascent, descent, lineGap, fallbackFont, sizeAdjust } =
latinFont, calculateSizeAdjustValues(
require('next/dist/server/google-font-metrics.json')[fontFamily] require('next/dist/server/google-font-metrics.json')[fontFamily]
.category )
) adjustFontFallbackMetrics = {
fallbackFont,
ascentOverride: `${ascent}%`,
descentOverride: `${descent}%`,
lineGapOverride: `${lineGap}%`,
sizeAdjust: `${sizeAdjust}%`,
}
} catch { } catch {
Log.error( Log.error(
`Failed to find font override values for font \`${fontFamily}\`` `Failed to find font override values for font \`${fontFamily}\``
...@@ -148,8 +156,11 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -148,8 +156,11 @@ const downloadGoogleFonts: FontLoader = async ({
return { return {
css: updatedCssResponse, css: updatedCssResponse,
fallbackFonts: fallback, fallbackFonts: fallback,
weight: weight === 'variable' ? undefined : weight, weight:
style, weights.length === 1 && weights[0] !== 'variable'
? weights[0]
: undefined,
style: styles.length === 1 ? styles[0] : undefined,
variable, variable,
adjustFontFallback: adjustFontFallbackMetrics, adjustFontFallback: adjustFontFallbackMetrics,
} }
......
...@@ -9,8 +9,8 @@ const formatValues = (values: string[]) => ...@@ -9,8 +9,8 @@ const formatValues = (values: string[]) =>
type FontOptions = { type FontOptions = {
fontFamily: string fontFamily: string
weight: string weights: string[]
style: string styles: string[]
display: string display: string
preload: boolean preload: boolean
selectedVariableAxes?: string[] selectedVariableAxes?: string[]
...@@ -44,10 +44,17 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -44,10 +44,17 @@ export function validateData(functionName: string, data: any): FontOptions {
} }
const fontStyles = fontFamilyData.styles const fontStyles = fontFamilyData.styles
// Set variable as default, throw if not available const weights = !weight
if (!weight) { ? []
: [...new Set(Array.isArray(weight) ? weight : [weight])]
const styles = !style
? []
: [...new Set(Array.isArray(style) ? style : [style])]
if (weights.length === 0) {
// Set variable as default, throw if not available
if (fontWeights.includes('variable')) { if (fontWeights.includes('variable')) {
weight = 'variable' weights.push('variable')
} else { } else {
throw new Error( throw new Error(
`Missing weight for font \`${fontFamily}\`.\nAvailable weights: ${formatValues( `Missing weight for font \`${fontFamily}\`.\nAvailable weights: ${formatValues(
...@@ -56,28 +63,40 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -56,28 +63,40 @@ export function validateData(functionName: string, data: any): FontOptions {
) )
} }
} }
if (!fontWeights.includes(weight)) {
if (weights.length > 1 && weights.includes('variable')) {
throw new Error( throw new Error(
`Unknown weight \`${weight}\` for font \`${fontFamily}\`.\nAvailable weights: ${formatValues( `Unexpected \`variable\` in weight array for font \`${fontFamily}\`. You only need \`variable\`, it includes all available weights.`
fontWeights
)}`
) )
} }
if (!style) { weights.forEach((selectedWeight) => {
if (!fontWeights.includes(selectedWeight)) {
throw new Error(
`Unknown weight \`${selectedWeight}\` for font \`${fontFamily}\`.\nAvailable weights: ${formatValues(
fontWeights
)}`
)
}
})
if (styles.length === 0) {
if (fontStyles.length === 1) { if (fontStyles.length === 1) {
style = fontStyles[0] styles.push(fontStyles[0])
} else { } else {
style = 'normal' styles.push('normal')
} }
} }
if (!fontStyles.includes(style)) {
throw new Error( styles.forEach((selectedStyle) => {
`Unknown style \`${style}\` for font \`${fontFamily}\`.\nAvailable styles: ${formatValues( if (!fontStyles.includes(selectedStyle)) {
fontStyles throw new Error(
)}` `Unknown style \`${selectedStyle}\` for font \`${fontFamily}\`.\nAvailable styles: ${formatValues(
) fontStyles
} )}`
)
}
})
if (!allowedDisplayValues.includes(display)) { if (!allowedDisplayValues.includes(display)) {
throw new Error( throw new Error(
...@@ -87,14 +106,14 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -87,14 +106,14 @@ export function validateData(functionName: string, data: any): FontOptions {
) )
} }
if (weight !== 'variable' && axes) { if (weights[0] !== 'variable' && axes) {
throw new Error('Axes can only be defined for variable fonts') throw new Error('Axes can only be defined for variable fonts')
} }
return { return {
fontFamily, fontFamily,
weight, weights,
style, styles,
display, display,
preload, preload,
selectedVariableAxes: axes, selectedVariableAxes: axes,
......
...@@ -100,13 +100,13 @@ export const OPTIMIZED_FONT_PROVIDERS = [ ...@@ -100,13 +100,13 @@ export const OPTIMIZED_FONT_PROVIDERS = [
export const DEFAULT_SERIF_FONT = { export const DEFAULT_SERIF_FONT = {
name: 'Times New Roman', name: 'Times New Roman',
xAvgCharWidth: 821, xAvgCharWidth: 821,
azAvgWidth: 940.6538, azAvgWidth: 854.3953488372093,
unitsPerEm: 2048, unitsPerEm: 2048,
} }
export const DEFAULT_SANS_SERIF_FONT = { export const DEFAULT_SANS_SERIF_FONT = {
name: 'Arial', name: 'Arial',
xAvgCharWidth: 904, xAvgCharWidth: 904,
azAvgWidth: 1002.5769, azAvgWidth: 934.5116279069767,
unitsPerEm: 2048, unitsPerEm: 2048,
} }
export const STATIC_STATUS_PAGES = ['/500'] export const STATIC_STATUS_PAGES = ['/500']
......
...@@ -49,23 +49,32 @@ const fetch = require('node-fetch') ...@@ -49,23 +49,32 @@ const fetch = require('node-fetch')
axes: hasVariableFont ? axes : undefined, axes: hasVariableFont ? axes : undefined,
} }
const optionalIfVariableFont = hasVariableFont ? '?' : '' const optionalIfVariableFont = hasVariableFont ? '?' : ''
const formatUnion = (values) =>
values.map((value) => `"${value}"`).join('|')
const weightTypes = [...weights]
const styleTypes = [...styles]
fontFunctions += `export declare function ${family.replaceAll( fontFunctions += `export declare function ${family.replaceAll(
' ', ' ',
'_' '_'
)}(options${optionalIfVariableFont}: { )}(options${optionalIfVariableFont}: {
weight${optionalIfVariableFont}:${[...weights] weight${optionalIfVariableFont}:${formatUnion(
.map((weight) => `"${weight}"`) weightTypes
.join('|')} )} | Array<${formatUnion(
style?: ${[...styles].map((style) => `"${style}"`).join('|')} weightTypes.filter((weight) => weight !== 'variable')
)}>
style?: ${formatUnion(styleTypes)} | Array<${formatUnion(styleTypes)}>
display?:Display display?:Display
variable?: CssVariable variable?: CssVariable
preload?:boolean preload?:boolean
fallback?: string[] fallback?: string[]
adjustFontFallback?: boolean adjustFontFallback?: boolean
subsets?: Array<${subsets.map((subset) => `"${subset}"`).join('|')}> subsets?: Array<${formatUnion(subsets)}>
${ ${
optionalAxes optionalAxes
? `axes?:(${optionalAxes.map(({ tag }) => `'${tag}'`).join('|')})[]` ? `axes?:(${formatUnion(optionalAxes.map(({ tag }) => tag))})[]`
: '' : ''
} }
}):FontModule }):FontModule
......
...@@ -45,7 +45,9 @@ describe('@next/font/google', () => { ...@@ -45,7 +45,9 @@ describe('@next/font/google', () => {
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
variable: expect.stringMatching(/^__variable_.{6}$/), variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__Open_Sans_.{6}'$/), fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
),
fontStyle: 'normal', fontStyle: 'normal',
}, },
}) })
...@@ -55,7 +57,9 @@ describe('@next/font/google', () => { ...@@ -55,7 +57,9 @@ describe('@next/font/google', () => {
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
variable: expect.stringMatching(/^__variable_.{6}$/), variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__Open_Sans_.{6}'$/), fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
),
fontStyle: 'normal', fontStyle: 'normal',
}, },
}) })
...@@ -64,7 +68,9 @@ describe('@next/font/google', () => { ...@@ -64,7 +68,9 @@ describe('@next/font/google', () => {
expect(JSON.parse($('#comp-with-fonts-inter').text())).toEqual({ expect(JSON.parse($('#comp-with-fonts-inter').text())).toEqual({
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__Inter_.{6}'$/), fontFamily: expect.stringMatching(
/^'__Inter_.{6}', '__Inter_Fallback_.{6}'$/
),
fontWeight: 900, fontWeight: 900,
fontStyle: 'normal', fontStyle: 'normal',
}, },
...@@ -72,7 +78,9 @@ describe('@next/font/google', () => { ...@@ -72,7 +78,9 @@ describe('@next/font/google', () => {
expect(JSON.parse($('#comp-with-fonts-roboto').text())).toEqual({ expect(JSON.parse($('#comp-with-fonts-roboto').text())).toEqual({
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__Roboto_.{6}'$/), fontFamily: expect.stringMatching(
/^'__Roboto_.{6}', '__Roboto_Fallback_.{6}'$/
),
fontStyle: 'italic', fontStyle: 'italic',
fontWeight: 100, fontWeight: 100,
}, },
...@@ -88,7 +96,9 @@ describe('@next/font/google', () => { ...@@ -88,7 +96,9 @@ describe('@next/font/google', () => {
className: expect.stringMatching(/__className_.{6}/), className: expect.stringMatching(/__className_.{6}/),
variable: expect.stringMatching(/__variable_.{6}/), variable: expect.stringMatching(/__variable_.{6}/),
style: { style: {
fontFamily: expect.stringMatching(/^'__Open_Sans_.{6}'$/), fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
),
fontStyle: 'normal', fontStyle: 'normal',
}, },
}) })
...@@ -125,7 +135,7 @@ describe('@next/font/google', () => { ...@@ -125,7 +135,7 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#app-open-sans")).fontFamily' 'getComputedStyle(document.querySelector("#app-open-sans")).fontFamily'
) )
).toMatch(/^__Open_Sans_.{6}$/) ).toMatch(/^__Open_Sans_.{6}, __Open_Sans_Fallback_.{6}$/)
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#app-open-sans")).fontWeight' 'getComputedStyle(document.querySelector("#app-open-sans")).fontWeight'
...@@ -142,7 +152,7 @@ describe('@next/font/google', () => { ...@@ -142,7 +152,7 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontFamily' 'getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontFamily'
) )
).toMatch(/^__Open_Sans_.{6}$/) ).toMatch(/^__Open_Sans_.{6}, __Open_Sans_Fallback_.{6}$/)
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontWeight' 'getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontWeight'
...@@ -169,7 +179,7 @@ describe('@next/font/google', () => { ...@@ -169,7 +179,7 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontFamily' 'getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontFamily'
) )
).toMatch(/^__Inter_.{6}$/) ).toMatch(/^__Inter_.{6}, __Inter_Fallback_.{6}$/)
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontWeight' 'getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontWeight'
...@@ -185,7 +195,7 @@ describe('@next/font/google', () => { ...@@ -185,7 +195,7 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontFamily' 'getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontFamily'
) )
).toMatch(/^__Roboto_.{6}$/) ).toMatch(/^__Roboto_.{6}, __Roboto_Fallback_.{6}$/)
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontWeight' 'getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontWeight'
...@@ -202,7 +212,7 @@ describe('@next/font/google', () => { ...@@ -202,7 +212,7 @@ describe('@next/font/google', () => {
const browser = await webdriver(next.url, '/variables') const browser = await webdriver(next.url, '/variables')
// Fira Code Variable // Fira Code Variable
const firaCodeRegex = /^__Fira_Code_.{6}$/ const firaCodeRegex = /^__Fira_Code_.{6}, __Fira_Code_Fallback_.{6}$/
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#variables-fira-code")).fontFamily' 'getComputedStyle(document.querySelector("#variables-fira-code")).fontFamily'
...@@ -215,7 +225,7 @@ describe('@next/font/google', () => { ...@@ -215,7 +225,7 @@ describe('@next/font/google', () => {
).not.toMatch(firaCodeRegex) ).not.toMatch(firaCodeRegex)
// Roboto 100 Italic // Roboto 100 Italic
const roboto100ItalicRegex = /^__Roboto_.{6}$/ const roboto100ItalicRegex = /^__Roboto_.{6}, __Roboto_Fallback_.{6}$/
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#variables-roboto-100-italic")).fontFamily' 'getComputedStyle(document.querySelector("#variables-roboto-100-italic")).fontFamily'
...@@ -249,21 +259,27 @@ describe('@next/font/google', () => { ...@@ -249,21 +259,27 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#with-fallback-fonts-classname")).fontFamily' 'getComputedStyle(document.querySelector("#with-fallback-fonts-classname")).fontFamily'
) )
).toMatch(/^__Open_Sans_.{6}, system-ui, Arial$/) ).toMatch(
/^__Open_Sans_.{6}, system-ui, Arial, __Open_Sans_Fallback_.{6}$/
)
// .style // .style
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#with-fallback-fonts-style")).fontFamily' 'getComputedStyle(document.querySelector("#with-fallback-fonts-style")).fontFamily'
) )
).toMatch(/^__Open_Sans_.{6}, system-ui, Arial$/) ).toMatch(
/^__Open_Sans_.{6}, system-ui, Arial, __Open_Sans_Fallback_.{6}$/
)
// .variable // .variable
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#with-fallback-fonts-variable")).fontFamily' 'getComputedStyle(document.querySelector("#with-fallback-fonts-variable")).fontFamily'
) )
).toMatch(/^__Open_Sans_.{6}, system-ui, Arial$/) ).toMatch(
/^__Open_Sans_.{6}, system-ui, Arial, __Open_Sans_Fallback_.{6}$/
)
}) })
}) })
......
...@@ -332,14 +332,14 @@ describe('Font Optimization', () => { ...@@ -332,14 +332,14 @@ describe('Font Optimization', () => {
) )
expect(inlineStyle.length).toBe(1) expect(inlineStyle.length).toBe(1)
expect(inlineStyle.html()).toContain( expect(inlineStyle.html()).toContain(
'@font-face{font-family:"Roboto Fallback";ascent-override:99.23%;descent-override:26.11%;line-gap-override:0.00%;size-adjust:93.49%;src:local("Arial")}' '@font-face{font-family:"Roboto Fallback";ascent-override:92.49%;descent-override:24.34%;line-gap-override:0.00%;size-adjust:100.30%;src:local("Arial")}'
) )
expect(inlineStyleMultiple.length).toBe(1) expect(inlineStyleMultiple.length).toBe(1)
expect(inlineStyleMultiple.html()).toContain( expect(inlineStyleMultiple.html()).toContain(
'@font-face{font-family:"Libre Baskerville Fallback";ascent-override:83.98%;descent-override:23.37%;line-gap-override:0.00%;size-adjust:115.51%;src:local("Times New Roman")}@font-face{font-family:"Open Sans Fallback";ascent-override:108.98%;descent-override:29.87%;line-gap-override:0.00%;size-adjust:98.08%;src:local("Arial")}' '@font-face{font-family:"Libre Baskerville Fallback";ascent-override:76.28%;descent-override:21.23%;line-gap-override:0.00%;size-adjust:127.17%;src:local("Times New Roman")}'
) )
expect(inlineStyleMultiple.html()).toContain( expect(inlineStyleMultiple.html()).toContain(
'@font-face{font-family:"Open Sans Fallback";ascent-override:108.98%;descent-override:29.87%;line-gap-override:0.00%;size-adjust:98.08%;src:local("Arial")}' '@font-face{font-family:"Open Sans Fallback";ascent-override:101.58%;descent-override:27.84%;line-gap-override:0.00%;size-adjust:105.22%;src:local("Arial")}'
) )
}) })
}) })
......
...@@ -87,10 +87,65 @@ describe('@next/font/google loader', () => { ...@@ -87,10 +87,65 @@ describe('@next/font/google loader', () => {
fs: {} as any, fs: {} as any,
isServer: true, isServer: true,
}) })
expect(css).toBe('OK') expect(css).toBe('OK\n')
expect(fetch).toHaveBeenCalledTimes(1) expect(fetch).toHaveBeenCalledTimes(1)
expect(fetch).toHaveBeenCalledWith(url, expect.any(Object)) expect(fetch).toHaveBeenCalledWith(url, expect.any(Object))
}) })
test('Multiple weights and styles', async () => {
let i = 1
fetch.mockResolvedValue({
ok: true,
text: async () => `${i++}`,
})
const { css } = await loader({
functionName: 'Roboto',
data: [
{
weight: ['300', '400', '500'],
style: ['normal', 'italic'],
},
],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
isServer: true,
})
expect(css).toBe('1\n2\n3\n4\n5\n6\n')
expect(fetch).toHaveBeenCalledTimes(6)
expect(fetch).toHaveBeenNthCalledWith(
1,
'https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=optional',
expect.any(Object)
)
expect(fetch).toHaveBeenNthCalledWith(
2,
'https://fonts.googleapis.com/css2?family=Roboto:ital,wght@1,300&display=optional',
expect.any(Object)
)
expect(fetch).toHaveBeenNthCalledWith(
3,
'https://fonts.googleapis.com/css2?family=Roboto:wght@400&display=optional',
expect.any(Object)
)
expect(fetch).toHaveBeenNthCalledWith(
4,
'https://fonts.googleapis.com/css2?family=Roboto:ital,wght@1,400&display=optional',
expect.any(Object)
)
expect(fetch).toHaveBeenNthCalledWith(
5,
'https://fonts.googleapis.com/css2?family=Roboto:wght@500&display=optional',
expect.any(Object)
)
expect(fetch).toHaveBeenNthCalledWith(
6,
'https://fonts.googleapis.com/css2?family=Roboto:ital,wght@1,500&display=optional',
expect.any(Object)
)
})
}) })
describe('Errors', () => { describe('Errors', () => {
...@@ -280,5 +335,21 @@ describe('@next/font/google loader', () => { ...@@ -280,5 +335,21 @@ describe('@next/font/google loader', () => {
Available axes: \`GRAD\`, \`XTRA\`, \`YOPQ\`, \`YTAS\`, \`YTDE\`, \`YTFI\`, \`YTLC\`, \`YTUC\`, \`opsz\`, \`slnt\`, \`wdth\`" Available axes: \`GRAD\`, \`XTRA\`, \`YOPQ\`, \`YTAS\`, \`YTDE\`, \`YTFI\`, \`YTLC\`, \`YTUC\`, \`opsz\`, \`slnt\`, \`wdth\`"
`) `)
}) })
test('Variable in weight array', async () => {
await expect(
loader({
functionName: 'Inter',
data: [{ weight: ['100', 'variable'] }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
isServer: true,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unexpected \`variable\` in weight array for font \`Inter\`. You only need \`variable\`, it includes all available weights."`
)
})
}) })
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment