UNPKG

@zohodesk/utils

Version:

Unified Component Library - Utils

53 lines (48 loc) 2.13 kB
const REPLACER_SYMBOL = '$'; // $ startWith is used for replace the existing style. // all other will be append export default function mergeStyle(defaultStyle) { let customStyle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let additionalStyle = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; // if(!Object.keys(defaultStyle).includes('base')) { // throw new Error(`STYLE CUSTOMIZATION RULE - Your style sheet should have "base" class name for customization`); // } return Object.keys(customStyle).reduce((res, next) => { if (next.startsWith(REPLACER_SYMBOL)) { let styleValue = customStyle[next]; let styleName = next.replace(REPLACER_SYMBOL, ''); if (!res[styleName] && !additionalStyle.includes(styleName)) { throw new Error(`UNKNOWN CLASSNAME DETECTED - Given customStyle's key "${styleName}" is not available in that component style`); } else if (additionalStyle.includes(styleName)) { res[styleName] = styleValue; } else { let val = res[styleName]; Object.keys(res).map(keyName => { let styleKey = res[keyName]; let ind = styleKey.indexOf(val); if (ind !== -1) { res[keyName] = styleKey.replace(val, styleValue); } }); } } else if (res[next]) { let val = res[next]; Object.keys(res).map(keyName => { let styleKey = res[keyName]; let styleClasses = styleKey.split(' '); val = val.split(' ')[0]; let ind = styleClasses.indexOf(val); if (ind !== -1) { styleClasses[ind] = styleClasses[ind] + ' ' + customStyle[next]; res[keyName] = styleClasses.join(' '); } }); } else if (additionalStyle.includes(next)) { res[next] = customStyle[next]; } else if (!res[next] && !additionalStyle.includes(next)) { // res[next] = customStyle[next]; throw new Error(`UNKNOWN CLASSNAME DETECTED - Given customStyle's key "${next}" is not available in that component style`); } return res; }, { ...defaultStyle }); }