LibWeb: Narrow @keyframes insertRule() invalidation

Handle inline stylesheet @keyframes insertions without falling back to
broad owner invalidation. Recompute only elements whose computed
animation-name already references the inserted keyframes name.

Document-scoped insertions still walk the shadow-including tree so
existing shadow trees pick up inherited animations, and shadow-root
stylesheets fan out through the host root so :host combinators can
refresh host-side consumers as well. Also introduce the shared
ShadowRootStylesheetEffects analysis so later stylesheet mutation paths
can reuse the same per-scope escape classification.
This commit is contained in:
Andreas Kling
2026-04-22 22:32:20 +02:00
committed by Andreas Kling
parent b6559d3846
commit 4e92765211
Notes: github-actions[bot] 2026-04-23 14:49:46 +00:00
15 changed files with 421 additions and 1 deletions

View File

@@ -11,6 +11,7 @@
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/CSS/CSSCounterStyleRule.h>
#include <LibWeb/CSS/CSSImportRule.h>
#include <LibWeb/CSS/CSSKeyframesRule.h>
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/FontComputer.h>
@@ -165,7 +166,9 @@ WebIDL::ExceptionOr<unsigned> CSSStyleSheet::insert_rule(StringView rule, unsign
// NOTE: The spec doesn't say where to set the parent style sheet, so we'll do it here.
parsed_rule->set_parent_style_sheet(this);
if (!constructed() && owner_node() && owner_node()->is_html_style_element() && parsed_rule->type() == CSSRule::Type::Style)
if (!constructed() && owner_node() && owner_node()->is_html_style_element() && parsed_rule->type() == CSSRule::Type::Keyframes)
invalidate_owners_for_inserted_keyframes_rule(*this, as<CSSKeyframesRule>(*parsed_rule));
else if (!constructed() && owner_node() && owner_node()->is_html_style_element() && parsed_rule->type() == CSSRule::Type::Style)
invalidate_owners_for_inserted_style_rule(*this, as<CSSStyleRule>(*parsed_rule), DOM::StyleInvalidationReason::StyleSheetInsertRule);
else
invalidate_owners(DOM::StyleInvalidationReason::StyleSheetInsertRule);

View File

@@ -4,12 +4,17 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/CSS/CSSKeyframesRule.h>
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/ComputedProperties.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/SelectorEngine.h>
#include <LibWeb/CSS/StyleScope.h>
#include <LibWeb/CSS/StyleSheetInvalidation.h>
#include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
#include <LibWeb/CSS/StyleValues/StringStyleValue.h>
#include <LibWeb/CSS/StyleValues/StyleValueList.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/ShadowRoot.h>
@@ -365,4 +370,175 @@ void invalidate_owners_for_inserted_style_rule(CSSStyleSheet const& style_sheet,
}
}
static void for_each_tree_affected_by_shadow_root_stylesheet_change(
DOM::Node& root,
bool include_host,
bool include_light_dom_under_shadow_host,
Function<void(DOM::Node&)> const& callback)
{
callback(root);
if (auto* shadow_root = as_if<DOM::ShadowRoot>(root)) {
auto* host = shadow_root->host();
if (!host)
return;
// Slotted selectors only reach the current host subtree, but :host combinators can also reach siblings rooted
// alongside the host. A bare :host selector, however, only needs the host itself.
if (include_host && include_light_dom_under_shadow_host)
callback(host->root());
else if (include_host || include_light_dom_under_shadow_host)
callback(*host);
}
}
static bool style_value_references_animation_name(StyleValue const& value, FlyString const& animation_name)
{
if (value.is_custom_ident())
return value.as_custom_ident().custom_ident() == animation_name;
if (value.is_string())
return value.as_string().string_value() == animation_name;
if (!value.is_value_list())
return false;
for (auto const& item : value.as_value_list().values()) {
if (item->is_custom_ident() && item->as_custom_ident().custom_ident() == animation_name)
return true;
if (item->is_string() && item->as_string().string_value() == animation_name)
return true;
}
return false;
}
static bool element_or_pseudo_references_animation_name(DOM::Element const& element, FlyString const& animation_name)
{
auto references_animation_name_in_properties = [&](CSS::ComputedProperties const& computed_properties) {
return style_value_references_animation_name(computed_properties.property(PropertyID::AnimationName), animation_name);
};
if (auto computed_properties = element.computed_properties(); computed_properties && references_animation_name_in_properties(*computed_properties))
return true;
for (u8 i = 0; i < to_underlying(CSS::PseudoElement::KnownPseudoElementCount); ++i) {
auto pseudo_element = static_cast<CSS::PseudoElement>(i);
if (auto computed_properties = element.computed_properties(pseudo_element); computed_properties && references_animation_name_in_properties(*computed_properties))
return true;
}
return false;
}
static void invalidate_elements_affected_by_inserted_keyframes_rule(DOM::Node& root, FlyString const& animation_name)
{
auto invalidate_matching_element = [&](DOM::Element& element) {
// A new @keyframes rule only matters for elements or pseudo-elements that were already referencing the
// inserted animation-name.
if (element_or_pseudo_references_animation_name(element, animation_name))
element.set_needs_style_update(true);
return TraversalDecision::Continue;
};
if (root.is_document()) {
// Document styles are inherited by existing shadow trees too, so document-scoped @keyframes insertions must
// walk the shadow-including tree instead of stopping at shadow hosts.
root.for_each_shadow_including_inclusive_descendant([&](DOM::Node& node) {
if (auto* element = as_if<DOM::Element>(node))
return invalidate_matching_element(*element);
return TraversalDecision::Continue;
});
return;
}
root.for_each_in_inclusive_subtree_of_type<DOM::Element>(invalidate_matching_element);
}
static ShadowRootStylesheetEffects determine_shadow_root_stylesheet_effects_for_sheet(CSSStyleSheet const& style_sheet, DOM::ShadowRoot const& shadow_root)
{
ShadowRootStylesheetEffects effects;
Vector<GC::Ptr<HTML::HTMLSlotElement const>> slots;
shadow_root.for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](HTML::HTMLSlotElement const& slot) {
slots.append(slot);
return TraversalDecision::Continue;
});
style_sheet.for_each_effective_style_producing_rule([&](CSSRule const& rule) {
if (effects.may_match_shadow_host && effects.may_match_light_dom_under_shadow_host && effects.may_affect_assigned_nodes_via_slots)
return;
if (!is<CSSStyleRule>(rule))
return;
auto const& style_rule = as<CSSStyleRule>(rule);
for (auto const& selector : style_rule.absolutized_selectors()) {
effects.may_match_shadow_host |= selector->contains_pseudo_class(PseudoClass::Host);
effects.may_match_light_dom_under_shadow_host |= selector_may_match_light_dom_under_shadow_host(*selector);
if (!effects.may_affect_assigned_nodes_via_slots && !slots.is_empty()) {
for (auto const& slot : slots) {
SelectorEngine::MatchContext context {
.style_sheet_for_rule = style_sheet,
.subject = *slot,
.rule_shadow_root = &shadow_root,
};
if (SelectorEngine::matches(*selector, *slot, shadow_root.host(), context)) {
effects.may_affect_assigned_nodes_via_slots = true;
break;
}
}
}
if (effects.may_match_shadow_host && effects.may_match_light_dom_under_shadow_host && effects.may_affect_assigned_nodes_via_slots)
return;
}
});
return effects;
}
ShadowRootStylesheetEffects determine_shadow_root_stylesheet_effects(DOM::ShadowRoot const& shadow_root)
{
ShadowRootStylesheetEffects effects;
shadow_root.for_each_active_css_style_sheet([&](CSSStyleSheet& style_sheet) {
auto sheet_effects = determine_shadow_root_stylesheet_effects_for_sheet(style_sheet, shadow_root);
effects.may_match_shadow_host |= sheet_effects.may_match_shadow_host;
effects.may_match_light_dom_under_shadow_host |= sheet_effects.may_match_light_dom_under_shadow_host;
effects.may_affect_assigned_nodes_via_slots |= sheet_effects.may_affect_assigned_nodes_via_slots;
});
return effects;
}
void invalidate_owners_for_inserted_keyframes_rule(CSSStyleSheet const& style_sheet, CSSKeyframesRule const& keyframes_rule)
{
for (auto& document_or_shadow_root : style_sheet.owning_documents_or_shadow_roots()) {
auto& style_scope = document_or_shadow_root->is_shadow_root()
? as<DOM::ShadowRoot>(*document_or_shadow_root).style_scope()
: document_or_shadow_root->document().style_scope();
style_scope.invalidate_rule_cache();
if (!document_or_shadow_root->is_shadow_root() && document_or_shadow_root->entire_subtree_needs_style_update())
continue;
bool include_host = false;
bool include_light_dom_under_shadow_host = false;
if (auto* shadow_root = as_if<DOM::ShadowRoot>(*document_or_shadow_root)) {
auto effects = determine_shadow_root_stylesheet_effects(*shadow_root);
include_host = effects.may_match_shadow_host;
include_light_dom_under_shadow_host = effects.may_match_light_dom_under_shadow_host;
}
for_each_tree_affected_by_shadow_root_stylesheet_change(
*document_or_shadow_root,
include_host,
include_light_dom_under_shadow_host,
[&](DOM::Node& affected_root) {
invalidate_elements_affected_by_inserted_keyframes_rule(affected_root, keyframes_rule.name());
});
}
}
}

View File

@@ -39,6 +39,12 @@ struct StyleSheetInvalidationSet {
Vector<TrailingUniversalInvalidationRule> trailing_universal_rules;
};
struct ShadowRootStylesheetEffects {
bool may_match_shadow_host { false };
bool may_match_light_dom_under_shadow_host { false };
bool may_affect_assigned_nodes_via_slots { false };
};
// Extend `result` with the invalidation effects of `style_rule`'s selectors. Falls back to a whole-subtree
// invalidation flag inside `result` when a selector is not amenable to targeted invalidation.
void extend_style_sheet_invalidation_set_with_style_rule(StyleSheetInvalidationSet& result, CSSStyleRule const& style_rule);
@@ -54,8 +60,16 @@ WEB_API bool selector_may_match_light_dom_under_shadow_host(StringView selector_
// as @property or @keyframes) whose effects are not captured by selector invalidation alone.
void invalidate_root_for_style_sheet_change(DOM::Node& root, StyleSheetInvalidationSet const&, DOM::StyleInvalidationReason, bool force_broad_invalidation = false);
// Summarize how any currently-active stylesheet in `shadow_root` can escape the shadow subtree. Used by mutation
// paths that need host-side fallout derived from the whole shadow scope rather than a single sheet.
ShadowRootStylesheetEffects determine_shadow_root_stylesheet_effects(DOM::ShadowRoot const&);
// Apply a targeted invalidation to all documents and shadow roots that own `style_sheet` in response to inserting
// `style_rule` into it.
void invalidate_owners_for_inserted_style_rule(CSSStyleSheet const& style_sheet, CSSStyleRule const& style_rule, DOM::StyleInvalidationReason);
// Apply a targeted invalidation to all documents and shadow roots that own `style_sheet` in response to inserting
// `keyframes_rule` into it. Only elements already referencing the inserted animation-name are dirtied.
void invalidate_owners_for_inserted_keyframes_rule(CSSStyleSheet const& style_sheet, CSSKeyframesRule const& keyframes_rule);
}

