rn-variant
Version:
Light-weight, type-safe style variants for React Native.
55 lines (54 loc) • 1.56 kB
JavaScript
// src/create-variant.ts
import { StyleSheet } from "react-native";
function createVariantStyles(config) {
const { base = {}, variants, compoundVariants = [] } = config;
const styleMap = {};
for (const variantKey in variants) {
styleMap[variantKey] = {};
for (const optionKey in variants[variantKey]) {
styleMap[variantKey][optionKey] = StyleSheet.create({
style: variants[variantKey][optionKey]
});
}
}
function useVariants(input) {
const selected = [base];
for (const variantKey in input) {
const value = input[variantKey];
if (value !== void 0 && value !== null) {
let resolvedValue;
if (typeof value === "boolean") {
resolvedValue = value.toString();
} else {
resolvedValue = value;
}
if (styleMap[variantKey]?.[resolvedValue]) {
selected.push(styleMap[variantKey][resolvedValue].style);
}
}
}
compoundVariants.forEach(({ variants: compound, style }) => {
const isMatch = Object.entries(compound).every(([key, value]) => {
const inputValue = input[key];
const compoundValue = value;
if (typeof inputValue === "boolean") {
return inputValue.toString() === compoundValue;
}
return inputValue === compoundValue;
});
if (isMatch) {
selected.push(style);
}
});
return {
style: StyleSheet.flatten(selected)
};
}
return {
styles: styleMap,
useVariants
};
}
export {
createVariantStyles
};