aboutsummaryrefslogtreecommitdiff
path: root/material-symbols-plugin.js
blob: 48b1123ec88de79a0bb2bdb748d8efedae5335f0 (plain)
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
const fs = require("fs")
const path = require("path")
const crypto = require("crypto")
const axios = require("axios")
const { Compilation } = require("webpack")
const { generateAtlasViewsFromReferences, createDirectoriesForFile } = require("./utils.js")


class MaterialSymbolsDownloader {
	static validStyls = [ "outlined", "rounded", "sharp" ]
	static validWghts = [ 100, 200, 300, 400, 500, 600, 700 ]
	static validGrads = [ -25, 0, 200 ]
	static validFills = [ false, true ]
	static validOpszs = [ 20, 24, 40, 48 ]

	constructor(ref) {
		this.icon = ref.symbol
		this.styl = ref.style ?? "outlined"
		this.wght = ref.wght  ?? 400
		this.grad = ref.grad  ?? 0
		this.fill = ref.fill  ?? false
		this.opsz = ref.opsz  ?? 24
		this.validateProperties()
	}

	validateProperties() {
		// TODO validate icons
		if (!MaterialSymbolsDownloader.validStyls.includes(this.styl)) throw new Error(`Styl ${this.styl} is not valid, must be one of ${this.validStyls}`)
		if (!MaterialSymbolsDownloader.validWghts.includes(this.wght)) throw new Error(`Wght ${this.wght} is not valid, must be one of ${this.validWghts}`)
		if (!MaterialSymbolsDownloader.validGrads.includes(this.grad)) throw new Error(`Grad ${this.grad} is not valid, must be one of ${this.validGrads}`)
		if (!MaterialSymbolsDownloader.validFills.includes(this.fill)) throw new Error(`Fill ${this.fill} is not valid, must be one of ${this.validFills}`)
		if (!MaterialSymbolsDownloader.validOpszs.includes(this.opsz)) throw new Error(`Opsz ${this.opsz} is not valid, must be one of ${this.validOpszs}`)
	}

	get axes() {
		const wght = this.wght == 400 ? "" : `wght${this.wght}`
		const grad = this.grad == 0   ? "" : `grad${this.grad}`
		const fill = !this.fill       ? "" : "fill1"
		return wght + grad + fill || "default"
	}

	get svgDownloadUrl() {
		return `https://fonts.gstatic.com/s/i/short-term/release/materialsymbols${this.styl}/${this.icon}/${this.axes}/${this.opsz}px.svg`
	}

	async downloadSvg(cache) {
		const url = this.svgDownloadUrl
		const cached = await cache.getPromise(url, null)
		if (cached)
			return cached

		try {
			const res = await axios.get(url)
			const svg = res.data
			await cache.storePromise(url, null, svg)
			return svg
		} catch (err) {
			throw new Error(`Symbol ${this.icon} could not be downloaded. Error: ${err}`)
		}
	}
}


class MaterialSymbolsAtlasPlugin {
	constructor({ referenceFile, filename }) {
		this.referenceFile = path.resolve(referenceFile)
		this.filename = filename ?? "icons.svg"
	}

	readReferences() {
		const ext = path.extname(this.referenceFile)

		if (ext !== ".json")
			throw new Error(`Unsupported reference file extension: ${ext}. Only .json files are supported at this time`)

		const content = fs.readFileSync(this.referenceFile, "utf8")
		return JSON.parse(content)
	}

	async resolveRefs(refs, cache) {
		const root = path.dirname(this.referenceFile) // Relative to referenceFile

		for (const ref of refs) {
			if (ref.path) {
				// Local files
				const filePath = path.join(root, ref.path)
				if (!fs.existsSync(filePath))
					throw new Error(`SVG asset at ${filePath} does not exist`)
				ref.svg = fs.readFileSync(filePath, "utf8" )
			} else if (ref.symbol) {
				// Material symbol icon refs
				const symbolDl = new MaterialSymbolsDownloader(ref)
				ref.svg = await symbolDl.downloadSvg(cache)
			} else {
				throw new Error(`Ref does not provide a symbol name or path:\n${ref}`)
			}
		}
		return refs
	}

	apply(compiler) {
		compiler.hooks.thisCompilation.tap("MaterialSymbolsAtlasPlugin", (compilation) => {
			compilation.hooks.processAssets.tapPromise(
				{
					name: "MaterialSymbolsAtlasPlugin",
					stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
				},
				async () => {
					try {
						// Handle cache
						const cache = compilation.getCache("MaterialSymbolsAtlasPlugin")

						const content = this.readReferences()
						const cacheKey = crypto.createHash("sha256")
							.update(JSON.stringify(content))
							.digest("hex")

						const cached = await cache.getPromise(cacheKey, null)

						// Create asset if not existing
						let atlas = cached
						if (!cached) {
							const refs = content.refs
							const svgRefs = await this.resolveRefs(refs, cache)
							atlas = await generateAtlasViewsFromReferences(svgRefs)
							await cache.storePromise(cacheKey, null, atlas)
						}

						createDirectoriesForFile(this.filename)

						compilation.emitAsset(
							this.filename,
							new compiler.webpack.sources.RawSource(atlas)
						)
					} catch (err) {
						compilation.errors.push(err)
					}
				}
			)
		})

		compiler.hooks.afterCompile.tap("MaterialSymbolsAtlasPlugin", (compilation) => {
			// Watch the reference file for changes
			compilation.fileDependencies.add(this.referenceFile)
		})
	}
}

module.exports = MaterialSymbolsAtlasPlugin