Skip to content

Commit

Permalink
Prefix all classes in a selector, don't assume single class
Browse files Browse the repository at this point in the history
  • Loading branch information
adamwathan committed Mar 7, 2018
1 parent d1423ba commit c3f021a
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 2 deletions.
15 changes: 15 additions & 0 deletions __tests__/prefixTree.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ test('it handles a function as the prefix', () => {
`

const prefixFunc = selector => {
return selector === '.foo' ? 'tw-' : ''
if (selector === '.foo') {
return 'tw-'
}
Expand All @@ -40,3 +41,17 @@ test('it handles a function as the prefix', () => {
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})

test('it prefixes all classes in a selector', () => {
const input = postcss.parse(`
.btn-blue .w-1\\/4 > h1.text-xl + a .bar { color: red; }
`)

const expected = `
.tw-btn-blue .tw-w-1\\/4 > h1.tw-text-xl + a .tw-bar { color: red; }
`

const result = prefixTree(input, 'tw-').toResult()
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})
23 changes: 23 additions & 0 deletions __tests__/processPlugins.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -755,3 +755,26 @@ test('variants can still be specified when ignoring prefix and important options
}
`)
})

test('prefix will prefix all classes in a selector', () => {
const [components] = processPluginsWithValidConfig({
plugins: [
function({ addComponents, prefix }) {
addComponents({
[prefix('.btn-blue .w-1\\/4 > h1.text-xl + a .bar')]: {
backgroundColor: 'blue',
},
})
},
],
options: {
prefix: 'tw-',
},
})

expect(css(components)).toMatchCss(`
.tw-btn-blue .tw-w-1\\/4 > h1.tw-text-xl + a .tw-bar {
background-color: blue
}
`)
})
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@
"postcss": "^6.0.9",
"postcss-functions": "^3.0.0",
"postcss-js": "^1.0.1",
"postcss-nested": "^3.0.0"
"postcss-nested": "^3.0.0",
"postcss-selector-parser": "^3.1.1"
},
"browserslist": [
"> 1%"
Expand Down
8 changes: 7 additions & 1 deletion src/util/prefixSelector.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import parser from 'postcss-selector-parser'

export default function(prefix, selector) {
const getPrefix = typeof prefix === 'function' ? prefix : () => prefix

return `.${getPrefix(selector)}${selector.slice(1)}`
return parser(selectors => {
selectors.walkClasses((classSelector) => {
classSelector.value = `${getPrefix('.' + classSelector.value)}${classSelector.value}`
})
}).processSync(selector)
}

0 comments on commit c3f021a

Please sign in to comment.