Skip to content

Instantly share code, notes, and snippets.

@evanrs
Last active December 11, 2015 19:33
Show Gist options
  • Save evanrs/974b21489e472d86e9cb to your computer and use it in GitHub Desktop.
Save evanrs/974b21489e472d86e9cb to your computer and use it in GitHub Desktop.
import result from 'lodash/object/result';
function decomposeProperty (style, propName) {
if (arguments.length < 2)
return decomposeProperty.bind(this, ...arguments);
let prop = style[propName];
if (! prop) {
return false;
}
let [Top, Right, Bottom, Left] =
typeof prop === 'string' ? prop.split(' ')
: typeof prop === 'number' ? [prop]
: prop
;
prop = {
Top,
Right: Right || Top,
Bottom: Bottom || Top,
Left: Left || Right || Top,
}
Object.keys(prop).forEach(key =>
style[`${propName}${key}`] = prop[key]);
delete style[propName];
return true;
}
const decomposeCSS = traverse('props.children', (node, idx, col, parent) => {
let style = result(node, 'props.style');
if (! style) {
return node
}
let decomposed = ['padding', 'margin'].map(decomposeProperty(style))
return (
decomposed.reduce((a, b) => a || b) ?
node : React.cloneElement(node, {style})
)
});
function traverse(key, iteratee, collection, recursed) {
return (
// exit or transduce
! collection ?
arguments.length === 4 ?
recursed
: traverse.bind(this, ...arguments)
// traverse
: [].concat(collection).
map((node, idx, col) =>
traverse(
key,
iteratee,
result(
iteratee(node, idx, col, recursed),
key
),
node
)
)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment