Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce remote requests in google fonts #41306

Merged
merged 3 commits into from Oct 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 18 additions & 10 deletions packages/font/src/google/loader.ts
@@ -1,15 +1,17 @@
import type { AdjustFontFallback, FontLoader } from 'next/font'
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
// @ts-ignore
import { calculateSizeAdjustValues } from 'next/dist/server/font-utils'
import {
fetchCSSFromGoogleFonts,
fetchFontFile,
getFontAxes,
getUrl,
validateData,
} from './utils'

const cssCache = new Map<string, Promise<string>>()
const fontCache = new Map<string, any>()

const downloadGoogleFonts: FontLoader = async ({
functionName,
data,
Expand All @@ -36,7 +38,14 @@ const downloadGoogleFonts: FontLoader = async ({
const fontAxes = getFontAxes(fontFamily, weight, style, selectedVariableAxes)
const url = getUrl(fontFamily, fontAxes, display)

const fontFaceDeclarations = await fetchCSSFromGoogleFonts(url, fontFamily)
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
const fontFiles: Array<{
Expand All @@ -63,14 +72,13 @@ const downloadGoogleFonts: FontLoader = async ({
// Download font files
const downloadedFiles = await Promise.all(
fontFiles.map(async ({ googleFontFileUrl, preloadFontFile }) => {
let fontFileBuffer: Buffer
if (process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES) {
fontFileBuffer = Buffer.from(googleFontFileUrl)
let cachedFontRequest = fontCache.get(googleFontFileUrl)
const fontFileBuffer =
cachedFontRequest ?? (await fetchFontFile(googleFontFileUrl))
if (!cachedFontRequest) {
fontCache.set(googleFontFileUrl, fontFileBuffer)
} else {
const arrayBuffer = await fetch(googleFontFileUrl).then((r: any) =>
r.arrayBuffer()
)
fontFileBuffer = Buffer.from(arrayBuffer)
fontCache.delete(googleFontFileUrl)
}

const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(googleFontFileUrl)![1]
Expand Down
8 changes: 8 additions & 0 deletions packages/font/src/google/utils.ts
Expand Up @@ -141,6 +141,14 @@ export async function fetchCSSFromGoogleFonts(url: string, fontFamily: string) {
return cssResponse
}

export async function fetchFontFile(url: string) {
if (process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES) {
return Buffer.from(url)
}
const arrayBuffer = await fetch(url).then((r: any) => r.arrayBuffer())
return Buffer.from(arrayBuffer)
}

export function getFontAxes(
fontFamily: string,
weight: string,
Expand Down
10 changes: 5 additions & 5 deletions test/unit/google-font-loader.test.ts
Expand Up @@ -183,17 +183,17 @@ describe('@next/font/google loader', () => {

await expect(
loader({
functionName: 'Inter',
data: [],
functionName: 'Alkalami',
data: [{ variant: '400' }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Failed to fetch font \`Inter\`.
URL: https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=optional"
`)
"Failed to fetch font \`Alkalami\`.
URL: https://fonts.googleapis.com/css2?family=Alkalami:wght@400&display=optional"
`)
})

test('Missing config with subsets', async () => {
Expand Down