View File

@@ -0,0 +1 @@
PASS: bare :host keyframes insertRule only invalidates the host (0 invalidations)

View File

@@ -0,0 +1,2 @@
opacity before keyframes insertRule: 1
opacity after keyframes insertRule: 0.25

View File

@@ -0,0 +1,2 @@
opacity before keyframes: 1
opacity after keyframes: 0.25

View File

@@ -0,0 +1,3 @@
before: 1
after: 1
keyframes: 0

View File

@@ -0,0 +1 @@
PASS: keyframes insertRule only invalidates animation users (1 invalidations)

View File

@@ -0,0 +1,6 @@
slotted before rule: rgb(0, 0, 0)
slotted after rule: rgb(0, 0, 255)
inherited before slot rule: rgb(0, 0, 0)
inherited after slot rule: rgb(255, 0, 0)
opacity before keyframes: 1
opacity after keyframes: 0.25

View File

@@ -0,0 +1,42 @@
<!DOCTYPE html>
<script src="../include.js"></script>
<div id="host"></div>
<script>
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).animationName;
getComputedStyle(triggerElement).animationName;
internals.resetStyleInvalidationCounters();
}
function addBystanders(parent, count) {
for (let i = 0; i < count; ++i) {
const bystander = document.createElement("div");
bystander.textContent = `bystander ${i}`;
parent.appendChild(bystander);
}
}
test(() => {
const host = document.getElementById("host");
const shadowRoot = host.attachShadow({ mode: "open" });
const sheet = new CSSStyleSheet();
sheet.replaceSync(`
:host {
animation-name: fade;
animation-duration: 1s;
}
`);
shadowRoot.adoptedStyleSheets = [sheet];
addBystanders(document.body, 25);
settleAndReset(host);
sheet.insertRule("@keyframes fade { from { opacity: 0.25; } to { opacity: 0.25; } }", sheet.cssRules.length);
getComputedStyle(host).animationName;
const invalidations = internals.getStyleInvalidationCounters().styleInvalidations;
if (invalidations <= 1)
println(`PASS: bare :host keyframes insertRule only invalidates the host (${invalidations} invalidations)`);
else
println(`FAIL: bare :host keyframes insertRule only invalidates the host (${invalidations} invalidations)`);
});
</script>

