Skip to content

Instantly share code, notes, and snippets.

@xiaochengh
Last active October 6, 2022 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xiaochengh/437cbc4b9a6fc9afdbd97856d9946901 to your computer and use it in GitHub Desktop.
Save xiaochengh/437cbc4b9a6fc9afdbd97856d9946901 to your computer and use it in GitHub Desktop.
Extension: `DocumentOrShadowRoot.getCascadeLayers()`

This proposal extends the DocumentOrShadowRoot mixin with a new method getCascadeLayers(), which returns the names of all the CSS cascade layers defined in the tree scope, sorted by the layer ordering.

Motivation

DocumentOrShadowRoot.getCascadeLayers() allows browser DevTools to present a visualization of all layers, for example:

Without this extension, DevTools have to manually collect the @layer rules from the stylesheets and reconstruct the full layer names and the sorted layer ordering.

Technical Details

(IDL experts may feel free to revise it)

partial interface mixin DocumentOrShadowRoot {
  FrozenArray<CSSOMString> getCascadeLayers();
};

The return value is an array of the full names of all the cascade layers, sorted in the layer order, with anonymous parts replaced by "(anonymous layer)". The default layer is not included in return value. Examples:

  1. For nested layers, their full names are returned:
@layer foo {
  @layer bar;
}
@import url("data:text/css, @layer bar;") layer(foo);

The return value is ["foo.bar", "foo"].

  1. If any part of the full layer name is anonymous, it's replaced by (anonymous layer):
@layer {
  @layer foo
}

The return value is ["(anonymous layer).foo", "(anonymous layer)"].

  1. The return value may include duplicate strings due to anonymous layers:
@layer { /* some style */ }
@layer { @layer foo { /* some other style */ } }
@layer { @layer foo { /* some other style */ } }

The return value is ["(anonymous layer)", "(anonymous layer).foo", "(anonymous layer)", "(anonymous layer).foo", "(anonymous layer)"]

Alternative Ideas

  1. Return a layer tree/forest instead of a flat list, so that developers don't need to reconstruct the sublayer information. This also presents anonymous layers better.

  2. Represent each layer as an object with the references to all the CSSStyleSheet and CSSLayerBlockRule objects in this layer.

    • This may allow a DevTool to toggle a layer (not sure, I don't have much experience with DevTools)?
    • But is this even allowed? We can't access the child rules of cross-origin stylesheets...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment