Skip to content

Commit 7a77088

Browse files
authored
Merge pull request #133 from posthtml/fix/string-sources
2 parents b1bfc88 + dafcc48 commit 7a77088

2 files changed

Lines changed: 48 additions & 8 deletions

File tree

lib/postcssSafeCss.js

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
import cssEscape from 'css.escape'
22

3-
const headCSSRegex = needle => new RegExp(`\\\\[${needle}]`, 'g')
3+
function unescapeRegExp(string) {
4+
return string.replace(/\\(.)/g, '$1')
5+
}
46

57
export default (options = {}) => root => {
6-
root.walkDecls(decl => {
7-
if (decl.parent.selector) {
8-
Object.entries(options.replacements).forEach(([from, to]) => {
9-
decl.parent.selector = decl.parent.selector
10-
.replace(headCSSRegex(cssEscape(from)), to)
11-
.replace('\\2c ', '_')
8+
const replacementsRegex = new RegExp('\\\\(' + Object.keys(options.replacements).map(cssEscape).join('|') + ')', 'g')
9+
10+
root.walkRules(rule => {
11+
rule.selector = rule.selector
12+
.replace(replacementsRegex, matched => {
13+
return options.replacements[unescapeRegExp(matched)]
1214
})
13-
}
15+
// Replace escaped commas with underscores
16+
.replaceAll('\\2c ', '_')
1417
})
1518
}

test/index.test.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,40 @@ test('Ignores known class name patterns', t => {
8181
],
8282
})
8383
})
84+
85+
test('Works with escaped selectors in string sources', async () => {
86+
const html = `
87+
<style>
88+
.sm\\:text-left {
89+
text-align: left;
90+
}
91+
.w-1\\.5 {
92+
width: 1.5rem;
93+
}
94+
</style>
95+
<div class="sm:text-left w-1.5">foo</div>
96+
`
97+
98+
const result = await posthtml([
99+
plugin({
100+
replacements: {
101+
':': '__',
102+
'.': '_dot_',
103+
}
104+
})
105+
])
106+
.process(html)
107+
.then(result => result.html)
108+
109+
expect(result).toBe(`
110+
<style>
111+
.sm__text-left {
112+
text-align: left;
113+
}
114+
.w-1_dot_5 {
115+
width: 1.5rem;
116+
}
117+
</style>
118+
<div class="sm__text-left w-1_dot_5">foo</div>
119+
`)
120+
})

0 commit comments

Comments
 (0)