Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions objectifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}
Expand All @@ -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
}
Expand Down
25 changes: 25 additions & 0 deletions test/objectifier.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading