Skip to content

Instantly share code, notes, and snippets.

@Gravy59
Last active August 19, 2023 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gravy59/60db321d312f283a20f312ec9e74d138 to your computer and use it in GitHub Desktop.
Save Gravy59/60db321d312f283a20f312ec9e74d138 to your computer and use it in GitHub Desktop.
Use radix colors in tailwind css with full intellisense support
import * as radixColors from "@radix-ui/colors";
/**
* We could probably get away with *not* using this but
* proper usage of tailwind leaves all dependencies compiled
* to css, so this only affects the build step.
*/
import parse from "parse-css-color";
import plugin from "tailwindcss/plugin";
// Extracts the step without the color prefix
function getStepWithoutColorPrefix(step: string, color: string): string {
const colorRegex = new RegExp(`${color}a?`, "i");
return step.replace(colorRegex, "");
}
// Initial color values
const initialColors = {
white: "white",
black: "black",
current: "currentColor",
transparent: "transparent",
};
// Process color steps and organize them
const processedColors = Object.entries(radixColors).reduce(
(accumulator, [color, colorSteps]) => {
const colorNameParts = color.replace("A", "Alpha").split(/(?=[A-Z])/);
const colorStepValues = Object.entries(colorSteps).reduce(
(stepAccumulator, [step, value]) => {
const parsedValue = parse(value);
return {
...stepAccumulator,
[getStepWithoutColorPrefix(
step,
colorNameParts[0],
)]: `hsl(${parsedValue?.values[0]} ${parsedValue
?.values[1]}% ${parsedValue?.values[2]}% / ${
colorNameParts.includes("Alpha")
? parsedValue?.alpha
: "<alpha-value>"
})`,
};
},
{},
);
return {
...accumulator,
[colorNameParts.join("-").toLowerCase()]: colorStepValues,
};
},
initialColors,
);
export default plugin(({}) => {}, {
theme: {
extend: {
colors: {
...processedColors,
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment