diff --git a/objectifier.js b/objectifier.js index 6cb9d88..07b05e1 100644 --- a/objectifier.js +++ b/objectifier.js @@ -55,6 +55,28 @@ function camelcase(property) { return result + property.slice(cursor) } +function isObject(value) { + return typeof value === 'object' && !Array.isArray(value) +} + +function merge(object, body, options) { + for (let i in body) { + if ( + options.stringifyImportant && + typeof object[i] === 'string' && + object[i].endsWith('!important') + ) { + if (typeof body[i] === 'string' && body[i].endsWith('!important')) { + object[i] = body[i] + } + } else if (isObject(object[i]) && isObject(body[i])) { + merge(object[i], body[i], options) + } else { + object[i] = body[i] + } + } +} + function process(node, options = {}) { let name let result = {} @@ -73,20 +95,7 @@ function process(node, options = {}) { } else if (child.type === 'rule') { let body = process(child) if (result[child.selector]) { - for (let i in body) { - let object = result[child.selector] - if ( - options.stringifyImportant && - typeof object[i] === 'string' && - object[i].endsWith('!important') - ) { - if (typeof body[i] === 'string' && body[i].endsWith('!important')) { - object[i] = body[i] - } - } else { - object[i] = body[i] - } - } + merge(result[child.selector], body, options) } else { result[child.selector] = body } diff --git a/test/objectifier.test.js b/test/objectifier.test.js index cfbe2d5..4cb4dcc 100644 --- a/test/objectifier.test.js +++ b/test/objectifier.test.js @@ -202,4 +202,29 @@ test('keeps last important with priority', () => { }) }) +test('merges nested rules in merged rules', () => { + let root = parse( + '.btn { color: red; &:hover { color: blue; padding: 1px } } ' + + '.btn { &:hover { margin: 0 } }' + ) + equal(postcssJS.objectify(root), { + '.btn': { + 'color': 'red', + '&:hover': { color: 'blue', padding: '1px', margin: '0' } + } + }) +}) + +test('merges nested at-rules in merged rules', () => { + let root = parse( + 'a { @media print { color: red; b { c: d } } } ' + + 'a { @media print { margin: 0; b { e: f } } }' + ) + equal(postcssJS.objectify(root), { + a: { + '@media print': { color: 'red', margin: '0', b: { c: 'd', e: 'f' } } + } + }) +}) + test.run()