forked from vercel/satori
-
Notifications
You must be signed in to change notification settings - Fork 0
/
font.ts
454 lines (407 loc) · 12.7 KB
/
font.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**
* This class handles everything related to fonts.
*/
import opentype from '@shuding/opentype.js'
import { Locale, locales, isValidLocale } from './language'
export type Weight = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
type WeightName = 'normal' | 'bold'
export type Style = 'normal' | 'italic'
const SUFFIX_WHEN_LANG_NOT_SET = 'unknown'
export interface FontOptions {
data: Buffer | ArrayBuffer
name: string
weight?: Weight
style?: Style
lang?: string
}
function compareFont(
weight,
style,
[matchedWeight, matchedStyle],
[nextWeight, nextStyle]
) {
if (matchedWeight !== nextWeight) {
// Put the defined weight first.
if (!matchedWeight) return 1
if (!nextWeight) return -1
// Exact match.
if (matchedWeight === weight) return -1
if (nextWeight === weight) return 1
// 400 and 500.
if (weight === 400 && matchedWeight === 500) return -1
if (weight === 500 && matchedWeight === 400) return -1
if (weight === 400 && nextWeight === 500) return 1
if (weight === 500 && nextWeight === 400) return 1
// Less than 400.
if (weight < 400) {
if (matchedWeight < weight && nextWeight < weight)
return nextWeight - matchedWeight
if (matchedWeight < weight) return -1
if (nextWeight < weight) return 1
return matchedWeight - nextWeight
}
// Greater than 500.
if (weight < matchedWeight && weight < nextWeight)
return matchedWeight - nextWeight
if (weight < matchedWeight) return -1
if (weight < nextWeight) return 1
return nextWeight - matchedWeight
}
if (matchedStyle !== nextStyle) {
// Exact match.
if (matchedStyle === style) return -1
if (nextStyle === style) return 1
}
return -1
}
export default class FontLoader {
defaultFont: opentype.Font
fonts = new Map<string, [opentype.Font, Weight?, Style?][]>()
constructor(fontOptions: FontOptions[]) {
this.addFonts(fontOptions)
}
// Get font by name and weight.
private get({
name,
weight,
style,
}: {
name: string
weight: Weight | WeightName
style: Style
}) {
if (!this.fonts.has(name)) {
return null
}
if (weight === 'normal') weight = 400
if (weight === 'bold') weight = 700
if (typeof weight === 'string')
weight = Number.parseInt(weight, 10) as Weight
const fonts = [...this.fonts.get(name)]
let matchedFont = fonts[0]
// Fallback to the closest weight and style according to the strategy here:
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#fallback_weights
for (let i = 1; i < fonts.length; i++) {
const [, weight1, style1] = matchedFont
const [, weight2, style2] = fonts[i]
if (
compareFont(weight, style, [weight1, style1], [weight2, style2]) > 0
) {
matchedFont = fonts[i]
}
}
return matchedFont[0]
}
public addFonts(fontOptions: FontOptions[]) {
for (const fontOption of fontOptions) {
const { name, data, lang } = fontOption
if (lang && !isValidLocale(lang)) {
throw new Error(
`Invalid value for props \`lang\`: "${lang}". The value must be one of the following: ${locales.join(
', '
)}.`
)
}
const _lang = lang ?? SUFFIX_WHEN_LANG_NOT_SET
const font = opentype.parse(
// Buffer to ArrayBuffer.
'buffer' in data
? data.buffer.slice(
data.byteOffset,
data.byteOffset + data.byteLength
)
: data,
// @ts-ignore
{ lowMemory: true }
)
// Modify the `charToGlyphIndex` method, so we can know which char is
// being mapped to which glyph.
const originalCharToGlyphIndex = font.charToGlyphIndex
font.charToGlyphIndex = (char) => {
const index = originalCharToGlyphIndex.call(font, char)
if (index === 0) {
// The current requested char is missing a glyph.
if ((font as any)._trackBrokenChars) {
;(font as any)._trackBrokenChars.push(char)
}
}
return index
}
// We use the first font as the default font fallback.
if (!this.defaultFont) this.defaultFont = font
const _name = `${name.toLowerCase()}_${_lang}`
if (!this.fonts.has(_name)) {
this.fonts.set(_name, [])
}
this.fonts.get(_name).push([font, fontOption.weight, fontOption.style])
}
}
public getEngine(
fontSize = 16,
lineHeight = 1.2,
{
fontFamily,
fontWeight = 400,
fontStyle = 'normal',
}: {
fontFamily: string | string[]
fontWeight?: Weight | WeightName
fontStyle?: Style
},
locale: Locale | undefined
) {
if (!this.fonts.size) {
throw new Error(
'No fonts are loaded. At least one font is required to calculate the layout.'
)
}
fontFamily = (Array.isArray(fontFamily) ? fontFamily : [fontFamily]).map(
(name) => name.toLowerCase()
)
const fonts = fontFamily
.map((face) =>
this.get({
name: face,
weight: fontWeight,
style: fontStyle,
})
)
.filter(Boolean)
// Add additional fonts as the fallback.
const keys = Array.from(this.fonts.keys())
const specifiedLangFonts = []
const nonSpecifiedLangFonts = []
const additionalFonts = []
for (const name of keys) {
if (fontFamily.includes(name)) continue
if (locale) {
const lang = getLangFromFontName(name)
if (lang) {
if (lang === locale) {
specifiedLangFonts.push(
this.get({
name,
weight: fontWeight,
style: fontStyle,
})
)
} else {
nonSpecifiedLangFonts.push(
this.get({
name,
weight: fontWeight,
style: fontStyle,
})
)
}
} else {
additionalFonts.push(
this.get({
name,
weight: fontWeight,
style: fontStyle,
})
)
}
} else {
additionalFonts.push(
this.get({
name,
weight: fontWeight,
style: fontStyle,
})
)
}
}
const cachedFontResolver = new Map<number, opentype.Font | undefined>()
const resolveFont = (word: string, fallback = true) => {
const code = word.charCodeAt(0)
if (cachedFontResolver.has(code)) return cachedFontResolver.get(code)
const _fonts = [
...fonts,
...additionalFonts,
...specifiedLangFonts,
...(fallback ? nonSpecifiedLangFonts : []),
]
const font = _fonts.find((_font, index) => {
return (
!!_font.charToGlyphIndex(word) ||
(fallback && index === _fonts.length - 1)
)
})
if (font) {
cachedFontResolver.set(code, font)
}
return font
}
const ascender = (resolvedFont: opentype.Font, useOS2Table = false) => {
const _ascender =
(useOS2Table ? resolvedFont.tables?.os2?.sTypoAscender : 0) ||
resolvedFont.ascender
return (_ascender / resolvedFont.unitsPerEm) * fontSize
}
const descender = (resolvedFont: opentype.Font, useOS2Table = false) => {
const _descender =
(useOS2Table ? resolvedFont.tables?.os2?.sTypoDescender : 0) ||
resolvedFont.descender
return (_descender / resolvedFont.unitsPerEm) * fontSize
}
const resolve = (s: string) => {
return resolveFont(s, false)
}
const engine = {
has: (s: string) => {
if (s === '\n') return true
const font = resolve(s)
if (!font) return false
;(font as any)._trackBrokenChars = []
font.stringToGlyphs(s)
if (!(font as any)._trackBrokenChars.length) return true
;(font as any)._trackBrokenChars = undefined
return false
},
baseline: (
s?: string,
resolvedFont = typeof s === 'undefined' ? fonts[0] : resolveFont(s)
) => {
// https://www.w3.org/TR/css-inline-3/#css-metrics
// https://www.w3.org/TR/CSS2/visudet.html#leading
// Note. It is recommended that implementations that use OpenType or
// TrueType fonts use the metrics "sTypoAscender" and "sTypoDescender"
// from the font's OS/2 table for A and D (after scaling to the current
// element's font size). In the absence of these metrics, the "Ascent"
// and "Descent" metrics from the HHEA table should be used.
const A = ascender(resolvedFont, true)
const D = descender(resolvedFont, true)
const glyphHeight = engine.height(s, resolvedFont)
const { yMax, yMin } = resolvedFont.tables.head
const sGlyphHeight = A - D
const baselineOffset = (yMax / (yMax - yMin) - 1) * sGlyphHeight
return glyphHeight * ((1.2 / lineHeight + 1) / 2) + baselineOffset
},
height: (
s?: string,
resolvedFont = typeof s === 'undefined' ? fonts[0] : resolveFont(s)
) => {
return (
(ascender(resolvedFont) - descender(resolvedFont)) *
(lineHeight / 1.2)
)
},
measure: (s: string, style: any) => {
return this.measure(resolveFont, s, style)
},
getSVG: (s: string, style: any) => {
return this.getSVG(resolveFont, s, style)
},
}
return engine
}
private patchFontFallbackResolver(
font: opentype.Font,
resolveFont: (word: string, fallback?: boolean) => opentype.Font
) {
const brokenChars = []
;(font as any)._trackBrokenChars = brokenChars
const originalStringToGlyphs = font.stringToGlyphs
font.stringToGlyphs = (s: string, ...args: any) => {
const glyphs = originalStringToGlyphs.call(font, s, ...args)
for (let i = 0; i < glyphs.length; i++) {
// Hitting an undefined glyph. We have to try to resolve it from other
// fonts.
// @TODO: This affects the kerning resolution but should be fine for now.
if (glyphs[i].unicode === undefined) {
const char = brokenChars.shift()
const anotherFont = resolveFont(char)
if (anotherFont !== font) {
const glyph = anotherFont.charToGlyph(char)
// Scale the glyph to match the current units per em.
const scale = font.unitsPerEm / anotherFont.unitsPerEm
const p = new opentype.Path()
p.unitsPerEm = font.unitsPerEm
p.commands = glyph.path.commands.map((command) => {
const scaledCommand = { ...command }
for (let k in scaledCommand) {
if (typeof scaledCommand[k] === 'number') {
scaledCommand[k] *= scale
}
}
return scaledCommand
})
const g = new opentype.Glyph({
...glyph,
advanceWidth: glyph.advanceWidth * scale,
xMin: glyph.xMin * scale,
xMax: glyph.xMax * scale,
yMin: glyph.yMin * scale,
yMax: glyph.yMax * scale,
path: p,
})
glyphs[i] = g
}
}
}
return glyphs
}
return () => {
font.stringToGlyphs = originalStringToGlyphs
;(font as any)._trackBrokenChars = undefined
}
}
private measure(
resolveFont: (word: string, fallback?: boolean) => opentype.Font,
content: string,
{
fontSize,
letterSpacing = 0,
}: {
fontSize: number
letterSpacing: number
}
) {
const font = resolveFont(content)
const unpatch = this.patchFontFallbackResolver(font, resolveFont)
try {
return font.getAdvanceWidth(content, fontSize, {
letterSpacing: letterSpacing / fontSize,
})
} finally {
unpatch()
}
}
private getSVG(
resolveFont: (word: string, fallback?: boolean) => opentype.Font,
content: string,
{
fontSize,
top,
left,
letterSpacing = 0,
}: {
fontSize: number
top: number
left: number
letterSpacing: number
}
) {
const font = resolveFont(content)
const unpatch = this.patchFontFallbackResolver(font, resolveFont)
try {
if (fontSize === 0) {
return ''
}
return font
.getPath(content.replace(/\n/g, ''), left, top, fontSize, {
letterSpacing: letterSpacing / fontSize,
})
.toPathData(1)
} finally {
unpatch()
}
}
}
function getLangFromFontName(name: string): Locale | undefined {
const arr = name.split('_')
const lang = arr[arr.length - 1]
return lang === SUFFIX_WHEN_LANG_NOT_SET ? undefined : (lang as Locale)
}