w3c / csswg-drafts

CSS Working Group Editor Drafts
https://drafts.csswg.org/
Other
4.35k stars 641 forks source link

[css-cascade-5] Add an adoptStyles capability in ShadowRoots (WICG 909: open-stylable Shadow Roots) #10176

Open robglidden opened 3 months ago

robglidden commented 3 months ago

Add an adoptStyles capability in ShadowRoots (WICG 909: open-stylable Shadow Roots)

Table of Contents

This "Shadow Layers" proposal, web platform tests, and polyfill address "open-stylable" Shadow Roots #909 (2020) with a proposed way for document-level CSS ("page styles") from the outer context of a shadow tree to be referenced and prioritized (in other words "adopted") from inside the inner context of the shadow tree.

The proposal leverages two new platform features now available in all modern browsers:

"Page styles" are document-level CSS rules in the outer context outside a shadow tree in a grouping like a cascade layer or other grouping.

The proposal includes an instance method shadowRoot.adoptStyles() that sets and/or returns a styleReferenceList as well as a declarative parse location in an @layer statement rule inside a shadow tree:

@layer inherit.resets;

Or in an attribute on a declaratively created shadow tree:

<custom-element adoptstyles="inherit.resets">
    <template shadowrootmode="open">
        ...
    </tempate>
</custom-element>

Background

Bringing Page Styles into Shadow Trees

"Open-stylable" Shadow Roots #909 was opened in 2020 for the primary use case of component library authors or maintainers who want to move to web components while supporting stylesheets that they don't control. It was perceived that "strong style encapsulation is a major hinderance - perhaps the primary obstacle - to using shadow DOM".

The original issue posited a new mode for shadow trees imperatively attached to custom elements: this.attachShadow({mode: 'open-stylable'}) "that allows selectors to reach into a shadow root from above".

Over 250 ensuing comments discussed topics like:

It is of note that all modern browsers already support CSS rules in declaratively or imperatively created shadow trees that are already inside a shadow tree either through CSS files in a link or import tag or through user-written CSS rules inside the shadow tree.

New Tools, New Solutions

Since 2020, new standardized features have become available in all modern browsers, opening up new potential approaches to solve this longstanding issue:

Declarative Shadow DOM

Declarative shadow DOM solves a fundamental Web platform issue, the declarative subtree problem in markup languages that predates even HTML itself. Until recently, the only way to create a shadow tree was in Javascript.

But that is behind. Now, anyone using or authoring a web component (or designing or using a stand-alone shadow tree) can use declarative shadow DOM.

There are two obvious consequences of the modern availability of declarative shadow trees as to issue 909:

But also and more fundamentally for issue 909, declarative shadow DOM provides a new safe path for users to present styles to web components:

Said differently: "Declarative Shadow DOM can be used on its own as a way to encapsulate styles or customize child placement, but it's most powerful when used with Custom Elements".

So declarative shadow DOM already gives web component users a way to present a shadow tree (with user-written CSS styles and CSS files in link and import tags in it) to the web component. And a way for the web component to accept, reject (the default), or use those styles as it sees fit.

Thus, declarative shadow DOM already answers the often-expressed need on behalf of web component authors to have opt-in say before accepting user styles into web components.

So the Shadow Layers proposal uses declarative shadow trees to "pull" in page styles. Any page style accessing syntax would therefore of necessity be declarative and work from "inside", not "outside", the shadow tree.

Cascade Layers

CSS cascade layers (@layer) provide a cascade-level mechanism for author origin grouping and prioritizing of CSS rules.

Cascade layers already work inside shadow trees (but do not now reference page styles outside the shadow tree).

Also, cascade layers have particular characteristics desirable for bringing in page styles into shadow trees:

Proposal

DOM Interface ShadowRoot

Add to DOM § 4.8 Interface ShadowRoot:

Shadow roots have an associated method adoptStyles() that sets and returns a styleReferenceList sequence of references to a shadow tree's outer context style groupings, in the following allowed string formats:

