Skip to content

Commit

Permalink
Generate focus variants as separate declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
adamwathan committed Nov 22, 2017
1 parent 7746f64 commit 37b06c8
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 8 deletions.
8 changes: 5 additions & 3 deletions __tests__/focusableAtRule.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ test('it adds a focusable variant to each nested class definition', () => {
`

const output = `
.banana, .focus\\:banana:focus { color: yellow; }
.chocolate, .focus\\:chocolate:focus { color: brown; }
.banana { color: yellow; }
.chocolate { color: brown; }
.focus\\:banana:focus { color: yellow; }
.focus\\:chocolate:focus { color: brown; }
`

return run(input).then(result => {
expect(result.css).toEqual(output)
expect(result.css).toMatchCss(output)
expect(result.warnings().length).toBe(0)
})
})
22 changes: 22 additions & 0 deletions jest/customMatchers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
expect.extend({
// Compare two CSS strings with all whitespace removed
// This is probably naive but it's fast and works well enough.
toMatchCss(received, argument) {
function stripped(str) {
return str.replace(/\s/g, '')
}

if (stripped(received) == stripped(argument)) {
return {
message: () =>
`expected ${received} not to match CSS ${argument}`,
pass: true,
};
} else {
return {
message: () => `expected ${received} to match CSS ${argument}`,
pass: false,
};
}
}
})
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@
"react"
]
},
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/jest/customMatchers.js"
},
"engines": {
"node": ">=6.9.0"
}
Expand Down
11 changes: 6 additions & 5 deletions src/lib/substituteFocusableAtRules.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import cloneNodes from '../util/cloneNodes'

export default function() {
return function(css) {
css.walkAtRules('focusable', atRule => {
atRule.walkRules(rule => {
const clonedRule = atRule.clone()

clonedRule.walkRules(rule => {
// Might be wise to error if the rule has multiple selectors,
// or weird compound selectors like .bg-blue>p>h1
rule.selectors = [rule.selector, `.focus\\:${rule.selector.slice(1)}:focus`]
rule.selector = `.focus\\:${rule.selector.slice(1)}:focus`
})

atRule.before(cloneNodes(atRule.nodes))
atRule.before(atRule.clone().nodes)
atRule.after(clonedRule.nodes)

atRule.remove()
})
Expand Down

0 comments on commit 37b06c8

Please sign in to comment.