Skip to content

Commit

Permalink
feat: new attribute scope style strategy (#7893)
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico authored Aug 8, 2023
1 parent ba73dea commit 7bd1b86
Show file tree
Hide file tree
Showing 9 changed files with 101 additions and 29 deletions.
17 changes: 17 additions & 0 deletions .changeset/neat-suns-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'astro': major
---

Implements a new scope style strategy called `"attribute"`. When enabled, styles are applied using `data-*` attributes.

The **default** value of `scopedStyleStrategy` is `"attribute"`.

If you want to use the previous behaviour, you have to use the `"where"` option:

```diff
import { defineConfig } from 'astro/config';

export default defineConfig({
+ scopedStyleStrategy: 'where',
});
```
2 changes: 1 addition & 1 deletion packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@
"test:e2e:match": "playwright test -g"
},
"dependencies": {
"@astrojs/compiler": "^1.8.0",
"@astrojs/compiler": "^1.8.1",
"@astrojs/internal-helpers": "workspace:*",
"@astrojs/markdown-remark": "workspace:*",
"@astrojs/telemetry": "workspace:*",
Expand Down
13 changes: 8 additions & 5 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ import type { AstroConfigSchema } from '../core/config';
import type { AstroTimer } from '../core/config/timer';
import type { AstroCookies } from '../core/cookies';
import type { LogOptions, LoggerLevel } from '../core/logger/core';
import { AstroIntegrationLogger } from '../core/logger/core';
import type { AstroIntegrationLogger } from '../core/logger/core';
import type { AstroComponentFactory, AstroComponentInstance } from '../runtime/server';
import type { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from './../core/constants.js';

export type {
MarkdownHeading,
MarkdownMetadata,
Expand Down Expand Up @@ -609,19 +610,21 @@ export interface AstroUserConfig {
/**
* @docs
* @name scopedStyleStrategy
* @type {('where' | 'class')}
* @type {('where' | 'class' | 'attribute')}
* @default `'where'`
* @version 2.4
* @description
*
* Specify the strategy used for scoping styles within Astro components. Choose from:
* - `'where'` - Use `:where` selectors, causing no specifity increase.
* - `'class'` - Use class-based selectors, causing a +1 specifity increase.
* - `'where'` - Use `:where` selectors, causing no specifity increase.
* - `'class'` - Use class-based selectors, causing a +1 specifity increase.
* - `'attribute'` - Use `data-` attributes, causing no specifity increase.
*
* Using `'class'` is helpful when you want to ensure that element selectors within an Astro component override global style defaults (e.g. from a global stylesheet).
* Using `'where'` gives you more control over specifity, but requires that you use higher-specifity selectors, layers, and other tools to control which selectors are applied.
* Using `'attribute'` is useful in case there's manipulation of the class attributes, so the styling emitted by Astro doesn't go in conflict with the user's business logic.
*/
scopedStyleStrategy?: 'where' | 'class';
scopedStyleStrategy?: 'where' | 'class' | 'attribute';

/**
* @docs
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ export const AstroConfigSchema = z.object({
.optional()
.default('static'),
scopedStyleStrategy: z
.union([z.literal('where'), z.literal('class')])
.union([z.literal('where'), z.literal('class'), z.literal('attribute')])
.optional()
.default('where'),
.default('attribute'),
adapter: z.object({ name: z.string(), hooks: z.object({}).passthrough().default({}) }).optional(),
integrations: z.preprocess(
// preprocess
Expand Down
42 changes: 29 additions & 13 deletions packages/astro/test/0-css.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,27 @@ describe('CSS', function () {
it('HTML and CSS scoped correctly', async () => {
const el1 = $('#dynamic-class');
const el2 = $('#dynamic-vis');
const classes = $('#class').attr('class').split(' ');
const scopedClass = classes.find((name) => /^astro-[A-Za-z0-9-]+/.test(name));
const classes = $('#class');
let scopedAttribute;
for (const [key] of Object.entries(classes[0].attribs)) {
if (/^data-astro-cid-[A-Za-z0-9-]+/.test(key)) {
// Ema: this is ugly, but for reasons that I don't want to explore, cheerio
// lower case the hash of the attribute
scopedAttribute = key
.toUpperCase()
.replace('data-astro-cid-'.toUpperCase(), 'data-astro-cid-');
}
}
if (!scopedAttribute) {
throw new Error("Couldn't find scoped attribute");
}

// 1. check HTML
expect(el1.attr('class')).to.equal(`blue ${scopedClass}`);
expect(el2.attr('class')).to.equal(`visible ${scopedClass}`);
expect(el1.attr('class')).to.equal(`blue`);
expect(el2.attr('class')).to.equal(`visible`);

// 2. check CSS
const expected = `.blue:where(.${scopedClass}){color:#b0e0e6}.color\\:blue:where(.${scopedClass}){color:#b0e0e6}.visible:where(.${scopedClass}){display:block}`;
const expected = `.blue[${scopedAttribute}],.color\\:blue[${scopedAttribute}]{color:#b0e0e6}.visible[${scopedAttribute}]{display:block}`;
expect(bundledCSS).to.include(expected);
});

Expand All @@ -60,8 +72,12 @@ describe('CSS', function () {
expect($('#no-scope').attr('class')).to.equal(undefined);
});

it('Child inheritance', async () => {
expect($('#passed-in').attr('class')).to.match(/outer astro-[A-Z0-9]+ astro-[A-Z0-9]+/);
it('Child inheritance', (done) => {
for (const [key] of Object.entries($('#passed-in')[0].attribs)) {
if (/^data-astro-cid-[A-Za-z0-9-]+/.test(key)) {
done();
}
}
});

it('Using hydrated components adds astro-island styles', async () => {
Expand All @@ -70,11 +86,11 @@ describe('CSS', function () {
});

it('<style lang="sass">', async () => {
expect(bundledCSS).to.match(new RegExp('h1\\:where\\(.astro-[^{]*{color:#90ee90}'));
expect(bundledCSS).to.match(new RegExp('h1\\[data-astro-cid-[^{]*{color:#90ee90}'));
});

it('<style lang="scss">', async () => {
expect(bundledCSS).to.match(new RegExp('h1\\:where\\(.astro-[^{]*{color:#ff69b4}'));
expect(bundledCSS).to.match(new RegExp('h1\\[data-astro-cid-[^{]*{color:#ff69b4}'));
});
});

Expand Down Expand Up @@ -331,10 +347,10 @@ describe('CSS', function () {
it('resolves Astro styles', async () => {
const allInjectedStyles = $('style').text();

expect(allInjectedStyles).to.contain('.linked-css:where(.astro-');
expect(allInjectedStyles).to.contain('.linked-sass:where(.astro-');
expect(allInjectedStyles).to.contain('.linked-scss:where(.astro-');
expect(allInjectedStyles).to.contain('.wrapper:where(.astro-');
expect(allInjectedStyles).to.contain('.linked-css[data-astro-cid-');
expect(allInjectedStyles).to.contain('.linked-sass[data-astro-cid-');
expect(allInjectedStyles).to.contain('.linked-scss[data-astro-cid-');
expect(allInjectedStyles).to.contain('.wrapper[data-astro-cid-');
});

it('resolves Styles from React', async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/test/astro-partial-html.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('Partial HTML', async () => {

// test 2: correct CSS present
const allInjectedStyles = $('style').text();
expect(allInjectedStyles).to.match(/\:where\(\.astro-[^{]+{color:red}/);
expect(allInjectedStyles).to.match(/\[data-astro-cid-[^{]+{color:red}/);
});

it('injects framework styles', async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/test/config-vite-css-target.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('CSS', function () {

it('vite.build.cssTarget is respected', async () => {
expect(bundledCSS).to.match(
new RegExp('.class\\:where\\(.astro-[^{]*{top:0;right:0;bottom:0;left:0}')
new RegExp('.class\\[data-astro-[^{]*{top:0;right:0;bottom:0;left:0}')
);
});
});
Expand Down
34 changes: 33 additions & 1 deletion packages/astro/test/scoped-style-strategy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ import * as cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';

describe('scopedStyleStrategy', () => {
describe('default', () => {
describe('scopedStyleStrategy: "where"', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let stylesheet;

before(async () => {
fixture = await loadFixture({
root: './fixtures/scoped-style-strategy/',
scopedStyleStrategy: 'where',
});
await fixture.build();

Expand Down Expand Up @@ -57,4 +58,35 @@ describe('scopedStyleStrategy', () => {
expect(stylesheet).to.match(/h1\.astro/);
});
});

describe('default', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
let stylesheet;

before(async () => {
fixture = await loadFixture({
root: './fixtures/scoped-style-strategy/',
});
await fixture.build();

const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html);
const $link = $('link[rel=stylesheet]');
const href = $link.attr('href');
stylesheet = await fixture.readFile(href);
});

it('does not include :where pseudo-selector', () => {
expect(stylesheet).to.not.match(/:where/);
});

it('does not include the class name directly in the selector', () => {
expect(stylesheet).to.not.match(/h1\.astro/);
});

it('includes the data attribute hash', () => {
expect(stylesheet).to.include('h1[data-astro-cid-');
});
});
});
14 changes: 9 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 7bd1b86

Please sign in to comment.