Repository URL to install this package:
|
Version:
1.0.0-beta.6.webpack ▾
|
import { dasherize } from './util.strings';
import _ from 'underscore';
function BEMify(...bemObjectArray) {
const scopeSet = new Set();
const stateSet = new Set();
const bemObjectSet = new Set(bemObjectArray.map(({ scope = '', block = '', element = '', modifier = '', state = '' }) => {
if (scope) { scopeSet.add(dasherize(scope)); }
if (state) { stateSet.add(`is-${dasherize(state)}`); }
return [
(block ? ` ${dasherize(block)}` : ''),
(element ? `__${dasherize(element)}` : ''),
(modifier ? `--${dasherize(modifier)}` : '')
].join('');
}));
return `${Array.from(scopeSet).join(' ')} ${Array.from(bemObjectSet).join('')} ${Array.from(stateSet).join(' ')}`.trim();
}
function BEMifyFlatObject(...bemObjects) {
// this can take an abutrary amount of flattened bem objects (or normal ones) and turn them into a bem string
// { block: 'block1', element: 'elem1', block2: 'block2', modifier2: 'mod2', element3: 'elem' } => 'block__elem1 block2--mod2__elem'
const RE_KEYNAME = 1;
const RE_INDEX = 2;
const bemArray = _.flatten(_.flatten(bemObjects, true).map((bemObject) => {
const sortedBem = {};
for (const keyName in bemObject) {
// match key name patterns of a-zA-Z + number
// block1 => block, 1
// block => block, null
const regexMatch = /(\D+)(\d{0,})/g.exec(keyName);
// assume 0 index if no index is defined in keyname
let targetKeyName = keyName;
let targetIndex = 0;
let targetValue = bemObject[keyName];
// if regex match fails, then we'll just add whatever
// that key was to the first index object
if (regexMatch !== null) {
targetKeyName = regexMatch[RE_KEYNAME];
// if no number is matched then we will just
// place it in the first index object
targetIndex = regexMatch[RE_INDEX] || 0;
}
let index = parseInt(targetIndex);
if (targetKeyName && Number.isFinite(index) && index >= 0) {
if (sortedBem[index] === undefined) {
sortedBem[index] = {};
}
Object.assign(sortedBem[index], {
[targetKeyName]: targetValue
});
}
}
return _.toArray(sortedBem);
}), true);
return BEMify(...bemArray);
}
export default BEMifyFlatObject;