/
packager-v1.js
94 lines (84 loc) · 2.95 KB
/
packager-v1.js
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
const _ = require(`lodash`)
const async = require(`async`)
const flatten = require(`flat`)
const fs = require(`fs-extra`)
const isAbsoluteUrl = require(`is-absolute-url`)
const { APIv1 } = require(`google-font-metadata`)
const download = require(`./download-file`)
const { fontFace } = require(`./templates`)
module.exports = function (id) {
const font = APIv1[id]
const fontDir = `packages/${font.id}`
// Generate filenames
const makeFontDownloadPath = (subset, weight, style, extension) => {
return `./${fontDir}/files/${font.id}-${subset}-${weight}-${style}.${extension}`
}
const makeFontFilePath = (subset, weight, style, extension) => {
return `./files/${font.id}-${subset}-${weight}-${style}.${extension}`
}
// Parse API and split into variant + link array pairs. [['weight.style.subset.url|local.extension','link to font or local name'],...]
const downloadURLPairs = _.toPairs(flatten(font.variants))
// Filter out local font links and only leave URLs for each pair
const links = downloadURLPairs
.filter(pair => isAbsoluteUrl(pair[1].toString()))
.filter(file => {
const extension = file[0].split(".")[4]
if (extension === "truetype" || extension === "opentype") {
return false
} else {
return true
}
})
.map(file => {
const types = file[0].split(".")
const dest = makeFontDownloadPath(types[2], types[0], types[1], types[4])
const url = file[1]
return {
url,
dest,
}
})
// Download all font files
async.map(links, (d, downloadDone) => {
const { url, dest } = d
download(url, dest, err => {
if (err) {
console.log("Error downloading", font.id, url, err)
}
downloadDone()
})
})
// Generate CSS
font.subsets.forEach(subset => {
const cssSubset = []
font.weights.forEach(weight => {
font.styles.forEach(style => {
// Some fonts may have variants 400, 400i, 700 but not 700i.
if (style in font.variants[weight]) {
const css = fontFace({
fontId: font.id,
fontName: font.family,
locals: font.variants[weight][style][subset].local,
style,
subset,
weight,
woff2Path: makeFontFilePath(subset, weight, style, "woff2"),
woffPath: makeFontFilePath(subset, weight, style, "woff"),
})
if (style === "normal") {
const cssPath = `${fontDir}/${subset}-${weight}.css`
fs.writeFileSync(cssPath, css)
// Should only push normal variants into subset
cssSubset.push(css)
} else {
// If italic or else, define specific style CSS file
const cssStylePath = `${fontDir}/${subset}-${weight}-${style}.css`
fs.writeFileSync(cssStylePath, css)
}
}
})
})
const cssSubsetPath = `${fontDir}/${subset}.css`
fs.writeFileSync(cssSubsetPath, cssSubset.join(""))
})
}