Repository navigation
Description
Opening this as requested by @astearns
In #8738 we resolved to stop hoisting interleaved declarations and introduce an @nest rule that means "exactly the same thing as the parent" instead of wrapping in :is(), which is how interleaved declarations will be represented in the CSS OM. Since we were not able to get consensus on the specifics, but we had consensus that any solution along these lines is better than the status quo, we agreed that Tab would spec whatever (commit here), and we'd discuss the details later, since fixing the specifics is more web compatible than changing the current behavior after even longer.
Note
An interleaved declaration is a declaration that comes after one or more nested rules.
The issues around which we could not reach consensus were:
- If authors have no reason to write
@nestand it’s only introduced to represent interleaved declarations and rules, should they even be able to? - If
@nestrules are magically added around interleaved declarations should they also be removed during serialization?- If they are removed during serialization, does this happen always, or only when part of a larger rule (e.g. as part of
.cssText)?
- If they are removed during serialization, does this happen always, or only when part of a larger rule (e.g. as part of
- Do we even need a new
@nestrule? What if we simply use the existingCSSStyleDeclarationobject to represent interleaved rules? (proposed by @mdubet) - How does
setProperty()work if we go with one of the designs that involve more magic? - What happens when a rule is removed and thus two sets of interleaved declarations become adjacent?
- Similar issue not brought up in the call: what about the case when these rules are first? Should they be merged with
rule.style?
- Similar issue not brought up in the call: what about the case when these rules are first? Should they be merged with
These are not orthogonal decisions: it seems clear that if @nest serializes to include an actual @nest {} rule, that @nest rule needs to also be valid author code. So essentially there are three possible designs:
- Magic-minimizing
@nest(proposed by @tabatkins, supported by @emilio @andruud @Loirooriol): The rule is automatically added around interleaved declarations, but there is no more magic besides that. - Author-exposure minimizing
@nest(proposed by @LeaVerou, supported by @fantasai @astearns): The rule becomes a CSS OM detail, with no corresponding CSS syntax, and is removed on serialization (regardless of how serialization happens). - No
@nest, justCSSStyleDeclarationin the CSSOM (proposed by @mdubet, supported by @LeaVerou @fantasai).- Criticism: That means
.cssRuleswill also return non-rules? Would.insertRule()also acceptCSSStyleDeclaration?
- Criticism: That means
For 2 and 3, there are also design variations based on the answer to 4 and 5 above.
My position:
- As a design principle, I don't think CSS should have author-facing syntax that provides no benefit to authors. Either we should come up with actual use cases for
@nestor make it an internal detail. That said, there could conceivably be use cases for it. E.g. one of the problems with IACVT is that fallbacks are thrown away by the time the declaration becomes invalid. What if this was a way to preserve fallbacks? - Despite proposing 2, I actually now support 3 as I realized this version of
@nestis functionally equivalent toCSSStyleDeclarationand we should not be introducing new interfaces with philosophical purity being the only motivation (i.e. "but otherwise.cssRuleswould be returning a non-rule?!?") - Some voices are arguing for less magic as a goal in itself. I don't think avoiding magic at all costs should be a goal; the right magic can make a huge usability difference (at the cost of implementation complexity). It’s the wrong kind of magic that becomes problematic: magic that rarely predicts user intent well, and especially when they cannot opt-out of it. Neither seems to be the case here, at least if we design this well.
- I think authors should be able to interact with the CSS OM predictably without having to care whether there are interleaved declarations or not. This means that
setProperty()on the base rule should just work, without them having to do tree walking to find the last nested rule. Like,setProperty()is an incredibly common operation, and an API where calls tosetProperty()have no effect are exactly the kind of dreadful APIs that make utility libraries proliferate. - I strongly disagree with Tab that reading and modifying the CSS OM only affects about a hundred developers in the entire world (!). Reading and modifying the CSS OM is at the core of a ton of very widespread libraries (e.g. jQuery, D3, etc). Even if most authors do not use it directly, I assure you almost every developer reads and modifies the CSS OM regularly, it's just done through several layers of abstractions.
So I would propose a design that would minimize author exposure to all of this, and would just try to do what's reasonable when reading and modifying the CSS OM:
.cssRuleswould containCSSStyleDeclarationobjects with interleaved declarationsinsertRule()would acceptCSSStyleDeclarationobjects- No nonsensical or redundant structures:
- Adjacent
CSSStyleDeclarationobjects would be merged. - A
CSSStyleDeclarationobject cannot be at the start ofcssRules. Inserting one should simply merge the declarations withrule.style.
- Adjacent
Should rule.style be magic?
One thing I'm ambivalent about is whether rule.style should be magic too.
This would mean:
rule.stylereturns the union of all interleaved declarations (we can introduce another property to only get the non-interleaved ones)rule.style.setProperty()(and accessors) adds to the last interleavedCSSStyleDeclaration(if any are present). The third argument is turned into a dictionary with apriorityproperty and another property (name TBD) to reverse this behavior and actually add it to the first block of declarations.
Pros & Cons:
- 👍🏼 Max compatibility with existing code
- 👍🏼 Fewer footguns for authors (minimize bugs if authors forget to handle the case of interleaved declarations)
- 👍🏼 More sensible API for when inline styles also support nesting.
- 👀 Would this work or would it end up not predicting author intent well? What cases am I missing?
If we decide to avoid magic here, we can make the API more palatable by:
- Introducing a new
ruleproperty that returns aCSSStyleDeclarationfor the union ofrule.styleand interleaved declarations - Introducing a
rule.setProperty()method that would add the property at the end of the last interleaved declaration.rule.style.setProperty()would continue to do what it currently does. Same forremoveProperty(),getPropertyValue()etc.
Activity
romainmenke commentedon Apr 20, 2024
Thank you @LeaVerou.
I actually want the
@nestrule but as a more generic organizational tool.In JavaScript it is possible to write blocks without any condition. I use this very frequently to group bits of code in a larger section.
This new at-rule could serve a similar purpose. Most authors will never use it but they could to organise and structure their code.
Today we use either multiple rules with the same selector, or comments when we want to group lists of declarations. Neither is really good.
This is our list of custom props when we start a new project :
We need to add comments before and after each group so that we can have folding regions in code editors.
@tabatkins has also stated that they aren't attached to the name of this at-rule. Something that isn't tied to nesting would be nice.
If on the other hand, this can all be implementation details, then I prefer that.
I however fear that we can only kick this bucket further down the road and that some API will surface the warts.
andruud commentedon Apr 20, 2024
Do we need the
@nestpart of the rule? Can we use naked{}? Looking at css-syntax, I don't immediately see why not. In other words:To be clear, this issue blocks actually carrying out #8738. The more we mess around with the details here, the higher the risk that no change will happen at all.
LeaVerou commentedon Apr 20, 2024
That was not the resolution at all. Please implement the
@nestrule as currently specced by @tabatkins. It is far, far easier to change the details of that than to change the current behavior of nesting later. That's the whole point of the resolution we made on Wednesday!andruud commentedon Apr 22, 2024
@LeaVerou Oh. I thought the point of the resolution was to focus the discussion and hopefully converge on something.
Unfortunately I can't make a move on
@nestuntil this issue is resolved. I will likely not be able to ship a breaking change with the intent to break it again later, especially when there's no consensus on what the follow-up change would be.The specific changes we're discussing here can not necessarily be made later at all. It is sometimes very hard to understand the risk of changing CSSOM APIs.
Loirooriol commentedon Apr 22, 2024
@andruud It's not with the "intent to break it again later". It's with the intent to keep
@nestas a better option than the "shifting up", but leaving the door open to explore other possibilities.If later on we prefer to switch to something else but it's not compatible, then so be it, we can stay with
@nest.The point is that there was consensus that
@nestis better than "shifting up". Exploring other possible approaches shouldn't block@nest, since delaying it will just make it not compatible.tabatkins commentedon Apr 22, 2024
As I said in my final comment in 8738, when considering any new feature, or additional complexity in an existing feature, it's worth paying attention to both the size of the affected audience and the size of the benefit that audience will receive.
The existence of an
@nestrule is visible solely to authors who are crawling the CSSOM, or serializing the OM and then looking at it. Both of these are advanced use-cases, they're not something that 99% (and I think that's a very conservative percentage) of authors will ever do. I, myself, have never inspected the CSSOM in my entire webdev career except when writing WPTs.So, the audience of people affected by any change here is very tiny, I'll argue, and that audience is composed of relatively skilled authors. (I think this audience can be reasonably summarized as "people who are writing CSS tooling".)
Do any of these changes allow that audience to do something currently difficult or impossible? No, these are solely attempting to improve the consistency of how the OM is represented in certain aspects.
Do they improve this audience's experience in a meaningful way? Arguable. While they improve the consistency in some ways (making the OM and/or the reserialized string more closely resemble the originally authored code), they reduce consistency in other ways (unusual serialization rules; edge cases that require restrictions on where rules can be moved around; widening of the possible types in certain attributes).
For example, right now you can, in theory, take any of the objects in an MQ's
.cssRuleslist and move it out of that MQ, appending it to the stylesheet itself. If the object here is a CSSStyleDeclaration, what happens? Is that an error? If it's a CSSNestRule, but we have special serialization rules that make it look like raw declarations, how does it serialize in this case? (Or, again, maybe it causes an error?)Or take
.insertRule(). Its first argument is a string, which is parsed to obtain a rule to insert. (You can pass a rule object directly, but it's serialized and then re-parsed.) If you can't write@nestdirectly in a stylesheet, how do you insert such a rule? Do we have to now accept code likex.insertRule("color: blue;"), which is invalid today?Or a parsed stylesheet will never have an
@nestat the start of a style rule, or next to each other. But via CSSOM manipulation you can construct such situations. How do they serialize? Will you still end up with a stylesheet that parses into a different OM than it started fromWhatever we do, if it's "magic" in some way, it'll spawn corner cases like this. Magic like this can be justified, by sufficient benefit to a sufficient audience. I don't think that it qualifies on either metric in this case, however.
In summary, we should just do the simplest possible thing, with the least amount of magic possible, because all of the suggested magic (beyond the initial parser magic) won't actually pay for itself.
tabatkins commentedon Apr 22, 2024
We could, it would just be a new syntax construct to define. Relying on the existing at-rule syntax just makes for a slightly simpler model. And since we don't anticipate authors actually writing this themselves, I don't think the length of the name actually matter in any meaningful way.
LeaVerou commentedon Apr 22, 2024
@andruud
We are trying to avoid a breaking change by shipping
@nestin some shape or form. @tabatkins is arguing right under your comment that how we implement this in the OM only affects a tiny fraction of authors. You are saying that it would be a breaking change and that "it’s very hard to understand the risk of changing CSSOM APIs". It may be productive if you two have a breakout to align on this, since you work at the same company? Because unless I’m missing something, I don't see how both statements can be true (it is both impactful and not impactful).@tabatkins
Tab, nobody is disagreeing that I/E matters, we’re disagreeing on what the I is.
I have responded to this point in the OP:
Also, since we’re sharing anecdotes, I have crawled and modified the CSS OM dozens of times in my web dev career, none of which was while writing WPTs. I did not mention it earlier because as an anecdote, I didn’t think it was that relevant.
Again, the users of these tools are not a small audience.
I don’t see how this is different than defining what
@nest {}does in the root scope. We’ll have to define something however you look at it. And if anything, defining what root-level declarations do is actually quite useful (anecdotally, I’ve written special code to handle raw declarations at the root level several times when coding CSS demos).Actually, depending on how we define it root-level declarations could even solve all these use cases that require setting stuff on the document node.
Yes! Which again seems like a win and more broadly useful.
I’m not married to the details, but I was envisioning that these nodes would be merged automatically by the CSS OM, not during serialization. All the Web Platform’s OMs are full of these kinds of normalizations, so I don’t see what the problem is.
tabatkins commentedon Apr 22, 2024
The users of tools that crawl/modify the CSSOM only matter for this proposal insofar as those tools expose the CSSOM to them (or this proposal makes those tools work better, thus improving the experience of their users). Do you have examples of that?
Sure, we have to define what
@nestdoes in the global scope, in exactly the same way we defined what&matches in the global scope. (And it's currently defined to act exactly the same.) But these additional things are more corner cases to define.How is this a meaningful win over
x.insertRule("@nest { color: blue; }")? I mean, it's very slightly shorter, sure. But does it matter otherwise? Is it worth the consistency loss ofinsertRule()no longer being restricted to taking rules?I don't think that's accurate to say. For example, in the following:
You'll get two Text nodes, despite that being essentially identical to just having a single Text node with "foobar". Having nodes magically merge underneath you as a side-effect of doing something unrelated (like removing a rule that previously happened to separate two of them) is the sort of thing that causes bugs in author code very easily, since objects disappear, indexes change, etc. in an unpredictable manner.
andruud commentedon Apr 23, 2024
Yeah, sure.
{}was a response to @romainmenke's world where authors might actually want to write it themselves. If@nest{}basically does nothing (except add structure), perhaps{}is a better way to represent it (and more in line with other languages).That is not what I'm saying. I'm saying it's not always easy to prove that CSSOM changes won't break sites, even if you strongly believe it won't.
But OK, if shipping
@nestASAP is indeed what everyone wants here, I can try. I'll need positions from Apple and Mozilla. (EDIT: mozilla/standards-positions#1013, WebKit/standards-positions#337).LeaVerou commentedon Apr 23, 2024
If we have author facing syntax for this, I'd prefer it's not
{}so we can reserve{}for something that is actually useful (of course this changes if we can figure out a way to make@nest {}useful).Thank you!
dbaron commentedon Apr 24, 2024
One question that would affect my opinion of whether the CSSOM questions here matter: what's the chance that at some point in the future we'll allow the nesting syntax inside the
styleattribute? (This sort of syntax has been proposed and specified in the past, but it didn't get traction at the time.) I think the CSSOM is much more relevant for the style attribute than it is for style sheets, since it's more widely used there.cdoublev commentedon Apr 24, 2024
I am not sure I understood the whole conversation between mdubet and emilio about this in #8738, but intermixing list of declarations (or
CSSStyleDeclarations) and rules in specified order in an internal property (eg.contents) seemed like an idiomatic solution.The first list of declarations in
contentsshould be exposed bystyle..cssRulesand.insertRule()should ignore lists of declarations incontents..deleteRule()should eventually move declarations into the first list. It does not seem that painfull.I did not understood why contents would need to be exposed by the public
.cssRules. I guess in order to add declarations after rules via the CSSOM. Assuming there is a need for this, a new interface like.insertDeclaration()and/orstylescould be defined.But accepting declarations in
.insertRule(), ugh. 😬64 remaining items
[css-nesting] Retire @nest, introduce the 'nested declarations rule' (#…
[Interleaved Decls] Remove `@nest`
[css-nesting] Implement CSSNestedDeclarations behind a flag
[css-nesting] Implement CSSNestedDeclarations behind a flag
[css-nesting] Implement CSSNestedDeclarations behind a flag
[css-nesting] Implement CSSNestedDeclarations behind a flag
[css-nesting] Implement CSSNestedDeclarations behind a flag
Bug 1914427 [wpt PR 47744] - [css-nesting] Implement CSSNestedDeclara…
[css-nesting] New behavior for interleaved declarations and rules
Bug 1914427 [wpt PR 47744] - [css-nesting] Implement CSSNestedDeclara…