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'
type Display = 'auto' | 'block' | 'swap' | 'fallback' | 'optional'
type CssVariable = `--${string}`
type LocalFont = {
src: string
src:
| string
| Array<{
path: string
weight?: string
style?: string
}>
display?: Display
weight?: string
style?: string
......
......@@ -7,6 +7,50 @@ import { promisify } from 'util'
import { validateData } 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 ({
functionName,
data,
......@@ -17,60 +61,113 @@ const fetchFonts: FontLoader = async ({
const {
family,
src,
ext,
format,
display,
weight,
style,
fallback,
preload,
variable,
adjustFontFallback,
declarations,
} = validateData(functionName, data)
weight: defaultWeight,
style: defaultStyle,
} = validateData(functionName, data[0])
const resolved = await resolve(src)
const fileBuffer = await promisify(fs.readFile)(resolved)
const fontUrl = emitFontFile(fileBuffer, ext, preload)
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 fontUrl = emitFontFile(fileBuffer, ext, preload)
let fontMetadata: any
try {
fontMetadata = fontFromBuffer(fileBuffer)
} catch (e) {
console.error(`Failed to load font file: ${resolved}\n${e}`)
}
let fontMetadata: any
try {
fontMetadata = fontFromBuffer(fileBuffer)
} catch (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 = [
...(declarations
? declarations.map(({ prop, value }) => [prop, value])
: []),
['font-family', `'${fontMetadata?.familyName ?? family}'`],
['src', `url(${fontUrl}) format('${format}')`],
['font-display', display],
...(weight ?? defaultWeight
? [['font-weight', weight ?? defaultWeight]]
: []),
...(style ?? defaultStyle
? [['font-style', style ?? defaultStyle]]
: []),
]
const fontFaceProperties = [
...(declarations
? declarations.map(({ prop, value }) => [prop, value])
: []),
['font-family', `'${fontMetadata?.familyName ?? family}'`],
['src', `url(${fontUrl}) format('${format}')`],
['font-display', display],
...(weight ? [['font-weight', weight]] : []),
...(style ? [['font-style', style]] : []),
]
const css = `@font-face {
return {
css: `@font-face {
${fontFaceProperties
.map(([property, value]) => `${property}: ${value};`)
.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 {
css,
css: fontFiles.map(({ css }) => css).join('\n'),
fallbackFonts: fallback,
weight,
style,
weight: src.length === 1 ? src[0].weight : undefined,
style: src.length === 1 ? src[0].style : undefined,
variable,
adjustFontFallback: adjustFontFallbackMetrics,
}
......
......@@ -13,9 +13,13 @@ const extToFormat = {
type FontOptions = {
family: string
src: string
ext: string
format: string
src: Array<{
path: string
weight?: string
style?: string
ext: string
format: string
}>
display: string
weight?: string
style?: string
......@@ -25,7 +29,7 @@ type FontOptions = {
adjustFontFallback?: string | false
declarations?: Array<{ prop: string; value: string }>
}
export function validateData(functionName: string, data: any): FontOptions {
export function validateData(functionName: string, fontData: any): FontOptions {
if (functionName) {
throw new Error(`@next/font/local has no named exports`)
}
......@@ -39,7 +43,7 @@ export function validateData(functionName: string, data: any): FontOptions {
variable,
adjustFontFallback,
declarations,
} = data[0] || ({} as any)
} = fontData || ({} as any)
if (!allowedDisplayValues.includes(display)) {
throw new Error(
......@@ -53,12 +57,30 @@ export function validateData(functionName: string, data: any): FontOptions {
throw new Error('Missing required `src` property')
}
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(src)?.[1]
if (!ext) {
throw new Error(`Unexpected file \`${src}\``)
if (!Array.isArray(src)) {
src = [{ path: src, weight, style }]
} else {
if (src.length === 0) {
throw new Error('Unexpected empty `src` array.')
}
}
const family = /(.*\/)?(.+?)\.(woff|woff2|eot|ttf|otf)$/.exec(src)![2]
let family: string | undefined
src = src.map((fontFile: any) => {
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFile.path)?.[1]
if (!ext) {
throw new Error(`Unexpected file \`${fontFile.path}\``)
}
if (!family) {
family = /(.*\/)?(.+?)\.(woff|woff2|eot|ttf|otf)$/.exec(fontFile.path)![2]
}
return {
...fontFile,
ext,
format: extToFormat[ext as 'woff' | 'woff2' | 'eot' | 'ttf' | 'otf'],
}
})
if (Array.isArray(declarations)) {
declarations.forEach((declaration) => {
......@@ -77,10 +99,8 @@ export function validateData(functionName: string, data: any): FontOptions {
}
return {
family,
family: family!,
src,
ext,
format: extToFormat[ext as 'woff' | 'woff2' | 'eot' | 'ttf' | 'otf'],
display,
weight,
style,
......
......@@ -42,14 +42,8 @@ const postcssFontLoaderPlugn = ({
continue
}
const currentFamily = normalizeFamily(familyNode.value)
if (!fontFamily) {
fontFamily = currentFamily
} else if (fontFamily !== currentFamily) {
throw new Error(
`Font family mismatch, expected ${fontFamily} but got ${currentFamily}`
)
fontFamily = normalizeFamily(familyNode.value)
}
familyNode.value = formatFamily(fontFamily)
......
......@@ -13,6 +13,92 @@ const myFont2 = localFont({
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() {
return (
<>
......@@ -22,6 +108,15 @@ export default function WithFonts() {
<div id="second-local-font" className={myFont2.className}>
{JSON.stringify(myFont2)}
</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', () => {
)
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', () => {
......
......@@ -3,13 +3,13 @@ import loader from '@next/font/local/loader'
describe('@next/font/local', () => {
describe('generated CSS', () => {
test('Default CSS', async () => {
// @ts-expect-error
const { css } = await loader({
functionName: '',
data: [{ src: './my-font.woff2' }],
config: {},
emitFontFile: () => '/_next/static/media/my-font.woff2',
resolve: jest.fn(),
isServer: true,
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
......@@ -20,18 +20,19 @@ describe('@next/font/local', () => {
font-family: 'my-font';
src: url(/_next/static/media/my-font.woff2) format('woff2');
font-display: optional;
}"
}
"
`)
})
test('Weight and style', async () => {
// @ts-expect-error
const { css } = await loader({
functionName: '',
data: [{ src: './my-font.woff2', weight: '100 900', style: 'italic' }],
config: {},
emitFontFile: () => '/_next/static/media/my-font.woff2',
resolve: jest.fn(),
isServer: true,
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
......@@ -44,12 +45,12 @@ describe('@next/font/local', () => {
font-display: optional;
font-weight: 100 900;
font-style: italic;
}"
}
"
`)
})
test('Other properties', async () => {
// @ts-expect-error
const { css } = await loader({
functionName: '',
data: [
......@@ -64,6 +65,7 @@ describe('@next/font/local', () => {
config: {},
emitFontFile: () => '/_next/static/media/my-font.woff2',
resolve: jest.fn(),
isServer: true,
fs: {
readFile: (_, cb) => cb(null, 'fontdata'),
},
......@@ -76,7 +78,140 @@ describe('@next/font/local', () => {
font-family: 'my-font';
src: url(/_next/static/media/my-font.woff2) format('woff2');
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', () => {
describe('Errors', () => {
test('Not using default export', async () => {
await expect(
// @ts-expect-error
loader({
functionName: 'Named',
data: [],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isServer: true,
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
......@@ -100,13 +235,13 @@ describe('@next/font/local', () => {
test('Missing src', async () => {
await expect(
// @ts-expect-error
loader({
functionName: '',
data: [],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isServer: true,
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
......@@ -116,13 +251,13 @@ describe('@next/font/local', () => {
test('Invalid file extension', async () => {
await expect(
// @ts-expect-error
loader({
functionName: '',
data: [{ src: './font/font-file.abc' }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn().mockResolvedValue(''),
isServer: true,
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
......@@ -132,13 +267,13 @@ describe('@next/font/local', () => {
test('Invalid display value', async () => {
await expect(
// @ts-expect-error
loader({
functionName: '',
data: [{ src: './font-file.woff2', display: 'invalid' }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isServer: true,
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
......@@ -149,7 +284,6 @@ describe('@next/font/local', () => {
test('Invalid declaration', async () => {
await expect(
// @ts-expect-error
loader({
functionName: '',
data: [
......@@ -162,11 +296,82 @@ describe('@next/font/local', () => {
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isServer: true,
fs: {},
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"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