WICG / webcomponents

Web Components specifications
Other
4.38k stars 375 forks source link

Cascading Style Sheet module scripts #759

Closed justinfagnani closed 2 years ago

justinfagnani commented 6 years ago

In addition to HTML Modules, the ability to load CSS into a component definition is an important capability that we're currently lacking. Loading CSS is probably a more important use case judging by the popularity of CSS loaders in JavaScript bundlers.

Currently, styles are usually either defined inline with HTML templating or JSX or loaded with various JS Bundler CSS Loaders. The CSS loaders often have global side-effects like appending a <style> tag to the document, which does not generally work well with the style scoping of Shadow DOM.

I propose that we add Cascading Style Sheet module scripts to the platform, allowing CSS to be imported directly by JavaScript:

import styles from './styles.css';

Exports

The semantics for Cascading Style Sheet module scripts can be very simple, and combined with Constructable Stylesheets allow the importer to determine how the CSS should be applied to the document.

To start with, the only export of a Cascading Style Sheet module script would be a default export of the CSSStyleSheet object. This can then simply be added to document.styles or shadowRoot.styles:

import styles from './styles.css';

class MyElement extends HTMLElement {
  constructor() {
    this.attachShadow({mode: open});
    this.shadowRoot.adoptedStyleSheets = [styles];
  }
}

Additional Features

Other userland CSS module systems often have more features, like the ability to import or export symbols that are defined in the module. ie:

import (LitElement, html} from 'lit-element';
import styles from './styles.css';

class MyElement extends LitElement {
  constructor() {
    this.attachShadow({mode: open});
    this.shadowRoot.adoptedStyleSheets = [styles];
  }

  render() {
    return html`<div class=${styles.classes.exampleClass}></div>`;
  }
}

These features may be very useful, but they can be considered for addition to the CSSOM itself so that they're exposed on CSSStyleSheet and available to both Cascading Style Sheet module scripts and styles loaded via <style> and <link> tags, or constructed from a string.

Polyfilling

It's not easy to polyfill a new module type, but build-time tools can create JavaScript modules that adhere to the Cascading Style Sheet module script interface.

.exampleClass {
  color: red;
}

Can be compiled to:

// create a container and scope to hold a style sheet:
const container = document.createElement('div');
const shadowRoot = container.attachShadow({mode: 'open'});

// create a <style> element to add css text to
let styleElement = document.createElement('style');

// add the styles
styleElement.textContent = String.raw`
.exampleClass {
  color: red;
}
`;

// add the <style> to the document so it creates a StyleSheet
shadowRoot.appendChild(styleElement);

const stylesheet = styleElement.sheet;
export default stylesheet;

edit: updated to the actually Constructible StyleSheet API. edit: updated to refer to the feature by "Cascading Style Sheet module script"

justinfagnani commented 6 years ago

To clarify that this would be useful for non-Shadow DOM use cases, especially for those who aren't familiar with the Constructible StyleSheet Objects proposal, here's how you would implement the side-effectful style of loading common today:

import styles from './styles.css';
document.adoptedStyleSheets = [...document.adoptedStyleSheets, styles];

Modules that currently use CSS loaders that write to global styles would just have to add the document.adoptedStyleSheets = [...document.adoptedStyleSheets, styles] statement so rigger the side-effect.

Loaders that modify selectors could still work at build time, or runtime with a call to mutate the stylesheet:

import styles from './styles.css';
import 'styleScoper' from 'x-style-scoper';

// extract original class names, and rewrite class names in the StyleSheet
const classNames = styleScoper(styles);
document.adoptedStyleSheets = [...document.adoptedStyleSheets, styles];

// Use the rewritten class names
`<div class="${classNames.exampleClass}"></div>`

edit: updated to use current Constructible Stylesheets API

annevk commented 6 years ago

cc @tabatkins

tabatkins commented 6 years ago

So the idea is just that the browser would recognize .css files (or text/css files, something like that) and automatically parse and stuff them into a CSSStyleSheet object for you?

justinfagnani commented 6 years ago

