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

Multiple local font weights and styles (#42232)

Allows you to specify multiple weights and styles for a
`@next/font/local` font family.

When generating a fallback font family it will pick the font file with
the weight closest to normal, this will typically make up most of the
text on a page.

## 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 build && 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 cc0c85e5
...@@ -3,7 +3,13 @@ import type { FontModule } from 'next/font' ...@@ -3,7 +3,13 @@ import type { FontModule } from 'next/font'
type Display = 'auto' | 'block' | 'swap' | 'fallback' | 'optional' type Display = 'auto' | 'block' | 'swap' | 'fallback' | 'optional'
type CssVariable = `--${string}` type CssVariable = `--${string}`
type LocalFont = { type LocalFont = {
src: string src:
| string
| Array<{
path: string
weight?: string
style?: string
}>
display?: Display display?: Display
weight?: string weight?: string
style?: string style?: string
......
...@@ -7,6 +7,50 @@ import { promisify } from 'util' ...@@ -7,6 +7,50 @@ import { promisify } from 'util'
import { validateData } from './utils' import { validateData } from './utils'
import { calculateFallbackFontValues } from '../utils' import { calculateFallbackFontValues } from '../utils'
const NORMAL_WEIGHT = 400
const BOLD_WEIGHT = 700
function getWeightNumber(weight: string) {
// Weight can be 'normal', 'bold' or a number https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-weight
return weight === 'normal'
? NORMAL_WEIGHT
: weight === 'bold'
? BOLD_WEIGHT
: Number(weight)
}
function getDistanceFromNormalWeight(weight?: string) {
if (!weight) return 0
const [firstWeight, secondWeight] = weight
.trim()
.split(/ +/)
.map(getWeightNumber)
if (Number.isNaN(firstWeight) || Number.isNaN(secondWeight)) {
throw new Error(
`Invalid weight value in src array: \`${weight}\`.\nExpected \`normal\`, \`bold\` or a number.`
)
}
// Not a variable font
if (!secondWeight) {
return firstWeight - NORMAL_WEIGHT
}
// Normal weight is within variable font range
if (firstWeight <= NORMAL_WEIGHT && secondWeight >= NORMAL_WEIGHT) {
return 0
}
// Return the distance of normal weight to the variable font range
const firstWeightDistance = firstWeight - NORMAL_WEIGHT
const secondWeightDistance = secondWeight - NORMAL_WEIGHT
if (Math.abs(firstWeightDistance) < Math.abs(secondWeightDistance)) {
return firstWeightDistance
}
return secondWeightDistance
}
const fetchFonts: FontLoader = async ({ const fetchFonts: FontLoader = async ({
functionName, functionName,
data, data,
...@@ -17,19 +61,19 @@ const fetchFonts: FontLoader = async ({ ...@@ -17,19 +61,19 @@ const fetchFonts: FontLoader = async ({
const { const {
family, family,
src, src,
ext,
format,
display, display,
weight,
style,
fallback, fallback,
preload, preload,
variable, variable,
adjustFontFallback, adjustFontFallback,
declarations, declarations,
} = validateData(functionName, data) weight: defaultWeight,
style: defaultStyle,
} = validateData(functionName, data[0])
const resolved = await resolve(src) const fontFiles = await Promise.all(
src.map(async ({ path, style, weight, ext, format }) => {
const resolved = await resolve(path)
const fileBuffer = await promisify(fs.readFile)(resolved) const fileBuffer = await promisify(fs.readFile)(resolved)
const fontUrl = emitFontFile(fileBuffer, ext, preload) const fontUrl = emitFontFile(fileBuffer, ext, preload)
...@@ -40,15 +84,6 @@ const fetchFonts: FontLoader = async ({ ...@@ -40,15 +84,6 @@ const fetchFonts: FontLoader = async ({
console.error(`Failed to load font file: ${resolved}\n${e}`) console.error(`Failed to load font file: ${resolved}\n${e}`)
} }
// Add fallback font
let adjustFontFallbackMetrics: AdjustFontFallback | undefined
if (fontMetadata && adjustFontFallback !== false) {
adjustFontFallbackMetrics = calculateFallbackFontValues(
fontMetadata,
adjustFontFallback === 'Times New Roman' ? 'serif' : 'sans-serif'
)
}
const fontFaceProperties = [ const fontFaceProperties = [
...(declarations ...(declarations
? declarations.map(({ prop, value }) => [prop, value]) ? declarations.map(({ prop, value }) => [prop, value])
...@@ -56,21 +91,83 @@ const fetchFonts: FontLoader = async ({ ...@@ -56,21 +91,83 @@ const fetchFonts: FontLoader = async ({
['font-family', `'${fontMetadata?.familyName ?? family}'`], ['font-family', `'${fontMetadata?.familyName ?? family}'`],
['src', `url(${fontUrl}) format('${format}')`], ['src', `url(${fontUrl}) format('${format}')`],
['font-display', display], ['font-display', display],
...(weight ? [['font-weight', weight]] : []), ...(weight ?? defaultWeight
...(style ? [['font-style', style]] : []), ? [['font-weight', weight ?? defaultWeight]]
: []),
...(style ?? defaultStyle
? [['font-style', style ?? defaultStyle]]
: []),
] ]
const css = `@font-face { return {
css: `@font-face {
${fontFaceProperties ${fontFaceProperties
.map(([property, value]) => `${property}: ${value};`) .map(([property, value]) => `${property}: ${value};`)
.join('\n')} .join('\n')}
}` }\n`,
fontMetadata,
weight,
style,
}
})
)
// Add fallback font
let adjustFontFallbackMetrics: AdjustFontFallback | undefined
if (adjustFontFallback !== false) {
// Pick the font file to generate a fallback font from.
// Prefer the file closest to normal weight, this will typically make up most of the text on a page.
const fallbackFontFile = fontFiles.reduce(
(usedFontFile, currentFontFile) => {
if (!usedFontFile) return currentFontFile
const usedFontDistance = getDistanceFromNormalWeight(
usedFontFile.weight
)
const currentFontDistance = getDistanceFromNormalWeight(
currentFontFile.weight
)
// Prefer normal style if they have the same weight
if (
usedFontDistance === currentFontDistance &&
(typeof currentFontFile.style === 'undefined' ||
currentFontFile.style === 'normal')
) {
return currentFontFile
}
const absUsedDistance = Math.abs(usedFontDistance)
const absCurrentDistance = Math.abs(currentFontDistance)
// Use closest absolute distance to normal weight
if (absCurrentDistance < absUsedDistance) return currentFontFile
// Prefer the thinner font if both are the same absolute distance from normal weight
if (
absUsedDistance === absCurrentDistance &&
currentFontDistance < usedFontDistance
) {
return currentFontFile
}
return usedFontFile
}
)
if (fallbackFontFile.fontMetadata) {
adjustFontFallbackMetrics = calculateFallbackFontValues(
fallbackFontFile.fontMetadata,
adjustFontFallback === 'Times New Roman' ? 'serif' : 'sans-serif'
)
}
}
return { return {
css, css: fontFiles.map(({ css }) => css).join('\n'),
fallbackFonts: fallback, fallbackFonts: fallback,
weight, weight: src.length === 1 ? src[0].weight : undefined,
style, style: src.length === 1 ? src[0].style : undefined,
variable, variable,
adjustFontFallback: adjustFontFallbackMetrics, adjustFontFallback: adjustFontFallbackMetrics,
} }
......
...@@ -13,9 +13,13 @@ const extToFormat = { ...@@ -13,9 +13,13 @@ const extToFormat = {
type FontOptions = { type FontOptions = {
family: string family: string
src: string src: Array<{
path: string
weight?: string
style?: string
ext: string ext: string
format: string format: string
}>
display: string display: string
weight?: string weight?: string
style?: string style?: string
...@@ -25,7 +29,7 @@ type FontOptions = { ...@@ -25,7 +29,7 @@ type FontOptions = {
adjustFontFallback?: string | false adjustFontFallback?: string | false
declarations?: Array<{ prop: string; value: string }> declarations?: Array<{ prop: string; value: string }>
} }
export function validateData(functionName: string, data: any): FontOptions { export function validateData(functionName: string, fontData: any): FontOptions {
if (functionName) { if (functionName) {
throw new Error(`@next/font/local has no named exports`) throw new Error(`@next/font/local has no named exports`)
} }
...@@ -39,7 +43,7 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -39,7 +43,7 @@ export function validateData(functionName: string, data: any): FontOptions {
variable, variable,
adjustFontFallback, adjustFontFallback,
declarations, declarations,
} = data[0] || ({} as any) } = fontData || ({} as any)
if (!allowedDisplayValues.includes(display)) { if (!allowedDisplayValues.includes(display)) {
throw new Error( throw new Error(
...@@ -53,12 +57,30 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -53,12 +57,30 @@ export function validateData(functionName: string, data: any): FontOptions {
throw new Error('Missing required `src` property') throw new Error('Missing required `src` property')
} }
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(src)?.[1] if (!Array.isArray(src)) {
src = [{ path: src, weight, style }]
} else {
if (src.length === 0) {
throw new Error('Unexpected empty `src` array.')
}
}
let family: string | undefined
src = src.map((fontFile: any) => {
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFile.path)?.[1]
if (!ext) { if (!ext) {
throw new Error(`Unexpected file \`${src}\``) throw new Error(`Unexpected file \`${fontFile.path}\``)
}
if (!family) {
family = /(.*\/)?(.+?)\.(woff|woff2|eot|ttf|otf)$/.exec(fontFile.path)![2]
} }
const family = /(.*\/)?(.+?)\.(woff|woff2|eot|ttf|otf)$/.exec(src)![2] return {
...fontFile,
ext,
format: extToFormat[ext as 'woff' | 'woff2' | 'eot' | 'ttf' | 'otf'],
}
})
if (Array.isArray(declarations)) { if (Array.isArray(declarations)) {
declarations.forEach((declaration) => { declarations.forEach((declaration) => {
...@@ -77,10 +99,8 @@ export function validateData(functionName: string, data: any): FontOptions { ...@@ -77,10 +99,8 @@ export function validateData(functionName: string, data: any): FontOptions {
} }
return { return {
family, family: family!,
src, src,
ext,
format: extToFormat[ext as 'woff' | 'woff2' | 'eot' | 'ttf' | 'otf'],
display, display,
weight, weight,
style, style,
......
...@@ -42,14 +42,8 @@ const postcssFontLoaderPlugn = ({ ...@@ -42,14 +42,8 @@ const postcssFontLoaderPlugn = ({
continue continue
} }
const currentFamily = normalizeFamily(familyNode.value)
if (!fontFamily) { if (!fontFamily) {
fontFamily = currentFamily fontFamily = normalizeFamily(familyNode.value)
} else if (fontFamily !== currentFamily) {
throw new Error(
`Font family mismatch, expected ${fontFamily} but got ${currentFamily}`
)
} }
familyNode.value = formatFamily(fontFamily) familyNode.value = formatFamily(fontFamily)
......
...@@ -13,6 +13,92 @@ const myFont2 = localFont({ ...@@ -13,6 +13,92 @@ const myFont2 = localFont({
variable: '--my-font', variable: '--my-font',
}) })
const roboto = localFont({
preload: false,
src: [
{
path: '../fonts/roboto/roboto-100-italic.woff2',
weight: '100',
style: 'italic',
},
{
path: '../fonts/my-font.woff2',
weight: '100',
style: 'normal',
},
{
path: '../fonts/my-font.woff2',
weight: '400',
style: 'italic',
},
{
path: '../fonts/roboto/roboto-400.woff2',
weight: '400',
},
{
path: '../fonts/my-font.woff2',
style: 'italic',
},
{
path: '../fonts/my-font.woff2',
weight: '900',
style: 'normal',
},
],
})
const robotoVar1 = localFont({
preload: false,
src: [
{
path: '../fonts/roboto/roboto-400.woff2',
weight: '100 300',
style: 'normal',
},
{
path: '../fonts/my-font.woff2',
weight: '100 300',
style: 'italic',
},
{
path: '../fonts/my-font.woff2',
weight: '500 900',
style: 'italic',
},
{
path: '../fonts/my-font.woff2',
weight: '500 900',
style: 'normal',
},
],
})
const robotoVar2 = localFont({
preload: false,
src: [
{
path: '../fonts/roboto/roboto-900.woff2',
weight: '100 900',
style: 'italic',
},
{
path: '../fonts/roboto/roboto-400.woff2',
weight: '100 900',
style: 'normal',
},
{
path: '../fonts/my-font.woff2',
weight: '300 399',
style: 'italic',
},
{
path: '../fonts/my-font.woff2',
weight: '401 500',
style: 'normal',
},
],
})
export default function WithFonts() { export default function WithFonts() {
return ( return (
<> <>
...@@ -22,6 +108,15 @@ export default function WithFonts() { ...@@ -22,6 +108,15 @@ export default function WithFonts() {
<div id="second-local-font" className={myFont2.className}> <div id="second-local-font" className={myFont2.className}>
{JSON.stringify(myFont2)} {JSON.stringify(myFont2)}
</div> </div>
<div id="roboto-local-font" className={roboto.className}>
{JSON.stringify(roboto)}
</div>
<div id="roboto-local-font-var1" className={robotoVar1.className}>
{JSON.stringify(robotoVar1)}
</div>
<div id="roboto-local-font-var2" className={robotoVar2.className}>
{JSON.stringify(robotoVar2)}
</div>
</> </>
) )
} }
...@@ -404,6 +404,78 @@ describe('@next/font/google', () => { ...@@ -404,6 +404,78 @@ describe('@next/font/google', () => {
) )
expect(sizeAdjust).toBe('115.45%') expect(sizeAdjust).toBe('115.45%')
}) })
test('Roboto multiple weights and styles', async () => {
const browser = await webdriver(next.url, '/with-local-fonts')
const ascentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Thin_Fallback")).ascentOverride'
)
expect(ascentOverride).toBe('92.49%')
const descentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Thin_Fallback")).descentOverride'
)
expect(descentOverride).toBe('24.34%')
const lineGapOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Thin_Fallback")).lineGapOverride'
)
expect(lineGapOverride).toBe('0%')
const sizeAdjust = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Thin_Fallback")).sizeAdjust'
)
expect(sizeAdjust).toBe('100.3%')
})
test('Roboto multiple weights and styles - variable 1', async () => {
const browser = await webdriver(next.url, '/with-local-fonts')
const ascentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Fallback")).ascentOverride'
)
expect(ascentOverride).toBe('92.49%')
const descentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Fallback")).descentOverride'
)
expect(descentOverride).toBe('24.34%')
const lineGapOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Fallback")).lineGapOverride'
)
expect(lineGapOverride).toBe('0%')
const sizeAdjust = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Fallback")).sizeAdjust'
)
expect(sizeAdjust).toBe('100.3%')
})
test('Roboto multiple weights and styles - variable 2', async () => {
const browser = await webdriver(next.url, '/with-local-fonts')
const ascentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Black_Fallback")).ascentOverride'
)
expect(ascentOverride).toBe('92.49%')
const descentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Black_Fallback")).descentOverride'
)
expect(descentOverride).toBe('24.34%')
const lineGapOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Black_Fallback")).lineGapOverride'
)
expect(lineGapOverride).toBe('0%')
const sizeAdjust = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Roboto_Black_Fallback")).sizeAdjust'
)
expect(sizeAdjust).toBe('100.3%')
})
}) })
describe('google', () => { describe('google', () => {
......
...@@ -3,13 +3,13 @@ import loader from '@next/font/local/loader' ...@@ -3,13 +3,13 @@ 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' }],
config: {}, config: {},
emitFontFile: () => '/_next/static/media/my-font.woff2', emitFontFile: () => '/_next/static/media/my-font.woff2',
resolve: jest.fn(), resolve: jest.fn(),
isServer: true,
fs: { fs: {
readFile: (_, cb) => cb(null, 'fontdata'), readFile: (_, cb) => cb(null, 'fontdata'),
}, },
...@@ -20,18 +20,19 @@ describe('@next/font/local', () => { ...@@ -20,18 +20,19 @@ describe('@next/font/local', () => {
font-family: 'my-font'; font-family: 'my-font';
src: url(/_next/static/media/my-font.woff2) format('woff2'); src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional; font-display: optional;
}" }
"
`) `)
}) })
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' }],
config: {}, config: {},
emitFontFile: () => '/_next/static/media/my-font.woff2', emitFontFile: () => '/_next/static/media/my-font.woff2',
resolve: jest.fn(), resolve: jest.fn(),
isServer: true,
fs: { fs: {
readFile: (_, cb) => cb(null, 'fontdata'), readFile: (_, cb) => cb(null, 'fontdata'),
}, },
...@@ -44,12 +45,12 @@ describe('@next/font/local', () => { ...@@ -44,12 +45,12 @@ describe('@next/font/local', () => {
font-display: optional; font-display: optional;
font-weight: 100 900; font-weight: 100 900;
font-style: italic; font-style: italic;
}" }
"
`) `)
}) })
test('Other properties', async () => { test('Other properties', async () => {
// @ts-expect-error
const { css } = await loader({ const { css } = await loader({
functionName: '', functionName: '',
data: [ data: [
...@@ -64,6 +65,7 @@ describe('@next/font/local', () => { ...@@ -64,6 +65,7 @@ describe('@next/font/local', () => {
config: {}, config: {},
emitFontFile: () => '/_next/static/media/my-font.woff2', emitFontFile: () => '/_next/static/media/my-font.woff2',
resolve: jest.fn(), resolve: jest.fn(),
isServer: true,
fs: { fs: {
readFile: (_, cb) => cb(null, 'fontdata'), readFile: (_, cb) => cb(null, 'fontdata'),
}, },
...@@ -76,7 +78,140 @@ describe('@next/font/local', () => { ...@@ -76,7 +78,140 @@ describe('@next/font/local', () => {
font-family: 'my-font'; font-family: 'my-font';
src: url(/_next/static/media/my-font.woff2) format('woff2'); src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional; font-display: optional;
}" }
"
`)
})
test('Multiple weights default style', async () => {
const { css } = await loader({
functionName: '',
data: [
{
style: 'italic',
src: [
{
path: './fonts/font1.woff2',
weight: '100',
},
{
path: './fonts/font2.woff2',
weight: '400',
},
{
path: './fonts/font3.woff2',
weight: '700',
},
{
path: './fonts/font2.woff2',
weight: '400',
style: 'normal',
},
],
adjustFontFallback: false,
},
],
config: {},
emitFontFile: (buffer) => `/_next/static/media/my-font.woff2`,
resolve: jest.fn(),
isServer: true,
fs: {
readFile: (path, cb) => cb(null, path),
},
})
expect(css).toMatchInlineSnapshot(`
"@font-face {
font-family: 'font1';
src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 100;
font-style: italic;
}
@font-face {
font-family: 'font1';
src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 400;
font-style: italic;
}
@font-face {
font-family: 'font1';
src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 700;
font-style: italic;
}
@font-face {
font-family: 'font1';
src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 400;
font-style: normal;
}
"
`)
})
test('Multiple styles default weight', async () => {
const { css } = await loader({
functionName: '',
data: [
{
weight: '400',
src: [
{
path: './fonts/font1.woff2',
style: 'normal',
},
{
path: './fonts/font3.woff2',
style: 'italic',
},
{
path: './fonts/font2.woff2',
weight: '700',
},
],
adjustFontFallback: false,
},
],
config: {},
emitFontFile: (buffer) => `/_next/static/media/my-font.woff2`,
resolve: jest.fn(),
isServer: true,
fs: {
readFile: (path, cb) => cb(null, path),
},
})
expect(css).toMatchInlineSnapshot(`
"@font-face {
font-family: 'font1';
src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: 'font1';
src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 400;
font-style: italic;
}
@font-face {
font-family: 'font1';
src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional;
font-weight: 700;
}
"
`) `)
}) })
}) })
...@@ -84,13 +219,13 @@ describe('@next/font/local', () => { ...@@ -84,13 +219,13 @@ 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: [],
config: {}, config: {},
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
isServer: true,
fs: {}, fs: {},
}) })
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
...@@ -100,13 +235,13 @@ describe('@next/font/local', () => { ...@@ -100,13 +235,13 @@ 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: [],
config: {}, config: {},
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
isServer: true,
fs: {}, fs: {},
}) })
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
...@@ -116,13 +251,13 @@ describe('@next/font/local', () => { ...@@ -116,13 +251,13 @@ 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' }],
config: {}, config: {},
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn().mockResolvedValue(''), resolve: jest.fn().mockResolvedValue(''),
isServer: true,
fs: {}, fs: {},
}) })
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
...@@ -132,13 +267,13 @@ describe('@next/font/local', () => { ...@@ -132,13 +267,13 @@ 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' }],
config: {}, config: {},
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
isServer: true,
fs: {}, fs: {},
}) })
).rejects.toThrowErrorMatchingInlineSnapshot(` ).rejects.toThrowErrorMatchingInlineSnapshot(`
...@@ -149,7 +284,6 @@ describe('@next/font/local', () => { ...@@ -149,7 +284,6 @@ 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: [
...@@ -162,11 +296,82 @@ describe('@next/font/local', () => { ...@@ -162,11 +296,82 @@ describe('@next/font/local', () => {
config: {}, config: {},
emitFontFile: jest.fn(), emitFontFile: jest.fn(),
resolve: jest.fn(), resolve: jest.fn(),
isServer: true,
fs: {}, fs: {},
}) })
).rejects.toThrowErrorMatchingInlineSnapshot( ).rejects.toThrowErrorMatchingInlineSnapshot(
`"Invalid declaration prop: \`src\`"` `"Invalid declaration prop: \`src\`"`
) )
}) })
test('Empty src array', async () => {
await expect(
loader({
functionName: '',
data: [{ src: [] }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isServer: true,
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unexpected empty \`src\` array."`
)
})
test('Invalid weight in array', async () => {
await expect(
loader({
functionName: '',
data: [
{
src: [
{ path: './font1.woff2', weight: 'normal' },
{ path: './font2.woff2', weight: 'normal' },
{ path: './font3.woff2', weight: '400' },
{ path: './font3.woff2', weight: 'abc' },
],
},
],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isServer: true,
fs: { readFile: (path, cb) => cb(null, path) },
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid weight value in src array: \`abc\`.
Expected \`normal\`, \`bold\` or a number."
`)
})
test('Invalid variable weight in array', async () => {
await expect(
loader({
functionName: '',
data: [
{
src: [
{ path: './font1.woff2', weight: 'normal bold' },
{ path: './font2.woff2', weight: '400 bold' },
{ path: './font3.woff2', weight: 'normal 700' },
{ path: './font4.woff2', weight: '100 abc' },
],
},
],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isServer: true,
fs: { readFile: (path, cb) => cb(null, path) },
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid weight value in src array: \`100 abc\`.
Expected \`normal\`, \`bold\` or a number."
`)
})
}) })
}) })
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