Created
August 28, 2015 09:30
-
-
Save terpiljenya/45b9ce90bd3b618338cb to your computer and use it in GitHub Desktop.
BEM helper
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
import _ from 'lodash'; | |
function objectToArray(object) { | |
let keys = Object.keys(object); | |
let output = []; | |
keys.forEach(function(key) { | |
let predicate = object[key]; | |
if (_.isFunction(predicate)) { | |
predicate = predicate(); | |
} | |
if (predicate) { | |
output.push(key); | |
} | |
}); | |
return output; | |
} | |
function listToArray(list) { | |
if (_.isString(list) && list !== '') { | |
return list.split(' '); | |
} else if (list && list.length) { | |
return list; | |
} else if (_.isObject(list)) { | |
return objectToArray(list); | |
} else { | |
return []; | |
} | |
} | |
export default function createBEM(options) { | |
if (_.isString(options)) { | |
options = { name: options }; | |
} | |
return function(first, modifiers) { | |
let prefix = options.prefix || 'b-'; | |
let rootName = options.block; | |
let classNames = []; | |
let element; | |
// This means the first parameter is not the element, but a configuration letiable | |
if (_.isObject(first)) { | |
element = first.element; | |
modifiers = first.modifiers || first.modifier; | |
} else { | |
element = first; | |
} | |
if (element) { | |
rootName += '__' + element; | |
} | |
classNames.push(rootName); | |
// Compose an array of modifiers | |
listToArray(modifiers).forEach(function(modifier) { | |
classNames.push(rootName + '--' + modifier); | |
}); | |
// Add a prefix to all the classes in the classNames array | |
for (let i = 0; i < classNames.length; i++) { | |
classNames[i] = prefix + classNames[i]; | |
} | |
return classNames.join(' ').trim(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment