Build class strings from variant configs and compound rules
A design system ships components like badges and buttons in several tones and sizes. Writing the class logic by hand in every component leads to long, fragile chains of conditions. Instead, each component declares its variants once in a config object, and a small builder turns props into a class string.
Implement createVariants(config). It returns a function that takes props and returns the class string for them.
const getClasses = createVariants(config);
getClasses(props?) // => string
Every field is optional:
base: classes that are always included.variants: an object of variant names to option maps, e.g. { size: { sm: 'text-xs', md: 'text-sm' } }. Each option maps to a class string.defaults: the option used for a variant when the props do not choose one, e.g. { size: 'md' }.compounds: an array of { when, className } rules. className is added when every condition in when matches, e.g. { when: { tone: 'danger', pill: true }, className: 'ring-red' }.config.variants, the chosen option is props[name], or defaults[name] when that prop is undefined or missing.null means “no option”: the variant adds nothing, even if it has a default.true and false pick the 'true' and 'false' keys, and the number 2 picks '2'.size: 'xl') adds nothing. Only the variant’s own keys count, so 'toString' is not an option.className) are ignored.{ name: value } matches when the chosen option for name (after defaults) has the same string form as value. A condition value can also be an array, which matches if any of its values match.null, or no prop and no default) does not match.when always matches.base, then each variant’s class in the order the variants are declared in config.variants (not the order of the props), then the matching compound classes in array order, then props.className.''.config or the props.const badge = createVariants({
base: 'badge inline-flex',
variants: {
tone: { neutral: 'bg-gray', success: 'bg-green', danger: 'bg-red' },
size: { sm: 'text-xs px-1', md: 'text-sm px-2' },
pill: { true: 'rounded-full', false: 'rounded' },
},
defaults: { tone: 'neutral', size: 'md', pill: false },
compounds: [
{ when: { tone: 'danger', pill: true }, className: 'ring-red' },
{ when: { tone: 'success', size: ['sm', 'md'] }, className: 'font-bold' },
],
});
badge();
// => 'badge inline-flex bg-gray text-sm px-2 rounded'
badge({ pill: true, size: 'sm', tone: 'danger' });
// => 'badge inline-flex bg-red text-xs px-1 rounded-full ring-red'
badge({ tone: 'success', className: ' mt-2 badge ' });
// => 'badge inline-flex bg-green text-sm px-2 rounded font-bold mt-2'
badge({ size: null, tone: 'xl' });
// => 'badge inline-flex rounded'