@tabatkins yep. Though it'd be triggered off the mime-type, as I think WASM modules are proposed to do. (edit: uh, yes, you already said text/css :) )

I think this should be pretty simple. One question I didn't list is when to resolve the CSS Module in the presence of @import, and what to do with errors in loading @imports. I think you have similar open questions with Constructible StyleSheets.

calebdwilliams commented 6 years ago

I like this as a feature, but would mean that files containing custom elements must have a common structure in order to be reused (the path to './styles' will not always be consistent if the component is really being reused across apps). I do think this is needed, but would prefer a different entry point to add the styles such that any given file could simply export it's class and be consumed in another which would add the styles (I won't go into my thoughts on #468, but the custom element init object seems to make a lot of sense) so that the consumer of the component can point to the right files and the right structure for their app.

justinfagnani commented 6 years ago

the path to './styles' will not always be consistent if the component is really being reused across apps

I don't quite understand this. The import specifier is a URL like any other import, and can be a relative or absolute URL to a file anywhere a JS module could be. There won't need to be any additional conventions that I can see.

calebdwilliams commented 6 years ago

Right, but two different apps using the same component will need similar structures or to change the component file's code for their app. If I publish a component through NPM and it's consumed by one app that way and another pulls from GitHub, but has different locations for scripts/CSS, there might be issues. Ultimately it's not that big of a deal, but something that should be considered.

matthewp commented 6 years ago

I don't think there's anything to consider in this proposal. Component distribution is another issue entirely, one that might be solved by webpackage or something else. For the time being we can only distribute components as multiple files. In which case if someone hands you a JS script and a CSS module as siblings you should not be under the impression that you can then split those up in different locations on your server.

AshleyScirra commented 6 years ago

This could probably be implemented as a JS library if we had a more generic way to hook in to import. See https://github.com/AshleyScirra/import-as-and-html-modules for a POC which covers importing styles.

matthewp commented 6 years ago

@AshleyScirra I think that idea is interesting but probably has a lot more discussion needed before it's ready. I see a number of problems with it as is. For example, what exactly is the Type? In some cases it seems to be an existing global object and others something new. Is SelectorAll going to be a new global? Would it have a purpose outside of this use case? And what happens if the global doesn't exist? If do import something from "./foo.txt" as NotExists; do I get a ReferenceError at parse time or what exactly? What about the imported value, is it expected to always be an instanceof the Type? Does this preclude having named exports then? What's the relation to this idea vs. some service worker approach?

Not trying to downplay your work, it's an interesting approach and I like the simplicity of using a symbol. Having observed what happened with previous attempts at defining loader hooks I would really hope browser vendors don't pass on a chance at implementing a simple and practical solution such as the CSS module idea from this issue in favor of waiting on something more generic, but much more complex.

AshleyScirra commented 6 years ago

For example, what exactly is the Type?

It's any object that has a Symbol.importer property. They are all library-implemented, they don't have to be "real" types. This should answer most of your questions (e.g. no new globals; nothing to do with instanceof; etc).

justinfagnani commented 6 years ago

@AshleyScirra I think we should collect discussion of a more generic "import as" mechanism in it's own issue. I like the idea, but I think there's a place for extensible loading and several built-in module types other than just JavaScript. Browsers natively understand (including prescanning and parsing) JS, HTML and CSS. It makes sense for the module system to understand them as well.

jhnns commented 6 years ago

Regarding the import as proposal:

It doesn't belong to this particular discussion, but I think the question arises naturally when you're discussing about a way to import other things into JS. We (the webpack team) already had a long discussion when we tried to streamline this with browserify. It's kind of limiting if the platform defines how these assets are imported. In the long run, I'd really appreciate if there was a way to import assets into JS while allowing the importer to define the how. Kudos to @AshleyScirra 👏

Regarding this proposal:

However, it still makes sense to define a sensible default behavior for common things like importing CSS. It also helps us to get a better understanding of the domain and maybe also helps to speed up the development of these generic import proposals.

