Created
November 26, 2023 11:20
-
-
Save janispritzkau/e5cfdb2e8a9bbf378d7939b0efcc3f20 to your computer and use it in GitHub Desktop.
Tailwind Material Symbols Background Image SVG Plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Config } from "tailwindcss"; | |
import plugin from "tailwindcss/plugin"; | |
import { readFileSync, readdirSync } from "fs"; | |
import { dirname, join } from "path"; | |
export default { | |
// ... | |
plugins: [ | |
plugin(({ addBase, theme }) => { | |
const colors = flattenColorPalette(theme("colors")); | |
addBase({ | |
":root": Object.fromEntries( | |
Object.entries(colors).map(([key, value]) => { | |
return [key == "DEFAULT" ? `--color` : `--color-${key}`, value]; | |
}) | |
), | |
}); | |
}), | |
plugin(({ theme, matchUtilities, e }) => { | |
const dir = dirname( | |
require.resolve("@material-symbols/svg-500/package.json") | |
); | |
const iconNames = readdirSync(join(dir, "outlined")) | |
.map((f) => f.match(/(.*)\.svg$/)?.[1]) | |
.filter((f): f is string => f != null); | |
matchUtilities( | |
Object.fromEntries( | |
iconNames.map((name) => [ | |
`bg-icon-${name.replaceAll("_", "-")}`, | |
(value) => { | |
let svg = readFileSync( | |
join(dir, "outlined", `${name}.svg`), | |
"utf-8" | |
); | |
svg = svg.replace( | |
"<svg", | |
`<svg fill="${encodeURIComponent(value)}"` | |
); | |
svg = svg.replace(/(?<=width=")\d+(?=")/, "20"); | |
return { | |
"background-image": `url('data:image/svg+xml,${svg}')`, | |
}; | |
}, | |
]) | |
), | |
{ | |
values: flattenColorPalette(theme("colors")), | |
type: "color", | |
} | |
); | |
}), | |
], | |
} satisfies Config; | |
function flattenColorPalette( | |
colors: Record<string, string | Record<string, string>>, | |
prefix = "" | |
): Record<string, string> { | |
return Object.entries(colors).reduce((acc, [key, value]) => { | |
const prefixedKey = prefix ? `${prefix}-${key}` : key; | |
if (typeof value == "string") return { ...acc, [prefixedKey]: value }; | |
return { ...acc, ...flattenColorPalette(value, prefixedKey) }; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment