forked from vercel/next.js
/
loader.ts
176 lines (153 loc) · 5.02 KB
/
loader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// @ts-ignore
// eslint-disable-next-line import/no-extraneous-dependencies
import fontFromBuffer from '@next/font/dist/fontkit'
import type { AdjustFontFallback, FontLoader } from 'next/font'
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,
emitFontFile,
resolve,
fs,
}) => {
const {
family,
src,
display,
fallback,
preload,
variable,
adjustFontFallback,
declarations,
weight: defaultWeight,
style: defaultStyle,
} = validateData(functionName, data[0])
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}`)
}
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]]
: []),
]
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: fontFiles.map(({ css }) => css).join('\n'),
fallbackFonts: fallback,
weight: src.length === 1 ? src[0].weight : undefined,
style: src.length === 1 ? src[0].style : undefined,
variable,
adjustFontFallback: adjustFontFallbackMetrics,
}
}
export default fetchFonts