View File

@@ -0,0 +1,29 @@
<!DOCTYPE html>
<script src="../include.js"></script>
<div id="host"><span id="slotted" class="item">slotted</span></div>
<script>
asyncTest(async done => {
const host = document.getElementById("host");
const slotted = document.getElementById("slotted");
const shadowRoot = host.attachShadow({ mode: "open" });
const declarationsSheet = new CSSStyleSheet();
const keyframesSheet = new CSSStyleSheet();
shadowRoot.innerHTML = "<slot></slot>";
shadowRoot.adoptedStyleSheets = [declarationsSheet, keyframesSheet];
declarationsSheet.replaceSync(`
::slotted(.item) {
animation-name: fade;
animation-duration: 1s;
animation-fill-mode: both;
}
`);
println(`opacity before keyframes insertRule: ${getComputedStyle(slotted).opacity}`);
keyframesSheet.insertRule("@keyframes fade { from { opacity: 0.25; } to { opacity: 0.25; } }", keyframesSheet.cssRules.length);
await animationFrame();
println(`opacity after keyframes insertRule: ${getComputedStyle(slotted).opacity}`);
done();
});
</script>

View File

@@ -0,0 +1,31 @@
<!DOCTYPE html>
<script src="../include.js"></script>
<style id="document-style"></style>
<div id="host"></div>
<script>
asyncTest(async done => {
const host = document.getElementById("host");
const shadowRoot = host.attachShadow({ mode: "open" });
shadowRoot.innerHTML = `
<style>
#target {
animation-name: fade;
animation-duration: 1s;
animation-fill-mode: both;
}
</style>
<div id="target">target</div>
`;
const target = shadowRoot.getElementById("target");
const documentStyleSheet = document.getElementById("document-style").sheet;
println(`opacity before keyframes: ${getComputedStyle(target).opacity}`);
documentStyleSheet.insertRule("@keyframes fade { from { opacity: 0.25; } to { opacity: 0.25; } }", documentStyleSheet.cssRules.length);
await animationFrame();
println(`opacity after keyframes: ${getComputedStyle(target).opacity}`);
done();
});
</script>

