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 ({
)
}
let fontFaceDeclarations = ''
for (const weight of weights) {
for (const style of styles) {
const fontAxes = getFontAxes(
fontFamily,
weight,
style,
selectedVariableAxes
)
const url = getUrl(fontFamily, fontAxes, display)
const fontAxes = getFontAxes(
fontFamily,
weights,
styles,
selectedVariableAxes
)
const url = getUrl(fontFamily, fontAxes, display)
let cachedCssRequest = cssCache.get(url)
const fontFaceDeclaration =
cachedCssRequest ?? (await fetchCSSFromGoogleFonts(url, fontFamily))
if (!cachedCssRequest) {
cssCache.set(url, fontFaceDeclaration)
} else {
cssCache.delete(url)
}
fontFaceDeclarations += `${fontFaceDeclaration}\n`
}
let cachedCssRequest = cssCache.get(url)
const fontFaceDeclarations =
cachedCssRequest ?? (await fetchCSSFromGoogleFonts(url, fontFamily))
if (!cachedCssRequest) {
cssCache.set(url, fontFaceDeclarations)
} else {
cssCache.delete(url)
}
// Find font files to download
......
......@@ -126,25 +126,50 @@ export function validateData(functionName: string, data: any): FontOptions {
export function getUrl(
fontFamily: string,
axes: [string, string][],
axes: {
wght: string[]
ital: string[]
variableAxes?: [string, 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
axes.sort(([a], [b]) => {
const aIsLowercase = a.charCodeAt(0) > 96
const bIsLowercase = b.charCodeAt(0) > 96
if (aIsLowercase && !bIsLowercase) return -1
if (bIsLowercase && !aIsLowercase) return 1
if (axes.variableAxes) {
variants.forEach((variant) => {
variant.sort(([a], [b]) => {
const aIsLowercase = a.charCodeAt(0) > 96
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(
/ /g,
'+'
)}:${axes.map(([key]) => key).join(',')}@${axes
.map(([, val]) => val)
.join(',')}&display=${display}`
)}:${variants[0].map(([key]) => key).join(',')}@${variants
.map((variant) => variant.map(([, val]) => val).join(','))
.sort()
.join(';')}&display=${display}`
}
export async function fetchCSSFromGoogleFonts(url: string, fontFamily: string) {
......@@ -192,17 +217,23 @@ export async function fetchFontFile(url: string) {
export function getFontAxes(
fontFamily: string,
weight: string,
style: string,
weights: string[],
styles: string[],
selectedVariableAxes?: string[]
): [string, string][] {
): {
wght: string[]
ital: string[]
variableAxes?: [string, string][]
} {
const allAxes: Array<{ tag: string; min: number; max: number }> = (
fontData as any
)[fontFamily].axes
const italicAxis: [string, string][] =
style === 'italic' ? [['ital', '1']] : []
const hasItalic = styles.includes('italic')
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) {
const defineAbleAxes: string[] = allAxes
.map(({ tag }) => tag)
......@@ -228,14 +259,25 @@ export function getFontAxes(
})
}
const variableAxes: [string, string][] = allAxes
.filter(
({ tag }) => tag === 'wght' || selectedVariableAxes?.includes(tag)
)
.map(({ tag, min, max }) => [tag, `${min}..${max}`])
let weightAxis: string
const variableAxes: [string, string][] = []
for (const { tag, min, max } of allAxes) {
if (tag === 'wght') {
weightAxis = `${min}..${max}`
} else if (selectedVariableAxes?.includes(tag)) {
variableAxes.push([tag, `${min}..${max}`])
}
}
return [...italicAxis, ...variableAxes]
return {
wght: [weightAxis!],
ital,
variableAxes,
}
} 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 fraunces = Fraunces({ weight: '400' })
const indieFlower = Indie_Flower({ weight: '400', preload: false })
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() {
return (
......@@ -12,6 +21,12 @@ export default function WithFonts() {
<div id="second-google-font" className={fraunces.className}>
{JSON.stringify(fraunces)}
</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({
],
})
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() {
return (
<>
......@@ -117,6 +142,12 @@ export default function WithFonts() {
<div id="roboto-local-font-var2" className={robotoVar2.className}>
{JSON.stringify(robotoVar2)}
</div>
<div
id="roboto-local-font-preload"
className={robotoWithPreload.className}
>
{JSON.stringify(robotoWithPreload)}
</div>
</>
)
}
......@@ -335,23 +335,43 @@ describe('@next/font/google', () => {
expect($('link[rel="preconnect"]').length).toBe(0)
// Preload
expect($('link[as="font"]').length).toBe(2)
// _app
expect($('link[as="font"]').get(0).attribs).toEqual({
as: 'font',
crossorigin: 'anonymous',
href: '/_next/static/media/0812efcfaefec5ea.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
// with-local-fonts
expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font',
crossorigin: 'anonymous',
href: '/_next/static/media/ab6fdae82d1a8d92.p.woff2',
rel: 'preload',
type: 'font/woff2',
})
expect($('link[as="font"]').length).toBe(5)
expect(
Array.from($('link[as="font"]'))
.map((el) => el.attribs.href)
.sort()
).toEqual([
'/_next/static/media/02205c9944024f15.p.woff2',
'/_next/static/media/0812efcfaefec5ea.p.woff2',
'/_next/static/media/1deec1af325840fd.p.woff2',
'/_next/static/media/ab6fdae82d1a8d92.p.woff2',
'/_next/static/media/d55edb6f37902ebf.p.woff2',
])
})
test('google fonts with multiple weights/styles', async () => {
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', () => {
{ weight: '400' },
'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) => {
fetch.mockResolvedValue({
ok: true,
......@@ -88,66 +112,10 @@ describe('@next/font/google loader', () => {
isServer: true,
variableName: 'myFont',
})
expect(css).toBe('OK\n')
expect(css).toBe('OK')
expect(fetch).toHaveBeenCalledTimes(1)
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', () => {
......
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