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

Accept variable prop in google font loader (#41065)

Fixes local weight type which could break if you wrote "regular" instead of 400. Adds `variable` property to google font loader to let you define the name of the CSS variable.

## 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 67a5076b
...@@ -14,6 +14,9 @@ ...@@ -14,6 +14,9 @@
"Abril Fatface": { "Abril Fatface": {
"variants": ["400"] "variants": ["400"]
}, },
"Abyssinica SIL": {
"variants": ["400"]
},
"Aclonica": { "Aclonica": {
"variants": ["400"] "variants": ["400"]
}, },
...@@ -193,6 +196,9 @@ ...@@ -193,6 +196,9 @@
"Alike Angular": { "Alike Angular": {
"variants": ["400"] "variants": ["400"]
}, },
"Alkalami": {
"variants": ["400"]
},
"Allan": { "Allan": {
"variants": ["400", "700"] "variants": ["400", "700"]
}, },
...@@ -1656,6 +1662,7 @@ ...@@ -1656,6 +1662,7 @@
"700", "700",
"800", "800",
"900", "900",
"1000",
"variable" "variable"
], ],
"axes": [ "axes": [
...@@ -1677,6 +1684,7 @@ ...@@ -1677,6 +1684,7 @@
"700", "700",
"800", "800",
"900", "900",
"1000",
"variable" "variable"
], ],
"axes": [ "axes": [
...@@ -3473,6 +3481,7 @@ ...@@ -3473,6 +3481,7 @@
}, },
"Hepta Slab": { "Hepta Slab": {
"variants": [ "variants": [
"1",
"100", "100",
"200", "200",
"300", "300",
...@@ -3793,6 +3802,38 @@ ...@@ -3793,6 +3802,38 @@
} }
] ]
}, },
"Inter Tight": {
"variants": [
"100",
"200",
"300",
"400",
"500",
"600",
"700",
"800",
"900",
"100-italic",
"200-italic",
"300-italic",
"400-italic",
"500-italic",
"600-italic",
"700-italic",
"800-italic",
"900-italic",
"variable",
"variable-italic"
],
"axes": [
{
"tag": "wght",
"min": 100,
"max": 900,
"defaultValue": 400
}
]
},
"Irish Grover": { "Irish Grover": {
"variants": ["400"] "variants": ["400"]
}, },
...@@ -4349,7 +4390,7 @@ ...@@ -4349,7 +4390,7 @@
"variants": ["400"] "variants": ["400"]
}, },
"Lateef": { "Lateef": {
"variants": ["400"] "variants": ["200", "300", "400", "500", "600", "700", "800"]
}, },
"Lato": { "Lato": {
"variants": [ "variants": [
...@@ -5373,6 +5414,8 @@ ...@@ -5373,6 +5414,8 @@
"700", "700",
"800", "800",
"900", "900",
"1000",
"100-italic",
"200-italic", "200-italic",
"300-italic", "300-italic",
"400-italic", "400-italic",
...@@ -5637,7 +5680,15 @@ ...@@ -5637,7 +5680,15 @@
] ]
}, },
"Noto Nastaliq Urdu": { "Noto Nastaliq Urdu": {
"variants": ["400", "700"] "variants": ["400", "500", "600", "700", "variable"],
"axes": [
{
"tag": "wght",
"min": 400,
"max": 700,
"defaultValue": 400
}
]
}, },
"Noto Rashi Hebrew": { "Noto Rashi Hebrew": {
"variants": [ "variants": [
...@@ -6000,6 +6051,34 @@ ...@@ -6000,6 +6051,34 @@
"Noto Sans Elymaic": { "Noto Sans Elymaic": {
"variants": ["400"] "variants": ["400"]
}, },
"Noto Sans Ethiopic": {
"variants": [
"100",
"200",
"300",
"400",
"500",
"600",
"700",
"800",
"900",
"variable"
],
"axes": [
{
"tag": "wdth",
"min": 62.5,
"max": 100,
"defaultValue": 100
},
{
"tag": "wght",
"min": 100,
"max": 900,
"defaultValue": 400
}
]
},
"Noto Sans Georgian": { "Noto Sans Georgian": {
"variants": [ "variants": [
"100", "100",
...@@ -6160,7 +6239,15 @@ ...@@ -6160,7 +6239,15 @@
"variants": ["100", "300", "400", "500", "700", "900"] "variants": ["100", "300", "400", "500", "700", "900"]
}, },
"Noto Sans Javanese": { "Noto Sans Javanese": {
"variants": ["400", "700"] "variants": ["400", "500", "600", "700", "variable"],
"axes": [
{
"tag": "wght",
"min": 400,
"max": 700,
"defaultValue": 400
}
]
}, },
"Noto Sans KR": { "Noto Sans KR": {
"variants": ["100", "300", "400", "500", "700", "900"] "variants": ["100", "300", "400", "500", "700", "900"]
...@@ -6486,7 +6573,32 @@ ...@@ -6486,7 +6573,32 @@
"variants": ["400"] "variants": ["400"]
}, },
"Noto Sans Oriya": { "Noto Sans Oriya": {
"variants": ["100", "400", "700", "900"] "variants": [
"100",
"200",
"300",
"400",
"500",
"600",
"700",
"800",
"900",
"variable"
],
"axes": [
{
"tag": "wdth",
"min": 62.5,
"max": 100,
"defaultValue": 100
},
{
"tag": "wght",
"min": 100,
"max": 900,
"defaultValue": 400
}
]
}, },
"Noto Sans Osage": { "Noto Sans Osage": {
"variants": ["400"] "variants": ["400"]
...@@ -7392,6 +7504,8 @@ ...@@ -7392,6 +7504,8 @@
"700", "700",
"800", "800",
"900", "900",
"1000",
"100-italic",
"200-italic", "200-italic",
"300-italic", "300-italic",
"400-italic", "400-italic",
...@@ -8203,7 +8317,17 @@ ...@@ -8203,7 +8317,17 @@
] ]
}, },
"Recursive": { "Recursive": {
"variants": ["300", "400", "500", "600", "700", "800", "900", "variable"], "variants": [
"300",
"400",
"500",
"600",
"700",
"800",
"900",
"1000",
"variable"
],
"axes": [ "axes": [
{ {
"tag": "CASL", "tag": "CASL",
......
This diff is collapsed.
...@@ -31,6 +31,7 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -31,6 +31,7 @@ const downloadGoogleFonts: FontLoader = async ({
selectedVariableAxes, selectedVariableAxes,
fallback, fallback,
adjustFontFallback, adjustFontFallback,
variable,
} = validateData(functionName, data) } = validateData(functionName, data)
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)
...@@ -121,11 +122,9 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -121,11 +122,9 @@ const downloadGoogleFonts: FontLoader = async ({
return { return {
css: updatedCssResponse, css: updatedCssResponse,
fallbackFonts: fallback, fallbackFonts: fallback,
weight: weight === 'variable' ? undefined : weight, weight: weight === 'variable' ? undefined : Number(weight),
style, style,
variable: `--next-font-${fontFamily.toLowerCase().replace(/ /g, '-')}${ variable,
weight !== 'variable' ? `-${weight}` : ''
}${style === 'italic' ? `-italic` : ''}`,
adjustFontFallback: adjustFontFallbackMetrics, adjustFontFallback: adjustFontFallbackMetrics,
} }
} }
......
...@@ -15,6 +15,7 @@ type FontOptions = { ...@@ -15,6 +15,7 @@ type FontOptions = {
selectedVariableAxes?: string[] selectedVariableAxes?: string[]
fallback?: string[] fallback?: string[]
adjustFontFallback: boolean adjustFontFallback: boolean
variable?: string
} }
export function validateData(functionName: string, data: any): FontOptions { export function validateData(functionName: string, data: any): FontOptions {
let { let {
...@@ -24,6 +25,7 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -24,6 +25,7 @@ export function validateData(functionName: string, data: any): FontOptions {
axes, axes,
fallback, fallback,
adjustFontFallback = true, adjustFontFallback = true,
variable,
} = 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`)
...@@ -80,6 +82,7 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -80,6 +82,7 @@ export function validateData(functionName: string, data: any): FontOptions {
selectedVariableAxes: axes, selectedVariableAxes: axes,
fallback, fallback,
adjustFontFallback, adjustFontFallback,
variable,
} }
} }
......
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unused-vars */
import type { AdjustFontFallback, FontModule } from 'next/font' import type { AdjustFontFallback, FontModule } from 'next/font'
type Display = 'auto' | 'block' | 'swap' | 'fallback' | 'optional' type Display = 'auto' | 'block' | 'swap' | 'fallback' | 'optional'
type CssVariable = `--${string}`
type LocalFont = { type LocalFont = {
src: string | Array<{ file: string; unicodeRange: string }> src: string | Array<{ file: string; unicodeRange: string }>
display?: Display display?: Display
weight?: string weight?: number
style?: string style?: string
fallback?: string[] fallback?: string[]
preload?: boolean preload?: boolean
variable?: string variable?: CssVariable
fontStretch?: string fontStretch?: string
fontVariant?: string fontVariant?: string
......
...@@ -22,7 +22,7 @@ type FontOptions = { ...@@ -22,7 +22,7 @@ type FontOptions = {
unicodeRange?: string unicodeRange?: string
}> }>
display: string display: string
weight?: string weight?: number
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?: string weight?: number
style?: string style?: string
}) => { }) => {
return { return {
...@@ -133,7 +133,7 @@ const postcssFontLoaderPlugn = ({ ...@@ -133,7 +133,7 @@ const postcssFontLoaderPlugn = ({
? [ ? [
new postcss.Declaration({ new postcss.Declaration({
prop: 'font-weight', prop: 'font-weight',
value: weight, value: String(weight),
}), }),
] ]
: []), : []),
......
...@@ -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?: string weight?: number
style?: string style?: string
}> }>
...@@ -525,8 +525,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -525,8 +525,7 @@ export default class NextNodeServer extends BaseServer {
params.path[0] === 'media' || params.path[0] === 'media' ||
params.path[0] === this.buildId || params.path[0] === this.buildId ||
params.path[0] === 'pages' || params.path[0] === 'pages' ||
params.path[1] === 'pages' || params.path[1] === 'pages'
params.path[0] === 'fonts'
) { ) {
this.setImmutableAssetCacheControl(res) this.setImmutableAssetCacheControl(res)
} }
......
...@@ -7,8 +7,12 @@ const fetch = require('node-fetch') ...@@ -7,8 +7,12 @@ const fetch = require('node-fetch')
'https://fonts.google.com/metadata/fonts' 'https://fonts.google.com/metadata/fonts'
).then((r) => r.json()) ).then((r) => r.json())
let fontFunctions = `import type { FontModule } from 'next/font' let fontFunctions = `/**
* This is an autogenerated file by scripts/update-google-fonts.js
*/
import type { FontModule } from 'next/font'
type Display = 'auto'|'block'|'swap'|'fallback'|'optional' type Display = 'auto'|'block'|'swap'|'fallback'|'optional'
type CssVariable = \`--\${string}\`
` `
const fontData = {} const fontData = {}
for (let { family, fonts, axes } of familyMetadataList) { for (let { family, fonts, axes } of familyMetadataList) {
...@@ -49,6 +53,7 @@ const fetch = require('node-fetch') ...@@ -49,6 +53,7 @@ const fetch = require('node-fetch')
.map((variant) => `"${variant}"`) .map((variant) => `"${variant}"`)
.join('|')} .join('|')}
display?:Display, display?:Display,
variable?: CssVariable
preload?:boolean, preload?:boolean,
fallback?: string[] fallback?: string[]
adjustFontFallback?: boolean adjustFontFallback?: boolean
......
import { Open_Sans } from '@next/font/google' import { Open_Sans } from '@next/font/google'
const openSans = Open_Sans() const openSans = Open_Sans({ variable: '--open-sans' })
function MyApp({ Component, pageProps }) { function MyApp({ Component, pageProps }) {
return ( return (
......
import { Fira_Code, Albert_Sans, Inter, Roboto } from '@next/font/google' import { Fira_Code, Roboto } from '@next/font/google'
import localFont from '@next/font/local' import localFont from '@next/font/local'
const firaCode = Fira_Code() const firaCode = Fira_Code({ variable: '--fira-code' })
const albertSans = Albert_Sans({
variant: 'variable-italic',
adjustFontFallback: false,
})
const inter = Inter({ variant: '900', display: 'swap' }) // Don't preload by default when swap
const roboto = Roboto({ const roboto = Roboto({
variant: '100-italic', variant: '100-italic',
display: 'swap', display: 'swap',
preload: true, preload: true,
variable: '--roboto-100-italic',
}) })
const myFont = localFont({ const myFont = localFont({
src: '../fonts/my-font.woff2', src: '../fonts/my-font.woff2',
...@@ -25,43 +21,13 @@ export default function WithFonts() { ...@@ -25,43 +21,13 @@ export default function WithFonts() {
<div <div
id="variables-fira-code" id="variables-fira-code"
className={firaCode.variable} className={firaCode.variable}
style={{ fontFamily: 'var(--next-font-fira-code)' }} style={{ fontFamily: 'var(--fira-code)' }}
> >
With variables With variables
</div> </div>
<div <div
id="without-variables-fira-code" id="without-variables-fira-code"
style={{ fontFamily: 'var(--next-font-fira-code)' }} style={{ fontFamily: 'var(--fira-code)' }}
>
Without variables
</div>
{/* Albert Sant Variable Italic */}
<div
id="variables-albert-sans-italic"
className={albertSans.variable}
style={{ fontFamily: 'var(--next-font-albert-sans-italic)' }}
>
With variables
</div>
<div
id="without-variables-albert-sans-italic"
style={{ fontFamily: 'var(--next-font-albert-sans-italic)' }}
>
Without variables
</div>
{/* Inter 900 */}
<div
id="variables-inter-900"
className={inter.variable}
style={{ fontFamily: 'var(--next-font-inter-900)' }}
>
With variables
</div>
<div
id="without-variables-inter-900"
style={{ fontFamily: 'var(--next-font-inter-900)' }}
> >
Without variables Without variables
</div> </div>
...@@ -70,13 +36,13 @@ export default function WithFonts() { ...@@ -70,13 +36,13 @@ export default function WithFonts() {
<div <div
id="variables-roboto-100-italic" id="variables-roboto-100-italic"
className={roboto.variable} className={roboto.variable}
style={{ fontFamily: 'var(--next-font-roboto-100-italic)' }} style={{ fontFamily: 'var(--roboto-100-italic)' }}
> >
With variables With variables
</div> </div>
<div <div
id="without-variables-roboto-100-italic" id="without-variables-roboto-100-italic"
style={{ fontFamily: 'var(--next-font-roboto-100-italic)' }} style={{ fontFamily: 'var(--roboto-100-italic)' }}
> >
Without variables Without variables
</div> </div>
......
import { Open_Sans } from '@next/font/google' import { Open_Sans } from '@next/font/google'
const openSans = Open_Sans({ fallback: ['system-ui', 'Arial'] }) const openSans = Open_Sans({
fallback: ['system-ui', 'Arial'],
variable: '--open-sans',
})
export default function WithFonts() { export default function WithFonts() {
return ( return (
...@@ -12,7 +15,7 @@ export default function WithFonts() { ...@@ -12,7 +15,7 @@ export default function WithFonts() {
</div> </div>
<div <div
id="with-fallback-fonts-variable" id="with-fallback-fonts-variable"
style={{ fontFamily: 'var(--next-font-open-sans)' }} style={{ fontFamily: 'var(--open-sans)' }}
className={openSans.variable} className={openSans.variable}
> >
{JSON.stringify(openSans)} {JSON.stringify(openSans)}
......
...@@ -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'],
}) })
const myFont2 = localFont({ const myFont2 = localFont({
......
...@@ -65,7 +65,6 @@ describe('@next/font/google', () => { ...@@ -65,7 +65,6 @@ describe('@next/font/google', () => {
// CompWithFonts.js // CompWithFonts.js
expect(JSON.parse($('#comp-with-fonts-inter').text())).toEqual({ expect(JSON.parse($('#comp-with-fonts-inter').text())).toEqual({
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Inter_.{6}', '__Inter_Fallback_.{6}'$/ /^'__Inter_.{6}', '__Inter_Fallback_.{6}'$/
...@@ -75,7 +74,6 @@ describe('@next/font/google', () => { ...@@ -75,7 +74,6 @@ describe('@next/font/google', () => {
}) })
expect(JSON.parse($('#comp-with-fonts-roboto').text())).toEqual({ expect(JSON.parse($('#comp-with-fonts-roboto').text())).toEqual({
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Roboto_.{6}', '__Roboto_Fallback_.{6}'$/ /^'__Roboto_.{6}', '__Roboto_Fallback_.{6}'$/
...@@ -220,32 +218,6 @@ describe('@next/font/google', () => { ...@@ -220,32 +218,6 @@ describe('@next/font/google', () => {
) )
).not.toMatch(firaCodeRegex) ).not.toMatch(firaCodeRegex)
// Albert Sant Variable Italic
const albertSansItalicRegex = /^__Albert_Sans_.{6}$/
expect(
await browser.eval(
'getComputedStyle(document.querySelector("#variables-albert-sans-italic")).fontFamily'
)
).toMatch(albertSansItalicRegex)
expect(
await browser.eval(
'getComputedStyle(document.querySelector("#without-variables-albert-sans-italic")).fontFamily'
)
).not.toMatch(albertSansItalicRegex)
// Inter 900
const inter900Regex = /^__Inter_.{6}, __Inter_Fallback_.{6}$/
expect(
await browser.eval(
'getComputedStyle(document.querySelector("#variables-inter-900")).fontFamily'
)
).toMatch(inter900Regex)
expect(
await browser.eval(
'getComputedStyle(document.querySelector("#without-variables-inter-900")).fontFamily'
)
).not.toMatch(inter900Regex)
// Roboto 100 Italic // Roboto 100 Italic
const roboto100ItalicRegex = /^__Roboto_.{6}, __Roboto_Fallback_.{6}$/ const roboto100ItalicRegex = /^__Roboto_.{6}, __Roboto_Fallback_.{6}$/
expect( expect(
......
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