All other string formats are ignored and skipped.

CSS Cascading and Inheritance Context

Add to CSS Cascading and Inheritance (§ 6.1 Context in Level 5 or § 2.1 Context in Level 6): The styleReferenceList is populated at DOM parsing in the following sourcing order as last in final CSS style sheets (i.e. last in cascade Order of Appearance):

Declarative Parse Locations

This proposal recommends narrowing to only CSSLayerStatementRules of the three included declarative parse locations for styleReferenceLists to appear and be parsed.

The three included declarative parse locations:

In an @layer statement rule (CSSLayerStatementRule) inside a shadow tree:

@layer inherit.resets.as.outer-resets, outer-resets;

On an attribute on a declaratively created shadow host element:

<custom-element adoptstyles="inherit.resets">
    <template shadowrootmode="open">
        ...
    </tempate>
</custom-element>

On an attribute on the declaring template element of a declaratively created shadow host element:

<custom-element>
    <template shadowrootmode="open" adoptstyles="inherit.resets">
        ...
    </tempate>
</custom-element>

For all of the above declarative parse locations, the format inherit.<layerName>.as.<renamedLayerName> would require that <renamedLayerName> also be listed in an @layer statement rule inside the shadow tree to be prioritized by the @layer statement rule.

Summarizing some tradeoffs for the 3 declarative locations:

Location Polyfillable? Imperative? User action not required? Declarative & Imperative?
CSSLayerStatementRule yes yes yes yes
shadow host element yes no no no
template attribute no yes no no

The column "Imperative?" means would the declarative format location be automatically parsed for imperatively created shadow trees (i.e. those created by attachShadow()) without an additional function or necessary opt-in step.

The column "User action not required?" refers to the discussion and consideration of placing complexity and opt-in on the component author rather than the component user "... component user does not need to do absolutely anything ... the complexity and all the opt-in is within the component definition, which I think is essential for solving the use cases ...".

The column "Declarative & Imperative?" means the mechanism works the same in either a declarative shadow DOM created shadow tree or in an imperatively created shadow tree with attachShadow(). See user story 27 "Markdown component with automatic page styles".

Rationale

The proposed instance method, the styleReferenceList format, and the declarative parse locations are influenced by several considerations:

In short, the inherit.as.<renamedLayerName> formats work with shadowRoot.adoptStyles() and also with a declarative shadow DOM, a shadow tree created with this.attachShadow(), cascade @layer, and@scope without breaking or requiring change to any of them, and (except if attached to a declarative shadow tree <template>) are polyfillable.

