Created
March 20, 2017 16:40
-
-
Save creativetim/bf3d94b1938f3489f8194d2c73ab56a1 to your computer and use it in GitHub Desktop.
Plaintext CSS from object
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/lodash'; | |
/** | |
* Transforms a "CSS DOM" object into plaintext CSS. | |
* | |
* ex. of CSS DOM object | |
* cssDOM = { | |
* 'c-header': { | |
* 'border': '1px solid #000', | |
* 'border-color: obj.customColor, | |
* }, | |
* 'c-header__font': { | |
* 'font-family': '"InsaneClownPosse"', | |
* }, | |
* 'c-header__font-color': { | |
* 'font-color': obj.customColor, | |
* } | |
* } | |
* | |
* The method will iterate over the object and keep only | |
* items that have vaules. | |
* | |
* Assuming obj.customColor is undefined the output of the | |
* above cssDOM would be: | |
* .c-header{border:1px solid #000;}.c-header__font{font-family:"InsaneClownPosse"} | |
* | |
* @function plaintextCSS | |
* @param {Object} cssDOM An object representing selectors and their properties | |
* @returns {String} | |
*/ | |
export default function plaintextCSS(cssDOM){ | |
return _.reduce( | |
_.reduce(cssDOM, (scrubbedCSSDOM, rulesObj, selector) => { | |
// Scrub cssDOM object such that only keys with values remain | |
const rules = _.pickBy(rulesObj, (ruleVal) => !!ruleVal ); | |
if (rules && !_.isEmpty(rules)){ | |
scrubbedCSSDOM[selector] = _.reduce(rules, (cssProps, cssValue, cssProp) => { | |
// Output: css_property: value !important; | |
return `${cssProps}${cssProp}:${cssValue} !important;`; | |
}, ''); | |
} | |
return scrubbedCSSDOM; | |
}, {}) | |
, (cssString, cssProps, selector) => { | |
return `${cssString}.${selector}{${cssProps}}`; | |
} | |
, ''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment