Last active
June 17, 2022 17:22
-
-
Save guilhermemarconi/055fe8bf1ac0309373f3667d2c40425d to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Monta uma estrutura de classes CSS usando a metotologia BEM. | |
* @param {string} block | |
* Bloco base da classe CSS. Se passar apenas ele, retorna um construtor. | |
* @param {string} element | |
* @param {string[]} modifiers | |
* @returns {string|() => string} | |
* Classes CSS ou construtor baseado no bloco. | |
* @example | |
* const ordinaryClasses = mountBEMClass('block', 'element', 'modifier1', 'modifier2'); | |
* console.log(ordinaryClasses); // block__element block__element--modifier1 block__element--modifier2 | |
* const blockWithModifier = mountBEMClass('block', null, 'modifier'); | |
* console.log(blockWithModifier); // block block--modifier | |
* const constructorClass = mountBEMClass('block'); | |
* console.log(constructorClass('element')); // block__element | |
* console.log(constructorClass('element', 'modifier')) // block__element block__element--modifier | |
* console.log(constructorClass(null, 'modifier')) // block block--modifier | |
* console.log(constructorClass()); // block | |
*/ | |
function mountBEMClass(block, element, ...modifiers) { | |
try { | |
if (!block) return ''; | |
function getElementAndModifiers(str, element, ...modifiers) { | |
if (!element) { | |
if (!modifiers.length) return ''; | |
} | |
str += element ? `__${element}` : ''; | |
if (modifiers) { | |
str += modifiers.map(modifier => !!modifier && ` ${str}--${modifier}`).filter(Boolean).join(''); | |
} | |
return str; | |
} | |
return element || modifiers.length | |
? getElementAndModifiers(block, element, ...modifiers) | |
: function(element, ...modifiers) { | |
if (!element) return block; | |
return getElementAndModifiers(block, element, ...modifiers); | |
}; | |
} catch (error) { | |
console.error(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment