Unverified Commit 8fa78a5e authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Google fonts single request (#42406)

Make a single request when using several weights and/or styles for
google fonts instead of one for each variation.

## 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 build && 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 6edeb9d4
...@@ -49,27 +49,21 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -49,27 +49,21 @@ const downloadGoogleFonts: FontLoader = async ({
) )
} }
let fontFaceDeclarations = '' const fontAxes = getFontAxes(
for (const weight of weights) { fontFamily,
for (const style of styles) { weights,
const fontAxes = getFontAxes( styles,
fontFamily, selectedVariableAxes
weight, )
style, const url = getUrl(fontFamily, fontAxes, display)
selectedVariableAxes
)
const url = getUrl(fontFamily, fontAxes, display)
let cachedCssRequest = cssCache.get(url) let cachedCssRequest = cssCache.get(url)
const fontFaceDeclaration = const fontFaceDeclarations =
cachedCssRequest ?? (await fetchCSSFromGoogleFonts(url, fontFamily)) cachedCssRequest ?? (await fetchCSSFromGoogleFonts(url, fontFamily))
if (!cachedCssRequest) { if (!cachedCssRequest) {
cssCache.set(url, fontFaceDeclaration) cssCache.set(url, fontFaceDeclarations)
} else { } else {
cssCache.delete(url) cssCache.delete(url)
}
fontFaceDeclarations += `${fontFaceDeclaration}\n`
}
} }
// Find font files to download // Find font files to download
......
...@@ -126,25 +126,50 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -126,25 +126,50 @@ export function validateData(functionName: string, data: any): FontOptions {
export function getUrl( export function getUrl(
fontFamily: string, fontFamily: string,
axes: [string, string][], axes: {
wght: string[]
ital: string[]
variableAxes?: [string, string][]
},
display: string display: string
) { ) {
// Variants are all combinations of weight and style, each variant will result in a separate font file
const variants: Array<[string, string][]> = []
for (const wgth of axes.wght) {
if (axes.ital.length === 0) {
variants.push([['wght', wgth], ...(axes.variableAxes ?? [])])
} else {
for (const ital of axes.ital) {
variants.push([
['ital', ital],
['wght', wgth],
...(axes.variableAxes ?? []),
])
}
}
}
// Google api requires the axes to be sorted, starting with lowercase words // Google api requires the axes to be sorted, starting with lowercase words
axes.sort(([a], [b]) => { if (axes.variableAxes) {
const aIsLowercase = a.charCodeAt(0) > 96 variants.forEach((variant) => {
const bIsLowercase = b.charCodeAt(0) > 96 variant.sort(([a], [b]) => {
if (aIsLowercase && !bIsLowercase) return -1 const aIsLowercase = a.charCodeAt(0) > 96
if (bIsLowercase && !aIsLowercase) return 1 const bIsLowercase = b.charCodeAt(0) > 96
if (aIsLowercase && !bIsLowercase) return -1
if (bIsLowercase && !aIsLowercase) return 1
return a > b ? 1 : -1 return a > b ? 1 : -1
}) })
})
}
return `https://fonts.googleapis.com/css2?family=${fontFamily.replace( return `https://fonts.googleapis.com/css2?family=${fontFamily.replace(
/ /g, / /g,
'+' '+'
)}:${axes.map(([key]) => key).join(',')}@${axes )}:${variants[0].map(([key]) => key).join(',')}@${variants
.map(([, val]) => val) .map((variant) => variant.map(([, val]) => val).join(','))
.join(',')}&display=${display}` .sort()
.join(';')}&display=${display}`
} }
export async function fetchCSSFromGoogleFonts(url: string, fontFamily: string) { export async function fetchCSSFromGoogleFonts(url: string, fontFamily: string) {
...@@ -192,17 +217,23 @@ export async function fetchFontFile(url: string) { ...@@ -192,17 +217,23 @@ export async function fetchFontFile(url: string) {
export function getFontAxes( export function getFontAxes(
fontFamily: string, fontFamily: string,
weight: string, weights: string[],
style: string, styles: string[],
selectedVariableAxes?: string[] selectedVariableAxes?: string[]
): [string, string][] { ): {
wght: string[]
ital: string[]
variableAxes?: [string, string][]
} {
const allAxes: Array<{ tag: string; min: number; max: number }> = ( const allAxes: Array<{ tag: string; min: number; max: number }> = (
fontData as any fontData as any
)[fontFamily].axes )[fontFamily].axes
const italicAxis: [string, string][] = const hasItalic = styles.includes('italic')
style === 'italic' ? [['ital', '1']] : [] const hasNormal = styles.includes('normal')
const ital = hasItalic ? [...(hasNormal ? ['0'] : []), '1'] : []
if (weight === 'variable') { // Weights will always contain one element if it's a variable font
if (weights[0] === 'variable') {
if (selectedVariableAxes) { if (selectedVariableAxes) {
const defineAbleAxes: string[] = allAxes const defineAbleAxes: string[] = allAxes
.map(({ tag }) => tag) .map(({ tag }) => tag)
...@@ -228,14 +259,25 @@ export function getFontAxes( ...@@ -228,14 +259,25 @@ export function getFontAxes(
}) })
} }
const variableAxes: [string, string][] = allAxes let weightAxis: string
.filter( const variableAxes: [string, string][] = []
({ tag }) => tag === 'wght' || selectedVariableAxes?.includes(tag) for (const { tag, min, max } of allAxes) {
) if (tag === 'wght') {
.map(({ tag, min, max }) => [tag, `${min}..${max}`]) weightAxis = `${min}..${max}`
} else if (selectedVariableAxes?.includes(tag)) {
variableAxes.push([tag, `${min}..${max}`])
}
}
return [...italicAxis, ...variableAxes] return {
wght: [weightAxis!],
ital,
variableAxes,
}
} else { } else {
return [...italicAxis, ['wght', weight]] return {
ital,
wght: weights,
}
} }
} }
import { Fraunces, Indie_Flower } from '@next/font/google' import { Fraunces, Indie_Flower, Roboto } from '@next/font/google'
const indieFlower = Indie_Flower({ weight: '400' }) const indieFlower = Indie_Flower({ weight: '400', preload: false })
const fraunces = Fraunces({ weight: '400' }) const fraunces = Fraunces({ weight: '400', preload: false })
const robotoMultiple = Roboto({
weight: ['900', '100'],
style: ['normal', 'italic'],
})
const frauncesMultiple = Fraunces({
style: ['italic', 'normal'],
axes: ['SOFT', 'WONK', 'opsz'],
})
export default function WithFonts() { export default function WithFonts() {
return ( return (
...@@ -12,6 +21,12 @@ export default function WithFonts() { ...@@ -12,6 +21,12 @@ export default function WithFonts() {
<div id="second-google-font" className={fraunces.className}> <div id="second-google-font" className={fraunces.className}>
{JSON.stringify(fraunces)} {JSON.stringify(fraunces)}
</div> </div>
<div id="multiple-roboto" className={robotoMultiple.className}>
{JSON.stringify(robotoMultiple)}
</div>
<div id="multiple-fraunces" className={frauncesMultiple.className}>
{JSON.stringify(frauncesMultiple)}
</div>
</> </>
) )
} }
...@@ -99,6 +99,31 @@ const robotoVar2 = localFont({ ...@@ -99,6 +99,31 @@ const robotoVar2 = localFont({
], ],
}) })
const robotoWithPreload = localFont({
src: [
{
path: '../fonts/roboto/roboto-100.woff2',
weight: '100',
style: 'normal',
},
{
path: '../fonts/roboto/roboto-900-italic.woff2',
weight: '900',
style: 'italic',
},
{
path: '../fonts/roboto/roboto-100.woff2',
weight: '100',
style: 'normal',
},
{
path: '../fonts/roboto/roboto-100-italic.woff2',
weight: '900',
style: 'italic',
},
],
})
export default function WithFonts() { export default function WithFonts() {
return ( return (
<> <>
...@@ -117,6 +142,12 @@ export default function WithFonts() { ...@@ -117,6 +142,12 @@ export default function WithFonts() {
<div id="roboto-local-font-var2" className={robotoVar2.className}> <div id="roboto-local-font-var2" className={robotoVar2.className}>
{JSON.stringify(robotoVar2)} {JSON.stringify(robotoVar2)}
</div> </div>
<div
id="roboto-local-font-preload"
className={robotoWithPreload.className}
>
{JSON.stringify(robotoWithPreload)}
</div>
</> </>
) )
} }
...@@ -335,23 +335,43 @@ describe('@next/font/google', () => { ...@@ -335,23 +335,43 @@ describe('@next/font/google', () => {
expect($('link[rel="preconnect"]').length).toBe(0) expect($('link[rel="preconnect"]').length).toBe(0)
// Preload // Preload
expect($('link[as="font"]').length).toBe(2) expect($('link[as="font"]').length).toBe(5)
// _app expect(
expect($('link[as="font"]').get(0).attribs).toEqual({ Array.from($('link[as="font"]'))
as: 'font', .map((el) => el.attribs.href)
crossorigin: 'anonymous', .sort()
href: '/_next/static/media/0812efcfaefec5ea.p.woff2', ).toEqual([
rel: 'preload', '/_next/static/media/02205c9944024f15.p.woff2',
type: 'font/woff2', '/_next/static/media/0812efcfaefec5ea.p.woff2',
}) '/_next/static/media/1deec1af325840fd.p.woff2',
// with-local-fonts '/_next/static/media/ab6fdae82d1a8d92.p.woff2',
expect($('link[as="font"]').get(1).attribs).toEqual({ '/_next/static/media/d55edb6f37902ebf.p.woff2',
as: 'font', ])
crossorigin: 'anonymous', })
href: '/_next/static/media/ab6fdae82d1a8d92.p.woff2',
rel: 'preload', test('google fonts with multiple weights/styles', async () => {
type: 'font/woff2', const html = await renderViaHTTP(next.url, '/with-google-fonts')
}) const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
// Preload
expect($('link[as="font"]').length).toBe(7)
expect(
Array.from($('link[as="font"]'))
.map((el) => el.attribs.href)
.sort()
).toEqual([
'/_next/static/media/0812efcfaefec5ea.p.woff2',
'/_next/static/media/4f3dcdf40b3ca86d.p.woff2',
'/_next/static/media/560a6db6ac485cb1.p.woff2',
'/_next/static/media/686d1702f12625fe.p.woff2',
'/_next/static/media/86d92167ff02c708.p.woff2',
'/_next/static/media/c9baea324111137d.p.woff2',
'/_next/static/media/fb68b4558e2a718e.p.woff2',
])
}) })
}) })
......
...@@ -73,6 +73,30 @@ describe('@next/font/google loader', () => { ...@@ -73,6 +73,30 @@ describe('@next/font/google loader', () => {
{ weight: '400' }, { weight: '400' },
'https://fonts.googleapis.com/css2?family=Molle:ital,wght@1,400&display=optional', 'https://fonts.googleapis.com/css2?family=Molle:ital,wght@1,400&display=optional',
], ],
[
'Roboto',
{ weight: ['500', '300', '400'], style: ['normal', 'italic'] },
'https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=optional',
],
[
'Roboto Mono',
{ style: ['italic', 'normal'] },
'https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100..700;1,100..700&display=optional',
],
[
'Fraunces',
{
style: ['normal', 'italic'],
axes: ['WONK', 'opsz', 'SOFT'],
},
'https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght,SOFT,WONK@0,9..144,100..900,0..100,0..1;1,9..144,100..900,0..100,0..1&display=optional',
],
[
'Poppins',
{ weight: ['900', '400', '100'] },
'https://fonts.googleapis.com/css2?family=Poppins:wght@100;400;900&display=optional',
],
])('%s', async (functionName: string, data: any, url: string) => { ])('%s', async (functionName: string, data: any, url: string) => {
fetch.mockResolvedValue({ fetch.mockResolvedValue({
ok: true, ok: true,
...@@ -88,66 +112,10 @@ describe('@next/font/google loader', () => { ...@@ -88,66 +112,10 @@ describe('@next/font/google loader', () => {
isServer: true, isServer: true,
variableName: 'myFont', variableName: 'myFont',
}) })
expect(css).toBe('OK\n') expect(css).toBe('OK')
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,
variableName: 'myFont',
})
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', () => {
......
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