-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathparseFontInfo.ts
87 lines (72 loc) · 2.41 KB
/
parseFontInfo.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
import { kebabCase } from "../utils";
import { FontInfo } from './fontListener';
import { VARIATION_MATCH, WEIGHTS, STYLES } from '../consts';
export const parseFontInfo = (fontFamilies: string[]) => {
const length = fontFamilies.length
const parsedFonts: FontInfo[] = []
for (let i = 0; i < length; i++) {
const elements = fontFamilies[i].split(":")
const fontFamily = elements[0].replace(/\+/g, " ")
let variations = [{ fontStyle: '', fontWeight: '' }]
if (elements.length >= 2) {
const fvds = parseVariations(elements[1])
if (fvds.length > 0) {
variations = fvds
}
}
for (let j = 0; j < variations.length; j += 1) {
parsedFonts.push({ fontName: fontFamily, ...variations[j] })
}
}
return parsedFonts
}
const generateFontVariationDescription = (variation: string) => {
const normalizedVariation = variation.toLowerCase()
const groups = VARIATION_MATCH.exec(normalizedVariation)
if (groups == null) {
return ""
}
const styleMatch = normalizeStyle(groups[1])
const weightMatch = normalizeWeight(groups[2])
return (
{
fontStyle: styleMatch,
fontWeight: weightMatch
}
)
}
export const normalizeStyle = (parsedStyle: string): string => {
if (!parsedStyle) {
return ""
}
return STYLES[parsedStyle]
}
export const normalizeWeight = (parsedWeight: string | number): string => {
if (!parsedWeight) {
return ""
}
return WEIGHTS[parsedWeight]
}
const parseVariations = (variations: string) => {
let finalVariations: Omit<FontInfo, 'fontName'>[] = []
if (!variations) {
return finalVariations
}
const providedVariations = variations.split(",")
const length = providedVariations.length
for (let i = 0; i < length; i++) {
let variation = providedVariations[i]
const fvd = generateFontVariationDescription(variation)
if (fvd) {
finalVariations.push(fvd)
}
}
return finalVariations
}
export const convertToFVD = ({fontName, fontStyle, fontWeight}: FontInfo) => {
const weightVal = normalizeWeight(fontWeight)
const styleVal = normalizeStyle(fontStyle)
const styleWeight = styleVal + weightVal
const fontNameVal = kebabCase(fontName)
return styleWeight ? [fontNameVal, styleWeight].join('-') : fontNameVal
}