LibWeb: Add StyleScope to keep style caches per Document/ShadowRoot

Before this change, we've been maintaining various StyleComputer caches
at the document level.

This made sense for old-school documents without shadow trees, since
all the style information was document-wide anyway. However, documents
with many shadow trees ended up suffering since any time you mutated
a style sheet inside a shadow tree, *all* style caches for the entire
document would get invalidated.

This was particularly expensive on Reddit, which has tons of shadow
trees with their own style elements. Every time we'd create one of their
custom elements, we'd invalidate the document-level "rule cache" and
have to rebuild it, taking about ~60ms each time (ouch).

This commit introduces a new object called StyleScope.

Every Document and ShadowRoot has its own StyleScope. Rule caches etc
are moved from StyleComputer to StyleScope.

Rule cache invalidation now happens at StyleScope level. As an example,
rule cache rebuilds now take ~1ms on Reddit instead of ~60ms.

This is largely a mechanical change, moving things around, but there's
one key detail to be aware of: due to the :host selector, which works
across the shadow DOM boundary and reaches from inside a shadow tree out
into the light tree, there are various places where we have to check
both the shadow tree's StyleScope *and* the document-level StyleScope
in order to get all rules that may apply.
This commit is contained in:
Andreas Kling 2025-11-13 19:08:08 +01:00 committed by Andreas Kling
parent 70b5496ecd
commit 66263f142b
Notes: github-actions[bot] 2025-11-14 21:06:49 +00:00
21 changed files with 734 additions and 561 deletions

View file

@ -599,7 +599,11 @@ void Page::set_user_style(String source)
{
m_user_style_sheet_source = source;
if (top_level_traversable_is_initialized() && top_level_traversable()->active_document()) {
top_level_traversable()->active_document()->style_computer().invalidate_rule_cache();
auto& document = *top_level_traversable()->active_document();
document.style_scope().invalidate_rule_cache();
document.for_each_shadow_root([](auto& shadow_root) {
shadow_root.style_scope().invalidate_rule_cache();
});
}
}