-
Notifications
You must be signed in to change notification settings - Fork 4
/
fontHelper.ts
43 lines (41 loc) · 1.59 KB
/
fontHelper.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
import fontkit from 'fontkit';
import communicator from 'implementations/communicator';
import { FontDescriptor, FontHelper } from 'interfaces/IFont';
export default {
findFont(fontDescriptor: FontDescriptor): FontDescriptor {
return communicator.sendSync('FIND_FONT', fontDescriptor);
},
findFonts(fontDescriptor: FontDescriptor): FontDescriptor[] {
return communicator.sendSync('FIND_FONTS', fontDescriptor);
},
getAvailableFonts() {
return communicator.sendSync('GET_AVAILABLE_FONTS');
},
substituteFont(postscriptName: string, text: string) {
return communicator.sendSync('SUBSTITUTE_FONT', postscriptName, text);
},
getFontName(font: FontDescriptor): string {
let fontName = font.family;
try {
let fontInfo = fontkit.openSync(font.path);
if (fontInfo.fonts && fontInfo.fonts[0]) {
fontInfo = fontInfo.fonts.find((f) => {
if (f.familyName === font.family) return true;
if (f.name.records.fontFamily[navigator.language] === font.family) return true;
return false;
}) || fontInfo.fonts[0];
}
if (fontInfo) {
const firstNotEn = Object.keys(fontInfo.name.records.fontFamily).find((key) => key !== 'en');
fontName = (fontInfo.name.records.fontFamily[navigator.language]
|| fontInfo.name.records.fontFamily[firstNotEn]
|| fontInfo.name.records.fontFamily.en
|| fontName);
}
} catch (err) {
// eslint-disable-next-line no-console
console.warn(`Error when get font name of ${font.family}:`, err);
}
return fontName;
},
} as FontHelper;