UNPKG

native-variants

Version:

A library for handling variants in React Native components with theme support.

101 lines 3.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.styled = styled; exports.createNVA = createNVA; function cache(fn) { const memo = new Map(); return ((...args) => { const key = JSON.stringify(args); if (memo.has(key)) return memo.get(key); const result = fn(...args); memo.set(key, result); return result; }); } function variant(slot, variants, props) { let style = {}; for (const key in variants) { if (Object.prototype.hasOwnProperty.call(props, key)) { const value = props[key]; const variantConfig = variants[key]; const styleForValue = variantConfig?.[value]?.[slot]; if (styleForValue) { style = { ...style, ...styleForValue }; } } } return style; } function compound(slot, compoundVariants, props) { let style = {}; for (const cv of compoundVariants) { const { css, ...conds } = cv; const isMatch = Object.entries(conds).every(([k, v]) => props[k] === v); if (isMatch && css?.[slot]) { style = { ...style, ...css[slot] }; } } return style; } function set(slot, base, variants, compoundVariants, props) { return { ...base?.[slot], ...variant(slot, variants, props), ...compound(slot, compoundVariants, props), }; } function styled(config) { const { slots, base = {}, variants = {}, defaultVariants = {}, compoundVariants = [], } = config; const computeStyles = (props) => { const resolvedProps = { ...defaultVariants }; // Override only explicitly defined variant props, keeping defaults untouched if (props) { for (const key in props) { const value = props[key]; if (value !== undefined) { //@ts-ignore resolvedProps[key] = value; } } } const result = {}; for (const slot of slots) { result[slot] = set(slot, base, variants, compoundVariants, resolvedProps); } return result; }; const cachedComputeStyles = cache(computeStyles); return cachedComputeStyles; } function createNVA({ theme, } = {}) { function styled(configOrFactory) { const defineConfig = (config) => config; const config = typeof configOrFactory === "function" ? configOrFactory(defineConfig, theme) : configOrFactory; const { slots, base = {}, variants = {}, defaultVariants = {}, compoundVariants = [], } = config; const computeStyles = (props) => { const resolvedProps = { ...defaultVariants }; if (props) { for (const key in props) { if (props[key] !== undefined) { // @ts-ignore resolvedProps[key] = props[key]; } } } const result = {}; for (const slot of slots) { result[slot] = set(slot, base, variants, compoundVariants, resolvedProps); } return result; }; return cache(computeStyles); } return { theme: theme, styled, }; } //# sourceMappingURL=create-nva.js.map