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

Font loader types (#41591)

Make local and google font loaders more similar. Both should define `weight: string` and `style: string`.

## 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 138a7bfd
This diff is collapsed.
This diff is collapsed.
...@@ -130,7 +130,7 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -130,7 +130,7 @@ const downloadGoogleFonts: FontLoader = async ({
return { return {
css: updatedCssResponse, css: updatedCssResponse,
fallbackFonts: fallback, fallbackFonts: fallback,
weight: weight === 'variable' ? undefined : Number(weight), weight: weight === 'variable' ? undefined : weight,
style, style,
variable, variable,
adjustFontFallback: adjustFontFallbackMetrics, adjustFontFallback: adjustFontFallbackMetrics,
......
...@@ -19,7 +19,8 @@ type FontOptions = { ...@@ -19,7 +19,8 @@ type FontOptions = {
} }
export function validateData(functionName: string, data: any): FontOptions { export function validateData(functionName: string, data: any): FontOptions {
let { let {
variant, weight,
style,
display = 'optional', display = 'optional',
preload = true, preload = true,
axes, axes,
...@@ -33,28 +34,44 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -33,28 +34,44 @@ export function validateData(functionName: string, data: any): FontOptions {
const fontFamily = functionName.replace(/_/g, ' ') const fontFamily = functionName.replace(/_/g, ' ')
const fontVariants = (fontData as any)[fontFamily]?.variants const fontFamilyData = (fontData as any)[fontFamily]
if (!fontVariants) { const fontWeights = fontFamilyData?.weights
if (!fontWeights) {
throw new Error(`Unknown font \`${fontFamily}\``) throw new Error(`Unknown font \`${fontFamily}\``)
} }
const fontStyles = fontFamilyData.styles
// Set variable as default, throw if not available // Set variable as default, throw if not available
if (!variant) { if (!weight) {
if (fontVariants.includes('variable')) { if (fontWeights.includes('variable')) {
variant = 'variable' weight = 'variable'
} else { } else {
throw new Error( throw new Error(
`Missing variant for font \`${fontFamily}\`.\nAvailable variants: ${formatValues( `Missing weight for font \`${fontFamily}\`.\nAvailable weights: ${formatValues(
fontVariants fontWeights
)}` )}`
) )
} }
} }
if (!fontWeights.includes(weight)) {
throw new Error(
`Unknown weight \`${weight}\` for font \`${fontFamily}\`.\nAvailable weights: ${formatValues(
fontWeights
)}`
)
}
if (!fontVariants.includes(variant)) { if (!style) {
if (fontStyles.length === 1) {
style = fontStyles[0]
} else {
style = 'normal'
}
}
if (!fontStyles.includes(style)) {
throw new Error( throw new Error(
`Unknown variant \`${variant}\` for font \`${fontFamily}\`.\nAvailable variants: ${formatValues( `Unknown style \`${style}\` for font \`${fontFamily}\`.\nAvailable styles: ${formatValues(
fontVariants fontStyles
)}` )}`
) )
} }
...@@ -67,8 +84,6 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -67,8 +84,6 @@ export function validateData(functionName: string, data: any): FontOptions {
) )
} }
const [weight, style] = variant.split('-')
if (weight !== 'variable' && axes) { if (weight !== 'variable' && axes) {
throw new Error('Axes can only be defined for variable fonts') throw new Error('Axes can only be defined for variable fonts')
} }
......
...@@ -5,7 +5,7 @@ type CssVariable = `--${string}` ...@@ -5,7 +5,7 @@ type CssVariable = `--${string}`
type LocalFont = { type LocalFont = {
src: string src: string
display?: Display display?: Display
weight?: number weight?: string
style?: string style?: string
adjustFontFallback?: 'Arial' | 'Times New Roman' | false adjustFontFallback?: 'Arial' | 'Times New Roman' | false
fallback?: string[] fallback?: string[]
......
...@@ -17,7 +17,7 @@ type FontOptions = { ...@@ -17,7 +17,7 @@ type FontOptions = {
ext: string ext: string
format: string format: string
display: string display: string
weight?: number weight?: string
style?: string style?: string
fallback?: string[] fallback?: string[]
preload: boolean preload: boolean
......
...@@ -15,7 +15,7 @@ const postcssFontLoaderPlugn = ({ ...@@ -15,7 +15,7 @@ const postcssFontLoaderPlugn = ({
fallbackFonts?: string[] fallbackFonts?: string[]
adjustFontFallback?: AdjustFontFallback adjustFontFallback?: AdjustFontFallback
variable?: string variable?: string
weight?: number weight?: string
style?: string style?: string
}) => { }) => {
return { return {
...@@ -117,6 +117,8 @@ const postcssFontLoaderPlugn = ({ ...@@ -117,6 +117,8 @@ const postcssFontLoaderPlugn = ({
root.nodes.push(fallbackFontFace) root.nodes.push(fallbackFontFace)
} }
// Variable fonts can define ranges of values
const isRange = (value: string) => value.trim().includes(' ')
const formattedFontFamilies = [ const formattedFontFamilies = [
formatFamily(fontFamily), formatFamily(fontFamily),
...fallbackFonts, ...fallbackFonts,
...@@ -129,15 +131,15 @@ const postcssFontLoaderPlugn = ({ ...@@ -129,15 +131,15 @@ const postcssFontLoaderPlugn = ({
prop: 'font-family', prop: 'font-family',
value: formattedFontFamilies, value: formattedFontFamilies,
}), }),
...(weight ...(weight && !isRange(weight)
? [ ? [
new postcss.Declaration({ new postcss.Declaration({
prop: 'font-weight', prop: 'font-weight',
value: String(weight), value: weight,
}), }),
] ]
: []), : []),
...(style ...(style && !isRange(style)
? [ ? [
new postcss.Declaration({ new postcss.Declaration({
prop: 'font-style', prop: 'font-style',
...@@ -165,8 +167,10 @@ const postcssFontLoaderPlugn = ({ ...@@ -165,8 +167,10 @@ const postcssFontLoaderPlugn = ({
name: 'style', name: 'style',
value: { value: {
fontFamily: formattedFontFamilies, fontFamily: formattedFontFamilies,
fontWeight: weight && Number(weight), fontWeight: !Number.isNaN(Number(weight))
fontStyle: style, ? Number(weight)
: undefined,
fontStyle: style && !isRange(style) ? style : undefined,
}, },
}) })
}, },
......
...@@ -24,6 +24,6 @@ export type FontLoader = (options: { ...@@ -24,6 +24,6 @@ export type FontLoader = (options: {
fallbackFonts?: string[] fallbackFonts?: string[]
variable?: string variable?: string
adjustFontFallback?: AdjustFontFallback adjustFontFallback?: AdjustFontFallback
weight?: number weight?: string
style?: string style?: string
}> }>
...@@ -16,23 +16,25 @@ const fetch = require('node-fetch') ...@@ -16,23 +16,25 @@ const fetch = require('node-fetch')
` `
const fontData = {} const fontData = {}
for (let { family, fonts, axes } of familyMetadataList) { for (let { family, fonts, axes } of familyMetadataList) {
let hasItalic = false const weights = new Set()
const variants = Object.keys(fonts).map((variant) => { const styles = new Set()
for (const variant of Object.keys(fonts)) {
if (variant.endsWith('i')) { if (variant.endsWith('i')) {
hasItalic = true styles.add('italic')
return `${variant.slice(0, 3)}-italic` weights.add(variant.slice(0, -1))
continue
} else {
styles.add('normal')
weights.add(variant)
} }
return variant }
})
const hasVariableFont = axes.length > 0 const hasVariableFont = axes.length > 0
let optionalAxes let optionalAxes
if (hasVariableFont) { if (hasVariableFont) {
variants.push('variable') weights.add('variable')
if (hasItalic) {
variants.push('variable-italic')
}
const nonWeightAxes = axes.filter(({ tag }) => tag !== 'wght') const nonWeightAxes = axes.filter(({ tag }) => tag !== 'wght')
if (nonWeightAxes.length > 0) { if (nonWeightAxes.length > 0) {
...@@ -41,7 +43,8 @@ const fetch = require('node-fetch') ...@@ -41,7 +43,8 @@ const fetch = require('node-fetch')
} }
fontData[family] = { fontData[family] = {
variants, weights: [...weights],
styles: [...styles],
axes: hasVariableFont ? axes : undefined, axes: hasVariableFont ? axes : undefined,
} }
const optionalIfVariableFont = hasVariableFont ? '?' : '' const optionalIfVariableFont = hasVariableFont ? '?' : ''
...@@ -49,12 +52,13 @@ const fetch = require('node-fetch') ...@@ -49,12 +52,13 @@ const fetch = require('node-fetch')
' ', ' ',
'_' '_'
)}(options${optionalIfVariableFont}: { )}(options${optionalIfVariableFont}: {
variant${optionalIfVariableFont}:${variants weight${optionalIfVariableFont}:${[...weights]
.map((variant) => `"${variant}"`) .map((weight) => `"${weight}"`)
.join('|')} .join('|')}
display?:Display, style?: ${[...styles].map((style) => `"${style}"`).join('|')}
display?:Display
variable?: CssVariable variable?: CssVariable
preload?:boolean, preload?:boolean
fallback?: string[] fallback?: string[]
adjustFontFallback?: boolean adjustFontFallback?: boolean
${ ${
......
import { Inter, Roboto } from '@next/font/google' import { Inter, Roboto } from '@next/font/google'
const inter = Inter({ variant: '900', display: 'swap', preload: false }) const inter = Inter({ weight: '900', display: 'swap', preload: false })
const roboto = Roboto({ const roboto = Roboto({
variant: '100-italic', weight: '100',
style: 'italic',
display: 'swap', display: 'swap',
preload: true, preload: true,
}) })
......
...@@ -3,7 +3,8 @@ import localFont from '@next/font/local' ...@@ -3,7 +3,8 @@ import localFont from '@next/font/local'
const firaCode = Fira_Code({ variable: '--fira-code' }) const firaCode = Fira_Code({ variable: '--fira-code' })
const roboto = Roboto({ const roboto = Roboto({
variant: '100-italic', weight: '100',
style: 'italic',
display: 'swap', display: 'swap',
preload: true, preload: true,
variable: '--roboto-100-italic', variable: '--roboto-100-italic',
......
import { Fraunces, Indie_Flower } from '@next/font/google' import { Fraunces, Indie_Flower } from '@next/font/google'
const indieFlower = Indie_Flower({ variant: '400' }) const indieFlower = Indie_Flower({ weight: '400' })
const fraunces = Fraunces({ variant: '400' }) const fraunces = Fraunces({ weight: '400' })
export default function WithFonts() { export default function WithFonts() {
return ( return (
......
...@@ -3,7 +3,7 @@ import localFont from '@next/font/local' ...@@ -3,7 +3,7 @@ import localFont from '@next/font/local'
const myFont1 = localFont({ const myFont1 = localFont({
src: '../fonts/my-font.woff2', src: '../fonts/my-font.woff2',
style: 'italic', style: 'italic',
weight: 100, weight: '100',
fallback: ['system-ui'], fallback: ['system-ui'],
adjustFontFallback: 'Times New Roman', adjustFontFallback: 'Times New Roman',
}) })
......
...@@ -2,7 +2,7 @@ import { Html, Head, Main, NextScript } from 'next/document' ...@@ -2,7 +2,7 @@ import { Html, Head, Main, NextScript } from 'next/document'
import { Abel } from '@next/font/google' import { Abel } from '@next/font/google'
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
const abel = Abel({ variant: '400' }) const abel = Abel({ weight: '400' })
export default function Document() { export default function Document() {
return ( return (
......
...@@ -48,6 +48,7 @@ describe('@next/font/google', () => { ...@@ -48,6 +48,7 @@ describe('@next/font/google', () => {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/ /^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
), ),
fontStyle: 'normal',
}, },
}) })
...@@ -59,6 +60,7 @@ describe('@next/font/google', () => { ...@@ -59,6 +60,7 @@ describe('@next/font/google', () => {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/ /^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
), ),
fontStyle: 'normal',
}, },
}) })
...@@ -70,6 +72,7 @@ describe('@next/font/google', () => { ...@@ -70,6 +72,7 @@ describe('@next/font/google', () => {
/^'__Inter_.{6}', '__Inter_Fallback_.{6}'$/ /^'__Inter_.{6}', '__Inter_Fallback_.{6}'$/
), ),
fontWeight: 900, fontWeight: 900,
fontStyle: 'normal',
}, },
}) })
expect(JSON.parse($('#comp-with-fonts-roboto').text())).toEqual({ expect(JSON.parse($('#comp-with-fonts-roboto').text())).toEqual({
...@@ -96,6 +99,7 @@ describe('@next/font/google', () => { ...@@ -96,6 +99,7 @@ describe('@next/font/google', () => {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/ /^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
), ),
fontStyle: 'normal',
}, },
}) })
......
...@@ -9,10 +9,10 @@ import { ...@@ -9,10 +9,10 @@ import {
const openSans = Open_Sans() const openSans = Open_Sans()
const sourceCodePro = Source_Code_Pro({ display: 'swap', preload: false }) const sourceCodePro = Source_Code_Pro({ display: 'swap', preload: false })
const abel = Abel({ variant: '400', display: 'optional', preload: false }) const abel = Abel({ weight: '400', display: 'optional', preload: false })
export const inter = Inter({ display: 'block', preload: true }) export const inter = Inter({ display: 'block', preload: true })
export const roboto = Roboto({ variant: '400' }) export const roboto = Roboto({ weight: '400' })
export const myLocalFont = localFont({ export const myLocalFont = localFont({
src: './my-font.woff2', src: './my-font.woff2',
......
import { Abel } from '@next/font/google' import { Abel } from '@next/font/google'
const abel = Abel({ variant: '400', display: 'optional', preload: false }) const abel = Abel({ weight: '400', display: 'optional', preload: false })
function MyApp({ Component, pageProps }) { function MyApp({ Component, pageProps }) {
return ( return (
......
import { Abel } from '@next/font/google' import { Abel } from '@next/font/google'
const abel = Abel({ variant: '400', display: 'optional', preload: false }) const abel = Abel({ weight: '400', display: 'optional', preload: false })
export default function NoPreload() { export default function NoPreload() {
return <p className={abel.className}>Hello world</p> return <p className={abel.className}>Hello world</p>
......
...@@ -17,22 +17,22 @@ describe('@next/font/google loader', () => { ...@@ -17,22 +17,22 @@ describe('@next/font/google loader', () => {
], ],
[ [
'Inter', 'Inter',
{ variant: '400' }, { weight: '400' },
'https://fonts.googleapis.com/css2?family=Inter:wght@400&display=optional', 'https://fonts.googleapis.com/css2?family=Inter:wght@400&display=optional',
], ],
[ [
'Inter', 'Inter',
{ variant: '900', display: 'block' }, { weight: '900', display: 'block' },
'https://fonts.googleapis.com/css2?family=Inter:wght@900&display=block', 'https://fonts.googleapis.com/css2?family=Inter:wght@900&display=block',
], ],
[ [
'Source_Sans_Pro', 'Source_Sans_Pro',
{ variant: '900', display: 'auto' }, { weight: '900', display: 'auto' },
'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@900&display=auto', 'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@900&display=auto',
], ],
[ [
'Source_Sans_Pro', 'Source_Sans_Pro',
{ variant: '200-italic' }, { weight: '200', style: 'italic' },
'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@1,200&display=optional', 'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@1,200&display=optional',
], ],
[ [
...@@ -42,7 +42,7 @@ describe('@next/font/google loader', () => { ...@@ -42,7 +42,7 @@ describe('@next/font/google loader', () => {
], ],
[ [
'Roboto_Flex', 'Roboto_Flex',
{ display: 'fallback', variant: 'variable', axes: ['opsz'] }, { display: 'fallback', weight: 'variable', axes: ['opsz'] },
'https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=fallback', 'https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=fallback',
], ],
[ [
...@@ -55,19 +55,24 @@ describe('@next/font/google loader', () => { ...@@ -55,19 +55,24 @@ describe('@next/font/google loader', () => {
], ],
[ [
'Oooh_Baby', 'Oooh_Baby',
{ variant: '400' }, { weight: '400' },
'https://fonts.googleapis.com/css2?family=Oooh+Baby:wght@400&display=optional', 'https://fonts.googleapis.com/css2?family=Oooh+Baby:wght@400&display=optional',
], ],
[ [
'Albert_Sans', 'Albert_Sans',
{ variant: 'variable-italic' }, { weight: 'variable', style: 'italic' },
'https://fonts.googleapis.com/css2?family=Albert+Sans:ital,wght@1,100..900&display=optional', 'https://fonts.googleapis.com/css2?family=Albert+Sans:ital,wght@1,100..900&display=optional',
], ],
[ [
'Fraunces', 'Fraunces',
{ variant: 'variable-italic', axes: ['WONK', 'opsz', 'SOFT'] }, { weight: 'variable', style: 'italic', axes: ['WONK', 'opsz', 'SOFT'] },
'https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght,SOFT,WONK@1,9..144,100..900,0..100,0..1&display=optional', 'https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght,SOFT,WONK@1,9..144,100..900,0..100,0..1&display=optional',
], ],
[
'Molle',
{ weight: '400' },
'https://fonts.googleapis.com/css2?family=Molle:ital,wght@1,400&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,
...@@ -184,7 +189,7 @@ describe('@next/font/google loader', () => { ...@@ -184,7 +189,7 @@ describe('@next/font/google loader', () => {
await expect( await expect(
loader({ loader({
functionName: 'Alkalami', functionName: 'Alkalami',
data: [{ variant: '400' }], data: [{ weight: '400' }],
config: { subsets: [] }, config: { subsets: [] },
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
...@@ -241,23 +246,23 @@ describe('@next/font/google loader', () => { ...@@ -241,23 +246,23 @@ describe('@next/font/google loader', () => {
) )
}) })
test('Unknown variant', async () => { test('Unknown weight', async () => {
await expect( await expect(
loader({ loader({
functionName: 'Inter', functionName: 'Inter',
data: [{ variant: '123' }], data: [{ weight: '123' }],
config: { subsets: [] }, config: { subsets: [] },
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Unknown variant \`123\` for font \`Inter\`. "Unknown weight \`123\` for font \`Inter\`.
Available variants: \`100\`, \`200\`, \`300\`, \`400\`, \`500\`, \`600\`, \`700\`, \`800\`, \`900\`, \`variable\`" Available weights: \`100\`, \`200\`, \`300\`, \`400\`, \`500\`, \`600\`, \`700\`, \`800\`, \`900\`, \`variable\`"
`) `)
}) })
test('Missing variant for non variable font', async () => { test('Missing weight for non variable font', async () => {
await expect( await expect(
loader({ loader({
functionName: 'Abel', functionName: 'Abel',
...@@ -268,8 +273,24 @@ describe('@next/font/google loader', () => { ...@@ -268,8 +273,24 @@ describe('@next/font/google loader', () => {
fs: {} as any, fs: {} as any,
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
"Missing variant for font \`Abel\`. "Missing weight for font \`Abel\`.
Available variants: \`400\`" Available weights: \`400\`"
`)
})
test('Unknown style', async () => {
await expect(
loader({
functionName: 'Molle',
data: [{ weight: '400', style: 'normal' }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
fs: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Unknown style \`normal\` for font \`Molle\`.
Available styles: \`italic\`"
`) `)
}) })
...@@ -293,7 +314,7 @@ describe('@next/font/google loader', () => { ...@@ -293,7 +314,7 @@ describe('@next/font/google loader', () => {
await expect( await expect(
loader({ loader({
functionName: 'Abel', functionName: 'Abel',
data: [{ variant: '400', axes: [] }], data: [{ weight: '400', axes: [] }],
config: { subsets: [] }, config: { subsets: [] },
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
......
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