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

Font subsets in function call (#41694)

Enable setting font specific subsets in the 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)
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent a9d14521
This diff is collapsed.
...@@ -21,16 +21,8 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -21,16 +21,8 @@ const downloadGoogleFonts: FontLoader = async ({
data, data,
config, config,
emitFontFile, emitFontFile,
isServer,
}) => { }) => {
if (!config?.subsets) {
Log.warn(
`${chalk.bold('@next/font/google')} is missing ${chalk.bold(
'options.subsets'
)} in your ${chalk.bold(
'next.config.js'
)}. Please specify subsets, otherwise no fonts will be preloaded.`
)
}
const subsets = config?.subsets || [] const subsets = config?.subsets || []
const { const {
...@@ -43,7 +35,19 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -43,7 +35,19 @@ const downloadGoogleFonts: FontLoader = async ({
fallback, fallback,
adjustFontFallback, adjustFontFallback,
variable, variable,
subsets: callSubsets,
} = validateData(functionName, data) } = validateData(functionName, data)
if (isServer && preload && !callSubsets && !config?.subsets) {
Log.warn(
`The ${chalk.bold('@next/font/google')} font ${chalk.bold(
fontFamily
)} has no selected subsets. Please specify subsets in the function call or in your ${chalk.bold(
'next.config.js'
)}, otherwise no fonts will be preloaded. Read more: https://nextjs.org/docs/api-reference/components/font#nextfontgoogle`
)
}
const fontAxes = getFontAxes(fontFamily, weight, style, selectedVariableAxes) const fontAxes = getFontAxes(fontFamily, weight, style, selectedVariableAxes)
const url = getUrl(fontFamily, fontAxes, display) const url = getUrl(fontFamily, fontAxes, display)
...@@ -72,7 +76,8 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -72,7 +76,8 @@ const downloadGoogleFonts: FontLoader = async ({
if (googleFontFileUrl) { if (googleFontFileUrl) {
fontFiles.push({ fontFiles.push({
googleFontFileUrl, googleFontFileUrl,
preloadFontFile: !!preload && subsets.includes(currentSubset), preloadFontFile:
!!preload && (callSubsets ?? subsets).includes(currentSubset),
}) })
} }
} }
......
...@@ -16,6 +16,7 @@ type FontOptions = { ...@@ -16,6 +16,7 @@ type FontOptions = {
fallback?: string[] fallback?: string[]
adjustFontFallback: boolean adjustFontFallback: boolean
variable?: string variable?: string
subsets?: string[]
} }
export function validateData(functionName: string, data: any): FontOptions { export function validateData(functionName: string, data: any): FontOptions {
let { let {
...@@ -27,6 +28,7 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -27,6 +28,7 @@ export function validateData(functionName: string, data: any): FontOptions {
fallback, fallback,
adjustFontFallback = true, adjustFontFallback = true,
variable, variable,
subsets,
} = data[0] || ({} as any) } = data[0] || ({} as any)
if (functionName === '') { if (functionName === '') {
throw new Error(`@next/font/google has no default export`) throw new Error(`@next/font/google has no default export`)
...@@ -98,6 +100,7 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -98,6 +100,7 @@ export function validateData(functionName: string, data: any): FontOptions {
fallback, fallback,
adjustFontFallback, adjustFontFallback,
variable, variable,
subsets,
} }
} }
......
...@@ -78,6 +78,7 @@ export default async function nextFontLoader(this: any) { ...@@ -78,6 +78,7 @@ export default async function nextFontLoader(this: any) {
src.startsWith('.') ? src : `./${src}` src.startsWith('.') ? src : `./${src}`
), ),
fs: this.fs, fs: this.fs,
isServer,
}) })
const { postcss } = await getPostcss() const { postcss } = await getPostcss()
......
...@@ -19,6 +19,7 @@ export type FontLoader = (options: { ...@@ -19,6 +19,7 @@ export type FontLoader = (options: {
emitFontFile: (content: Buffer, ext: string, preload: boolean) => string emitFontFile: (content: Buffer, ext: string, preload: boolean) => string
resolve: (src: string) => string resolve: (src: string) => string
fs: any fs: any
isServer: boolean
}) => Promise<{ }) => Promise<{
css: string css: string
fallbackFonts?: string[] fallbackFonts?: string[]
......
...@@ -15,7 +15,8 @@ const fetch = require('node-fetch') ...@@ -15,7 +15,8 @@ const fetch = require('node-fetch')
type CssVariable = \`--\${string}\` type CssVariable = \`--\${string}\`
` `
const fontData = {} const fontData = {}
for (let { family, fonts, axes } of familyMetadataList) { for (let { family, fonts, axes, subsets } of familyMetadataList) {
subsets = subsets.filter((subset) => subset !== 'menu')
const weights = new Set() const weights = new Set()
const styles = new Set() const styles = new Set()
...@@ -61,6 +62,7 @@ const fetch = require('node-fetch') ...@@ -61,6 +62,7 @@ const fetch = require('node-fetch')
preload?:boolean preload?:boolean
fallback?: string[] fallback?: string[]
adjustFontFallback?: boolean adjustFontFallback?: boolean
subsets?: Array<${subsets.map((subset) => `"${subset}"`).join('|')}>
${ ${
optionalAxes optionalAxes
? `axes?:(${optionalAxes.map(({ tag }) => `'${tag}'`).join('|')})[]` ? `axes?:(${optionalAxes.map(({ tag }) => `'${tag}'`).join('|')})[]`
......
...@@ -5,6 +5,7 @@ const roboto = Roboto({ ...@@ -5,6 +5,7 @@ const roboto = Roboto({
style: 'italic', style: 'italic',
display: 'swap', display: 'swap',
preload: true, preload: true,
subsets: ['vietnamese'],
}) })
export default function Component() { export default function Component() {
......
...@@ -303,7 +303,7 @@ describe('@next/font/google', () => { ...@@ -303,7 +303,7 @@ describe('@next/font/google', () => {
expect($('link[as="font"]').get(1).attribs).toEqual({ expect($('link[as="font"]').get(1).attribs).toEqual({
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: 'anonymous',
href: '/_next/static/media/4f3dcdf40b3ca86d.p.woff2', href: '/_next/static/media/675c25f648fd6a30.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
}) })
......
...@@ -85,6 +85,7 @@ describe('@next/font/google loader', () => { ...@@ -85,6 +85,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
expect(css).toBe('OK') expect(css).toBe('OK')
expect(fetch).toHaveBeenCalledTimes(1) expect(fetch).toHaveBeenCalledTimes(1)
...@@ -105,6 +106,7 @@ describe('@next/font/google loader', () => { ...@@ -105,6 +106,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
expect(adjustFontFallback).toEqual({ expect(adjustFontFallback).toEqual({
ascentOverride: '88.84%', ascentOverride: '88.84%',
...@@ -128,6 +130,7 @@ describe('@next/font/google loader', () => { ...@@ -128,6 +130,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
expect(adjustFontFallback).toEqual({ expect(adjustFontFallback).toEqual({
ascentOverride: '80.28%', ascentOverride: '80.28%',
...@@ -151,6 +154,7 @@ describe('@next/font/google loader', () => { ...@@ -151,6 +154,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
expect(adjustFontFallback).toEqual({ expect(adjustFontFallback).toEqual({
ascentOverride: '83.79%', ascentOverride: '83.79%',
...@@ -174,6 +178,7 @@ describe('@next/font/google loader', () => { ...@@ -174,6 +178,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
expect(css).toBe('') expect(css).toBe('')
expect(fallbackFonts).toEqual(['system-ui', 'Arial']) expect(fallbackFonts).toEqual(['system-ui', 'Arial'])
...@@ -194,6 +199,7 @@ describe('@next/font/google loader', () => { ...@@ -194,6 +199,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Failed to fetch font \`Alkalami\`. "Failed to fetch font \`Alkalami\`.
...@@ -210,6 +216,7 @@ describe('@next/font/google loader', () => { ...@@ -210,6 +216,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"@next/font/google has no default export"` `"@next/font/google has no default export"`
...@@ -225,6 +232,7 @@ describe('@next/font/google loader', () => { ...@@ -225,6 +232,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unknown font \`Unknown Font\`"` `"Unknown font \`Unknown Font\`"`
...@@ -240,6 +248,7 @@ describe('@next/font/google loader', () => { ...@@ -240,6 +248,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Unknown weight \`123\` for font \`Inter\`. "Unknown weight \`123\` for font \`Inter\`.
...@@ -256,6 +265,7 @@ describe('@next/font/google loader', () => { ...@@ -256,6 +265,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Missing weight for font \`Abel\`. "Missing weight for font \`Abel\`.
...@@ -272,6 +282,7 @@ describe('@next/font/google loader', () => { ...@@ -272,6 +282,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Unknown style \`normal\` for font \`Molle\`. "Unknown style \`normal\` for font \`Molle\`.
...@@ -288,6 +299,7 @@ describe('@next/font/google loader', () => { ...@@ -288,6 +299,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid display value \`invalid\` for font \`Inter\`. "Invalid display value \`invalid\` for font \`Inter\`.
...@@ -304,6 +316,7 @@ describe('@next/font/google loader', () => { ...@@ -304,6 +316,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"Axes can only be defined for variable fonts"` `"Axes can only be defined for variable fonts"`
...@@ -319,6 +332,7 @@ describe('@next/font/google loader', () => { ...@@ -319,6 +332,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"Font \`Lora\` has no definable \`axes\`"` `"Font \`Lora\` has no definable \`axes\`"`
...@@ -334,6 +348,7 @@ describe('@next/font/google loader', () => { ...@@ -334,6 +348,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid axes value for font \`Inter\`, expected an array of axes. "Invalid axes value for font \`Inter\`, expected an array of axes.
...@@ -350,6 +365,7 @@ describe('@next/font/google loader', () => { ...@@ -350,6 +365,7 @@ describe('@next/font/google loader', () => {
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
isServer: true,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid axes value \`INVALID\` for font \`Roboto Flex\`. "Invalid axes value \`INVALID\` for font \`Roboto Flex\`.
......
...@@ -3,6 +3,7 @@ import loader from '@next/font/local/loader' ...@@ -3,6 +3,7 @@ import loader from '@next/font/local/loader'
describe('@next/font/local', () => { describe('@next/font/local', () => {
describe('generated CSS', () => { describe('generated CSS', () => {
test('Default CSS', async () => { test('Default CSS', async () => {
// @ts-expect-error
const { css } = await loader({ const { css } = await loader({
functionName: '', functionName: '',
data: [{ src: './my-font.woff2' }], data: [{ src: './my-font.woff2' }],
...@@ -24,6 +25,7 @@ describe('@next/font/local', () => { ...@@ -24,6 +25,7 @@ describe('@next/font/local', () => {
}) })
test('Weight and style', async () => { test('Weight and style', async () => {
// @ts-expect-error
const { css } = await loader({ const { css } = await loader({
functionName: '', functionName: '',
data: [{ src: './my-font.woff2', weight: '100 900', style: 'italic' }], data: [{ src: './my-font.woff2', weight: '100 900', style: 'italic' }],
...@@ -47,6 +49,7 @@ describe('@next/font/local', () => { ...@@ -47,6 +49,7 @@ describe('@next/font/local', () => {
}) })
test('Other properties', async () => { test('Other properties', async () => {
// @ts-expect-error
const { css } = await loader({ const { css } = await loader({
functionName: '', functionName: '',
data: [ data: [
...@@ -81,6 +84,7 @@ describe('@next/font/local', () => { ...@@ -81,6 +84,7 @@ describe('@next/font/local', () => {
describe('Errors', () => { describe('Errors', () => {
test('Not using default export', async () => { test('Not using default export', async () => {
await expect( await expect(
// @ts-expect-error
loader({ loader({
functionName: 'Named', functionName: 'Named',
data: [], data: [],
...@@ -96,6 +100,7 @@ describe('@next/font/local', () => { ...@@ -96,6 +100,7 @@ describe('@next/font/local', () => {
test('Missing src', async () => { test('Missing src', async () => {
await expect( await expect(
// @ts-expect-error
loader({ loader({
functionName: '', functionName: '',
data: [], data: [],
...@@ -111,6 +116,7 @@ describe('@next/font/local', () => { ...@@ -111,6 +116,7 @@ describe('@next/font/local', () => {
test('Invalid file extension', async () => { test('Invalid file extension', async () => {
await expect( await expect(
// @ts-expect-error
loader({ loader({
functionName: '', functionName: '',
data: [{ src: './font/font-file.abc' }], data: [{ src: './font/font-file.abc' }],
...@@ -126,6 +132,7 @@ describe('@next/font/local', () => { ...@@ -126,6 +132,7 @@ describe('@next/font/local', () => {
test('Invalid display value', async () => { test('Invalid display value', async () => {
await expect( await expect(
// @ts-expect-error
loader({ loader({
functionName: '', functionName: '',
data: [{ src: './font-file.woff2', display: 'invalid' }], data: [{ src: './font-file.woff2', display: 'invalid' }],
...@@ -142,6 +149,7 @@ describe('@next/font/local', () => { ...@@ -142,6 +149,7 @@ describe('@next/font/local', () => {
test('Invalid declaration', async () => { test('Invalid declaration', async () => {
await expect( await expect(
// @ts-expect-error
loader({ loader({
functionName: '', functionName: '',
data: [ data: [
......
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