I really like @justinfagnani 's proposal because it doesn't introduce new concepts. It looks very consistent with other parts of the web components API, like the shadowRoot.

Speaking as an application developer, it would be very useful to have a way to reference CSS class names from JavaScript. This makes it easier for bundlers and other tools to statically analyze the usage of class names. It allows them to remove unused class names. I think this makes current CSS-in-JS solutions like styled-components and the CSS modules project so appealing: it just plays well with existing tools because it makes it statically analyzable. It also makes things like Sass and Less obsolete as we can use JavaScript for that.

There is also a different approach:

Instead of standardizing CSS module imports, we could also make the CSSOM better approachable from the JS-side. The Constructable Stylesheet Objects proposal is a step in the right direction.

Consider we'd allow the developer to write code like this:

import uuid from "uuid";
import {regularPadding} from "../styles/paddings.js";
import {regularMargin} from "../styles/margins.js";
import {modularScale} from "../styles/typography.js";

const hamsterImage = new URL("../hamsters.jpg", import.meta.url);

export const modal = `modal-${uuid}`;
export const header = `header-${uuid}`;

export default CSSStyleSheet.parse`
.${modal} {
    background-image: url(${hamsterImage});
    padding: ${regularPadding};
}

.${header} {
    font-size: ${modularScale(2)};
}

.${modal} > ${header}:not(:last-child) {
    margin-bottom: ${regularMargin};
}
`;

Inside the component, you'd do:

import (LitElement, html} from "lit-element";
import styles, {modal, header} from "./styles.js";

class MyElement extends LitElement {
    constructor() {
        this.attachShadow({mode: open});
        this.shadowRoot.moreStyleSheets.push(styles); // push() doesn't actually exist yet
    }

    render() {
        return html`<section class="${modal}">
        <h1 class="${header}">
            This is a modal
        </h1>
    </section>`;
    }
}

You could also put everything into one file, leaving that decision up to the developer.

With that approach, we wouldn't need to standardize this and still had all the flexibility the ecosystem needs. Tools like bundlers are already able to analyze that code. They could even remove styles that are not used anymore (also this is a more complex operation with my example).

The developer could also decide to wrap the class names with a library:

import className from "some-library";

export const modal = className("modal");

This allows the library to track all used class names during render. This is how other CSS-in-JS libraries enable developers to include the critical styles on server render. Of course, this approach has several caveats, but the point is that this is all solvable in userland without specification.

rakina commented 6 years ago