View File

@@ -0,0 +1,27 @@
<!DOCTYPE html>
<style id="dynamic-style">
#target {
animation-duration: 1s;
animation-name: inserted;
}
</style>
<div id="target"></div>
<script src="../include.js"></script>
<script>
asyncTest(async done => {
const target = document.getElementById("target");
const sheet = document.getElementById("dynamic-style").sheet;
println(`before: ${target.getAnimations().length}`);
sheet.insertRule("@keyframes inserted { from { opacity: 0.25; } to { opacity: 0.75; } }", 1);
await animationFrame();
const animations = target.getAnimations();
println(`after: ${animations.length}`);
if (animations.length > 0)
println(`keyframes: ${animations[0].effect.getKeyframes().length}`);
done();
});
</script>

View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<script src="../include.js"></script>
<style id="style-sheet">
#target {
animation-name: fade;
animation-duration: 1s;
}
</style>
<div id="target">target</div>
<div>bystander 1</div>
<div>bystander 2</div>
<div>bystander 3</div>
<script>
function settleAndReset(triggerElement) {
// Force style resolution before we observe counters so the inserted
// @keyframes rule is the only thing contributing to the measurement.
getComputedStyle(triggerElement).animationName;
getComputedStyle(triggerElement).animationName;
internals.resetStyleInvalidationCounters();
}
function addBystanders(parent, count) {
for (let i = 0; i < count; ++i) {
const bystander = document.createElement("div");
bystander.textContent = `bystander ${i + 4}`;
parent.appendChild(bystander);
}
}
test(() => {
const target = document.getElementById("target");
addBystanders(document.body, 25);
const sheet = document.getElementById("style-sheet").sheet;
settleAndReset(target);
sheet.insertRule("@keyframes fade { from { opacity: 0; } to { opacity: 1; } }", sheet.cssRules.length);
getComputedStyle(target).animationName;
const invalidations = internals.getStyleInvalidationCounters().styleInvalidations;
if (invalidations <= 1)
println(`PASS: keyframes insertRule only invalidates animation users (${invalidations} invalidations)`);
else
println(`FAIL: keyframes insertRule only invalidates animation users (${invalidations} invalidations)`);
});
</script>

View File

@@ -0,0 +1,40 @@
<!DOCTYPE html>
<script src="../include.js"></script>
<div id="host"><span id="slotted" class="item">slotted</span><span id="inherited">inherited</span></div>
<script>
asyncTest(async done => {
const host = document.getElementById("host");
const slotted = document.getElementById("slotted");
const inherited = document.getElementById("inherited");
const shadowRoot = host.attachShadow({ mode: "open" });
shadowRoot.innerHTML = `
<style id="shadow-style">
::slotted(.item) {
animation-name: inserted;
animation-duration: 1s;
animation-fill-mode: both;
}
</style>
<slot></slot>
`;
const styleSheet = shadowRoot.getElementById("shadow-style").sheet;
println(`slotted before rule: ${getComputedStyle(slotted).color}`);
shadowRoot.appendChild(document.createElement("b"));
styleSheet.insertRule("::slotted(.item) { color: rgb(0, 0, 255); }", styleSheet.cssRules.length);
println(`slotted after rule: ${getComputedStyle(slotted).color}`);
println(`inherited before slot rule: ${getComputedStyle(inherited).color}`);
styleSheet.insertRule("slot { border-color: rgb(0, 0, 0); color: rgb(255, 0, 0); }", styleSheet.cssRules.length);
println(`inherited after slot rule: ${getComputedStyle(inherited).color}`);
println(`opacity before keyframes: ${getComputedStyle(slotted).opacity}`);
shadowRoot.appendChild(document.createElement("i"));
styleSheet.insertRule("@keyframes inserted { from { opacity: 0.25; } to { opacity: 0.25; } }", styleSheet.cssRules.length);
await animationFrame();
println(`opacity after keyframes: ${getComputedStyle(slotted).opacity}`);
done();
});
</script>