-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathparse.ts
More file actions
180 lines (159 loc) · 5.63 KB
/
parse.ts
File metadata and controls
180 lines (159 loc) · 5.63 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
import type { Declaration } from 'css-tree'
import type { FontFaceData, LocalFontSource, RemoteFontSource } from '../types'
import { findAll, parse } from 'css-tree'
const extractableKeyMap: Record<string, keyof FontFaceData> = {
'src': 'src',
'font-display': 'display',
'font-weight': 'weight',
'font-stretch': 'stretch',
'font-style': 'style',
'font-feature-settings': 'featureSettings',
'font-variation-settings': 'variationSettings',
'unicode-range': 'unicodeRange',
}
const formatMap: Record<string, string> = {
woff2: 'woff2',
woff: 'woff',
otf: 'opentype',
ttf: 'truetype',
eot: 'embedded-opentype',
svg: 'svg',
}
const formatPriorityList = Object.values(formatMap)
export function extractFontFaceData(css: string, family?: string): FontFaceData[] {
const fontFaces: FontFaceData[] = []
for (const node of findAll(parse(css), node => node.type === 'Atrule' && node.name === 'font-face')) {
/* v8 ignore next 3 */
if (node.type !== 'Atrule' || node.name !== 'font-face') {
continue
}
if (family) {
const isCorrectFontFace = node.block?.children.some((child) => {
if (child.type !== 'Declaration' || child.property !== 'font-family') {
return false
}
const value = extractCSSValue(child) as string | string[]
const slug = family.toLowerCase()
if (typeof value === 'string' && value.toLowerCase() === slug) {
return true
}
if (Array.isArray(value) && value.length > 0 && value.some(v => v.toLowerCase() === slug)) {
return true
}
return false
})
// Don't extract font face data from this `@font-face` rule if it doesn't match the specified family
if (!isCorrectFontFace) {
continue
}
}
const data: Partial<FontFaceData> = {}
for (const child of node.block?.children || []) {
if (child.type === 'Declaration' && child.property in extractableKeyMap) {
const value = extractCSSValue(child) as any
data[extractableKeyMap[child.property]!] = ['src', 'unicode-range'].includes(child.property) && !Array.isArray(value) ? [value] : value
}
}
if (!data.src) {
continue
}
fontFaces.push(data as FontFaceData)
}
return mergeFontSources(fontFaces)
}
const RE = /^(?<quote>['"])(.*)\k<quote>$/
function processRawValue(value: string) {
return value.split(',').map(v => v.trim().replace(RE, '$2'))
}
function extractCSSValue(node: Declaration) {
if (node.value.type === 'Raw') {
return processRawValue(node.value.value)
}
const values = [] as Array<string | number | RemoteFontSource | LocalFontSource>
let buffer = ''
for (const child of node.value.children) {
if (child.type === 'Function') {
if (child.name === 'local' && child.children.first?.type === 'String') {
values.push({ name: child.children.first.value })
}
if (child.name === 'format') {
if (child.children.first?.type === 'String') {
(values.at(-1) as RemoteFontSource).format = child.children.first.value
}
else if (child.children.first?.type === 'Identifier') {
(values.at(-1) as RemoteFontSource).format = child.children.first.name
}
}
if (child.name === 'tech') {
if (child.children.first?.type === 'String') {
(values.at(-1) as RemoteFontSource).tech = child.children.first.value
}
else if (child.children.first?.type === 'Identifier') {
(values.at(-1) as RemoteFontSource).tech = child.children.first.name
}
}
}
if (child.type === 'Url') {
values.push({ url: child.value })
}
if (child.type === 'Identifier') {
buffer = buffer ? `${buffer} ${child.name}` : child.name
}
if (child.type === 'String') {
values.push(child.value)
}
if (child.type === 'Dimension') {
const dimensionValue = child.value + child.unit
buffer = buffer ? `${buffer} ${dimensionValue}` : dimensionValue
}
if (child.type === 'Operator' && child.value === ',' && buffer) {
values.push(buffer)
buffer = ''
}
if (child.type === 'UnicodeRange') {
values.push(child.value)
}
if (child.type === 'Number') {
values.push(Number(child.value))
}
if (child.type === 'Percentage') {
const percentageValue = `${child.value}%`
buffer = buffer ? `${buffer} ${percentageValue}` : percentageValue
}
}
if (buffer) {
values.push(buffer)
}
if (values.length === 1) {
return values[0]
}
return values
}
function mergeFontSources(data: FontFaceData[]) {
const mergedData: FontFaceData[] = []
for (const face of data) {
const keys = Object.keys(face).filter(k => k !== 'src') as Array<keyof typeof face>
const existing = mergedData.find(f => (Object.keys(f).length === keys.length + 1) && keys.every(key => f[key]?.toString() === face[key]?.toString()))
if (existing) {
for (const s of face.src) {
// don't add duplicate sources
if (existing.src.every(src => 'url' in src ? !('url' in s) || s.url !== src.url : !('name' in s) || s.name !== src.name)) {
existing.src.push(s)
}
}
}
else {
mergedData.push(face)
}
}
// Sort font sources by priority
for (const face of mergedData) {
face.src.sort((a, b) => {
// Prioritise local fonts (with 'name' property) over remote fonts, and then formats by formatPriorityList
const aIndex = 'format' in a ? formatPriorityList.indexOf(a.format || 'woff2') : -2
const bIndex = 'format' in b ? formatPriorityList.indexOf(b.format || 'woff2') : -2
return aIndex - bIndex
})
}
return mergedData
}