Support for building an optimal, nested CSSStylesheet programmatically
Nobody has claimed this yet.
- Dominant language
- Bikeshed
- Stars
- 4.9k
- Forks
- 816
- PR merge metrics
- PR metrics pending
Description
I've been told this should be proposed here (I guess).
What problem are you trying to solve?
If a web component doesn't use ShadowDOM, but nevertheless wishes to provide a CSS Module to style the light children DOM elements that the web component generates, it would be natural, with the now shipping nested CSS support, to simply wrap the styles inside a selector that specifies the name of the custom element. The problem is, especially with scoped custom element registries, that name may not be uniform across all usages. Also, many web component libraries explicitly suggest using separate file to specify the name of the custom element.
It would also be quite useful to be able to use the same CSS Module, one for a custom element that doesn't use shadow DOM, one that does, that implements nearly identical content.
So we need a way to be able "wrap" the styles with a dynamic outer selector (typically the dynamic name of the custom element).
What solutions exist today?
I asked Claude AI how it would do it. It suggests:
function nestStyleSheet(originalSheet, outerSelector) {
const newSheet = new CSSStyleSheet();
// Build nested CSS text
let nestedRules = [];
for (const rule of originalSheet.cssRules) {
nestedRules.push(rule.cssText);
}
// Wrap all rules in the outer selector using nested CSS syntax
const nestedCSS = `${outerSelector} {
${nestedRules.join('\n ')}
}`;
newSheet.replaceSync(nestedCSS);
return newSheet;
}
This is probably all just fine, but I wonder if that means excessive string parsing? The browser now needs to reparse the entire contents again, rather than just cloning parsed "nodes".
How would you solve it?
Something like
new CssStyleSheet("outerSelector", {wraps: originalSheet}}
Anything else?
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the linked WHATWG DOM issue 1442 and the CSSStyleSheet API context described here. Determine whether wrapping an existing stylesheet with a dynamic outer selector can be specified without reparsing; done would be a resolved standards proposal with defined API behavior and compatibility considerations.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- css, javascript
- Domain
- frontend, web-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100