Skip to content

Commit

Permalink
Add support for passing a function as the prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
EmilTholin authored and adamwathan committed Jan 28, 2018
1 parent cd2f855 commit 357c873
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
24 changes: 24 additions & 0 deletions __tests__/applyClassPrefix.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,27 @@ test('it prefixes classes with the provided prefix', () => {
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})

test('it handles a function as the prefix', () => {
const input = postcss.parse(`
.foo { color: red; }
.apple, .pear { color: green; }
`)

const expected = `
.tw-foo { color: red; }
.apple, .pear { color: green; }
`

const prefixFunc = selector => {
if (selector === '.foo') {
return 'tw-'
}

return ''
}

const result = applyClassPrefix(input, prefixFunc).toResult()
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})
5 changes: 4 additions & 1 deletion src/util/applyClassPrefix.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
export default function(css, prefix) {
const prefixIsFunc = typeof prefix === 'function'
css.walkRules(rule => {
rule.selectors = rule.selectors.map(selector => `.${prefix}${selector.slice(1)}`)
rule.selectors = rule.selectors.map(
selector => `.${prefixIsFunc ? prefix(selector) : prefix}${selector.slice(1)}`
)
})
return css
}

0 comments on commit 357c873

Please sign in to comment.