From a915864acd0bb9b1fe4b7986c37f3c269b10eb37 Mon Sep 17 00:00:00 2001 From: Mert Akinc <7282195+m-akinc@users.noreply.github.com> Date: Fri, 9 Feb 2024 18:52:55 -0600 Subject: [PATCH] Avoid generating invalid selector with :has --- src/preview/rewriteStyleSheet.test.ts | 6 ++++++ src/preview/rewriteStyleSheet.ts | 12 ++++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/preview/rewriteStyleSheet.test.ts b/src/preview/rewriteStyleSheet.test.ts index 96e9093..957ae62 100644 --- a/src/preview/rewriteStyleSheet.test.ts +++ b/src/preview/rewriteStyleSheet.test.ts @@ -101,6 +101,12 @@ describe("rewriteStyleSheet", () => { expect(sheet.cssRules[0].cssText).toEqual(":not(:hover), :not(.pseudo-hover) { color: red }") }) + it('supports ":has"', () => { + const sheet = new Sheet(":has(:hover) { color: red }") + rewriteStyleSheet(sheet as any) + expect(sheet.cssRules[0].cssText).toEqual(":has(:hover), :has(.pseudo-hover) { color: red }") + }) + it("override correct rules with media query present", () => { const sheet = new Sheet( `@media (max-width: 790px) { diff --git a/src/preview/rewriteStyleSheet.ts b/src/preview/rewriteStyleSheet.ts index 36f77da..4824f9b 100644 --- a/src/preview/rewriteStyleSheet.ts +++ b/src/preview/rewriteStyleSheet.ts @@ -38,12 +38,12 @@ const rewriteRule = ({ cssText, selectorText }: CSSStyleRule, shadowRoot?: Shado return acc.replace(new RegExp(`:${state}`, "g"), `.pseudo-${state}`) }, selector) - const classAllSelector = states.reduce((acc, state) => { - if (isExcludedPseudoElement(selector, state)) return "" - return acc.replace(new RegExp(`:${state}`, "g"), `.pseudo-${state}-all`) - }, selector) - if (selector.startsWith(":host(") || selector.startsWith("::slotted(")) { + const classAllSelector = states.reduce((acc, state) => { + if (isExcludedPseudoElement(selector, state)) return "" + return acc.replace(new RegExp(`:${state}`, "g"), `.pseudo-${state}-all`) + }, selector) + return [selector, classSelector, classAllSelector].filter(Boolean) } @@ -52,7 +52,7 @@ const rewriteRule = ({ cssText, selectorText }: CSSStyleRule, shadowRoot?: Shado : `${states.map((s) => `.pseudo-${s}-all`).join("")} ${plainSelector}` return [selector, classSelector, ancestorSelector].filter( - (selector) => selector && !selector.includes(":not()") + (selector) => selector && !selector.includes(":not()") && !selector.includes(":has()") ) }) .join(", ")