Also, it is assumed that any CSSLayerStatementRule in the shadow tree will be parsed (See comment to Proposal: @layer initial should always be the first layer #10094).

Web Platform Tests & User Stories

A large range of user stories have been collected, see Collection user stories #1052, and the following have been implemented and tested in the polyfill as web platform tests:

01 Page resets As a web page author I just want my page resets to work in my shadow tree so that buttons in the shadow tree match buttons outside the shadow tree. ```html ```
02 Nested shadow trees As a web page author or shadow tree designer, I want to use declarative shadow DOM to design a `` for my page so that buttons in `nav-bar` get their style from ``, and the Home button gets its style from the page styles. No Javascript, no Flash of Unstyled Content, no attachShadow() or CustomElements.define(). ```html ```
03 Web component from another entity As a web page author I want to pass some page styles into a web component from another entity whose internal styles I do not control, so that the web component will use those styles. ```html ```
04 Web component rejects user styles As a web component author I want to reject any page styles that the web component user offers me to use, so that the styles in the web component are never affected by outer styles. ```html ```
05 Page styles at low priority As a shadow tree designer I want the user of the shadow tree to be able to bring in their page styles at a low priority, so that default styles in the shadow tree will win over brought-in page styles. ```html ```
06 Page styles at high priority As a shadow tree designer I want the user of the shadow tree to be able to bring in their page styles at a high priority, so that brought-in page styles will win over default styles in the shadow tree. ```html ```
07 All page styles at low priority As a shadow tree designer I want the user of the shadow tree to be able to bring in all their page styles at a low priority, so that default styles in the shadow tree will win over brought-in page styles. ```html ```
08 All page styles at high priority As a shadow tree designer I want the user of the shadow tree to be able to bring in all their page styles at a high priority, so that brought-in page styles will win over default styles in the shadow tree. ```html ```
09 Web component all page styles low priority As a web component author I want to bring in all page styles at a low priority without the web component user doing anything, so that default web component styles will win over brought-in page styles. ```html ```
10 Web component all page styles high priority As a web component author I want to bring in all page styles at a high priority without the web component user doing anything, so that brought-in page styles will win over default web component styles. ```html ```
11 Designer or author provided template As a shadow tree designer or web component author, I want to provide users a default template of CSS and/or HTML so that users can knowledgeably bring in page styles. ```html ```
12 Revert to parent shadow tree As a shadow tree user, I want to bring in styles from a parent shadow tree so that shadow trees that are children of shadow trees will have styles consistent with the parent shadow trees. (currently unimplemented in shadow layers proposal) CSS: ```css @layer buttons, revert.parentshadowbuttons; ``` Example: ```html ```
13 Polyfillable As a web author, shadow tree designer or user, or web component author or user I want any solution for bringing in page styles to shadow trees to be polyfillable, so that I can evaluate, test, adopt and deploy it in a timely matter. This seems particularly important for an HTML-parser level feature. See the user-story-tests folder in the shadow layers proposal [repository](https://github.com/htmlcomponents/shadow-layers).
14 Inherit resets layer as higher priority renamed layer As a web page author I want to bring in my resets layer as a renamed layer so that it can have higher priority than the shadow tree's own reset layer. ```html ```
15 Inherit resets layer as lower priority renamed layer As a web page author I want to bring in my resets layer as a renamed layer so that it can have lower priority than the shadow tree's own reset layer. CSS: ```css @layer inherit.resets.as.shadowresets, shadowresets, resets; ``` Example: ```html ```
16 Interweave priorities of outer and inner context layers As a web page author I want to interweave priorities of outer and inner context layers so some have lower priority of a shadow tree layer and some have higher priority of a shadow tree layer. CSS: ```css @layer inherit.A.as.outerA, inherit.B.as.outerB, outerA, A, B, outerB; ``` Example: ```html ```
17 Inherit @scope page style As a declarative shadow tree or web component user, I want to bring into a shadow tree a page style that includes an @scope rule in a layer, so that I can give the outer context @scope rule priority over an inner content @scope rule. ```html ```
18 Inherit named @sheet as layer As a declarative shadow tree or web component user, I want to bring into a shadow tree a page style that includes an @sheet in a layer, so that I can give the outer context @sheet priority over an inner content styles. [At-rule support detection in @supports](https://www.bram.us/2022/01/20/detect-at-rule-support-with-the-at-rule-function/) is not available, so @sheet would not be polyfillable [Multiple stylesheets per file #5629](https://github.com/w3c/csswg-drafts/issues/5629), so the POC does not implement @sheet. However, @layer is widely deployed so polyfillability is not needed for it, and @layer also provides the essential priority mechanism. Nonetheless, an @sheet supporting syntax would be possible: ```css //Inherit named sheet as layer @layer inherit.@sheet.mysheet.as.mysheet, mysheet; ```
19 Inherit unlayered page styles as lower priority layer As a user or author of a declarative shadow tree or web component I want to bring in unlayered page styles into a shadow tree so that the outer context unlayered page styles will have lower priority than the shadow tree styles. In CSS: ```css @layer inherit.unlayered.as.unlayered, unlayered, shadowstyles; ``` Example: ```html ```
20 Inherit unlayered page styles as higher priority layer As a user or author of a declarative shadow tree or web component I want to bring in unlayered page styles into a shadow tree so that the outer context unlayered page styles will have higher priority than the shadow tree styles. In CSS: ```css @layer inherit.unlayered.as.unlayered, unlayered, shadowstyles; ``` Example: ```html ```
21 Interweave priorities of outer layered and unlayered styles As a user or author of a declarative shadow tree or web component I want to bring in both layered unlayered page styles into a shadow tree, so that the outer context layered and unlayered page styles can interweave with the shadow tree styles. In CSS: ```css @layer inherit.layered.as.layered, inherit.unlayered.as.unlayered, layered, shadowstyles, unlayered; ``` Example: ```html ```
22 Inherit all outer page styles As a user or author of a declarative shadow tree or web component I want to bring in both layered unlayered page styles into a shadow tree, so that the outer context unlayered styles have priority over outer context layered styles. In CSS: ```css @layer inherit.unlayered.as.unlayered, inherit.unlayered.as.unlayered, layered, unlayered; ``` Example: ```html ```
23 Pass through from design system As a user of a design system and a web component or declarative shadow tree, neither of which I control the styles, I want to pass CSS framework styles into the web component or declarative shadow tree, so that the web component or declarative shadow tree can be styled consistent with the CSS framework. Example: ```html ```
24 Pass through from layered CSS framework As a user of a layer-aware [low-priority CSS framework](https://github.com/w3c/csswg-drafts/issues/6284#issuecomment-1006946621) and a web component or declarative shadow tree, neither of which I control the styles, I want to pass CSS framework styles into the web component or declarative shadow tree, so that the web component or declarative shadow tree can be styled consistent with the CSS framework. Example: ```html ```
25 Inherit @imported CSS file As a shadow tree or web component user, I want to inherit into a shadow tree a CSS file that I have already @imported into the page outside the shadow tree, so that I don't have to @import the same CSS file twice (once into the page, and again into the shadow tree). In other words, I don't want to have to do this: resets.css file: ```css button { border: thick dashed red; } ``` Double @import I don't want to do: ```html @import assets/resets.css; ``` See also [Allow authors to apply new css features (like cascade layers) while linking stylesheets #7540](https://github.com/whatwg/html/issues/7540) and [Provide an attribute for assigning a `` to a cascade layer #5853](https://github.com/w3c/csswg-drafts/issues/5853). Example: ```html ```
26 Page styles only affecting shadow tree

As a shadow tree or web component user, I want to provide some page styles outside a shadow tree that won't affect the page at all but can be inherited into the shadow tree, so that I can write page styles that only affect shadow trees.

- Note that [when evaluated in the context of a shadow tree](https://drafts.csswg.org/css-scoping/#host-selector), `:host( )` matches the shadow tree’s shadow host if the shadow host, in its normal context, matches the selector argument. In any other context, it matches nothing. - `:host` behaves similarly in any other context. ```html ```
27 Markdown component with automatic page styles As a web component author, I want to write a web component that transforms markdown into HTML and brings in page styles, so that transformed markdown is styled from page styles without the web component user having to do anything. A [prototypical](https://github.com/WICG/webcomponents/issues/909#issuecomment-1936910846) `` web component with page styles. ```html

H2 outside shadow tree (thick dashed red)

```
28 Markdown component with author-defined page layer As a web component author, I want to write a web component that transforms markdown into HTML and brings in a page layer with a name that I designate, so that the transformed markdown is styled from the named page layer I designate. ```html

H2 outside shadow tree (thick dashed red)

```
29 Markdown component with author-defined lower priority shadow layer As a web component author, I want to write a web component that transforms markdown into HTML and brings in page styles, so that the transformed markdown is styled from page styles if they exist and if not the transformed markdown is styled by default web component provided styles, without the web component user having to do anything. ```html

H2 outside shadow tree (thick dashed red)

```
30 Markdown component with author-defined higher priority shadow layer As a web component author, I want to write a web component that transforms markdown into HTML and brings in page styles, so that the transformed markdown is styled from page styles, but if web component default styles exist they have higher priority, without the web component user having to do anything. ```html

H2 outside shadow tree (thick dashed red)

```
31 Markdown component with user-selectable page styles As a web component author, I want to write a web component that transforms markdown into HTML, and has default markdown styles and user-selectable page styles, so that the transformed markdown is styled by either the defaults or by the styled user-selectable page styles, as the user sees fit. ```html

H2 outside shadow tree (thick dashed red)

```
32 Markdown component with page @scope As a web component author, I want to write a web component that transforms markdown into HTML, and has default markdown styles and user-selectable page styles, so that the transformed markdown can be styled by a user-provided @scope page style. ```html

H2 outside shadow tree (unstyled)

```
33 Component library with CSS file and page styles As a shadow-tree-based component library author or maintainer I want to provide a single, once-imported CSS file for all the components in the library and also bring all page styles into some of the components, so that library and page styles only apply to some or all components as appropriate. Exemplar imperative components: - **``**: An imperative (Javascript) component that transforms and displays markdown contained in a `
Section outside shadow tree

H2 outside shadow tree (thick dashed red)

```
34 Component library with declarative and imperative components and page styles As a shadow-tree-based component library author or maintainer starting from the component library in "33 Component library with CSS file and page styles", I want to add declarative-only components (components built with declarative shadow DOM and no Javascript), so that the library provides both declarative and imperative components. Exemplar declarative component: - **``**: A declarative component (no Javascript declarative shadow tree) that styles semantic HTML elements section, header, and footer. (A platform-encapusulated version of a [very commonly](https://wordpress.com/support/wordpress-editor/blocks/group-block/) implemented [web design pattern](https://university.webflow.com/lesson/container?topics=elements)). ```html
Section outside shadow tree

H2 outside shadow tree (thick dashed red)

section-container
```
35 Component library with multi-component user-settable lower and higher priority page styles As a shadow-tree-based component library author or maintainer starting from the component library in "34 Component library with declarative and imperative components and page styles", I want to add multi-component user-settable lower and higher priority page styles, so that users can provide page styles that have either lower or higher priority than component default styles. ```html
Section outside shadow tree

H2 outside shadow tree (thick dashed red)

```
36 Component library with individual component user-settable lower and higher priority page styles As a shadow-tree-based component library author or maintainer starting from the component library in "35 Component library with multi-component user-settable lower and higher priority page styles", I want to add to individual components user-settable lower and higher priority page styles, so that users can bring in and priortize any page style layers they want. ```html
Section outside shadow tree

H2 outside shadow tree (thick dashed red)

```

Potential Extensions

@sheet (see Multiple stylesheets per file #5629) proposes a mechanism to have named groups of styles, primarily for the purpose of importing groups of styles in Javascript imports.

At-rule support detection in @supports is not available, so @sheet would not be polyfillable, so the shadow layers polyfill does not implement @sheet.

Nonetheless, the styleReferenceList format could easily be extended to support @sheet or other possible future CSS grouping mechanisms:

//Inherit named @sheet as layer
@layer inherit.@sheet.mysheet.as.mysheet, mysheet;

However, @layer is already widely deployed so polyfillability is not needed for it, and @layer also already provides the essential priority mechanism.

Polyfill

The polyfill simulates the referencing capability of shadowRoot.adoptStyles() by copying the relevant layers into the shadow tree.

Core function:

Support functions:

Conclusion & Proposed CSS Working Group Resolution

"Open-stylable" Shadow Roots #909 was opened in 2020 to address the strongly perceived view that "strong style encapsulation is a major hinderance - perhaps the primary obstacle - to using shadow DOM".

Since then, a large outpouring of sentiment, comments, and proposals have validated this strong perception.

The CSS Working Group can encourage proceeding to a solution and resolution of this longstanding open-stylable issue with a resolution like:

The CSS Working Group can guide resolution of the declarative parse location for the open-stylable issue with a resolution like:

raphaelokon commented 1 month ago

Cheers @robglidden for the great proposal. Adding https://github.com/w3c/csswg-drafts/labels/css-cascade-5 could help to raise the visibility of this issue.