Skip to content
Merged
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
43 changes: 42 additions & 1 deletion src/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,8 @@ test("includes pseudo elements", () => {
background: green;
}

div ::before {
.test ::before {
content: "";
display: block;
}
`;
Expand All @@ -307,6 +308,10 @@ test("includes pseudo elements", () => {
}}</style>
<span>
<style>@scope{:scope{
&::before {
content: \\"\\";
display: block
}
&::selection {background: blue}
}}</style>
Content
Expand All @@ -315,6 +320,42 @@ test("includes pseudo elements", () => {
`);
});

test("pseudo elements only included when they render", () => {
const html = `
<div class="test"><div class="other">Content</div></div>
`;

const styles = `
.test::before { content: "prefix"; color: blue; }
.test::after { content: ""; color: red; }
.test::selection { background: yellow; }
.test::first-line { font-weight: bold; }

.other::before { display: block; }
.other::after { content: none; color: red; }
`;

expect(testHTML(html, styles)).toMatchInlineSnapshot(`
"<div>
<style>@scope{:scope{
&::after {
color: red;
content: \\"\\"
}
&::before {
color: blue;
content: \\"prefix\\"
}
&::first-line {font-weight: bold}
&::selection {background: yellow}
}}</style>
<div>
Content
</div>
</div>"
`);
});

function testHTML(html: string, styles: string = "") {
const div = document.createElement("div");
const style = document.createElement("style");
Expand Down
20 changes: 19 additions & 1 deletion src/stylesheets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export function getPseudoElementStyles(
name,
stylesByPseudoElement[name]
);
if (styles) {
if (styles && shouldIncludePseudoElement(name, styles)) {
appliedPseudoElementStyles ||= {};
appliedPseudoElementStyles[name] = styles;
}
Expand All @@ -103,6 +103,24 @@ export function getPseudoElementStyles(
return appliedPseudoElementStyles;
}

function shouldIncludePseudoElement(
pseudoName: string,
styles: { [property: string]: string }
): boolean {
if (pseudoName !== "::before" && pseudoName !== "::after") {
// Other pseudo-elements (::selection, ::first-line, etc.) should always be included.
return true;
}

const contentValue = styles.content;

// Pseudo-element renders if:
// - content property exists (not undefined).
// - content: "" (empty string).
// - content is not "none".
return contentValue !== undefined && contentValue !== "none";
}

/**
* Given a stylesheet returns all css rules including rules from
* nested stylesheets such as media queries or supports.
Expand Down
Loading