-
Notifications
You must be signed in to change notification settings - Fork 357
Expand file tree
/
Copy pathfont.ts
More file actions
569 lines (508 loc) · 15.1 KB
/
Copy pathfont.ts
File metadata and controls
569 lines (508 loc) · 15.1 KB
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/**
* This class handles everything related to fonts.
*/
import opentype from '@shuding/opentype.js'
import { Locale, locales, isValidLocale } from './language.js'
export type Weight = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
export type WeightName = 'normal' | 'bold'
export type FontWeight = Weight | WeightName
export type FontStyle = 'normal' | 'italic'
const SUFFIX_WHEN_LANG_NOT_SET = 'unknown'
export interface FontOptions {
data: Buffer | ArrayBuffer
name: string
weight?: Weight
style?: FontStyle
lang?: string
}
export type FontEngine = {
has: (s: string) => boolean
baseline: (s?: string, resolvedFont?: any) => number
height: (s?: string, resolvedFont?: any) => number
measure: (
s: string,
style: {
fontSize: number
letterSpacing: number
}
) => number
getSVG: (
s: string,
style: {
fontSize: number
top: number
left: number
letterSpacing: number
}
) => 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
}
const cachedParsedFont = new WeakMap<
Buffer | ArrayBuffer,
opentype.Font | null | undefined
>()
export default class FontLoader {
defaultFont: opentype.Font
fonts = new Map<string, [opentype.Font, Weight?, FontStyle?][]>()
cachedFontResolver = new Map<number, opentype.Font | undefined>()
constructor(fontOptions: FontOptions[]) {
this.addFonts(fontOptions)
}
// Get font by name and weight.
private get({
name,
weight,
style,
}: {
name: string
weight: Weight | WeightName
style: FontStyle
}) {
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
let font
if (cachedParsedFont.has(data)) {
font = cachedParsedFont.get(data)
} else {
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
}
cachedParsedFont.set(data, font)
}
// 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: number | string = 'normal',
{
fontFamily = 'sans-serif',
fontWeight = 400,
fontStyle = 'normal',
}: {
fontFamily?: string | string[]
fontWeight?: FontWeight
fontStyle?: FontStyle
},
locale: Locale | undefined
): FontEngine {
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.forEach((face) => {
const getNormal = this.get({
name: face,
weight: fontWeight,
style: fontStyle,
})
if (getNormal) {
fonts.push(getNormal)
return
}
const getUnknown = this.get({
name: face + '_unknown',
weight: fontWeight,
style: fontStyle,
})
if (getUnknown) {
fonts.push(getUnknown)
return
}
})
// 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 resolveFont = (word: string, fallback = true) => {
const _fonts = [
...fonts,
...additionalFonts,
...specifiedLangFonts,
...(fallback ? nonSpecifiedLangFonts : []),
]
if (typeof word === 'undefined') {
if (fallback) {
return _fonts[_fonts.length - 1]
}
return undefined
}
const code = word.charCodeAt(0)
if (this.cachedFontResolver.has(code))
return this.cachedFontResolver.get(code)
const font = _fonts.find((_font, index) => {
return (
!!_font.charToGlyphIndex(word) ||
(fallback && index === _fonts.length - 1)
)
})
if (font) {
this.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 height = (resolvedFont: opentype.Font, useOS2Table = false) => {
if ('string' === typeof lineHeight && 'normal' === lineHeight) {
const _lineGap =
(useOS2Table ? resolvedFont.tables?.os2?.sTypoLineGap : 0) || 0
return (
ascender(resolvedFont, useOS2Table) -
descender(resolvedFont, useOS2Table) +
(_lineGap / resolvedFont.unitsPerEm) * fontSize
)
} else if ('number' === typeof lineHeight) {
return fontSize * lineHeight
}
}
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)
) => {
const asc = ascender(resolvedFont)
const desc = descender(resolvedFont)
const contentHeight = asc - desc
return asc + (height(resolvedFont) - contentHeight) / 2
},
height: (
s?: string,
resolvedFont = typeof s === 'undefined' ? fonts[0] : resolveFont(s)
) => {
return height(resolvedFont)
},
measure: (
s: string,
style: {
fontSize: number
letterSpacing: number
}
) => {
return this.measure(resolveFont, s, style)
},
getSVG: (
s: string,
style: {
fontSize: number
top: number
left: number
letterSpacing: number
}
) => {
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 ''
}
const fullPath = new opentype.Path()
const options = {
letterSpacing: letterSpacing / fontSize,
}
const cachedPath = new WeakMap<
opentype.Glyph,
[number, number, opentype.Path]
>()
font.forEachGlyph(
content.replace(/\n/g, ''),
left,
top,
fontSize,
options,
function (glyph, gX, gY, gFontSize) {
let glyphPath: opentype.Path
if (!cachedPath.has(glyph)) {
glyphPath = glyph.getPath(gX, gY, gFontSize, options)
cachedPath.set(glyph, [gX, gY, glyphPath])
} else {
const [_x, _y, _glyphPath] = cachedPath.get(glyph)
glyphPath = new opentype.Path()
glyphPath.commands = _glyphPath.commands.map((command) => {
const movedCommand = { ...command }
for (let k in movedCommand) {
if (typeof movedCommand[k] === 'number') {
if (k === 'x' || k === 'x1' || k === 'x2') {
movedCommand[k] += gX - _x
}
if (k === 'y' || k === 'y1' || k === 'y2') {
movedCommand[k] += gY - _y
}
}
}
return movedCommand
})
}
fullPath.extend(glyphPath)
}
)
return fullPath.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)
}