Skip to content

Commit

Permalink
Merge pull request #329 from sunesimonsen/ssimonsen/support-media-que…
Browse files Browse the repository at this point in the history
…ries

Support media queries
  • Loading branch information
sunesimonsen committed Jan 18, 2024
2 parents 52a8e34 + b66f929 commit 1144058
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,10 @@ class CSSTemplate {
let result = "";
let close = null;
const tokens = this._content
.split(/(&\([^)]+\)|[:;{}&]|\\?["']|\\)/g)
.split(/(&\([^)]+\)|@media|[:;{}&]|\\?["']|\\)/g)
.filter(Boolean);

let inMediaRule = false;
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];

Expand All @@ -109,6 +110,10 @@ class CSSTemplate {
continue;
}

if (token === "@media") {
inMediaRule = true;
}

if (close) {
if (token === close) {
close = null;
Expand All @@ -117,7 +122,11 @@ class CSSTemplate {
continue;
}

close = pairs[token];
if (inMediaRule && token === "{") {
inMediaRule = false;
} else {
close = pairs[token];
}

if (close) {
result += token;
Expand Down
23 changes: 23 additions & 0 deletions test/index.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,29 @@ describe("css", () => {
);
});

it("supports media queries", () => {
const foo = css`
& {
background: red;
}
@media only screen and (width <= 1000px) {
& {
background: green;
}
}
`;

expect(foo.toString(), "to equal snapshot", "c4212962c");

expect(
document,
"to have CSS satisfying",
"to equal snapshot",
".c4212962c {background: red;}@media only screen and (width <= 1000px) {.c4212962c {background: green;}}",
);
});

it("returns a hash of the content", () => {
const foo = css`
& {
Expand Down

0 comments on commit 1144058

Please sign in to comment.