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

Add support for fallback font and css variable for font/local (#40990)

Adds support for generating a fallback font by providing font override
metrics for the given local font. Also adds support for providing a CSS
variable name that then can be accessed through the `.variable` export,
it contains the hashed font family name.

## 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 <jj@jjsweb.site>
parent a89d760d
import type { FontLoader } from 'next/font' import type { AdjustFontFallback, FontLoader } from 'next/font'
// @ts-ignore // @ts-ignore
import fetch from 'next/dist/compiled/node-fetch' import fetch from 'next/dist/compiled/node-fetch'
// @ts-ignore // @ts-ignore
import { calculateOverrideCSS } from 'next/dist/server/font-utils' import { calculateOverrideValues } from 'next/dist/server/font-utils'
import { import {
fetchCSSFromGoogleFonts, fetchCSSFromGoogleFonts,
getFontAxes, getFontAxes,
...@@ -97,20 +97,36 @@ const downloadGoogleFonts: FontLoader = async ({ ...@@ -97,20 +97,36 @@ const downloadGoogleFonts: FontLoader = async ({
} }
// Add fallback font // Add fallback font
let adjustFontFallbackMetrics: AdjustFontFallback | undefined
if (adjustFontFallback) { if (adjustFontFallback) {
try { try {
updatedCssResponse += calculateOverrideCSS( const { ascent, descent, lineGap, fallbackFont } =
fontFamily, calculateOverrideValues(
require('next/dist/server/google-font-metrics.json') fontFamily,
require('next/dist/server/google-font-metrics.json')
)
adjustFontFallbackMetrics = {
fallbackFont,
ascentOverride: ascent,
descentOverride: descent,
lineGapOverride: lineGap,
}
} catch {
console.error(
`Failed to find font override values for font \`${fontFamily}\``
) )
} catch (e) {
console.log('Error getting font override values - ', e)
} }
} }
return { return {
css: updatedCssResponse, css: updatedCssResponse,
fallbackFonts: fallback, fallbackFonts: fallback,
weight: weight === 'variable' ? undefined : weight,
style,
variable: `--next-font-${fontFamily.toLowerCase().replace(/ /g, '-')}${
weight !== 'variable' ? `-${weight}` : ''
}${style === 'italic' ? `-italic` : ''}`,
adjustFontFallback: adjustFontFallbackMetrics,
} }
} }
......
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unused-vars */
import type { 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 LocalFont = { type LocalFont = {
src: string | Array<{ file: string; unicodeRange: string }> src: string | Array<{ file: string; unicodeRange: string }>
...@@ -8,15 +8,18 @@ type LocalFont = { ...@@ -8,15 +8,18 @@ type LocalFont = {
style?: string style?: string
fallback?: string[] fallback?: string[]
preload?: boolean preload?: boolean
variable?: string
ascentOverride?: string
descentOverride?: string
fontStretch?: string fontStretch?: string
fontVariant?: string fontVariant?: string
fontFeatureSettings?: string fontFeatureSettings?: string
fontVariationSettings?: string fontVariationSettings?: string
ascentOverride?: string
descentOverride?: string
lineGapOverride?: string lineGapOverride?: string
sizeAdjust?: string sizeAdjust?: string
adjustFontFallback?: AdjustFontFallback
} }
export default function localFont(options: LocalFont): FontModule { export default function localFont(options: LocalFont): FontModule {
......
...@@ -18,12 +18,14 @@ const fetchFonts: FontLoader = async ({ ...@@ -18,12 +18,14 @@ const fetchFonts: FontLoader = async ({
style, style,
fallback, fallback,
preload, preload,
variable,
ascentOverride, ascentOverride,
descentOverride, descentOverride,
lineGapOverride, lineGapOverride,
fontStretch, fontStretch,
fontFeatureSettings, fontFeatureSettings,
sizeAdjust, sizeAdjust,
adjustFontFallback,
} = validateData(functionName, data) } = validateData(functionName, data)
const fontFaces = await Promise.all( const fontFaces = await Promise.all(
...@@ -61,6 +63,10 @@ ${fontFaceProperties ...@@ -61,6 +63,10 @@ ${fontFaceProperties
return { return {
css: fontFaces.join('\n'), css: fontFaces.join('\n'),
fallbackFonts: fallback, fallbackFonts: fallback,
weight,
style,
variable,
adjustFontFallback,
} }
} }
......
import { AdjustFontFallback } from 'next/font'
const allowedDisplayValues = ['auto', 'block', 'swap', 'fallback', 'optional'] const allowedDisplayValues = ['auto', 'block', 'swap', 'fallback', 'optional']
const formatValues = (values: string[]) => const formatValues = (values: string[]) =>
...@@ -24,6 +26,7 @@ type FontOptions = { ...@@ -24,6 +26,7 @@ type FontOptions = {
style?: string style?: string
fallback?: string[] fallback?: string[]
preload: boolean preload: boolean
variable?: string
ascentOverride?: string ascentOverride?: string
descentOverride?: string descentOverride?: string
fontStretch?: string fontStretch?: string
...@@ -32,6 +35,7 @@ type FontOptions = { ...@@ -32,6 +35,7 @@ type FontOptions = {
fontVariationSettings?: string fontVariationSettings?: string
lineGapOverride?: string lineGapOverride?: string
sizeAdjust?: string sizeAdjust?: string
adjustFontFallback?: AdjustFontFallback
} }
export function validateData(functionName: string, data: any): FontOptions { export function validateData(functionName: string, data: any): FontOptions {
if (functionName) { if (functionName) {
...@@ -44,6 +48,7 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -44,6 +48,7 @@ export function validateData(functionName: string, data: any): FontOptions {
style, style,
fallback, fallback,
preload = true, preload = true,
variable,
ascentOverride, ascentOverride,
descentOverride, descentOverride,
fontStretch, fontStretch,
...@@ -52,6 +57,7 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -52,6 +57,7 @@ export function validateData(functionName: string, data: any): FontOptions {
fontVariationSettings, fontVariationSettings,
lineGapOverride, lineGapOverride,
sizeAdjust, sizeAdjust,
adjustFontFallback,
} = data[0] || ({} as any) } = data[0] || ({} as any)
if (!allowedDisplayValues.includes(display)) { if (!allowedDisplayValues.includes(display)) {
...@@ -100,6 +106,7 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -100,6 +106,7 @@ export function validateData(functionName: string, data: any): FontOptions {
style, style,
fallback, fallback,
preload, preload,
variable,
ascentOverride, ascentOverride,
descentOverride, descentOverride,
fontStretch, fontStretch,
...@@ -108,5 +115,6 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -108,5 +115,6 @@ export function validateData(functionName: string, data: any): FontOptions {
fontVariationSettings, fontVariationSettings,
lineGapOverride, lineGapOverride,
sizeAdjust, sizeAdjust,
adjustFontFallback,
} }
} }
...@@ -43,18 +43,21 @@ export default async function nextFontLoader(this: any) { ...@@ -43,18 +43,21 @@ export default async function nextFontLoader(this: any) {
this.resourcePath, this.resourcePath,
'../loader.js' '../loader.js'
)).default )).default
let { css, fallbackFonts } = await fontLoader({ let { css, fallbackFonts, adjustFontFallback, weight, style, variable } =
functionName, await fontLoader({
data, functionName,
config: fontLoaderOptions, data,
emitFontFile, config: fontLoaderOptions,
resolve: (src: string) => emitFontFile,
promisify(this.resolve)( resolve: (src: string) =>
path.dirname(path.join(this.rootContext, relativeFilePathFromRoot)), promisify(this.resolve)(
src path.dirname(
), path.join(this.rootContext, relativeFilePathFromRoot)
fs: this.fs, ),
}) src
),
fs: this.fs,
})
const { postcss } = await getPostcss() const { postcss } = await getPostcss()
...@@ -68,7 +71,15 @@ export default async function nextFontLoader(this: any) { ...@@ -68,7 +71,15 @@ export default async function nextFontLoader(this: any) {
) )
// Add CSS classes, exports and make the font-family localy scoped by turning it unguessable // Add CSS classes, exports and make the font-family localy scoped by turning it unguessable
const result = await postcss( const result = await postcss(
postcssFontLoaderPlugn(exports, fontFamilyHash, fallbackFonts) postcssFontLoaderPlugn({
exports,
fontFamilyHash,
fallbackFonts,
weight,
style,
adjustFontFallback,
variable,
})
).process(css, { ).process(css, {
from: undefined, from: undefined,
}) })
...@@ -79,9 +90,14 @@ export default async function nextFontLoader(this: any) { ...@@ -79,9 +90,14 @@ export default async function nextFontLoader(this: any) {
version: result.processor.version, version: result.processor.version,
root: result.root, root: result.root,
} }
callback(null, result.css, null, { exports, ast, fontFamilyHash }) callback(null, result.css, null, {
exports,
ast,
fontFamilyHash,
})
} catch (err: any) { } catch (err: any) {
err.stack = false err.stack = false
err.message = `Font loader error:\n${err.message}`
err.message += ` err.message += `
${chalk.cyan(`Location: ${relativeFilePathFromRoot}`)}` ${chalk.cyan(`Location: ${relativeFilePathFromRoot}`)}`
......
import type { AdjustFontFallback } from '../../../../font'
import postcss, { Declaration } from 'postcss' import postcss, { Declaration } from 'postcss'
const postcssFontLoaderPlugn = ( const postcssFontLoaderPlugn = ({
exports: { name: any; value: any }[], exports,
fontFamilyHash: string, fontFamilyHash,
fallbackFonts: string[] = [] fallbackFonts = [],
) => { adjustFontFallback,
variable,
weight,
style,
}: {
exports: { name: any; value: any }[]
fontFamilyHash: string
fallbackFonts?: string[]
adjustFontFallback?: AdjustFontFallback
variable?: string
weight?: string
style?: string
}) => {
return { return {
postcssPlugin: 'postcss-font-loader', postcssPlugin: 'postcss-font-loader',
Once(root: any) { Once(root: any) {
const fontFamilies: string[] = [] let fontFamily: string | undefined
let rawFamily: string | undefined
let fontWeight: string | undefined const normalizeFamily = (family: string) => {
let fontStyle: string | undefined return family.replace(/['"]/g, '')
}
const formatFamily = (family: string) => { const formatFamily = (family: string) => {
if (family[0] === "'" || family[0] === '"') {
family = family.slice(1, family.length - 1)
}
// Turn the font family unguessable to make it localy scoped // Turn the font family unguessable to make it localy scoped
return `'__${family.replace(/ /g, '_')}_${fontFamilyHash}'` return `'__${family.replace(/ /g, '_')}_${fontFamilyHash}'`
} }
// Hash font-family name
for (const node of root.nodes) { for (const node of root.nodes) {
if (node.type === 'atrule' && node.name === 'font-face') { if (node.type === 'atrule' && node.name === 'font-face') {
const familyNode = node.nodes.find( const familyNode = node.nodes.find(
...@@ -30,52 +42,85 @@ const postcssFontLoaderPlugn = ( ...@@ -30,52 +42,85 @@ const postcssFontLoaderPlugn = (
continue continue
} }
if (!rawFamily) { const currentFamily = normalizeFamily(familyNode.value)
let family: string = familyNode.value
if (family[0] === "'" || family[0] === '"') {
family = family.slice(1, family.length - 1)
}
rawFamily = family
}
const formattedFamily = formatFamily(familyNode.value)
familyNode.value = formattedFamily
if (fontFamilies.includes(formattedFamily)) { if (!fontFamily) {
continue fontFamily = currentFamily
} else if (fontFamily !== currentFamily) {
throw new Error(
`Font family mismatch, expected ${fontFamily} but got ${currentFamily}`
)
} }
fontFamilies.push(formattedFamily)
// Only extract weight and style from first encountered family, the rest will treated as fallbacks familyNode.value = formatFamily(fontFamily)
if (fontFamilies.length > 1) { }
continue }
}
// Extract weight and style from first encountered @font-face
const weight = node.nodes.find(
(decl: Declaration) => decl.prop === 'font-weight'
)
// Skip if the value includes ' ', then it's a range of possible values if (!fontFamily) {
if (weight && !weight.value.includes(' ')) { throw new Error('Font loaders must have exactly one font family')
fontWeight = weight.value }
}
const style = node.nodes.find( // Add fallback font with override values
(decl: Declaration) => decl.prop === 'font-style' let adjustFontFallbackFamily: string | undefined
) if (adjustFontFallback) {
// Skip if the value includes ' ', then it's a range of possible values adjustFontFallbackFamily = formatFamily(`${fontFamily} Fallback`)
if (style && !style.value.includes(' ')) { const fallbackFontFace = postcss.atRule({ name: 'font-face' })
fontStyle = style.value const {
} fallbackFont,
} ascentOverride,
descentOverride,
lineGapOverride,
sizeAdjust,
} = adjustFontFallback
fallbackFontFace.nodes = [
new postcss.Declaration({
prop: 'font-family',
value: adjustFontFallbackFamily,
}),
new postcss.Declaration({
prop: 'src',
value: `local("${fallbackFont}")`,
}),
...(ascentOverride
? [
new postcss.Declaration({
prop: 'ascent-override',
value: ascentOverride,
}),
]
: []),
...(descentOverride
? [
new postcss.Declaration({
prop: 'descent-override',
value: descentOverride,
}),
]
: []),
...(lineGapOverride
? [
new postcss.Declaration({
prop: 'line-gap-override',
value: lineGapOverride,
}),
]
: []),
...(sizeAdjust
? [
new postcss.Declaration({
prop: 'size-adjust',
value: sizeAdjust,
}),
]
: []),
]
root.nodes.push(fallbackFontFace)
} }
const [mainFontFamily, ...adjustFontFallbacks] = fontFamilies
// If fallback fonts were provided from the font loader, they should be used before the adjustFontFallbacks
const formattedFontFamilies = [ const formattedFontFamilies = [
mainFontFamily, formatFamily(fontFamily),
...fallbackFonts, ...fallbackFonts,
...adjustFontFallbacks, ...(adjustFontFallbackFamily ? [adjustFontFallbackFamily] : []),
].join(', ') ].join(', ')
// Add class with family, weight and style // Add class with family, weight and style
const classRule = new postcss.Rule({ selector: '.className' }) const classRule = new postcss.Rule({ selector: '.className' })
...@@ -84,19 +129,19 @@ const postcssFontLoaderPlugn = ( ...@@ -84,19 +129,19 @@ const postcssFontLoaderPlugn = (
prop: 'font-family', prop: 'font-family',
value: formattedFontFamilies, value: formattedFontFamilies,
}), }),
...(fontWeight ...(weight
? [ ? [
new postcss.Declaration({ new postcss.Declaration({
prop: 'font-weight', prop: 'font-weight',
value: fontWeight, value: weight,
}), }),
] ]
: []), : []),
...(fontStyle ...(style
? [ ? [
new postcss.Declaration({ new postcss.Declaration({
prop: 'font-style', prop: 'font-style',
value: fontStyle, value: style,
}), }),
] ]
: []), : []),
...@@ -104,26 +149,24 @@ const postcssFontLoaderPlugn = ( ...@@ -104,26 +149,24 @@ const postcssFontLoaderPlugn = (
root.nodes.push(classRule) root.nodes.push(classRule)
// Add class that defines a variable with the font family // Add class that defines a variable with the font family
const varialbeRule = new postcss.Rule({ selector: '.variable' }) if (variable) {
varialbeRule.nodes = [ const varialbeRule = new postcss.Rule({ selector: '.variable' })
new postcss.Declaration({ varialbeRule.nodes = [
prop: rawFamily new postcss.Declaration({
? `--next-font-${rawFamily.toLowerCase().replace(/ /g, '-')}${ prop: variable,
fontWeight ? `-${fontWeight}` : '' value: formattedFontFamilies,
}${fontStyle === 'italic' ? `-${fontStyle}` : ''}` }),
: '', ]
value: formattedFontFamilies, root.nodes.push(varialbeRule)
}), }
]
root.nodes.push(varialbeRule)
// Export @font-face values as is // Export @font-face values as is
exports.push({ exports.push({
name: 'style', name: 'style',
value: { value: {
fontFamily: formattedFontFamilies, fontFamily: formattedFontFamilies,
fontWeight: fontWeight && Number(fontWeight), fontWeight: weight && Number(weight),
fontStyle, fontStyle: style,
}, },
}) })
}, },
......
...@@ -173,6 +173,16 @@ function formatWebpackMessages(json, verbose) { ...@@ -173,6 +173,16 @@ function formatWebpackMessages(json, verbose) {
const formattedErrors = json.errors.map(function (message) { const formattedErrors = json.errors.map(function (message) {
let importTraceNote let importTraceNote
if (
message &&
message.message &&
/Font loader error:/.test(message.message)
) {
return message.message.slice(
message.message.indexOf('Font loader error:')
)
}
// TODO: Shall we use invisible characters in the original error // TODO: Shall we use invisible characters in the original error
// message as meta information? // message as meta information?
if (message && message.message && /NEXT_RSC_ERR_/.test(message.message)) { if (message && message.message && /NEXT_RSC_ERR_/.test(message.message)) {
......
export type FontModule = { export type FontModule = {
className: string className: string
variable: string variable?: string
style: { fontFamily: string; fontWeight?: number; fontStyle?: string } style: { fontFamily: string; fontWeight?: number; fontStyle?: string }
} }
export type AdjustFontFallback = {
fallbackFont: string
ascentOverride?: string
descentOverride?: string
lineGapOverride?: string
sizeAdjust?: string
}
export type FontLoader = (options: { export type FontLoader = (options: {
functionName: string functionName: string
data: any[] data: any[]
...@@ -11,4 +19,11 @@ export type FontLoader = (options: { ...@@ -11,4 +19,11 @@ 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
}) => Promise<{ css: string; fallbackFonts?: string[] }> }) => Promise<{
css: string
fallbackFonts?: string[]
variable?: string
adjustFontFallback?: AdjustFontFallback
weight?: string
style?: string
}>
...@@ -98,8 +98,7 @@ function parseGoogleFontName(css: string): Array<string> { ...@@ -98,8 +98,7 @@ function parseGoogleFontName(css: string): Array<string> {
return [...fontNames] return [...fontNames]
} }
export function calculateOverrideCSS(font: string, fontMetrics: any) { export function calculateOverrideValues(font: string, fontMetrics: any) {
const fontName = font.toLowerCase().trim().replace(/ /g, '-')
const fontKey = font.toLowerCase().trim().replace(/ /g, '') const fontKey = font.toLowerCase().trim().replace(/ /g, '')
const { category, ascentOverride, descentOverride, lineGapOverride } = const { category, ascentOverride, descentOverride, lineGapOverride } =
fontMetrics[fontKey] fontMetrics[fontKey]
...@@ -109,6 +108,22 @@ export function calculateOverrideCSS(font: string, fontMetrics: any) { ...@@ -109,6 +108,22 @@ export function calculateOverrideCSS(font: string, fontMetrics: any) {
const descent = (descentOverride * 100).toFixed(2) const descent = (descentOverride * 100).toFixed(2)
const lineGap = (lineGapOverride * 100).toFixed(2) const lineGap = (lineGapOverride * 100).toFixed(2)
return {
ascent,
descent,
lineGap,
fallbackFont,
}
}
function calculateOverrideCSS(font: string, fontMetrics: any) {
const fontName = font.toLowerCase().trim().replace(/ /g, '-')
const { ascent, descent, lineGap, fallbackFont } = calculateOverrideValues(
font,
fontMetrics
)
return ` return `
@font-face { @font-face {
font-family: "${fontName}-fallback"; font-family: "${fontName}-fallback";
......
...@@ -55,7 +55,6 @@ describe('app dir next-font', () => { ...@@ -55,7 +55,6 @@ describe('app dir next-font', () => {
// Comp // Comp
expect(JSON.parse($('#root-comp').text())).toEqual({ expect(JSON.parse($('#root-comp').text())).toEqual({
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__font3_.{6}'$/), fontFamily: expect.stringMatching(/^'__font3_.{6}'$/),
fontStyle: 'italic', fontStyle: 'italic',
...@@ -80,7 +79,6 @@ describe('app dir next-font', () => { ...@@ -80,7 +79,6 @@ describe('app dir next-font', () => {
// layout // layout
expect(JSON.parse($('#client-layout').text())).toEqual({ expect(JSON.parse($('#client-layout').text())).toEqual({
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__font4_.{6}'$/), fontFamily: expect.stringMatching(/^'__font4_.{6}'$/),
fontWeight: 100, fontWeight: 100,
...@@ -89,7 +87,6 @@ describe('app dir next-font', () => { ...@@ -89,7 +87,6 @@ describe('app dir next-font', () => {
// page // page
expect(JSON.parse($('#client-page').text())).toEqual({ expect(JSON.parse($('#client-page').text())).toEqual({
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__font5_.{6}'$/), fontFamily: expect.stringMatching(/^'__font5_.{6}'$/),
fontStyle: 'italic', fontStyle: 'italic',
...@@ -98,7 +95,6 @@ describe('app dir next-font', () => { ...@@ -98,7 +95,6 @@ describe('app dir next-font', () => {
// Comp // Comp
expect(JSON.parse($('#client-comp').text())).toEqual({ expect(JSON.parse($('#client-comp').text())).toEqual({
className: expect.stringMatching(/^__className_.{6}$/), className: expect.stringMatching(/^__className_.{6}$/),
variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__font6_.{6}'$/), fontFamily: expect.stringMatching(/^'__font6_.{6}'$/),
}, },
......
import localFont from '@next/font/local' import localFont from '@next/font/local'
export const font1 = localFont({ src: './font1.woff2' }) export const font1 = localFont({ src: './font1.woff2', variable: '--font-1' })
export const font2 = localFont({ src: './font2.woff2' }) export const font2 = localFont({ src: './font2.woff2', variable: '--font-2' })
export const font3 = localFont({ export const font3 = localFont({
src: './font3.woff2', src: './font3.woff2',
weight: '900', weight: '900',
......
import { Fira_Code, Albert_Sans, Inter, Roboto } from '@next/font/google' import { Fira_Code, Albert_Sans, Inter, Roboto } from '@next/font/google'
import localFont from '@next/font/local'
const firaCode = Fira_Code() const firaCode = Fira_Code()
const albertSans = Albert_Sans({ const albertSans = Albert_Sans({
variant: 'variable-italic', variant: 'variable-italic',
...@@ -10,6 +12,11 @@ const roboto = Roboto({ ...@@ -10,6 +12,11 @@ const roboto = Roboto({
display: 'swap', display: 'swap',
preload: true, preload: true,
}) })
const myFont = localFont({
src: '../fonts/my-font.woff2',
preload: false,
variable: '--my-font',
})
export default function WithFonts() { export default function WithFonts() {
return ( return (
...@@ -73,6 +80,21 @@ export default function WithFonts() { ...@@ -73,6 +80,21 @@ export default function WithFonts() {
> >
Without variables Without variables
</div> </div>
{/* Local font */}
<div
id="variables-local-font"
className={myFont.variable}
style={{ fontFamily: 'var(--my-font)' }}
>
With variables
</div>
<div
id="without-variables-local-font"
style={{ fontFamily: 'var(--my-font)' }}
>
Without variables
</div>
</> </>
) )
} }
...@@ -4,10 +4,16 @@ const myFont1 = localFont({ ...@@ -4,10 +4,16 @@ const myFont1 = localFont({
src: '../fonts/my-font.woff2', src: '../fonts/my-font.woff2',
style: 'italic', style: 'italic',
weight: '100', weight: '100',
fallback: ['system-ui'],
}) })
const myFont2 = localFont({ const myFont2 = localFont({
src: '../fonts/my-other-font.woff', src: '../fonts/my-other-font.woff',
preload: false, preload: false,
variable: '--my-font',
adjustFontFallback: {
fallbackFont: 'Arial',
sizeAdjust: '120%',
},
}) })
export default function WithFonts() { export default function WithFonts() {
......
...@@ -46,9 +46,8 @@ describe('@next/font/google', () => { ...@@ -46,9 +46,8 @@ describe('@next/font/google', () => {
variable: expect.stringMatching(/^__variable_.{6}$/), variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__open-sans-fallback_.{6}'$/ /^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
), ),
fontStyle: 'normal',
}, },
}) })
...@@ -58,9 +57,8 @@ describe('@next/font/google', () => { ...@@ -58,9 +57,8 @@ describe('@next/font/google', () => {
variable: expect.stringMatching(/^__variable_.{6}$/), variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__open-sans-fallback_.{6}'$/ /^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
), ),
fontStyle: 'normal',
}, },
}) })
...@@ -70,9 +68,8 @@ describe('@next/font/google', () => { ...@@ -70,9 +68,8 @@ describe('@next/font/google', () => {
variable: expect.stringMatching(/^__variable_.{6}$/), variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Inter_.{6}', '__inter-fallback_.{6}'$/ /^'__Inter_.{6}', '__Inter_Fallback_.{6}'$/
), ),
fontStyle: 'normal',
fontWeight: 900, fontWeight: 900,
}, },
}) })
...@@ -81,7 +78,7 @@ describe('@next/font/google', () => { ...@@ -81,7 +78,7 @@ describe('@next/font/google', () => {
variable: expect.stringMatching(/^__variable_.{6}$/), variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Roboto_.{6}', '__roboto-fallback_.{6}'$/ /^'__Roboto_.{6}', '__Roboto_Fallback_.{6}'$/
), ),
fontStyle: 'italic', fontStyle: 'italic',
fontWeight: 100, fontWeight: 100,
...@@ -95,31 +92,31 @@ describe('@next/font/google', () => { ...@@ -95,31 +92,31 @@ describe('@next/font/google', () => {
// _app.js // _app.js
expect(JSON.parse($('#app-open-sans').text())).toEqual({ expect(JSON.parse($('#app-open-sans').text())).toEqual({
className: '__className_f32d04', className: expect.stringMatching(/__className_.{6}/),
variable: '__variable_f32d04', variable: expect.stringMatching(/__variable_.{6}/),
style: { style: {
fontFamily: expect.stringMatching( fontFamily: expect.stringMatching(
/^'__Open_Sans_.{6}', '__open-sans-fallback_.{6}'$/ /^'__Open_Sans_.{6}', '__Open_Sans_Fallback_.{6}'$/
), ),
fontStyle: 'normal',
}, },
}) })
// with-local-fonts.js // with-local-fonts.js
expect(JSON.parse($('#first-local-font').text())).toEqual({ expect(JSON.parse($('#first-local-font').text())).toEqual({
className: '__className_410624', className: expect.stringMatching(/__className_.{6}/),
variable: '__variable_410624',
style: { style: {
fontFamily: expect.stringMatching(/^'__my-font_.{6}'$/), fontFamily: expect.stringMatching(/^'__my-font_.{6}', system-ui$/),
fontStyle: 'italic', fontStyle: 'italic',
fontWeight: 100, fontWeight: 100,
}, },
}) })
expect(JSON.parse($('#second-local-font').text())).toEqual({ expect(JSON.parse($('#second-local-font').text())).toEqual({
className: '__className_3ff726', className: expect.stringMatching(/^__className_.{6}$/),
variable: '__variable_3ff726', variable: expect.stringMatching(/^__variable_.{6}$/),
style: { style: {
fontFamily: expect.stringMatching(/^'__my-other-font_.{6}'$/), fontFamily: expect.stringMatching(
/^'__my-other-font_.{6}', '__my-other-font_Fallback_.{6}'$/
),
}, },
}) })
}) })
...@@ -134,7 +131,7 @@ describe('@next/font/google', () => { ...@@ -134,7 +131,7 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#app-open-sans")).fontFamily' 'getComputedStyle(document.querySelector("#app-open-sans")).fontFamily'
) )
).toMatch(/^__Open_Sans_.{6}, __open-sans-fallback_.{6}$/) ).toMatch(/^__Open_Sans_.{6}, __Open_Sans_Fallback_.{6}$/)
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#app-open-sans")).fontWeight' 'getComputedStyle(document.querySelector("#app-open-sans")).fontWeight'
...@@ -151,7 +148,7 @@ describe('@next/font/google', () => { ...@@ -151,7 +148,7 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontFamily' 'getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontFamily'
) )
).toMatch(/^__Open_Sans_.{6}, __open-sans-fallback_.{6}$/) ).toMatch(/^__Open_Sans_.{6}, __Open_Sans_Fallback_.{6}$/)
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontWeight' 'getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontWeight'
...@@ -178,7 +175,7 @@ describe('@next/font/google', () => { ...@@ -178,7 +175,7 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontFamily' 'getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontFamily'
) )
).toMatch(/^__Inter_.{6}, __inter-fallback_.{6}$/) ).toMatch(/^__Inter_.{6}, __Inter_Fallback_.{6}$/)
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontWeight' 'getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontWeight'
...@@ -194,7 +191,7 @@ describe('@next/font/google', () => { ...@@ -194,7 +191,7 @@ describe('@next/font/google', () => {
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontFamily' 'getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontFamily'
) )
).toMatch(/^__Roboto_.{6}, __roboto-fallback_.{6}$/) ).toMatch(/^__Roboto_.{6}, __Roboto_Fallback_.{6}$/)
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontWeight' 'getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontWeight'
...@@ -211,7 +208,7 @@ describe('@next/font/google', () => { ...@@ -211,7 +208,7 @@ describe('@next/font/google', () => {
const browser = await webdriver(next.url, '/variables') const browser = await webdriver(next.url, '/variables')
// Fira Code Variable // Fira Code Variable
const firaCodeRegex = /^__Fira_Code_.{6}, __fira-code-fallback_.{6}$/ const firaCodeRegex = /^__Fira_Code_.{6}, __Fira_Code_Fallback_.{6}$/
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#variables-fira-code")).fontFamily' 'getComputedStyle(document.querySelector("#variables-fira-code")).fontFamily'
...@@ -237,7 +234,7 @@ describe('@next/font/google', () => { ...@@ -237,7 +234,7 @@ describe('@next/font/google', () => {
).not.toMatch(albertSansItalicRegex) ).not.toMatch(albertSansItalicRegex)
// Inter 900 // Inter 900
const inter900Regex = /^__Inter_.{6}, __inter-fallback_.{6}$/ const inter900Regex = /^__Inter_.{6}, __Inter_Fallback_.{6}$/
expect( expect(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#variables-inter-900")).fontFamily' 'getComputedStyle(document.querySelector("#variables-inter-900")).fontFamily'
...@@ -250,7 +247,7 @@ describe('@next/font/google', () => { ...@@ -250,7 +247,7 @@ describe('@next/font/google', () => {
).not.toMatch(inter900Regex) ).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(
await browser.eval( await browser.eval(
'getComputedStyle(document.querySelector("#variables-roboto-100-italic")).fontFamily' 'getComputedStyle(document.querySelector("#variables-roboto-100-italic")).fontFamily'
...@@ -261,6 +258,19 @@ describe('@next/font/google', () => { ...@@ -261,6 +258,19 @@ describe('@next/font/google', () => {
'getComputedStyle(document.querySelector("#without-variables-roboto-100-italic")).fontFamily' 'getComputedStyle(document.querySelector("#without-variables-roboto-100-italic")).fontFamily'
) )
).not.toMatch(roboto100ItalicRegex) ).not.toMatch(roboto100ItalicRegex)
// Local font
const localFontRegex = /^__my-font_.{6}$/
expect(
await browser.eval(
'getComputedStyle(document.querySelector("#variables-local-font")).fontFamily'
)
).toMatch(localFontRegex)
expect(
await browser.eval(
'getComputedStyle(document.querySelector("#without-variables-local-font")).fontFamily'
)
).not.toMatch(localFontRegex)
}) })
test('page using fallback fonts', async () => { test('page using fallback fonts', async () => {
...@@ -272,7 +282,7 @@ describe('@next/font/google', () => { ...@@ -272,7 +282,7 @@ describe('@next/font/google', () => {
'getComputedStyle(document.querySelector("#with-fallback-fonts-classname")).fontFamily' 'getComputedStyle(document.querySelector("#with-fallback-fonts-classname")).fontFamily'
) )
).toMatch( ).toMatch(
/^__Open_Sans_.{6}, system-ui, Arial, __open-sans-fallback_.{6}$/ /^__Open_Sans_.{6}, system-ui, Arial, __Open_Sans_Fallback_.{6}$/
) )
// .style // .style
...@@ -281,7 +291,7 @@ describe('@next/font/google', () => { ...@@ -281,7 +291,7 @@ describe('@next/font/google', () => {
'getComputedStyle(document.querySelector("#with-fallback-fonts-style")).fontFamily' 'getComputedStyle(document.querySelector("#with-fallback-fonts-style")).fontFamily'
) )
).toMatch( ).toMatch(
/^__Open_Sans_.{6}, system-ui, Arial, __open-sans-fallback_.{6}$/ /^__Open_Sans_.{6}, system-ui, Arial, __Open_Sans_Fallback_.{6}$/
) )
// .variable // .variable
...@@ -290,7 +300,7 @@ describe('@next/font/google', () => { ...@@ -290,7 +300,7 @@ describe('@next/font/google', () => {
'getComputedStyle(document.querySelector("#with-fallback-fonts-variable")).fontFamily' 'getComputedStyle(document.querySelector("#with-fallback-fonts-variable")).fontFamily'
) )
).toMatch( ).toMatch(
/^__Open_Sans_.{6}, system-ui, Arial, __open-sans-fallback_.{6}$/ /^__Open_Sans_.{6}, system-ui, Arial, __Open_Sans_Fallback_.{6}$/
) )
}) })
}) })
......
...@@ -93,7 +93,7 @@ describe('@next/font/google loader', () => { ...@@ -93,7 +93,7 @@ describe('@next/font/google loader', () => {
ok: true, ok: true,
text: async () => '', text: async () => '',
}) })
const { css, fallbackFonts } = await loader({ const { adjustFontFallback, fallbackFonts } = await loader({
functionName: 'Inter', functionName: 'Inter',
data: [], data: [],
config: { subsets: [] }, config: { subsets: [] },
...@@ -101,17 +101,12 @@ describe('@next/font/google loader', () => { ...@@ -101,17 +101,12 @@ describe('@next/font/google loader', () => {
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
}) })
expect(css).toMatchInlineSnapshot(` expect(adjustFontFallback).toEqual({
" ascentOverride: '96.88',
@font-face { descentOverride: '24.15',
font-family: \\"inter-fallback\\"; fallbackFont: 'Arial',
ascent-override: 96.88%; lineGapOverride: '0.00',
descent-override: 24.15%; })
line-gap-override: 0.00%;
src: local(\\"Arial\\");
}
"
`)
expect(fallbackFonts).toBeUndefined() expect(fallbackFonts).toBeUndefined()
}) })
...@@ -120,7 +115,7 @@ describe('@next/font/google loader', () => { ...@@ -120,7 +115,7 @@ describe('@next/font/google loader', () => {
ok: true, ok: true,
text: async () => '', text: async () => '',
}) })
const { css, fallbackFonts } = await loader({ const { fallbackFonts, adjustFontFallback } = await loader({
functionName: 'Source_Code_Pro', functionName: 'Source_Code_Pro',
data: [], data: [],
config: { subsets: [] }, config: { subsets: [] },
...@@ -128,17 +123,12 @@ describe('@next/font/google loader', () => { ...@@ -128,17 +123,12 @@ describe('@next/font/google loader', () => {
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
}) })
expect(css).toMatchInlineSnapshot(` expect(adjustFontFallback).toEqual({
" ascentOverride: '98.40',
@font-face { descentOverride: '27.30',
font-family: \\"source-code-pro-fallback\\"; fallbackFont: 'Arial',
ascent-override: 98.40%; lineGapOverride: '0.00',
descent-override: 27.30%; })
line-gap-override: 0.00%;
src: local(\\"Arial\\");
}
"
`)
expect(fallbackFonts).toBeUndefined() expect(fallbackFonts).toBeUndefined()
}) })
...@@ -147,7 +137,7 @@ describe('@next/font/google loader', () => { ...@@ -147,7 +137,7 @@ describe('@next/font/google loader', () => {
ok: true, ok: true,
text: async () => '', text: async () => '',
}) })
const { css, fallbackFonts } = await loader({ const { adjustFontFallback, fallbackFonts } = await loader({
functionName: 'Fraunces', functionName: 'Fraunces',
data: [{ fallback: ['Abc', 'Def'] }], data: [{ fallback: ['Abc', 'Def'] }],
config: { subsets: [] }, config: { subsets: [] },
...@@ -155,17 +145,12 @@ describe('@next/font/google loader', () => { ...@@ -155,17 +145,12 @@ describe('@next/font/google loader', () => {
resolve: jest.fn(), resolve: jest.fn(),
fs: {} as any, fs: {} as any,
}) })
expect(css).toMatchInlineSnapshot(` expect(adjustFontFallback).toEqual({
" ascentOverride: '97.80',
@font-face { descentOverride: '25.50',
font-family: \\"fraunces-fallback\\"; fallbackFont: 'Times New Roman',
ascent-override: 97.80%; lineGapOverride: '0.00',
descent-override: 25.50%; })
line-gap-override: 0.00%;
src: local(\\"Times New Roman\\");
}
"
`)
expect(fallbackFonts).toEqual(['Abc', 'Def']) expect(fallbackFonts).toEqual(['Abc', 'Def'])
}) })
......
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