Skip to content

Commit

Permalink
make keyframes scoped (close #731)
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Apr 27, 2017
1 parent 7529218 commit 35229b0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
19 changes: 17 additions & 2 deletions lib/style-compiler/plugins/scope-id.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,18 @@ var selectorParser = require('postcss-selector-parser')

module.exports = postcss.plugin('add-id', function (opts) {
return function (root) {
var keyframes = Object.create(null)

root.each(function rewriteSelector (node) {
if (!node.selector) {
// handle media queries
if (node.type === 'atrule' && node.name === 'media') {
node.each(rewriteSelector)
if (node.type === 'atrule') {
if (node.name === 'media') {
node.each(rewriteSelector)
} else if (node.name === 'keyframes') {
// register keyframes
keyframes[node.params] = node.params = node.params + '-' + opts.id
}
}
return
}
Expand All @@ -23,5 +30,13 @@ module.exports = postcss.plugin('add-id', function (opts) {
})
}).process(node.selector).result
})

if (Object.keys(keyframes).length) {
root.walkDecls(decl => {
if (/-?animation$/.test(decl.prop) && keyframes[decl.value]) {
decl.value = keyframes[decl.value]
}
})
}
}
})
7 changes: 7 additions & 0 deletions test/fixtures/scoped-css.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
h1 {
color: green;
}
.anim {
animation: color;
}
@keyframes color {
from { color: red; }
to { color: green; }
}
</style>

<template>
Expand Down
9 changes: 6 additions & 3 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,12 @@ describe('vue-loader', function () {

var style = window.document.querySelector('style').textContent
style = normalizeNewline(style)
expect(style).to.contain('.test[' + id + '] {\n color: yellow;\n}')
expect(style).to.contain('.test[' + id + ']:after {\n content: \'bye!\';\n}')
expect(style).to.contain('h1[' + id + '] {\n color: green;\n}')
expect(style).to.contain(`.test[${id}] {\n color: yellow;\n}`)
expect(style).to.contain(`.test[${id}]:after {\n content: \'bye!\';\n}`)
expect(style).to.contain(`h1[${id}] {\n color: green;\n}`)
// scoped keyframes
expect(style).to.contain(`.anim[${id}] {\n animation: color-${id};\n}`)
expect(style).to.contain(`@keyframes color-${id} {`)
done()
})
})
Expand Down

0 comments on commit 35229b0

Please sign in to comment.