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