Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly replace pseudo states when multiple colons in classname #80

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/preview/rewriteStyleSheet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,16 @@ describe("rewriteStyleSheet", () => {
expect(sheet.cssRules[3].selectorText).toContain(".pseudo-hover .test2")

})

it("supports classnames with a colon followed by state", () => {
const sheet = new Sheet(".focus:hover:border-red:hover:focus {border: red;}")
rewriteStyleSheet(sheet)
expect(sheet.cssRules[0].selectorText).toContain(".focus:hover:border-red:hover:focus")
expect(sheet.cssRules[0].selectorText).toContain(
".focus:hover:border-red.pseudo-hover.pseudo-focus"
)
expect(sheet.cssRules[0].selectorText).toContain(
".pseudo-hover.pseudo-focus .focus:hover:border-red"
)
})
})
13 changes: 10 additions & 3 deletions src/preview/rewriteStyleSheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ import { splitSelectors } from "./splitSelectors"

const pseudoStates = Object.values(PSEUDO_STATES)
const matchOne = new RegExp(`:(${pseudoStates.join("|")})`)
const matchAll = new RegExp(`:(${pseudoStates.join("|")})`, "g")

const getMatcherAll = (state: string | null = null) => {
if (!state) {
state = pseudoStates.join("|")
}

return new RegExp(`:(${state})(?=(?::(${pseudoStates.join("|")}))*$|\\\))`, "g")
}

const warnings = new Set()
const warnOnce = (message: string) => {
Expand All @@ -29,13 +36,13 @@ const rewriteRule = ({ cssText, selectorText }: CSSStyleRule, shadowRoot?: Shado
}

const states: string[] = []
const plainSelector = selector.replace(matchAll, (_, state) => {
const plainSelector = selector.replace(getMatcherAll(), (_, state) => {
states.push(state)
return ""
})
const classSelector = states.reduce((acc, state) => {
if (isExcludedPseudoElement(selector, state)) return ""
return acc.replace(new RegExp(`:${state}`, "g"), `.pseudo-${state}`)
return acc.replace(getMatcherAll(state), `.pseudo-${state}`)
}, selector)

if (selector.startsWith(":host(") || selector.startsWith("::slotted(")) {
Expand Down