From 1f13e40316a6f97394c26c942f11e5f8e4633d58 Mon Sep 17 00:00:00 2001 From: Drew Powers <1369770+drwpow@users.noreply.github.com> Date: Mon, 16 Aug 2021 18:47:09 -0500 Subject: [PATCH] Fix body scoping (#1130) Fixes #1074 --- .changeset/calm-walls-unite.md | 5 +++++ .../compiler/transform/postcss-scoped-styles/index.ts | 9 +++++++-- packages/astro/test/astro-scoped-styles.test.js | 1 + 3 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 .changeset/calm-walls-unite.md diff --git a/.changeset/calm-walls-unite.md b/.changeset/calm-walls-unite.md new file mode 100644 index 000000000..a0b3441d3 --- /dev/null +++ b/.changeset/calm-walls-unite.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix CSS scoping issue diff --git a/packages/astro/src/compiler/transform/postcss-scoped-styles/index.ts b/packages/astro/src/compiler/transform/postcss-scoped-styles/index.ts index 7ee20fb6d..82551effa 100644 --- a/packages/astro/src/compiler/transform/postcss-scoped-styles/index.ts +++ b/packages/astro/src/compiler/transform/postcss-scoped-styles/index.ts @@ -1,4 +1,4 @@ -import { Declaration, Plugin } from 'postcss'; +import { Plugin } from 'postcss'; interface AstroScopedOptions { className: string; @@ -13,6 +13,11 @@ interface Selector { const CSS_SEPARATORS = new Set([' ', ',', '+', '>', '~']); const KEYFRAME_PERCENT = /\d+\.?\d*%/; +/** minify selector CSS */ +function minifySelector(selector: string): string { + return selector.replace(/(\r?\n|\s)+/g, ' ').replace(/\s*(,|\+|>|~|\(|\))\s*/g, '$1'); +} + /** HTML tags that should never get scoped classes */ export const NEVER_SCOPED_TAGS = new Set(['base', 'body', 'font', 'frame', 'frameset', 'head', 'html', 'link', 'meta', 'noframes', 'noscript', 'script', 'style', 'title']); /** @@ -101,7 +106,7 @@ export default function astroScopedStyles(options: AstroScopedOptions): Plugin { postcssPlugin: '@astrojs/postcss-scoped-styles', Rule(rule) { if (!rulesScopedCache.has(rule)) { - rule.selector = scopeRule(rule.selector, options.className); + rule.selector = scopeRule(minifySelector(rule.selector), options.className); rulesScopedCache.add(rule); } }, diff --git a/packages/astro/test/astro-scoped-styles.test.js b/packages/astro/test/astro-scoped-styles.test.js index 548386168..dc8cfba5b 100644 --- a/packages/astro/test/astro-scoped-styles.test.js +++ b/packages/astro/test/astro-scoped-styles.test.js @@ -24,6 +24,7 @@ ScopedStyles('Scopes rules correctly', () => { '.class :global(ul li)': `.class.${className} ul li`, // allow doubly-scoped selectors '.class:not(.is-active)': `.class.${className}:not(.is-active)`, // Note: the :not() selector can NOT contain multiple classes, so this is correct; if this causes issues for some people then it‘s worth a discussion 'body h1': `body h1.${className}`, // body shouldn‘t be scoped; it‘s not a component + 'html,body': `html,body`, from: 'from', // ignore keyframe keywords (below) to: 'to', '55%': '55%',