Merged in feat/svg-instead-of-fonts (pull request #3411)
feat(SW-3695): use svg icons instead of font icons * feat(icons): use svg instead of font icons * feat(icons): use webpack/svgr for inlined svgs. Now support for isFilled again * Merge master * Remove old font icon Approved-by: Joakim Jäderberg
This commit is contained in:
@@ -1,24 +1,9 @@
|
||||
import crypto from "node:crypto"
|
||||
import { createWriteStream } from "node:fs"
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises"
|
||||
import { join, resolve } from "node:path"
|
||||
import { Readable } from "node:stream"
|
||||
import { pipeline } from "node:stream/promises"
|
||||
import { writeFile } from "node:fs/promises"
|
||||
import { resolve } from "node:path"
|
||||
import { existsSync } from "node:fs"
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = resolve(__filename, "..")
|
||||
|
||||
// Defines where the font lives
|
||||
const FONT_DIR = resolve(__dirname, "../shared/fonts/material-symbols")
|
||||
|
||||
// Defines the settings for the font
|
||||
const FONT_BASE_URL = `https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0..1,0`
|
||||
|
||||
// Defines the subset of icons for the font
|
||||
const icons = [
|
||||
// Your full list of Material Symbol icon names
|
||||
const ICONS = [
|
||||
"accessibility",
|
||||
"accessible",
|
||||
"acute",
|
||||
@@ -59,7 +44,7 @@ const icons = [
|
||||
"camera",
|
||||
"cancel",
|
||||
"chair",
|
||||
"charging_station",
|
||||
"mobile_charge",
|
||||
"check_box",
|
||||
"check_circle",
|
||||
"check",
|
||||
@@ -84,6 +69,7 @@ const icons = [
|
||||
"credit_score",
|
||||
"curtains_closed",
|
||||
"curtains",
|
||||
"dangerous",
|
||||
"deck",
|
||||
"delete",
|
||||
"desk",
|
||||
@@ -103,7 +89,6 @@ const icons = [
|
||||
"electric_car",
|
||||
"elevator",
|
||||
"emoji_transportation",
|
||||
"error_circle_rounded",
|
||||
"error",
|
||||
"exercise",
|
||||
"family_restroom",
|
||||
@@ -174,7 +159,7 @@ const icons = [
|
||||
"pedal_bike",
|
||||
"person",
|
||||
"pets",
|
||||
"phone",
|
||||
"phone_enabled",
|
||||
"photo_camera",
|
||||
"play_arrow",
|
||||
"pool",
|
||||
@@ -234,122 +219,105 @@ const icons = [
|
||||
"yard",
|
||||
].sort()
|
||||
|
||||
function createHash(value: unknown) {
|
||||
const stringified = stringify(value)
|
||||
const hash = crypto.createHash("sha256")
|
||||
hash.update(stringified)
|
||||
return hash.digest("hex")
|
||||
}
|
||||
const STYLES = ["outlined", "rounded", "sharp"] as const
|
||||
|
||||
const hash = createHash(icons).substring(0, 8)
|
||||
const OUT = resolve(
|
||||
__dirname,
|
||||
"../packages/design-system/lib/components/Icons/MaterialIcon/generated.tsx"
|
||||
)
|
||||
|
||||
async function fetchIconUrl(url: string) {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
Accept:
|
||||
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
|
||||
"User-Agent":
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
|
||||
},
|
||||
})
|
||||
const PACKAGE_BASE = resolve(
|
||||
__dirname,
|
||||
"../node_modules/@material-symbols/svg-400"
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Unable to fetch woff2 for ${url}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const text = await response.text()
|
||||
|
||||
const isWoff2 = /format\('woff2'\)/.test(text)
|
||||
if (!isWoff2) {
|
||||
console.error(`Unable to identify woff2 font in response`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const srcUrl = text.match(/src: url\(([^)]+)\)/)
|
||||
|
||||
if (srcUrl && srcUrl[1]) {
|
||||
return srcUrl[1]
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function download(url: string, destFolder: string) {
|
||||
const dest = resolve(join(destFolder, `/rounded-${hash}.woff2`))
|
||||
|
||||
try {
|
||||
const response = await fetch(url)
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Unable to fetch ${url}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
console.error(`Bad response from ${url}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const fileStream = createWriteStream(dest)
|
||||
|
||||
// @ts-expect-error: type mismatch
|
||||
const readableNodeStream = Readable.fromWeb(response.body)
|
||||
|
||||
await pipeline(readableNodeStream, fileStream)
|
||||
} catch (error) {
|
||||
console.error(`Error downloading file from ${url}:`, error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
async function cleanFontDirs() {
|
||||
await rm(FONT_DIR, { recursive: true, force: true })
|
||||
await mkdir(FONT_DIR, { recursive: true })
|
||||
await writeFile(
|
||||
join(FONT_DIR, ".auto-generated"),
|
||||
`Auto-generated, do not edit. Use scripts/material-symbols-update.mts to update.\nhash=${hash}\ncreated=${new Date().toISOString()}\n`,
|
||||
{ encoding: "utf-8" }
|
||||
)
|
||||
}
|
||||
|
||||
async function updateFontCSS() {
|
||||
const file = resolve(__dirname, "../packages/design-system/lib/fonts.css")
|
||||
|
||||
const css = await readFile(file, {
|
||||
encoding: "utf-8",
|
||||
})
|
||||
|
||||
await writeFile(
|
||||
file,
|
||||
css.replace(
|
||||
/url\(\/_static\/shared\/fonts\/material-symbols\/rounded[^)]+\)/,
|
||||
`url(/_static/shared/fonts/material-symbols/rounded-${hash}.woff2)`
|
||||
),
|
||||
{
|
||||
encoding: "utf-8",
|
||||
}
|
||||
)
|
||||
function camelCase(str: string) {
|
||||
return str.replace(/[-_](\w)/g, (_, c: string) => c.toUpperCase())
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const fontUrl = `${FONT_BASE_URL}&icon_names=${icons.join(",")}&display=block`
|
||||
const imports: string[] = []
|
||||
const registryEntries: string[] = []
|
||||
|
||||
const iconUrl = await fetchIconUrl(fontUrl)
|
||||
const missing: string[] = []
|
||||
|
||||
if (iconUrl) {
|
||||
await cleanFontDirs()
|
||||
for (const icon of ICONS) {
|
||||
const styleEntries: string[] = []
|
||||
|
||||
await download(iconUrl, FONT_DIR)
|
||||
for (const style of STYLES) {
|
||||
const parts: string[] = []
|
||||
|
||||
await updateFontCSS()
|
||||
const fill0Path = resolve(PACKAGE_BASE, style, `${icon}.svg`)
|
||||
const fill1Path = resolve(PACKAGE_BASE, style, `${icon}-fill.svg`)
|
||||
|
||||
console.log("Successfully updated icons!")
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(
|
||||
`Unable to find the icon font src URL in CSS response from Google Fonts at ${fontUrl}`
|
||||
)
|
||||
let outlinedVar: string | undefined
|
||||
let filledVar: string | undefined
|
||||
|
||||
if (existsSync(fill0Path)) {
|
||||
outlinedVar = `${camelCase(icon)}${camelCase(style)}Outlined`
|
||||
imports.push(
|
||||
`import ${outlinedVar} from "@material-symbols/svg-400/${style}/${icon}.svg"`
|
||||
)
|
||||
parts.push(`outlined: ${outlinedVar}`)
|
||||
} else {
|
||||
missing.push(`${style}/${icon}.svg`)
|
||||
}
|
||||
|
||||
if (existsSync(fill1Path)) {
|
||||
filledVar = `${camelCase(icon)}${camelCase(style)}Filled`
|
||||
imports.push(
|
||||
`import ${filledVar} from "@material-symbols/svg-400/${style}/${icon}-fill.svg"`
|
||||
)
|
||||
parts.push(`filled: ${filledVar}`)
|
||||
}
|
||||
|
||||
if (parts.length) {
|
||||
styleEntries.push(`${style}: { ${parts.join(", ")} }`)
|
||||
}
|
||||
}
|
||||
|
||||
// ALWAYS emit the icon key (even if partial)
|
||||
if (styleEntries.length) {
|
||||
registryEntries.push(`"${icon}": { ${styleEntries.join(", ")} },`)
|
||||
} else {
|
||||
missing.push(`❌ no variants for "${icon}"`)
|
||||
}
|
||||
}
|
||||
|
||||
const content =
|
||||
`
|
||||
/* AUTO-GENERATED — DO NOT EDIT */
|
||||
|
||||
import type { FunctionComponent, SVGProps } from "react"
|
||||
|
||||
${imports.join("\n")}
|
||||
|
||||
type SvgIcon = FunctionComponent<SVGProps<SVGSVGElement>>
|
||||
|
||||
export const materialIcons: Record<
|
||||
string,
|
||||
Partial<{
|
||||
outlined: { outlined: SvgIcon; filled?: SvgIcon }
|
||||
rounded: { outlined: SvgIcon; filled?: SvgIcon }
|
||||
sharp: { outlined: SvgIcon; filled?: SvgIcon }
|
||||
}>
|
||||
> = {
|
||||
${registryEntries.join("\n")}
|
||||
}
|
||||
|
||||
export type MaterialIconName = keyof typeof materialIcons
|
||||
`.trim() + "\n"
|
||||
|
||||
await writeFile(OUT, content, "utf8")
|
||||
|
||||
console.log(`✅ Generated ${registryEntries.length} icons`)
|
||||
if (missing.length) {
|
||||
console.warn("⚠️ Missing SVGs:")
|
||||
missing.slice(0, 20).forEach((m) => console.warn(" ", m))
|
||||
if (missing.length > 20) {
|
||||
console.warn(` …and ${missing.length - 20} more`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
main().catch(console.error)
|
||||
|
||||
Reference in New Issue
Block a user