Skip to content

Commit

Permalink
Sort classes between tags and pseudos when rewriting selectors
Browse files Browse the repository at this point in the history
  • Loading branch information
thecrypticace committed Aug 15, 2022
1 parent c4fd71e commit 8bdf4f4
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/lib/expandApplyAtRules.js
Expand Up @@ -332,6 +332,24 @@ function processApply(root, context, localCache) {
})
})

// Sort tag names before class names
// This happens when replacing `.bar` in `.foo.bar` with a tag like `section`
for (const sel of replaced) {
sel.sort((a, b) => {
if (a.type === 'tag' && b.type === 'class') {
return -1
} else if (a.type === 'class' && b.type === 'tag') {
return 1
} else if (a.type === 'class' && b.type === 'pseudo') {
return -1
} else if (a.type === 'pseudo' && b.type === 'class') {
return 1
}

return sel.index(a) - sel.index(b)
})
}

sel.replaceWith(...replaced)
})

Expand Down
56 changes: 56 additions & 0 deletions tests/apply.test.js
Expand Up @@ -1585,6 +1585,62 @@ it('can apply user utilities that start with a dash', async () => {
`)
})

it('can apply joined classes when using elements', async () => {
let config = {
content: [{ raw: html`<div class="foo-1 -foo-1 new-class"></div>` }],
plugins: [],
}

let input = css`
.foo.bar {
color: red;
}
.bar.foo {
color: green;
}
header:nth-of-type(odd) {
@apply foo;
}
main {
@apply foo bar;
}
footer {
@apply bar;
}
`

let result = await run(input, config)

expect(result.css).toMatchFormattedCss(css`
.foo.bar {
color: red;
}
.bar.foo {
color: green;
}
header.bar:nth-of-type(odd) {
color: red;
color: green;
}
main.bar {
color: red;
}
main.foo {
color: red;
}
main.bar {
color: green;
}
main.foo {
color: green;
}
footer.foo {
color: red;
color: green;
}
`)
})

it('can produce selectors that replace multiple instances of the same class', async () => {
let config = {
content: [{ raw: html`<div class="foo-1 -foo-1 new-class"></div>` }],
Expand Down

0 comments on commit 8bdf4f4

Please sign in to comment.