-
Notifications
You must be signed in to change notification settings - Fork 667
/
Copy pathfont.ts
471 lines (414 loc) · 14.8 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import { defined } from './util';
export interface FontInfo {
/** CSS font-family, e.g., 'Arial', 'Helvetica Neue, Arial, sans-serif', 'Times, serif' */
family?: string;
/**
* CSS font-size (e.g., '10pt', '12px').
* For backwards compatibility with 3.0.9, plain numbers are assumed to be specified in 'pt'.
*/
size?: number | string;
/** `bold` or a number (e.g., 900) as inspired by CSS font-weight. */
weight?: string | number;
/** `italic` as inspired by CSS font-style. */
style?: string;
}
export type FontModule = { data: FontData; metrics: FontMetrics };
export interface FontData {
glyphs: Record<string, FontGlyph>;
fontFamily?: string;
resolution: number;
generatedOn?: string;
}
/** Specified in the `xxx_metrics.ts` files. */
// eslint-disable-next-line
export interface FontMetrics extends Record<string, any> {
name: string;
smufl: boolean;
stave?: Record<string, number>;
accidental?: Record<string, number>;
// eslint-disable-next-line
clef?: Record<string, any>;
pedalMarking?: Record<string, Record<string, number>>;
digits?: Record<string, number>;
// Not specified in gonville_metrics.ts.
articulation?: Record<string, Record<string, number>>;
tremolo?: Record<string, Record<string, number>>;
// Not specified in bravura_metrics.ts or gonville_metrics.ts.
noteHead?: Record<string, Record<string, number>>;
// eslint-disable-next-line
glyphs: Record<string, Record<string, any>>;
}
export interface FontGlyph {
x_min: number;
x_max: number;
y_min?: number;
y_max?: number;
ha: number;
leftSideBearing?: number;
advanceWidth?: number;
// The o (outline) field is optional, because robotoslab_glyphs.ts & petalumascript_glyphs.ts
// do not include glyph outlines. We rely on *.woff files to provide the glyph outlines.
o?: string;
cached_outline?: number[];
}
export enum FontWeight {
NORMAL = 'normal',
BOLD = 'bold',
}
export enum FontStyle {
NORMAL = 'normal',
ITALIC = 'italic',
}
// Internal <span></span> element for parsing CSS font shorthand strings.
let fontParser: HTMLSpanElement;
const Fonts: Record<string, Font> = {};
export class Font {
//////////////////////////////////////////////////////////////////////////////////////////////////
// STATIC MEMBERS
/** Default sans-serif font family. */
static SANS_SERIF: string = 'Arial, sans-serif';
/** Default serif font family. */
static SERIF: string = 'Times New Roman, serif';
/** Default font size in `pt`. */
static SIZE: number = 10;
// CSS Font Sizes: 36pt == 48px == 3em == 300% == 0.5in
/** Given a length (for units: pt, px, em, %, in, mm, cm) what is the scale factor to convert it to px? */
static scaleToPxFrom: Record<string, number> = {
pt: 4 / 3,
px: 1,
em: 16,
'%': 4 / 25,
in: 96,
mm: 96 / 25.4,
cm: 96 / 2.54,
};
/**
* @param fontSize a font size to convert. Can be specified as a CSS length string (e.g., '16pt', '1em')
* or as a number (the unit is assumed to be 'pt'). See `Font.scaleToPxFrom` for the supported
* units (e.g., pt, em, %).
* @returns the number of pixels that is equivalent to `fontSize`
*/
static convertSizeToPixelValue(fontSize: string | number = Font.SIZE): number {
if (typeof fontSize === 'number') {
// Assume the numeric fontSize is specified in pt.
return fontSize * Font.scaleToPxFrom.pt;
} else {
const value = parseFloat(fontSize);
if (isNaN(value)) {
return 0;
}
const unit = fontSize.replace(/[\d.\s]/g, '').toLowerCase(); // Extract the unit by removing all numbers, dots, spaces.
const conversionFactor = Font.scaleToPxFrom[unit] ?? 1;
return value * conversionFactor;
}
}
/**
* @param fontSize a font size to convert. Can be specified as a CSS length string (e.g., '16pt', '1em')
* or as a number (the unit is assumed to be 'pt'). See `Font.scaleToPxFrom` for the supported
* units (e.g., pt, em, %).
* @returns the number of points that is equivalent to `fontSize`
*/
static convertSizeToPointValue(fontSize: string | number = Font.SIZE): number {
if (typeof fontSize === 'number') {
// Assume the numeric fontSize is specified in pt.
return fontSize;
} else {
const value = parseFloat(fontSize);
if (isNaN(value)) {
return 0;
}
const unit = fontSize.replace(/[\d.\s]/g, '').toLowerCase(); // Extract the unit by removing all numbers, dots, spaces.
const conversionFactor = (Font.scaleToPxFrom[unit] ?? 1) / Font.scaleToPxFrom.pt;
return value * conversionFactor;
}
}
/**
* @param f
* @param size
* @param weight
* @param style
* @returns the `size` field will include the units (e.g., '12pt', '16px').
*/
static validate(
f?: string | FontInfo,
size?: string | number,
weight?: string | number,
style?: string
): Required<FontInfo> {
// If f is a string but all other arguments are undefined, we assume that
// f is CSS font shorthand (e.g., 'italic bold 10pt Arial').
if (typeof f === 'string' && size === undefined && weight === undefined && style === undefined) {
return Font.fromCSSString(f);
}
let family: string | undefined;
if (typeof f === 'object') {
// f is a FontInfo object, so we extract its fields.
family = f.family;
size = f.size;
weight = f.weight;
style = f.style;
} else {
// f is a string representing the font family name or undefined.
family = f;
}
family = family ?? Font.SANS_SERIF;
size = size ?? Font.SIZE + 'pt';
weight = weight ?? FontWeight.NORMAL;
style = style ?? FontStyle.NORMAL;
if (weight === '') {
weight = FontWeight.NORMAL;
}
if (style === '') {
style = FontStyle.NORMAL;
}
// If size is a number, we assume the unit is `pt`.
if (typeof size === 'number') {
size = `${size}pt`;
}
// If weight is a number (e.g., 900), turn it into a string representation of that number.
if (typeof weight === 'number') {
weight = weight.toString();
}
// At this point, `family`, `size`, `weight`, and `style` are all strings.
return { family, size, weight, style };
}
/**
* @param cssFontShorthand a string formatted as CSS font shorthand (e.g., 'italic bold 15pt Arial').
*/
static fromCSSString(cssFontShorthand: string): Required<FontInfo> {
// Let the browser parse this string for us.
// First, create a span element.
// Then, set its style.font and extract it back out.
if (!fontParser) {
fontParser = document.createElement('span');
}
fontParser.style.font = cssFontShorthand;
const { fontFamily, fontSize, fontWeight, fontStyle } = fontParser.style;
return { family: fontFamily, size: fontSize, weight: fontWeight, style: fontStyle };
}
/**
* @returns a CSS font shorthand string of the form `italic bold 16pt Arial`.
*/
static toCSSString(fontInfo?: FontInfo): string {
if (!fontInfo) {
return '';
}
let style: string;
const st = fontInfo.style;
if (st === FontStyle.NORMAL || st === '' || st === undefined) {
style = ''; // no space! Omit the style section.
} else {
style = st.trim() + ' ';
}
let weight: string;
const wt = fontInfo.weight;
if (wt === FontWeight.NORMAL || wt === '' || wt === undefined) {
weight = ''; // no space! Omit the weight section.
} else if (typeof wt === 'number') {
weight = wt + ' ';
} else {
weight = wt.trim() + ' ';
}
let size: string;
const sz = fontInfo.size;
if (sz === undefined) {
size = Font.SIZE + 'pt ';
} else if (typeof sz === 'number') {
size = sz + 'pt ';
} else {
// size is already a string.
size = sz.trim() + ' ';
}
const family: string = fontInfo.family ?? Font.SANS_SERIF;
return `${style}${weight}${size}${family}`;
}
/**
* @param fontSize a number representing a font size, or a string font size with units.
* @param scaleFactor multiply the size by this factor.
* @returns size * scaleFactor (e.g., 16pt * 3 = 48pt, 8px * 0.5 = 4px, 24 * 2 = 48).
* If the fontSize argument was a number, the return value will be a number.
* If the fontSize argument was a string, the return value will be a string.
*/
static scaleSize<T extends number | string>(fontSize: T, scaleFactor: number): T {
if (typeof fontSize === 'number') {
return (fontSize * scaleFactor) as T;
} else {
const value = parseFloat(fontSize);
const unit = fontSize.replace(/[\d.\s]/g, ''); // Remove all numbers, dots, spaces.
return `${value * scaleFactor}${unit}` as T;
}
}
/**
* @param weight a string (e.g., 'bold') or a number (e.g., 600 / semi-bold in the OpenType spec).
* @returns true if the font weight indicates bold.
*/
static isBold(weight?: string | number): boolean {
if (!weight) {
return false;
} else if (typeof weight === 'number') {
return weight >= 600;
} else {
// a string can be 'bold' or '700'
const parsedWeight = parseInt(weight, 10);
if (isNaN(parsedWeight)) {
return weight.toLowerCase() === 'bold';
} else {
return parsedWeight >= 600;
}
}
}
/**
* @param style
* @returns true if the font style indicates 'italic'.
*/
static isItalic(style?: string): boolean {
if (!style) {
return false;
} else {
return style.toLowerCase() === FontStyle.ITALIC;
}
}
/**
* Customize this field to specify a different CDN for delivering web fonts.
* Alternative: https://cdn.jsdelivr.net/npm/vexflow-fonts@1.0.3/
* Or you can use your own host.
*/
static WEB_FONT_HOST = 'https://unpkg.com/vexflow-fonts@1.0.3/';
/**
* These font files will be loaded from the CDN specified by `Font.WEB_FONT_HOST` when
* `await Font.loadWebFonts()` is called. Customize this field to specify a different
* set of fonts to load. See: `Font.loadWebFonts()`.
*/
static WEB_FONT_FILES: Record<string /* fontName */, string /* fontPath */> = {
'Roboto Slab': 'robotoslab/RobotoSlab-Medium_2.001.woff',
PetalumaScript: 'petaluma/PetalumaScript_1.10_FS.woff',
};
/**
* @param fontName
* @param woffURL The absolute or relative URL to the woff file.
* @param includeWoff2 If true, we assume that a woff2 file is in
* the same folder as the woff file, and will append a `2` to the url.
*/
// Support distributions of the typescript compiler that do not yet include the FontFace API declarations.
// eslint-disable-next-line
// @ts-ignore
static async loadWebFont(fontName: string, woffURL: string, includeWoff2: boolean = true): Promise<FontFace> {
const woff2URL = includeWoff2 ? `url(${woffURL}2) format('woff2'), ` : '';
const woff1URL = `url(${woffURL}) format('woff')`;
const woffURLs = woff2URL + woff1URL;
// eslint-disable-next-line
// @ts-ignore
const fontFace = new FontFace(fontName, woffURLs);
await fontFace.load();
// eslint-disable-next-line
// @ts-ignore
document.fonts.add(fontFace);
return fontFace;
}
/**
* Load the web fonts that are used by ChordSymbol. For example, `flow.html` calls:
* `await Vex.Flow.Font.loadWebFonts();`
* Alternatively, you may load web fonts with a stylesheet link (e.g., from Google Fonts),
* and a @font-face { font-family: ... } rule in your CSS.
* If you do not load either of these fonts, ChordSymbol will fall back to Times or Arial,
* depending on the current music engraving font.
*
* You can customize `Font.WEB_FONT_HOST` and `Font.WEB_FONT_FILES` to load different fonts
* for your app.
*/
static async loadWebFonts(): Promise<void> {
const host = Font.WEB_FONT_HOST;
const files = Font.WEB_FONT_FILES;
for (const fontName in files) {
const fontPath = files[fontName];
Font.loadWebFont(fontName, host + fontPath);
}
}
/**
* @param fontName
* @param data optionally set the Font object's `.data` property.
* This is usually done when setting up a font for the first time.
* @param metrics optionally set the Font object's `.metrics` property.
* This is usually done when setting up a font for the first time.
* @returns a Font object with the given `fontName`.
* Reuse an existing Font object if a matching one is found.
*/
static load(fontName: string, data?: FontData, metrics?: FontMetrics): Font {
let font = Fonts[fontName];
if (!font) {
font = new Font(fontName);
Fonts[fontName] = font;
}
if (data) {
font.setData(data);
}
if (metrics) {
font.setMetrics(metrics);
}
return font;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// INSTANCE MEMBERS
protected name: string;
protected data?: FontData;
protected metrics?: FontMetrics;
/**
* Use `Font.load(fontName)` to get a Font object.
* Do not call this constructor directly.
*/
private constructor(fontName: string) {
this.name = fontName;
}
getName(): string {
return this.name;
}
getData(): FontData {
return defined(this.data, 'FontError', 'Missing font data');
}
getMetrics(): FontMetrics {
return defined(this.metrics, 'FontError', 'Missing metrics');
}
setData(data: FontData): void {
this.data = data;
}
setMetrics(metrics: FontMetrics): void {
this.metrics = metrics;
}
hasData(): boolean {
return this.data !== undefined;
}
getResolution(): number {
return this.getData().resolution;
}
getGlyphs(): Record<string, FontGlyph> {
return this.getData().glyphs;
}
/**
* Use the provided key to look up a value in this font's metrics file (e.g., bravura_metrics.ts, petaluma_metrics.ts).
* @param key is a string separated by periods (e.g., stave.endPaddingMax, clef.lineCount.'5'.shiftY).
* @param defaultValue is returned if the lookup fails.
* @returns the retrieved value (or `defaultValue` if the lookup fails).
*/
// eslint-disable-next-line
lookupMetric(key: string, defaultValue?: Record<string, any> | number): any {
const keyParts = key.split('.');
// Start with the top level font metrics object, and keep looking deeper into the object (via each part of the period-delimited key).
let currObj = this.getMetrics();
for (let i = 0; i < keyParts.length; i++) {
const keyPart = keyParts[i];
const value = currObj[keyPart];
if (value === undefined) {
// If the key lookup fails, we fall back to the defaultValue.
return defaultValue;
}
// The most recent lookup succeeded, so we drill deeper into the object.
currObj = value;
}
// After checking every part of the key (i.e., the loop completed), return the most recently retrieved value.
return currObj;
}
/** For debugging. */
toString(): string {
return '[' + this.name + ' Font]';
}
}