Skip to content

Instantly share code, notes, and snippets.

@creativetim
Created March 20, 2017 16:40
Show Gist options
  • Save creativetim/bf3d94b1938f3489f8194d2c73ab56a1 to your computer and use it in GitHub Desktop.
Save creativetim/bf3d94b1938f3489f8194d2c73ab56a1 to your computer and use it in GitHub Desktop.
Plaintext CSS from object
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