One of the things to be noted about using imported stylesheets is document.adoptedStyleSheets and shadowRoot.adoptedStyleSheets (previously moreStyleSheets) can only accept CSSStyleSheets that belong to the same document tree (see https://github.com/WICG/construct-stylesheets/issues/23), and in constructed stylesheets, the url of the stylesheet is the url of the document it is constructed on (https://github.com/WICG/construct-stylesheets/issues/10).

So my question is, what should be the document and url of an imported stylesheet?

annevk commented 6 years ago

@TakayoshiKochi it would help if you could elaborate on how you reached the single-document conclusion. If we allow reuse across shadow trees it seems reuse across documents isn't necessarily problematic either.

There is some state obtained from the document I suppose (e.g., quirks, fallback encoding), but we could simply set those to no-quirks and UTF-8 for these new style sheets.

annevk commented 6 years ago

(The URL of an imported style sheet should be the (eventual) response URL btw.)

rakina commented 6 years ago

@annevk I think there was also a problem with which fetch groups the stylesheet will be in if it's constructed in one Document and used in another (see https://github.com/WICG/construct-stylesheets/issues/15)

annevk commented 6 years ago

Hmm yeah, it'd be nice if we had those formally defined. It seems in this case it should reuse the fetch group used by the JavaScript module.

annevk commented 6 years ago

It does seem that ownerNode would also be problematic, so not being 1:1 with documents might have a lot of gotchas that would need to be thought through. Having said that, ownerNode would also be problematic for reuse across shadow roots?

rakina commented 6 years ago

It does seem that ownerNode would also be problematic, so not being 1:1 with documents might have a lot of gotchas that would need to be thought through. Having said that, ownerNode would also be problematic for reuse across shadow roots?

In the case of constructed stylesheets, the ownerNode is null and we have not encountered any problems yet with reusing it across shadow roots, as long as it is in the same document tree.

For imported stylesheets, what if we do this: ownerNode to null, and it can only be used in the document tree where the script is run on.

annevk commented 6 years ago

It sounds reasonable, except I'd still like to see justification for the document restriction.

rakina commented 6 years ago

It sounds reasonable, except I'd still like to see justification for the document restriction.

Oh, sorry - I misunderstood your previous comments. I'm actually not quite familiar with fetch groups (do you know where can I look for background reading? I tried looking for the specs but no luck...)

But if the imported stylesheet can just reuse the fetch group used by the JavaScript module then that sounds fine to me to make it usable in many document trees. For constructed stylesheet case, let's continue discussion on https://github.com/WICG/construct-stylesheets/issues/15.

annevk commented 6 years ago

@rakina now it's my turn to apologize. The high-level concept is documented at https://fetch.spec.whatwg.org/#fetch-groups, but it requires integration with HTML and that isn't done. It's effectively a collection of all fetches a document/global is responsible for so they can be managed together in case the document/global goes away (e.g., a tab is closed). In Gecko this is called a "load group". I suspect Chromium has a similar concept.

rakina commented 6 years ago

@annevk Thank you for the explanation!! From the spec I'm not so sure which things have their own fetch groups and how fetch records might interact with each another.

From @bzbarsky's first comment in https://github.com/WICG/construct-stylesheets/issues/15,

As a concrete question, if I create a sheet from document A's window, and am using it in documents B and C, and B matches a rule with one background image while C matches a rule with another, which load events, if any, are blocked by the resulting image loads.

Will that be a problem too if we end up using the JavaScript module's fetch group? If not, then can we also apply similarly to constructable stylesheet's case?

annevk commented 6 years ago

That's not a problem, it's a question illustrating that if you don't define the fetch group it's unclear what the answer is. (The answer might also be somewhat unclear since not all user agents might consider images referenced from style sheets critical subresources (see the HTML Standard).)

CarterLi commented 6 years ago

I didn't read all the replies above, but for

import styles from './styles.css';

it can be easily implemented by server side, because browsers only recognize file types using its Content-Type ( aka MIME ) regardless of its file extension.

I did this before:

// node
const handleTypes = {
  css(content: string, request: http.ServerRequest, response: http.ServerResponse) {
    if (request.headers.accept.startsWith('text/css')) {
      // <link rel="stylesheet" href="/path/to/file.css" />
      response.writeHead(200, { 'Content-Type': 'text/css' });
      return content;
    }
    // import '/path/to/file.css';
    response.writeHead(200, { 'Content-Type': 'application/javascript' });
    return 'document.head.insertAdjacentHTML("beforeEnd", `<style>' + content + '</style>`)'; // or create a style element and `export default`
  },
}
justinfagnani commented 6 years ago

@CarterLi that's interesting, but we'd first have to get browsers to send an Accept header other than */* for imports.

CarterLi commented 6 years ago

@CarterLi that's interesting, but we'd first have to get browsers to send an Accept header other than / for imports.

What about writing import styles from "./style.cssm" or import styles from "./style.css?module"

justinfagnani commented 6 years ago

What about writing import styles from "./style.cssm" or import styles from "./style.css?module"

I don't understand the question.

Right now browsers only send Accept: */* for requests from imports. That'll need to change if servers are going to send .css vs .css.js depending on browser support.

CarterLi commented 6 years ago

What about writing import styles from "./style.cssm" or import styles from "./style.css?module"

I don't understand the question.

Right browsers only send Accept: */* for requests from imports. That'll need to change if servers are going to send .css vs .css.js depending on browser support.

Yes browsers only send Accept: */* for requests from imports, but they still send Accept: text/css for requests from <link rel="stylesheet">. Servers can decide what to send depending on what the Accept header is.

What I mean is that if you don't like Accept: */*, you can send request like style.cssm ( m means module ). Servers can decide what to send based on its file extension.

developit commented 5 years ago

Could polyfill via ServiceWorker too, or import maps (though awkward).

I'm mostly here to drop a firm +1 on the idea. I threw a proposal together that turned out to be exactly what Justin is pushing for here, just using the current version of Constructable Stylesheets.

import sheet from './style.css';

// global CSS:
document.adoptedStyleSheets = [sheet];

const node = document.createElement('div');
const shadow = node.attachShadow({ mode: 'open' });
// scoped CSS:
shadow.adoptedStyleSheets = [sheet];

// Updates! (propagates out to all affected trees)
sheet.insertRule('.foo { color: red; }');

// "hot CSS replacement": (to be taken with healthy dose of salt)
module.hot.accept('style.css', req => {
  sheet.replace(req('style.css'));
});
developit commented 5 years ago

Update: here's a prototype that abuses Service Worker to rewrite import "*.css" to use constructable stylesheets (and a poorlyfill for the latter API):

https://codesandbox.io/s/xrr68044ww

Rich-Harris commented 5 years ago

Just got directed towards this proposal. Overall I like it; it fills an important gap in the platform, and anything that allows us to avoid storing things that aren't JavaScript inside JavaScript files is a good thing.

I am concerned about the one-stylesheet-per-file thing though. With JavaScript modules, we can optimise apps by concatenating them into coarse-grained code-split chunks, which generally results in better performance than serving many small modules. It stands to reason that the performance considerations are similar for CSS modules, but as far as I can tell it's not possible to 'concatenate' multiple .css files under this proposal. I've drawn up a gist explaining what I mean in more detail.

domenic commented 5 years ago

The current proposal for allowing "concatenation", not just of CSS but of other file types as well, is https://github.com/WICG/webpackage.

justinfagnani commented 5 years ago

As a possible layering on modules, I wrote up an issue for CSS "references": https://github.com/w3c/csswg-drafts/issues/3714

They would serve some of the same purposes as exporting class names.

chanar commented 5 years ago

https://github.com/chanar/lit-scss-vaadin

// Import the LitElement base class and html helper function
import { LitElement, html } from 'lit-element';
import '@vaadin/vaadin-button/vaadin-button.js';

import styles from './my-element.scss';

// Extend the LitElement base class
class MyElement extends LitElement {
  static get properties() {
    return {
      prop1: { type: String }
    };
  }

  render() {
    return html`
      <style>
        ${styles}
      </style>

      <div class="wrap">
        <vaadin-button theme="primary your-custom-overwrite" @click="${this.fireClickEvent}">
          <slot></slot>
        </vaadin-button>
      </div>
    `;
  }

  fireClickEvent() {
    alert('Yesss!!');

    this.prop1 = 'prop1 now has a value';
  }
}

// Register the new element with the browser.
customElements.define('my-element', MyElement);
dandclark commented 5 years ago

A question that I don't see resolved in this thread is whether CSS modules should be leaf nodes in the module graph. That is to say, how do we handle @import url("foo.css") in a CSS module? I see three possibilities:

  1. CSS Modules are leaf modules, and don't allow @import references (following the example of replaceSync in constructable stylesheets). module.
  2. CSS modules are leaf modules; prior to creating the module record for a CSS module, load the full @import tree of its stylesheet and if any fail to resolve, treat it as a parse error for the module.
  3. CSS Modules are non-leaf (cyclic) modules. Process a CSS Module's @imported stylesheets as its requested module children in the module graph, with their own module records. They will Instantiate and Evaluate as distinct modules.

I don't think we want to do option 1 as that seems too restrictive. One of the main differences I see between options 2 and 3 is that 3 implies that if a CSS file is @imported multiple times for a given realm, each import would share a single CSSStyleSheet between them (because a module is only instantiated/evaluated once for a given module specifier). This has the advantage that if a developer includes a stylesheet multiple times by mistake or because of shared CSS dependencies, there will be performance and memory gains in sharing it. On the other hand, this is a divergence from the existing behavior where multiple @imports of the same .css file each come with their own CSSStyleSheet. I'm not sure how developers count on the existing behavior and whether it would be disruptive to make CSS modules work differently.

Performance-wise I don't think there is much difference between 2 and 3 (other than from only evaluating redundant @imports once). In both cases, we can fetch all the CSS files (and the rest of the module graph) in parallel, and we can't move on to graph Instantiation until all the CSS files (and other modules) are fetched.

Does anyone have thoughts on this? Any other considerations I'm missing?

tabatkins commented 5 years ago

I think this should go with behavior 2, as that's the behavior you'd get if, instead of using import, you just ran fetch("foo.css").then(r=>{const s = new CSSStyleSheet(); return s.replace(r.text);});. It also causes the minimal changes to the normal mechanics of nested stylesheets, with each @import rule continuing to get its own unique stylesheet object.

matthewp commented 5 years ago

I'm a developer and not an implementer, I would prefer option 3. Not being able to declare dependencies of a stylesheet is one of the big reasons people use preprocessors. I'd be fine with a new syntax for the module case if that's preferable from an implementation perspective though.

bzbarsky commented 5 years ago

there will be performance and memory gains in sharing it

Note that at least Gecko already coalesces multiple loads of the same stylesheet into doing a single load+parse, and has a single copy-on-write data structure with all the actual information backing multiple very small CSSStyleSheet objects. So the gains here would be much smaller than one would think.

@matthewp I'd like to understand the issue you raise about dependencies better. What are people trying to do that the current @import syntax/semantics do not allow but option 3 would allow?

matthewp commented 5 years ago

@bzbarsky A CSS module might @import a dependency and override one of its selectors. Another CSS module might then @import that same dependency, thus reapplying the styles and overriding the changes that Module A made. To fix this Module B must remove its @import to prevent it from happening. Thus it can't express its own dependency because of the effect it has on others.

bzbarsky commented 5 years ago

@matthewp So just to make sure I understand, we have three sheets: A, B, C. B and C both import A. B contains a selector with the same specificity as a selector in A, but B's selector wins out because of the "order specified" rule in https://www.w3.org/TR/CSS21/cascade.html#cascading-order step 4 or equivalent in later CSS specs. C comes after B in the declaration order, so the version of A imported by C ends up winning out over B. Is that the situation we're trying to address?

It's not clear to me how the "order specified" would even be defined in the option 3 case, and hence whether it would avoid this problem....

bzbarsky commented 5 years ago

I was under the impression that A would be applied once, before B, and not reapplied when C imports it

Are we assuming that there's a single toplevel module import that ends up including both B and C, or are they separate toplevel module imports?

It's really not clear to me what this proposal envisions in general for how the nonlinear module graph maps onto the linear cascade. I guess for options 1 and 2 this is not an issue, because the module subgraph for any given CSS module is in fact just one node and that hands back a CSSStyleSheet; after that ordering in the cascade is just determined by where you place that CSSStyleSheet and existing cascading rules. For option 3, it's not really clear to me what the proposal is. If A and B are imported as separate modules, then B is inserted in a sheet list, then A is inserted, what happens? What if the order of insertions is reversed?

matthewp commented 5 years ago

@bzbarsky That is the correct scenario yes. I might be misunderstanding option 3 in that case. I was expecting there not to be 2 versions of A in option 3, only 1 that is applied before B (and not reapplied by C).

bzbarsky commented 5 years ago

@matthewp There's one version of A, sure. But note that the proposal is to just return a CSSStyleSheet, not apply anything. So say the sheets for both B and C (as separate modules) are returned, then the one for C is inserted into a sheet list, so C should start applying. Does that make A start applying? Note that B is not applying at this point. If B later starts applying, what changes? Does it depend on how B is ordered with respect to C?

justinfagnani commented 5 years ago

With my user hat on, I think option 3 is preferable because it maps to the module loader behavior better.

This has the advantage that if a developer includes a stylesheet multiple times by mistake or because of shared CSS dependencies, there will be performance and memory gains in sharing it. On the other hand, this is a divergence from the existing behavior where multiple @imports of the same .css file each come with their own CSSStyleSheet.

This is analogous to JS Modules as well. import has the advantage that when a module is imported multiple times there's only one module instance. JS Modules also have a divergence from scripts, where multiple script tags (which happens easier than one might think with dynamic loaders) load a script multiple times.

dandclark commented 5 years ago

@matthewp , @bzbarsky Option 2 vs 3 would not behave differently in terms of the the styles that are applied. The difference is just whether a doubly-@imported stylesheet in a CSS module tree would have distinct identities for each time that it is @imported (as is the case for non-module CSS), or whether each @import of the same stylesheet in a CSS module tree would point to the same CSSStyleSheet object. I suppose that the order in which CSS files are fetched could be affected by whether @imports are modules or not but this is more of an implementation detail as that doesn't change the form of the final cascade and CSS OM.

I think it would be helpful to write out the example being discussed above as code:

a.css:

div { background-color: azure }

b.css:

@import url("a.css");
div { background-color: brown }

c.css:

@import url("a.css");
div { background-color: chartreuse }

main.html:

<style>
  @import url("b.css");
  @import url("c.css");
</style>
<div>This div will be chartreuse</div>
<script>
  let style = document.querySelector("style");
  let bSheet = style.sheet.rules[0].styleSheet;
  let cSheet = style.sheet.rules[1].styleSheet;
  let aSheetFromBSheet = bSheet.rules[0].styleSheet;
  let aSheetFromCSheet = cSheet.rules[0].styleSheet;
  console.log(`${aSheetFromBSheet === aSheetFromCSheet}`); // Prints 'false'; duplicate @imports have their own identities
</script>

mainUsingCSSModules.html

<script type="module">
  import bSheet from "./b.css";
  import cSheet from "./c.css";

  document.adoptedStyleSheets = [bSheet, cSheet];

  let aSheetFromBSheet = bSheet.rules[0].styleSheet;
  let aSheetFromCSheet = cSheet.rules[0].styleSheet;
  console.log(`${aSheetFromBSheet === aSheetFromCSheet}`); // Prints 'false' if option 2, 'true' if option 3
</script>
<div>This div will be chartreuse</div>

For mainUsingCSSModule.html, the resulting cascade is mostly the same regardless of whether we go with option 2 or option 3. The difference is that for option 3, a single CSSStyleSheet is shared by the @import from B and the @import from C since "a.css" would participate in the module graph and thus be processed only once for the page. As @justinfagnani pointed out this is similar to JS modules where multiple imports of a single script share one instance.

However, option 3 may come with certain other complications that we would need to contend with. For example, what is the parentStyleSheet and the ownerRule of aSheetFromBSheet/aSheetFromCSheet if they are the same CSSStyleSheet? I'm not sure that this divergence from existing invariants is worth it, especially since as @bzbarsky pointed out here, browser engines should generally coalesce duplicate stylesheet loads anyway, minimizing the additional performance wins that would come with option 3. Is there some concrete improvement in developer experience that option 3 would provide that would tip the scale in its direction?

justinfagnani commented 5 years ago

However, option 3 may come with certain other complications that we would need to contend with. For example, what is the parentStyleSheet and the ownerRule of aSheetFromBSheet/aSheetFromCSheet if they are the same CSSStyleSheet?

Much like document.currentScript is set to null for modules, parentStyleSheet and ownerRule can be null for CSS modules.

Is there some concrete improvement in developer experience that option 3 would provide that would tip the scale in its direction?

It think that the equivalence to the behavior to the module loader is important in an of itself. Consider these two ways to load CSS modules base.css, element.css, into a JS module element.js:

Variant 1: using @import

base.css

...

element.css:

@import 'base.css';
...

element.js:

import styles from './element.css';
class Element1 extends HTMLElement {
  constructor() {
    this.attachShadow().adoptedStyleshets = [styles];
  }
}

Variant 2: direct import into JS

base.css

...

element-1.css:

...

element.js:

import baseStyles from './base.css';
import elementStyles from './element.css';
class Element1 extends HTMLElement {
  constructor() {
    this.attachShadow().adoptedStyleshets = [baseStyles, elementStyles];
  }
}

I think these two should be equivalent in terms of the modules that they instantiate, but if you extend the example to multiple JS modules, you'll get a difference where Variant 1 creates N CSSStyleSheet objects for base.css and Variant 2 creates only 1.

The difference is user observable if you're trying to dynamically edit styles, like a visual editor might do:

element.js:

import baseStyles from './base.css';
import elementStyles from './element.css';

makeBackgroundDark() {
  baseStyles.cssRules[0].styleMap.set('background-color', 'gray');
}

This only has global effect if we choose option 3, otherwise the developer has to avoid @import.

Yes, there are better ways to dynamically update a single or few properties, like custom variables, but there are cases where a tool will want to edit CSS, or a theming system will want to replace an entire shared stylesheet.

tabatkins commented 5 years ago

With my user hat on, I think option 3 is preferable because it maps to the module loader behavior better.

If we assume that CSS's @import rule is directly analogous to the JS import statement. Today it's definitely not; linking in a stylesheet multiple times does fresh requests for each of its @import rules and constructs independent CSSStyleSheet object for them.

This would be changing the behavior of @import in a way that can't be reproduced manually; there's no way to cause two stylesheets to share a single child stylesheet with the CSSOM as it stands.

This is analogous to JS Modules as well. import has the advantage that when a module is imported multiple times there's only one module instance.

JS and CSS have significant divergences here:

Can you explain any particular advantage that having imported stylesheets sharing an @imported stylesheet would provide?

Much like document.currentScript is set to null for modules, parentStyleSheet and ownerRule can be null for CSS modules.

The question was what the .parentStyleSheet and .ownerRule would be for the @imported sheet, if it's shared between two imported sheets. That probably shouldn't be null, but it can't correctly be just one of the two sheets.


All in all, it looks like Option 3 (treat @import like a JS import, deduping same-url imports) would give us a brand new behavior for nested stylesheets which cannot be reproduced by hand, and would also have some awkward interactions with the existing CSSOM APIs which expect a tree structure with two-way links. I've come to strongly feel that Option 3 is definitely the wrong choice, and that we should be using Option 2 (the "import "foo.css" just fetches the sheet and constructs a CSSStyleSheet from its text" option).

justinfagnani commented 5 years ago

linking in a stylesheet multiple times does fresh requests for each of its @import rules

Is this always true? Didn't @bzbarsky just say that Firefox doesn't do this?

If this should always be true, then it seems like a big knock against @import in CSS modules. You wouldn't want a bunch of CSS modules to ever @import a common stylesheet because you'd cause multiple fetches. Imagine 100 components that import 100 different component-specific CSS modules that each @import a few common stylesheets. That's a few 100 extra fetches.

Maybe we should disallow @import in that case, and treat CSS modules as if the called replaceSync? It wouldn't seem to behave how developers using modules would expect otherwise.

JS commonly shares mutable global state across a module, and having multiple instances use the same state is usually what you want, while CSS has virtually no stylesheet-global state

Isn't the stylesheet itself the stylesheet-global state?

Can you explain any particular advantage that having imported stylesheets sharing an @imported stylesheet would provide?

I thought I did with the base.css example - mutating a common stylesheet object seems like a reasonable way to switch themes across ShadowRoots. It's the only way I can see that doesn't involve getting every component to opt into some out-of-band system, in addition to loading a base CSS module.

Let's frame the example another way:

theme.js

import styles from './base.css';

export function switchTheme(url) {
  styles.replace(await (await fetch(url)).text()));
}

element.css

@import './base.css';

element.js

import styles from './element.css';

class MyElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow().adoptedStylesheet = [styles];
  }
}

It would be great if this worked. And not just for theme switching in an app, but for visual design tools and IDEs with live previews. Otherwise it does seem to discourage use of @import, which would be bad because there's no other way to have CSS modules load dependencies.