tailwindcss/src/util/generateVariantFunction.js
Robin Malfait aa7ae6af37 re-use classNameParser
We were re-creating the classNameParser inside the loop. Since that code
is all pretty pure we can hoist it so that we don't have to recreate
that parser all the time.
2020-08-18 08:21:33 -04:00

41 lines
1.1 KiB
JavaScript

import _ from 'lodash'
import postcss from 'postcss'
import selectorParser from 'postcss-selector-parser'
const classNameParser = selectorParser(selectors => {
return selectors.first.filter(({ type }) => type === 'class').pop().value
})
export default function generateVariantFunction(generator) {
return (container, config) => {
const cloned = postcss.root({ nodes: container.clone().nodes })
container.before(
_.defaultTo(
generator({
container: cloned,
separator: config.separator,
modifySelectors: modifierFunction => {
cloned.each(rule => {
if (rule.type !== 'rule') {
return
}
rule.selectors = rule.selectors.map(selector => {
const className = classNameParser.transformSync(selector)
return modifierFunction({
className,
selector,
})
})
})
return cloned
},
}),
cloned
).nodes
)
}
}