Last active
January 5, 2022 17:15
-
-
Save elsangedy/7a641969eeaaef0f8aea0f41f472d67c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
type VariantValue<T> = { [K in keyof T]?: keyof T[K] } | |
type Variant = { [k: string]: string } | |
type VariantConfig = { [k: string]: Variant } | |
const cns = <T extends VariantConfig>(base: string, variantsConfig?: T, defaultVariants: VariantValue<T> = {}) => (variantsValues: VariantValue<T> = {}): string => { | |
const variants = Object.entries(variantsConfig || {}).map(([name, values]) => values?.[variantsValues[name] || defaultVariants[name]] ?? '') | |
return [base, ...variants].filter(Boolean).join(' ') | |
} | |
const button = cns( | |
'flex items-center justify-center', | |
{ | |
variant: { | |
primary: 'bg-primary', | |
secondary: 'bg-secondary', | |
neutral: 'bg-neutral' | |
}, | |
disabled: { | |
true: 'a', | |
false: 'b' | |
} | |
}, | |
{ | |
variant: 'primary', | |
disabled: 'true' | |
} | |
) | |
const classes = button({ variant: 'neutral' }) | |
console.log(classes) // "flex items-center justify-center bg-neutral a" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment